hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
70e036053ffc63c30da421d96d564d43b8de29da
3,693
cpp
C++
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
Applications/DataExplorer/DataView/FemConditionModel.cpp
MManicaM/ogs
6d5ee002f7ac1d046b34655851b98907d5b8cc4f
[ "BSD-4-Clause" ]
null
null
null
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "FemConditionModel.h" #include "Applications/DataHolderLib/BoundaryCondition.h" #include "Applications/DataHolderLib/SourceTerm.h" #include "TreeItem.h" /** * Constructor. */ FemConditionModel::FemConditionModel(QObject* parent) : TreeModel(parent) { QList<QVariant> root_data; delete _rootItem; root_data << "Parameter" << "Value"; _rootItem = new TreeItem(root_data, nullptr); } void FemConditionModel::setFemCondition(DataHolderLib::FemCondition* cond) { beginResetModel(); this->clearView(); QList<QVariant> cond_data; cond_data << QString::fromStdString(cond->getConditionClassStr()) + ":" << QString::fromStdString(cond->getParamName()); TreeItem* cond_item = new TreeItem(cond_data, _rootItem); _rootItem->appendChild(cond_item); QList<QVariant> type_data; std::string type_str; if (cond->getConditionClassStr() == "Boundary Condition") type_str = DataHolderLib::BoundaryCondition::convertTypeToString( static_cast<DataHolderLib::BoundaryCondition*>(cond)->getType()); else if (cond->getConditionClassStr() == "Source Term") type_str = DataHolderLib::SourceTerm::convertTypeToString( static_cast<DataHolderLib::SourceTerm*>(cond)->getType()); type_data << "Type:" << QString::fromStdString(type_str); TreeItem* type_item = new TreeItem(type_data, cond_item); cond_item->appendChild(type_item); QString const obj_class_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? "Mesh:" : "Geometry:"; QList<QVariant> obj_class_data; obj_class_data << "Set on " + obj_class_str << QString::fromStdString(cond->getBaseObjName()); TreeItem* obj_class_item = new TreeItem(obj_class_data, cond_item); cond_item->appendChild(obj_class_item); QString const obj_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? "Mesh array:" : "Geo-Object:"; QString const name_str = (cond->getBaseObjType() == DataHolderLib::BaseObjType::MESH) ? QString::fromStdString(cond->getParamName()) : QString::fromStdString(cond->getObjName()); QList<QVariant> obj_data; obj_data << obj_str << name_str; TreeItem* obj_item = new TreeItem(obj_data, cond_item); cond_item->appendChild(obj_item); endResetModel(); } void FemConditionModel::setProcessVariable(DataHolderLib::FemCondition* cond) { beginResetModel(); this->clearView(); DataHolderLib::ProcessVariable const& var(cond->getProcessVar()); QList<QVariant> pvar_data; pvar_data << "Process variable:" << QString::fromStdString(var.name); TreeItem* pvar_item = new TreeItem(pvar_data, _rootItem); _rootItem->appendChild(pvar_item); QList<QVariant> order_data; order_data << "Order:" << QString::number(var.order); TreeItem* order_item = new TreeItem(order_data, pvar_item); pvar_item->appendChild(order_item); QList<QVariant> comp_data; comp_data << "Number of components:" << QString::number(var.components); TreeItem* comp_item = new TreeItem(comp_data, pvar_item); pvar_item->appendChild(comp_item); endResetModel(); } void FemConditionModel::clearView() { beginResetModel(); _rootItem->removeChildren(0, _rootItem->childCount()); endResetModel(); }
33.572727
77
0.679664
MManicaM
70e1bebdcbd96978cdd7c021889ad9f3b7c189e4
1,723
hpp
C++
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
types/NullCoercibilityCheckMacro.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * 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. **/ #ifndef QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_ #define QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_ #include "types/Type.hpp" #include "types/TypeID.hpp" /** \addtogroup Types * @{ */ /** * @brief A code-snippet for use in implementations of Type::isCoercibleFrom() * and Type::isSafelyCoercibleFrom() that does common checks for * nullability of types. **/ #define QUICKSTEP_NULL_COERCIBILITY_CHECK() \ do { \ if (original_type.isNullable() && !nullable_) { \ return false; \ } else if (original_type.getTypeID() == kNullType) { \ return true; \ } \ } while (false) /** @} */ #endif // QUICKSTEP_TYPES_NULL_COERCIBILITY_CHECK_MACRO_HPP_
36.659574
78
0.639582
Hacker0912
70e676213a71532c8ff231c8514ae5f76a826ac8
471
cpp
C++
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
11
2019-11-27T00:40:43.000Z
2020-01-29T14:31:52.000Z
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T00:29:08.000Z
2020-01-08T18:53:39.000Z
tests/main.cpp
NazaraEngine/NazaraEngine
093d9d344e4459f40fc0119c8779673fa7e16428
[ "MIT" ]
7
2019-11-27T10:27:40.000Z
2020-01-15T17:43:33.000Z
#define CATCH_CONFIG_RUNNER #include <catch2/catch.hpp> #include <Nazara/Audio/Audio.hpp> #include <Nazara/Core/Log.hpp> #include <Nazara/Core/AbstractLogger.hpp> #include <Nazara/Core/Modules.hpp> #include <Nazara/Network/Network.hpp> #include <Nazara/Physics2D/Physics2D.hpp> #include <Nazara/Utility/Utility.hpp> int main(int argc, char* argv[]) { Nz::Modules<Nz::Audio, Nz::Network, Nz::Physics2D, Nz::Utility> nazaza; return Catch::Session().run(argc, argv); }
26.166667
72
0.747346
NazaraEngine
70e6892f94a72a7c21bb275f99762fdedde036c3
589
cpp
C++
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
c-develop/pertemuan ke 6/ifBilTerbesar2.cpp
GustiArsyad123/C-Language-Test
90a2eb45d1db2b039acbe5d3499aaff0aed99f82
[ "MIT" ]
null
null
null
#include <iostream> //import input output using namespace std; //mengguanakan file fungsi std int main() //fungsi { double x, y; //deklarasi variable menggunakan tipe data double cout << "Masukkan x: "; //cetak ke layar monitor x cin >> x; //inputan kemudian di simpan di variable x cout << "Masukkan y: "; //cetak ke layar monitor Y cin >> y; ////cetak ke layar monitor Y if (x > y) { cout << "Bilangan terbesar adalah X" << "\n"; } else { cout << "Bilangan terbesar adalah Y" << "\n"; } return 0; }
32.722222
70
0.570458
GustiArsyad123
70e7b889c539f5c96bd117e38e3670c378800b0f
1,771
cpp
C++
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
29
2020-04-05T21:27:46.000Z
2021-08-29T20:24:21.000Z
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
66
2020-03-31T00:29:00.000Z
2022-03-02T11:54:24.000Z
CK2ToEU4Tests/MapperTests/PrimaryTagMapper/PrimaryTagMapperTests.cpp
Osariusz/CK2ToEU4
a2786f00febb23c63f91b2ff27b788f926e18ea7
[ "MIT" ]
27
2020-03-30T15:56:24.000Z
2022-02-05T22:54:25.000Z
#include "../../CK2ToEU4/Source/Mappers/PrimaryTagMapper/PrimaryTagMapper.h" #include "gtest/gtest.h" #include <sstream> TEST(Mappers_PrimaryTagMapperTests, CultureTagsDefaultToEmpty) { std::stringstream input; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_TRUE(tagMapper.getCultureTags().empty()); } TEST(Mappers_PrimaryTagMapperTests, CultureTagsCanBeLoaded) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_EQ(tagMapper.getCultureTags().size(), 4); } TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsNullOnMiss) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture2")); ASSERT_FALSE(tagMapper.getPrimaryTagForCulture("culture5")); } TEST(Mappers_PrimaryTagMapperTests, TagMapperReturnsTagOnHit) { std::stringstream input; input << "group1 = { culture1 = {primary = TAG} culture2 = {} culture3 = {primary = GAT} }\n"; input << "group2 = { culture4 = {primary = GAT} culture5 = {} culture6 = {primary = GOT} }\n"; const mappers::PrimaryTagMapper tagMapper(input); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture1"), "TAG"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture3"), "GAT"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture4"), "GAT"); ASSERT_EQ(*tagMapper.getPrimaryTagForCulture("culture6"), "GOT"); }
37.680851
95
0.730661
Osariusz
70ea05cbd69458cf0478333141d31420a240b899
10,123
cc
C++
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
23
2021-02-17T16:58:52.000Z
2022-02-12T17:01:06.000Z
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
1
2021-04-01T22:41:32.000Z
2021-09-24T14:14:17.000Z
src/core/breakpoint/BreakpointManager.cc
IntroVirt/IntroVirt
917f735f3430d0855d8b59c814bea7669251901c
[ "Apache-2.0" ]
4
2021-02-17T16:53:18.000Z
2021-04-13T16:51:10.000Z
/* * Copyright 2021 Assured Information Security, 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. */ #include "BreakpointManager.hh" #include "core/breakpoint/BreakpointImpl.hh" #include "core/domain/DomainImpl.hh" #include "core/domain/VcpuImpl.hh" #include <introvirt/core/exception/CommandFailedException.hh> #include <introvirt/util/compiler.hh> #include <log4cxx/logger.h> #include <cassert> #include <stdexcept> namespace introvirt { static InternalBreakpoint* HiddenBreakpoint = nullptr; static thread_local std::shared_ptr<InternalBreakpoint> active_breakpoint = nullptr; static log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("introvirt.breakpoint.BreakpointManager")); void InternalBreakpoint::watchpoint_event(Event& event) { if (mapping_.address() != event.mem_access().physical_address().address()) { LOG4CXX_WARN(logger, "Incorrect physical address: " << event.mem_access().physical_address()); } if (event.mem_access().read_violation()) { LOG4CXX_DEBUG(logger, event.task().process_name() << ": Hiding breakpoint from guest at " << mapping_ << " RIP: 0x" << std::hex << event.vcpu().registers().rip()); } if (event.mem_access().write_violation()) { LOG4CXX_DEBUG(logger, event.task().process_name() << ": Guest attempted to write breakpoint memory at " << mapping_); } if (*mapping_ == 0xCC && !nested_bp()) { disable(); HiddenBreakpoint = this; } } void InternalBreakpoint::step_event() { // Re-read the original byte and then restore the breakpoint LOG4CXX_TRACE(logger, "Restoring breakpoint after guest memory access"); original_byte_ = *mapping_; enable(); single_step_.reset(); } void InternalBreakpoint::deliver_breakpoint(Event& event) { // Get a copy of the callback set so that we don't have to hold a lock std::unique_lock lock(mtx_); std::vector<std::shared_ptr<BreakpointImplCallback>> callbacks; callbacks.reserve(breakpoint_list_.size()); for (auto& weakptr : breakpoint_list_) { auto entry = weakptr.lock(); if (entry) callbacks.push_back(entry->callback()); } lock.unlock(); LOG4CXX_DEBUG(logger, "Delivering " << callbacks.size() << " breakpoint callbacks"); for (auto& entry : callbacks) { try { entry->deliver_event(event); } catch (TraceableException& ex) { LOG4CXX_WARN(logger, "Caught exception in deliver_breakpoint(): " << ex); } } } void InternalBreakpoint::add_callback(const std::shared_ptr<BreakpointImpl>& bpimpl) { std::unique_lock lock(mtx_); breakpoint_list_.push_back(bpimpl); if (breakpoint_list_.size() == 1) { enable(); } } bool InternalBreakpoint::remove_expired() { std::unique_lock lock(mtx_); for (auto iter = breakpoint_list_.begin(); iter != breakpoint_list_.end();) { auto& weakptr = *iter; if (weakptr.expired()) { iter = breakpoint_list_.erase(iter); } else { ++iter; } } if (breakpoint_list_.empty()) { disable(); return true; } return false; } InternalBreakpoint::InternalBreakpoint(const guest_phys_ptr<void>& address) : mapping_(static_ptr_cast<uint8_t>(address)), original_byte_(*mapping_) { enable(); // Configure out watchpoint if supported try { #if 0 auto& domain = const_cast<DomainImpl&>(static_cast<const DomainImpl&>(address.domain())); watchpoint_ = domain.create_watchpoint( address, 1, true, true, false, std::bind(&InternalBreakpoint::watchpoint_event, this, std::placeholders::_1)); #endif } catch (CommandFailedException& ex) { // Guest doesn't support watchpoints LOG4CXX_DEBUG(logger, "Failed to create watchpoint for breakpoint: " << ex.what()); } } InternalBreakpoint::~InternalBreakpoint() { disable(); } void BreakpointManager::add_ref(const std::shared_ptr<BreakpointImpl>& breakpoint) { std::lock_guard lock(breakpoints_.mtx_); if (unlikely(interrupted_)) return; std::shared_ptr<InternalBreakpoint> entry; guest_phys_ptr<uint8_t> physical_address = breakpoint->ptr(); // See if we can find it in the breakpoint map auto iter = breakpoints_.map_.find(physical_address.address()); if (iter == breakpoints_.map_.end()) { // Entry doesn't exist, create it entry = std::make_shared<InternalBreakpoint>(physical_address); iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first; } else { // Entry exists, try to lock it entry = iter->second.lock(); if (!entry) { // Entry has expired, recreate it entry = std::make_shared<InternalBreakpoint>(physical_address); iter = breakpoints_.map_.emplace(physical_address.address(), std::move(entry)).first; } } // Store it with the breakpoint breakpoint->internal_breakpoint(entry); // Register the breakpoint with the internal breakpoint entry->add_callback(breakpoint); } void BreakpointManager::remove_ref(BreakpointImpl& breakpoint) { std::lock_guard lock(breakpoints_.mtx_); if (unlikely(interrupted_)) return; auto entry = breakpoint.internal_breakpoint(); if (entry->remove_expired()) { // The internal breakpoint has no more callbacks and can be erased breakpoints_.map_.erase(breakpoint.ptr().address()); } } bool BreakpointManager::handle_int3_event(Event& event, bool deliver_events) { auto& vcpu = event.vcpu(); auto& regs = vcpu.registers(); guest_ptr<uint8_t> rip(vcpu, regs.rip()); const uint64_t physical_rip = guest_phys_ptr<uint8_t>(rip).address(); if (unlikely(interrupted_)) { return false; } // Find the breakpoint for the event std::unique_lock breakpoints_lock(breakpoints_.mtx_); LOG4CXX_DEBUG(logger, "VCPU " << vcpu.id() << ": INT3 received for " << rip); auto iter = breakpoints_.map_.find(physical_rip); if (unlikely(iter == breakpoints_.map_.end())) { // We don't have a breakpoint for this! // Check to see if there's an actual int3 instruction in place if (*guest_ptr<uint8_t>(rip) == 0xCC) { LOG4CXX_DEBUG(logger, "Injecting unwanted Int3"); vcpu.inject_exception(x86::Exception::INT3); return false; } else { LOG4CXX_DEBUG(logger, "Hit unknown breakpoint. This is probably bad for the guest.") } return false; } // Get our breakpoint entry active_breakpoint = iter->second.lock(); if (unlikely(!active_breakpoint)) { // Maybe all of our breakpoints were removed while we were waiting. // If that's the case, the breakpoint instruction should have already been removed. LOG4CXX_DEBUG(logger, "Failed to lock internal breakpoint from weak_ptr."); return false; } // No longer need to lock on this since we have out internal breakpoint breakpoints_lock.unlock(); // Reinject the exeception if this is a nested Int3 if (active_breakpoint->nested_bp()) vcpu.inject_exception(x86::Exception::INT3); // Run callbacks active_breakpoint->disable(); if (deliver_events) { active_breakpoint->deliver_breakpoint(event); if (active_breakpoint->remove_expired()) { // No one left waiting for this breakpoint. No need for a callback. LOG4CXX_TRACE(logger, "Breakpoing removed, not stepping VCPU " << vcpu.id()); active_breakpoint.reset(); breakpoints_lock.lock(); breakpoints_.map_.erase(physical_rip); return false; } // Check if one of our callbacks changed RIP if (regs.rip() != rip.address()) { // A callback must have changed RIP, just turn the breakpoint back on active_breakpoint.reset(); active_breakpoint->enable(); LOG4CXX_TRACE(logger, "RIP changed, not stepping VCPU " << vcpu.id()); return false; } } // It did not, we need to single step the guest LOG4CXX_DEBUG(logger, "Waiting for BP step on VCPU " << vcpu.id()); return true; } void BreakpointManager::step(Event& event) { if (HiddenBreakpoint != nullptr) { // Unhide the BP HiddenBreakpoint->step_event(); HiddenBreakpoint = nullptr; } // Stepping done, turn the breakpoint back on if (active_breakpoint != nullptr) { active_breakpoint->enable(); active_breakpoint.reset(); LOG4CXX_DEBUG(logger, "BP step on VCPU " << event.vcpu().id()); } } void BreakpointManager::interrupt() { // Clean up and unblock any pending events interrupted_ = true; std::lock_guard lock2(breakpoints_.mtx_); // Disable all breakpoints for (auto& [address, weakptr] : breakpoints_.map_) { auto entry = weakptr.lock(); if (entry) entry->disable(); } } void BreakpointManager::start_injection() { if (active_breakpoint) { active_breakpoint->enable(); } } void BreakpointManager::end_injection() { if (active_breakpoint) { active_breakpoint->disable(); } } BreakpointManager::BreakpointManager() {} BreakpointManager::~BreakpointManager() = default; } // namespace introvirt
33.190164
99
0.648721
IntroVirt
70eb371268b94be63aa8e022a1837b2d6bfb77bf
17,204
hpp
C++
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/type_erasure/tuple.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Boost.TypeErasure library // // Copyright 2011-2012 Steven Watanabe // // 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) // // $Id$ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED #define BOOST_TYPE_ERASURE_TUPLE_HPP_INCLUDED #include <boost/config.hpp> #ifdef BOOST_TYPE_ERASURE_DOXYGEN namespace boost { namespace type_erasure { /** * @ref tuple is a Boost.Fusion Random Access Sequence containing * @ref any "anys". @c Concept specifies the \Concept for each * of the elements. The remaining arguments must be (possibly const * and/or reference qualified) placeholders, which are the * @ref placeholder "placeholders" of the elements. */ template <class Concept, class... T> class tuple { public: /** * Constructs a tuple. Each element of @c args will * be used to initialize the corresponding @ref any member. * The @ref binding for the tuple elements is determined * by mapping the placeholders in @c T to the corresponding * types in @c U. */ template <class... U> explicit tuple(U &&... args); }; /** * Returns the Nth @ref any in the tuple. */ template <int N, class Concept, class... T> any<Concept, TN> &get(tuple<Concept, T...> &arg); /** \overload */ template <int N, class Concept, class... T> const any<Concept, TN> &get(const tuple<Concept, T...> &arg); } // namespace type_erasure } // namespace boost #elif !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && \ !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) #include <boost/fusion/include/category_of.hpp> #include <boost/fusion/include/iterator_facade.hpp> #include <boost/fusion/include/sequence_facade.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/insert.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/map.hpp> #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/config.hpp> #include <boost/type_erasure/static_binding.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> namespace boost { namespace type_erasure { template <class Concept, class... T> struct cons; template <class Concept> struct cons<Concept> { template <class Binding> cons(const Binding &) {} }; template <class Concept, class T0, class... T> struct cons<Concept, T0, T...> { typedef any<Concept, T0> value_type; typedef cons<Concept, T...> rest_type; template <class Binding, class U0, class... U> cons(const Binding &b, U0 &&u0, U &&... u) : value(std::forward<U0>(u0), b), rest(b, std::forward<U>(u)...) {} any<Concept, T0> value; cons<Concept, T...> rest; }; namespace detail { template <int N, class Cons> struct cons_advance { typedef typename cons_advance<N - 1, Cons>::type::rest_type type; static const type &call(const Cons &c) { return cons_advance<N - 1, Cons>::call(c).rest; } }; template <class Cons> struct cons_advance<0, Cons> { typedef Cons type; static const type &call(const Cons &c) { return c; } }; template <class... T> struct make_map; template <class T0, class... T> struct make_map<T0, T...> { typedef typename ::boost::mpl::insert< typename ::boost::type_erasure::detail::make_map<T...>::type, T0>::type type; }; template <> struct make_map<> { typedef ::boost::mpl::map0<> type; }; } // namespace detail /** INTERNAL ONLY */ template <class Tuple, int N> class tuple_iterator : public ::boost::fusion::iterator_facade< tuple_iterator<Tuple, N>, ::boost::fusion::random_access_traversal_tag> { public: typedef ::boost::mpl::int_<N> index; explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {} template <class It> struct value_of { typedef typename Tuple::template value_at<Tuple, mpl::int_<N>>::type type; }; template <class It> struct deref { typedef typename Tuple::template at<Tuple, mpl::int_<N>>::type type; static type call(It it) { return Tuple::template at<Tuple, mpl::int_<N>>::call(*it.t); } }; template <class It, class M> struct advance { typedef tuple_iterator<Tuple, (It::index::value + M::value)> type; static type call(It it) { return type(*it.t); } }; template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {}; template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {}; template <class It1, class It2> struct distance { typedef typename ::boost::mpl::minus<typename It2::index, typename It1::index>::type type; static type call(It1, It2) { return type(); } }; private: Tuple *t; }; template <class Concept, class... T> class tuple : public ::boost::fusion::sequence_facade< ::boost::type_erasure::tuple<Concept, T...>, ::boost::fusion::forward_traversal_tag> { public: template <class... U> explicit tuple(U &&... args) : impl(::boost::type_erasure::make_binding< typename ::boost::type_erasure::detail::make_map< ::boost::mpl::pair< typename ::boost::remove_const< typename ::boost::remove_reference<T>::type>::type, typename ::boost::remove_const< typename ::boost::remove_reference<U>::type>:: type>...>::type>(), std::forward<U>(args)...) {} template <class Seq> struct begin { typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct end { typedef ::boost::type_erasure::tuple_iterator<Seq, sizeof...(T)> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct size { typedef ::boost::mpl::int_<sizeof...(T)> type; static type call(Seq &seq) { return type(); } }; template <class Seq> struct empty { typedef ::boost::mpl::bool_<sizeof...(T) == 0> type; static type call(Seq &seq) { return type(); } }; template <class Seq, class N> struct at { typedef typename ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type value_type; typedef typename ::boost::mpl::if_<::boost::is_const<Seq>, const value_type &, value_type &>::type type; static type call(Seq &seq) { return const_cast<type>( ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::call(seq.impl) .value); } }; template <class Seq, class N> struct value_at { typedef typename ::boost::type_erasure::detail::cons_advance< N::value, ::boost::type_erasure::cons<Concept, T...>>::type::value_type value_type; }; ::boost::type_erasure::cons<Concept, T...> impl; }; template <int N, class Concept, class... T> typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type & get(::boost::type_erasure::tuple<Concept, T...> &t) { return const_cast<typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type &>( ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl) .value); } template <int N, class Concept, class... T> const typename ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::type::value_type & get(const ::boost::type_erasure::tuple<Concept, T...> &t) { return ::boost::type_erasure::detail::cons_advance< N, ::boost::type_erasure::cons<Concept, T...>>::call(t.impl) .value; } } // namespace type_erasure } // namespace boost #else #include <boost/fusion/include/category_of.hpp> #include <boost/fusion/include/iterator_facade.hpp> #include <boost/fusion/include/sequence_facade.hpp> #include <boost/mpl/equal_to.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/map.hpp> #include <boost/mpl/minus.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/config.hpp> #include <boost/type_erasure/static_binding.hpp> namespace boost { namespace type_erasure { /** INTERNAL ONLY */ struct na {}; namespace detail { template <int N, class Tuple> struct get_impl; template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T, ::boost::type_erasure::na)> struct tuple_storage; } // namespace detail /** INTERNAL ONLY */ template <class Tuple, int N> class tuple_iterator : public ::boost::fusion::iterator_facade< tuple_iterator<Tuple, N>, ::boost::fusion::random_access_traversal_tag> { public: typedef ::boost::mpl::int_<N> index; explicit tuple_iterator(Tuple &t_arg) : t(&t_arg) {} template <class It> struct value_of { typedef typename ::boost::type_erasure::detail::get_impl< It::index::value, Tuple>::value_type type; }; template <class It> struct deref : ::boost::type_erasure::detail::get_impl<It::index::value, Tuple> { typedef typename ::boost::type_erasure::detail::get_impl<It::index::value, Tuple>::type type; static type call(It it) { return ::boost::type_erasure::detail::get_impl<It::index::value, Tuple>::call(*it.t); } }; template <class It, class M> struct advance { typedef tuple_iterator<Tuple, (It::index::value + M::value)> type; static type call(It it) { return type(*it.t); } }; template <class It> struct next : advance<It, ::boost::mpl::int_<1>> {}; template <class It> struct prior : advance<It, ::boost::mpl::int_<-1>> {}; template <class It1, class It2> struct distance { typedef typename ::boost::mpl::minus<typename It2::index, typename It1::index>::type type; static type call(It1, It2) { return type(); } }; private: Tuple *t; }; /** INTERNAL ONLY */ template <class Derived> struct tuple_base : ::boost::fusion::sequence_facade< Derived, ::boost::fusion::random_access_traversal_tag> { template <class Seq> struct begin { typedef ::boost::type_erasure::tuple_iterator<Seq, 0> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct end { typedef ::boost::type_erasure::tuple_iterator<Seq, Seq::tuple_size::value> type; static type call(Seq &seq) { return type(seq); } }; template <class Seq> struct size { typedef typename Seq::tuple_size type; static type call(Seq &seq) { return type(); } }; template <class Seq> struct empty { typedef typename boost::mpl::equal_to<typename Seq::tuple_size, boost::mpl::int_<0>>::type type; static type call(Seq &seq) { return type(); } }; template <class Seq, class N> struct at : ::boost::type_erasure::detail::get_impl<N::value, Seq> {}; template <class Seq, class N> struct value_at { typedef typename ::boost::type_erasure::detail::get_impl<N::value, Seq>::value_type type; }; }; template <class Concept, BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T, ::boost::type_erasure::na)> class tuple; template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)> typename detail::get_impl<N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type get(tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) { return detail::get_impl< N, tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg); } template <int N, class Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, class T)> typename detail::get_impl<N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::type get(const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)> &arg) { return detail::get_impl< N, const tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS( BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE, T)>>::call(arg); } /** INTERNAL ONLY */ #define BOOST_PP_FILENAME_1 <boost/type_erasure/tuple.hpp> /** INTERNAL ONLY */ #define BOOST_PP_ITERATION_LIMITS (0, BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE) #include BOOST_PP_ITERATE() } // namespace type_erasure } // namespace boost #endif #endif #else #define N BOOST_PP_ITERATION() #define BOOST_TYPE_ERASURE_TAG_TYPEDEF(z, n, data) \ typedef BOOST_PP_CAT(T, n) BOOST_PP_CAT(tag_type, n); \ typedef typename ::boost::remove_reference<BOOST_PP_CAT(T, n)>::type \ BOOST_PP_CAT(tag, n); #define BOOST_TYPE_ERASURE_PAIR(z, n, data) \ ::boost::mpl::pair<BOOST_PP_CAT(tag, n), BOOST_PP_CAT(U, n)> #define BOOST_TYPE_ERASURE_CONSTRUCT(z, n, data) \ BOOST_PP_CAT(t, n)(BOOST_PP_CAT(u, n), table) #define BOOST_TYPE_ERASURE_TUPLE_MEMBER(z, n, data) \ ::boost::type_erasure::any<Concept, BOOST_PP_CAT(T, n)> BOOST_PP_CAT(t, n); #if N == 1 #define BOOST_TYPE_ERASURE_EXPLICIT explicit #else #define BOOST_TYPE_ERASURE_EXPLICIT #endif namespace detail { template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)> struct tuple_storage #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE <Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> #endif { #if N template <class Table BOOST_PP_ENUM_TRAILING_PARAMS(N, class U)> tuple_storage(const Table &table BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(N, U, &u)) : BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_CONSTRUCT, ~) {} #else template <class Table> explicit tuple_storage(const Table &) {} #endif BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TUPLE_MEMBER, `) }; #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE template <class Tuple> struct get_impl<N, Tuple> { typedef any<typename Tuple::concept_type, typename Tuple::BOOST_PP_CAT(tag_type, N)> value_type; typedef value_type &type; static type call(Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); } }; template <class Tuple> struct get_impl<N, const Tuple> { typedef any<typename Tuple::concept_type, typename Tuple::BOOST_PP_CAT(tag_type, N)> value_type; typedef const value_type &type; static type call(const Tuple &arg) { return arg.impl.BOOST_PP_CAT(t, N); } }; #endif } // namespace detail template <class Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, class T)> class tuple #if N != BOOST_TYPE_ERASURE_MAX_TUPLE_SIZE <Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> #endif : public tuple_base<tuple<Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)>> { typedef Concept concept_type; BOOST_PP_REPEAT(N, BOOST_TYPE_ERASURE_TAG_TYPEDEF, ~) public: typedef ::boost::mpl::int_<N> tuple_size; #if N template <BOOST_PP_ENUM_PARAMS(N, class U)> #endif BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, U, &u)) : impl(::boost::type_erasure::make_binding< ::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>() BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) { } #if N template <BOOST_PP_ENUM_PARAMS(N, class U)> BOOST_TYPE_ERASURE_EXPLICIT tuple(BOOST_PP_ENUM_BINARY_PARAMS(N, const U, &u)) : impl(::boost::type_erasure::make_binding< ::boost::mpl::map<BOOST_PP_ENUM(N, BOOST_TYPE_ERASURE_PAIR, ~)>>() BOOST_PP_ENUM_TRAILING_PARAMS(N, u)) {} #endif private: template <int M, class Tuple> friend struct ::boost::type_erasure::detail::get_impl; ::boost::type_erasure::detail::tuple_storage< Concept BOOST_PP_ENUM_TRAILING_PARAMS(N, T)> impl; }; #undef BOOST_TYPE_ERASURE_EXPLICIT #undef BOOST_TYPE_ERASURE_TUPLE_MEMBER #undef BOOST_TYPE_ERASURE_CONSTRUCT #undef BOOST_TYPE_ERASURE_PAIR #undef BOOST_TYPE_ERASURE_TAG_TYPEDEF #undef N #endif
35.767152
80
0.659614
henrywarhurst
70f0557ff129f7473a43940ce69dcfc4b5fd7d63
25,506
hpp
C++
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
src/netcdf/lpm_netcdf_impl.hpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
#include "netcdf/lpm_netcdf.hpp" #ifdef LPM_USE_NETCDF #include "util/lpm_string_util.hpp" #include <sstream> namespace Lpm { template <typename Geo> void NcWriter<Geo>::open() { int retval = nc_create(fname.c_str(), NC_NETCDF4 | NC_CLOBBER, &ncid); CHECK_NCERR(retval); text_att_type att = std::make_pair("LPM", "Lagrangian Particle Methods"); define_file_attribute(att); att = std::make_pair("LPM_version", std::string(version())); define_file_attribute(att); att = std::make_pair("LPM_revision", std::string(revision())); define_file_attribute(att); att = std::make_pair("LPM_has_uncommitted_changes", (has_uncomitted_changes() ? "true" : "false")); define_file_attribute(att); } template <typename Geo> void NcWriter<Geo>::define_file_attribute(const text_att_type& att_pair) const { const int att_len = att_pair.second.size(); int retval = nc_put_att_text(ncid, NC_GLOBAL, att_pair.first.c_str(), att_len, att_pair.second.c_str()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::define_time_dim() { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(time_dimid == NC_EBADID, "time dimension already defined."); int retval = nc_def_dim(ncid, "time", NC_UNLIMITED, &time_dimid); CHECK_NCERR(retval); n_nc_dims++; int varid = NC_EBADID; retval = nc_def_var(ncid, "time", nc_real_type::value, 1, &time_dimid, &varid); CHECK_NCERR(retval); const auto unit_str = ekat::units::to_string(ekat::units::s); retval = nc_put_att_text(ncid, varid, "units", unit_str.size(), unit_str.c_str()); CHECK_NCERR(retval); name_varid_map.emplace("time", varid); add_time_value(0); } template <typename Geo> void NcWriter<Geo>::add_time_value(const Real t) const { const int varid = name_varid_map.at("time"); size_t next_time_idx = 0; int retval = nc_inq_dimlen(ncid, time_dimid, &next_time_idx); CHECK_NCERR(retval); retval = nc_put_var1(ncid, varid, &next_time_idx, &t); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::define_particles_dim(const Index np) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(particles_dimid != NC_EBADID); int retval = nc_def_dim(ncid, "n_particles", np, &particles_dimid); CHECK_NCERR(retval); n_nc_dims++; } template <typename Geo> void NcWriter<Geo>::define_coord_dim() { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(coord_dimid == NC_EBADID); int retval = nc_def_dim(ncid, "coord", Geo::ndim, &coord_dimid); CHECK_NCERR(retval); n_nc_dims++; } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::define_scalar_field(const ScalarField<FL>& s) { LPM_ASSERT(ncid != NC_EBADID); LPM_ASSERT(time_dimid != NC_EBADID); int m_ndims = 2; int dimids[2]; dimids[0] = time_dimid; std::string loc_string; switch (FL) { case( ParticleField ) : { LPM_REQUIRE(particles_dimid != NC_EBADID); dimids[1] = particles_dimid; break; } case( VertexField ) : { LPM_REQUIRE(vertices_dimid != NC_EBADID); dimids[1] = vertices_dimid; break; } case( EdgeField ) : { LPM_REQUIRE(edges_dimid != NC_EBADID); dimids[1] = edges_dimid; break; } case( FaceField ) : { LPM_REQUIRE(faces_dimid != NC_EBADID); dimids[1] = faces_dimid; break; } } int varid = NC_EBADID; int retval = nc_def_var(ncid, s.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace(s.name, varid); for (auto& md : s.metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } } template <typename Geo> void NcWriter<Geo>::define_edges(const Edges& edges) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(edges_dimid == NC_EBADID, "edges dimension already defined."); LPM_REQUIRE(two_dimid == NC_EBADID); int retval = nc_def_dim(ncid, "edges", edges.nh(), &edges_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "two", 2, &two_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto nedges = edges.nh(); const auto nmaxedges = edges.n_max(); const auto nleaves = edges._hn_leaves(); int origs_varid = NC_EBADID; int dests_varid = NC_EBADID; int lefts_varid = NC_EBADID; int rights_varid = NC_EBADID; int kids_varid = NC_EBADID; int parents_varid = NC_EBADID; retval = nc_def_var(ncid, "edges.origs", nc_index_type::value, 1, &edges_dimid, &origs_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.origs", origs_varid); retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_max", nc_index_type::value, 1, &nmaxedges); CHECK_NCERR(retval); retval = nc_put_att(ncid, NC_GLOBAL, "edges.n_leaves", nc_index_type::value, 1, &nleaves); CHECK_NCERR(retval); retval = nc_def_var(ncid, "edges.dests", nc_index_type::value, 1, &edges_dimid, &dests_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.dests", dests_varid); retval = nc_def_var(ncid, "edges.lefts", nc_index_type::value, 1, &edges_dimid, &lefts_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.lefts", lefts_varid); retval = nc_def_var(ncid, "edges.rights", nc_index_type::value, 1, &edges_dimid, &rights_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.rights", rights_varid); const int kid_dims[2] = {edges_dimid, two_dimid}; retval = nc_def_var(ncid, "edges.kids", nc_index_type::value, 2, kid_dims, &kids_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.kids", kids_varid); retval = nc_def_var(ncid, "edges.parent", nc_index_type::value, 1, &edges_dimid, &parents_varid); CHECK_NCERR(retval); name_varid_map.emplace("edges.parent", parents_varid); const size_t start = 0; const size_t count = nedges; retval = nc_put_vara(ncid, origs_varid, &start, &count, edges._ho.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, dests_varid, &start, &count, edges._hd.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, lefts_varid, &start, &count, edges._hl.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, rights_varid, &start, &count, edges._hr.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, parents_varid, &start, &count, edges._hp.data()); for (size_t i=0; i<nedges; ++i) { for (size_t j=0; j<2; ++j) { const size_t idx[2] = {i,j}; const auto kid_idx = edges.kid_host(i,j); retval = nc_put_var1(ncid, kids_varid, idx, &kid_idx); CHECK_NCERR(retval); } } } template <typename Geo> template <typename FaceType> void NcWriter<Geo>::define_faces(const Faces<FaceType, Geo>& faces) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(faces_dimid == NC_EBADID, "faces dimension already defined."); LPM_REQUIRE(facekind_dimid == NC_EBADID); LPM_REQUIRE(coord_dimid != NC_EBADID); int retval = nc_def_dim(ncid, "faces", faces.nh(), &faces_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "four", 4, &four_dimid); CHECK_NCERR(retval); n_nc_dims++; retval = nc_def_dim(ncid, "facekind", FaceType::nverts, &facekind_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto nmaxfaces = faces.n_max(); const auto nfaces = faces.nh(); const auto nleaves = faces.n_leaves_host(); int mask_varid = NC_EBADID; int verts_varid = NC_EBADID; int edges_varid = NC_EBADID; int phys_crd_varid = NC_EBADID; int lag_crd_varid = NC_EBADID; int level_varid = NC_EBADID; int parents_varid = NC_EBADID; int kids_varid = NC_EBADID; int area_varid = NC_EBADID; int crd_inds_varid = NC_EBADID; retval = nc_def_var(ncid, "faces.mask", NC_UBYTE, 1, &faces_dimid, &mask_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.mask", mask_varid); const int vert_and_edge_dims[2] = {faces_dimid, facekind_dimid}; retval = nc_def_var(ncid, "faces.vertices", nc_index_type::value, 2, vert_and_edge_dims, &verts_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.vertices", verts_varid); retval = nc_def_var(ncid, "faces.edges", nc_index_type::value, 2, vert_and_edge_dims, &edges_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.edges", edges_varid); retval = nc_def_var(ncid, "faces.crd_inds", nc_index_type::value, 1, &faces_dimid, &crd_inds_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.crd_inds", crd_inds_varid); retval = nc_def_var(ncid, "faces.level", NC_INT, 1, &faces_dimid, &level_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.level", level_varid); retval = nc_def_var(ncid, "faces.parent", nc_index_type::value, 1, &faces_dimid, &parents_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.parent", parents_varid); const int kid_dims[2] = {faces_dimid, four_dimid}; retval = nc_def_var(ncid, "faces.kids", nc_index_type::value, 2, kid_dims, &kids_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.kids", kids_varid); retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_leaves", nc_index_type::value, 1, &nleaves); CHECK_NCERR(retval); retval = nc_put_att(ncid, NC_GLOBAL, "faces.n_max", nc_index_type::value, 1, &nmaxfaces); CHECK_NCERR(retval); const int pcrd_dims[3] = {time_dimid, faces_dimid, coord_dimid}; retval = nc_def_var(ncid, "faces.phys_crds", nc_real_type::value, 3, pcrd_dims, &phys_crd_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.phys_crds", phys_crd_varid); const int lcrd_dims[2] = {faces_dimid, coord_dimid}; retval = nc_def_var(ncid, "faces.lag_crds", nc_real_type::value, 2, lcrd_dims, &lag_crd_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.lag_crds", lag_crd_varid); retval = nc_def_var(ncid, "faces.area", nc_real_type::value, 1, &faces_dimid, &area_varid); CHECK_NCERR(retval); name_varid_map.emplace("faces.area", area_varid); const auto area_unit_str = ekat::units::to_string(ekat::units::m * ekat::units::m); retval = nc_put_att_text(ncid, area_varid, "units", area_unit_str.size(), area_unit_str.c_str()); for (size_t i=0; i<nfaces; ++i) { const size_t mask_idx = i; const uint_fast8_t mask_val = (faces._hmask(i) ? 1 : 0); retval = nc_put_var1(ncid, mask_varid, &mask_idx, &mask_val); CHECK_NCERR(retval); for (size_t j=0; j<4; ++j) { const size_t kids_idx[2] = {i,j}; retval = nc_put_var1(ncid, kids_varid, kids_idx, &faces._hostkids(i,j)); CHECK_NCERR(retval); } for (size_t j=0; j<FaceType::nverts; ++j) { const size_t vert_and_edge_idx[2] = {i,j}; retval = nc_put_var1(ncid, verts_varid, vert_and_edge_idx, &faces._hostverts(i,j)); CHECK_NCERR(retval); retval = nc_put_var1(ncid, edges_varid, vert_and_edge_idx, &faces._hostedges(i,j)); } for (size_t j=0; j<Geo::ndim; ++j) { const size_t pcrd_idx[3] = {0, i, j}; const size_t lcrd_idx[2] = {i,j}; const Real pcrd_val = faces.phys_crds->get_crd_component_host(i,j); const Real lcrd_val = faces.lag_crds->get_crd_component_host(i,j); retval = nc_put_var1(ncid, phys_crd_varid, pcrd_idx, &pcrd_val); CHECK_NCERR(retval); retval = nc_put_var1(ncid, lag_crd_varid, lcrd_idx, &lcrd_val); CHECK_NCERR(retval); } } const size_t start = 0; const size_t count = nfaces; retval = nc_put_vara(ncid, crd_inds_varid, &start, &count, faces._host_crd_inds.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, parents_varid, &start, &count, faces._hostparent.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, area_varid, &start, &count, faces._hostarea.data()); CHECK_NCERR(retval); retval = nc_put_vara(ncid, level_varid, &start, &count, faces._hlevel.data()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::update_crds(const size_t time_idx, const int varid, const Coords<Geo>& crds) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE(varid != NC_EBADID); LPM_REQUIRE_MSG(time_idx < n_timesteps(), "time variable must be defined before adding timestep data."); for (size_t i=0; i<crds.nh(); ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {time_idx, i, j}; const Real crd_val = crds.get_crd_component_host(i,j); int retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } template <typename Geo> template <typename SeedType> void NcWriter<Geo>::define_polymesh(const PolyMesh2d<SeedType>& mesh) { define_vertices(mesh.vertices); define_edges(mesh.edges); define_faces(mesh.faces); int varid = NC_EBADID; int* ignore_me; int retval = nc_def_var(ncid, "base_tree_depth", NC_INT, 0, ignore_me, &varid); CHECK_NCERR(retval); name_varid_map.emplace("base_tree_depth", varid); const auto mesh_id_str = SeedType::id_string(); retval = nc_put_att_text(ncid, NC_GLOBAL, "MeshSeed", mesh_id_str.size(), mesh_id_str.c_str()); CHECK_NCERR(retval); } template <typename Geo> void NcWriter<Geo>::update_particle_phys_crds(const size_t time_idx, const Coords<Geo>& pcrds) { //TODO after particle class is defined } template <typename Geo> void NcWriter<Geo>::update_vertex_phys_crds(const size_t time_idx, const Vertices<Coords<Geo>>& verts) { update_crds(time_idx, name_varid_map.at("vertices.phys_crds"), *(verts.phys_crds)); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::put_scalar_field(const size_t time_idx, const ScalarField<FL>& s) { LPM_REQUIRE(time_idx < n_timesteps()); const int varid = name_varid_map.at(s.name); const size_t start[2] = {time_idx, 0}; size_t count[2]; count[0] = 1; switch (FL) { case (ParticleField) : { count[1] = n_particles(); break; } case( VertexField ) : { count[1] = n_vertices(); break; } case( EdgeField ) : { count[1] = n_edges(); break; } case( FaceField ) : { count[1] = n_faces(); break; } } int retval = nc_put_vara(ncid, varid, start, count, s.hview.data()); CHECK_NCERR(retval); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::put_vector_field(const size_t time_idx, const VectorField<Geo,FL>& v) { LPM_REQUIRE(time_idx < n_timesteps()); const int varid = name_varid_map.at(v.name); Index n_entries; switch (FL) { case (ParticleField) : { n_entries = n_particles(); break; } case( VertexField ) : { n_entries = n_vertices(); break; } case( EdgeField ) : { n_entries = n_edges(); break; } case( FaceField ) : { n_entries = n_faces(); break; } } for (size_t i=0; i<n_entries; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {time_idx, i, j}; int retval = nc_put_var1(ncid, varid, idx, &v.hview(i,j)); CHECK_NCERR(retval); } } } template <typename Geo> template <typename FaceType> void NcWriter<Geo>::update_face_phys_crds(const size_t time_idx, const Faces<FaceType, Geo>& faces) { update_crds(time_idx, name_varid_map.at("faces.phys_crds"), *(faces.phys_crds)); const size_t start[2] = {time_idx, 0}; const size_t count[2] = {1, faces.nh()}; int retval = nc_put_vara(ncid, name_varid_map.at("faces.area"), start, count, faces._hostarea.data()); } template <typename Geo> void NcWriter<Geo>::define_vertices(const Vertices<Coords<Geo>>& vertices) { LPM_ASSERT(ncid != NC_EBADID); LPM_REQUIRE_MSG(vertices_dimid == NC_EBADID, "vertices dimension already defined."); const Index nverts = vertices.nh(); int retval = nc_def_dim(ncid, "vertices", vertices.nh(), &vertices_dimid); CHECK_NCERR(retval); n_nc_dims++; const auto h_inds = vertices.host_crd_inds(); { int varid = NC_EBADID; retval = nc_def_var(ncid, "vertices.crd_inds", nc_index_type::value, 1, &vertices_dimid, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.crd_inds", varid); size_t start=0; size_t count=nverts; retval = nc_put_vara(ncid, varid, &start, &count, h_inds.data()); CHECK_NCERR(retval); const auto nmaxverts = vertices.n_max(); retval = nc_put_att(ncid, NC_GLOBAL, "vertices.n_max", nc_index_type::value, 1, &nmaxverts); CHECK_NCERR(retval); } { int varid = NC_EBADID; const int m_ndims = 3; const int dimids[3] = {time_dimid, vertices_dimid, coord_dimid}; retval = nc_def_var(ncid, "vertices.phys_crds", nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.phys_crds", varid); for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[3] = {0, i, j}; const Real crd_val = vertices.phys_crds->get_crd_component_host(h_inds(i),j); retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } { int varid = NC_EBADID; const int m_ndims = 2; const int dimids[2] = {vertices_dimid, coord_dimid}; retval = nc_def_var(ncid, "vertices.lag_crds", nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace("vertices.lag_crds", varid); for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t idx[2] = {i, j}; const Real crd_val = vertices.lag_crds->get_crd_component_host(h_inds(i),j); retval = nc_put_var1(ncid, varid, idx, &crd_val); CHECK_NCERR(retval); } } } { //TODO: If verts are dual... } } template <typename Geo> std::string NcWriter<Geo>::info_string(const int tab_level) const { auto tabstr = indent_string(tab_level); std::ostringstream ss; ss << tabstr << "NcWriter info:\n"; tabstr += "\t"; ss << tabstr << "filename: " << fname << "\n"; ss << tabstr << "ncid: " << ncid << "\n"; ss << tabstr << "n_nc_dims: " << n_nc_dims << "\n"; ss << tabstr << "variables:\n"; for (auto& v : name_varid_map) { ss << "\t" << v.first << "\n"; } return ss.str(); } template <typename Geo> template <FieldLocation FL> void NcWriter<Geo>::define_vector_field(const VectorField<Geo,FL>& v) { LPM_ASSERT(ncid != NC_EBADID); LPM_ASSERT(time_dimid != NC_EBADID); LPM_ASSERT(coord_dimid != NC_EBADID); int m_ndims = 3; int dimids[3]; dimids[0] = time_dimid; dimids[2] = coord_dimid; switch (FL) { case( ParticleField ) : { LPM_REQUIRE(particles_dimid != NC_EBADID); dimids[1] = particles_dimid; break; } case( VertexField ) : { LPM_REQUIRE(vertices_dimid != NC_EBADID); dimids[1] = vertices_dimid; break; } case( EdgeField ) : { LPM_REQUIRE(edges_dimid != NC_EBADID); dimids[1] = edges_dimid; break; } case( FaceField ) : { LPM_REQUIRE(faces_dimid != NC_EBADID); dimids[1] = faces_dimid; break; } } int varid = NC_EBADID; int retval = nc_def_var(ncid, v.name.c_str(), nc_real_type::value, m_ndims, dimids, &varid); CHECK_NCERR(retval); name_varid_map.emplace(v.name, varid); for (auto& md : v.metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } } template <typename Geo> void NcWriter<Geo>::define_single_real_var(const std::string& name, const ekat::units::Units& units, const Real val, const std::vector<text_att_type> metadata) { LPM_ASSERT(ncid != NC_EBADID); int* ignore_me; int varid = NC_EBADID; int retval = nc_def_var(ncid, name.c_str(), nc_real_type::value, 0, ignore_me, &varid); CHECK_NCERR(retval); name_varid_map.emplace(name, varid); const auto unitstr = ekat::units::to_string(units); retval = nc_put_att_text(ncid, varid, "units", unitstr.size(), unitstr.c_str()); for (auto& md : metadata) { retval = nc_put_att_text(ncid, varid, md.first.c_str(), md.second.size(), md.second.c_str()); CHECK_NCERR(retval); } retval = nc_put_var(ncid, varid, &val); } template <typename Geo> void NcWriter<Geo>::close() { int retval = nc_close(ncid); CHECK_NCERR(retval); } template <typename Geo> Index NcWriter<Geo>::n_timesteps() const { size_t nsteps; int retval = nc_inq_dimlen(ncid, time_dimid, &nsteps); CHECK_NCERR(retval); return Index(nsteps); } template <typename Geo> Index NcWriter<Geo>::n_particles() const { size_t np; int retval = nc_inq_dimlen(ncid, particles_dimid, &np); CHECK_NCERR(retval); return Index(np); } template <typename Geo> Index NcWriter<Geo>::n_vertices() const { size_t nverts; int retval = nc_inq_dimlen(ncid, vertices_dimid, &nverts); if (retval == NC_EBADDIM) { nverts = 0; } else { CHECK_NCERR(retval); } return Index(nverts); } template <typename Geo> Index NcWriter<Geo>::n_edges() const { size_t nedges; int retval = nc_inq_dimlen(ncid, edges_dimid, &nedges); if (retval == NC_EBADDIM) { nedges = 0; } else { CHECK_NCERR(retval); } return Index(nedges); } template <typename Geo> Index NcWriter<Geo>::n_faces() const { size_t nfaces; int retval = nc_inq_dimlen(ncid, faces_dimid, &nfaces); if (retval == NC_EBADDIM) { nfaces = 0; } else { CHECK_NCERR(retval); } return Index(nfaces); } template <typename SeedType> std::shared_ptr<PolyMesh2d<SeedType>> PolymeshReader::init_polymesh() { auto result = std::shared_ptr<PolyMesh2d<SeedType>>(new PolyMesh2d<SeedType>(nmaxverts, nmaxedges, nmaxfaces)); fill_vertices(result->vertices); fill_edges(result->edges); fill_faces(result->faces); fill_crds(*(result->vertices.phys_crds), *(result->vertices.lag_crds), *(result->faces.phys_crds), *(result->faces.lag_crds)); result->update_device(); return result; } template <typename Geo> void PolymeshReader::fill_vertices(Vertices<Coords<Geo>>& verts) { LPM_ASSERT(vertices_dimid != NC_EBADID); const Index nverts = n_vertices(); verts._nh() = nverts; auto h_vert_crds = verts.host_crd_inds(); const size_t start = 0; const size_t count = nverts; int retval = nc_get_vara(ncid, name_varid_map.at("vertices.crd_inds"), &start, &count, h_vert_crds.data()); CHECK_NCERR(retval); } template <typename FaceType, typename Geo> void PolymeshReader::fill_faces(Faces<FaceType, Geo>& faces) { LPM_ASSERT(faces_dimid != NC_EBADID); LPM_ASSERT(facekind_dimid != NC_EBADID); size_t nfaceverts; int retval = nc_inq_dimlen(ncid, facekind_dimid, &nfaceverts); CHECK_NCERR(retval); LPM_REQUIRE(nfaceverts == FaceType::nverts); const Index nfaces = n_faces(); Index nleaves; retval = nc_get_att(ncid, NC_GLOBAL, "faces.n_leaves", &nleaves); faces._nh() = nfaces; faces._hn_leaves() = nleaves; { const size_t start = 0; const size_t count = nfaces; retval = nc_get_vara(ncid, name_varid_map.at("faces.crd_inds"), &start, &count, faces._host_crd_inds.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.parent"), &start, &count, faces._hostparent.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.level"), &start, &count, faces._hlevel.data()); CHECK_NCERR(retval); retval = nc_get_vara(ncid, name_varid_map.at("faces.area"), &start, &count, faces._hostarea.data()); } for (size_t i=0; i<nfaces; ++i) { size_t idx1 = i; uint_fast8_t mask_val; retval = nc_get_var1(ncid, name_varid_map.at("faces.mask"), &idx1, &mask_val); CHECK_NCERR(retval); faces._hmask(i) = (mask_val > 0 ? true : false); for (size_t j=0; j<nfaceverts; ++j) { size_t idx2[2] = {i,j}; retval = nc_get_var1(ncid, name_varid_map.at("faces.vertices"), idx2, &faces._hostverts(i,j)); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("faces.edges"), idx2, &faces._hostedges(i,j)); CHECK_NCERR(retval); } for (size_t j=0; j<4; ++j) { size_t idx3[2] = {i,j}; retval = nc_get_var1(ncid, name_varid_map.at("faces.kids"), idx3, &faces._hostkids(i,j)); } } } template <typename Geo> void PolymeshReader::fill_crds(Coords<Geo>& vert_phys_crds, Coords<Geo>& vert_lag_crds, Coords<Geo>& face_phys_crds, Coords<Geo>& face_lag_crds) { const Index nverts = n_vertices(); vert_phys_crds._nh() = nverts; vert_lag_crds._nh() = nverts; const size_t last_time_idx = n_timesteps()-1; for (size_t i=0; i<nverts; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t pidx[3] = {last_time_idx, i,j}; const size_t lidx[2] = {i,j}; Real pcrdval; Real lcrdval; int retval = nc_get_var1(ncid, name_varid_map.at("vertices.phys_crds"), pidx, &pcrdval); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("vertices.lag_crds"), lidx, &lcrdval); CHECK_NCERR(retval); vert_phys_crds._hostcrds(i,j) = pcrdval; vert_lag_crds._hostcrds(i,j) = lcrdval; } } const Index nfaces = n_faces(); face_phys_crds._nh() = nfaces; face_lag_crds._nh() = nfaces; for (size_t i=0; i<nfaces; ++i) { for (size_t j=0; j<Geo::ndim; ++j) { const size_t pidx[3] = {last_time_idx, i,j}; const size_t lidx[2] = {i,j}; Real pcrdval; Real lcrdval; int retval = nc_get_var1(ncid, name_varid_map.at("faces.phys_crds"), pidx, &pcrdval); CHECK_NCERR(retval); retval = nc_get_var1(ncid, name_varid_map.at("faces.lag_crds"), lidx, &lcrdval); CHECK_NCERR(retval); face_phys_crds._hostcrds(i,j) = pcrdval; face_lag_crds._hostcrds(i,j) = lcrdval; } } } // ETI template class NcWriter<PlaneGeometry>; template class NcWriter<SphereGeometry>; } #endif
34.008
113
0.686231
pbosler
70f3b3aa51b0555247cc9f78af7e11a51239c6a5
4,784
cpp
C++
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
ZP-Hust/MITK
ca11353183c5ed4bc30f938eae8bde43a0689bf6
[ "BSD-3-Clause" ]
1
2021-11-20T08:19:27.000Z
2021-11-20T08:19:27.000Z
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
null
null
null
Plugins/org.blueberry.ui.qt/src/internal/intro/berryIntroRegistry.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
1
2019-01-09T08:20:18.000Z
2019-01-09T08:20:18.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIntroRegistry.h" #include <berryIConfigurationElement.h> #include <berryIExtension.h> #include "berryIntroDescriptor.h" #include "internal/berryRegistryReader.h" #include "berryWorkbenchPlugin.h" namespace berry { const QString IntroRegistry::TAG_INTRO = "intro"; const QString IntroRegistry::TAG_INTROPRODUCTBINDING = "introProductBinding"; const QString IntroRegistry::ATT_INTROID = "introId"; const QString IntroRegistry::ATT_PRODUCTID = "productId"; QString IntroRegistry::GetIntroForProduct( const QString& targetProductId, const QList<IExtension::Pointer>& extensions) const { for (int i = 0; i < extensions.size(); i++) { QList<IConfigurationElement::Pointer> elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTROPRODUCTBINDING) { QString introId = elements[j]->GetAttribute(ATT_INTROID); QString productId = elements[j]->GetAttribute(ATT_PRODUCTID); if (introId.isEmpty() || productId.isEmpty()) { //TODO IStatus /* IStatus status = new Status( IStatus.ERROR, elements[j].getDeclaringExtension() .getNamespace(), IStatus.ERROR, "introId and productId must be defined.", new IllegalArgumentException()); WorkbenchPlugin.log("Invalid intro binding", status); */ WorkbenchPlugin::Log( elements[j]->GetDeclaringExtension()->GetNamespaceIdentifier() + ": Invalid intro binding. introId and productId must be defined"); continue; } if (targetProductId == productId) { return introId; } } } } return ""; } int IntroRegistry::GetIntroCount() const { return static_cast<int> (GetIntros().size()); } QList<IIntroDescriptor::Pointer> IntroRegistry::GetIntros() const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return QList<IIntroDescriptor::Pointer>(); } QList<IExtension::Pointer> extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QList<IIntroDescriptor::Pointer> list; for (int i = 0; i < extensions.size(); i++) { QList<IConfigurationElement::Pointer> elements( extensions[i]->GetConfigurationElements()); for (int j = 0; j < elements.size(); j++) { if (elements[j]->GetName() == TAG_INTRO) { try { IIntroDescriptor::Pointer descriptor(new IntroDescriptor(elements[j])); list.push_back(descriptor); } catch (const CoreException& e) { // log an error since its not safe to open a dialog here //TODO IStatus WorkbenchPlugin::Log("Unable to create intro descriptor", e); // e.getStatus()); } } } } return list; } IIntroDescriptor::Pointer IntroRegistry::GetIntroForProduct( const QString& targetProductId) const { IExtensionPoint::Pointer point = Platform::GetExtensionRegistry()->GetExtensionPoint( PlatformUI::PLUGIN_ID() + "." + WorkbenchRegistryConstants::PL_INTRO); if (!point) { return IIntroDescriptor::Pointer(); } QList<IExtension::Pointer> extensions(point->GetExtensions()); extensions = RegistryReader::OrderExtensions(extensions); QString targetIntroId = GetIntroForProduct(targetProductId, extensions); if (targetIntroId.isEmpty()) { return IIntroDescriptor::Pointer(); } IIntroDescriptor::Pointer descriptor; QList<IIntroDescriptor::Pointer> intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { if (intros[i]->GetId() == targetIntroId) { descriptor = intros[i]; break; } } return descriptor; } IIntroDescriptor::Pointer IntroRegistry::GetIntro(const QString& id) const { QList<IIntroDescriptor::Pointer> intros(GetIntros()); for (int i = 0; i < intros.size(); i++) { IIntroDescriptor::Pointer desc = intros[i]; if (desc->GetId() == id) { return desc; } } return IIntroDescriptor::Pointer(); } }
27.653179
90
0.639214
ZP-Hust
70f631eeeaa44d21e18c79b374369fadbb3ccd72
398
hpp
C++
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
1
2020-12-29T01:35:03.000Z
2020-12-29T01:35:03.000Z
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
null
null
null
Horista.hpp
vinicassol/PolimorfismoEmpregados
b73a35536c1b6f6acd3cf64d02f71a923174e096
[ "MIT" ]
null
null
null
// // Horista.hpp // PolimorfismoEmpregados // // Created by Vini Cassol on 29/05/20. // Copyright © 2020 Vini Cassol. All rights reserved. // #ifndef Horista_hpp #define Horista_hpp #include "Empregado.hpp" class Horista : public Empregado { public: Horista(); double vencimento(); private: double precoHora; double horasTrabalhadas; }; #endif /* Horista_hpp */
14.214286
54
0.673367
vinicassol
70f7688501a0a51d243ec19077826b0657a1e230
32,725
cpp
C++
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
2
2017-04-20T20:21:16.000Z
2017-04-26T16:30:25.000Z
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
null
null
null
MNE/inverse/hpiFit/hpifit.cpp
13grife37/mne-cpp-swpold
9b89b3d7fe273d9f4ffd69b504e17f284eaba263
[ "BSD-3-Clause" ]
1
2017-04-23T15:55:31.000Z
2017-04-23T15:55:31.000Z
//============================================================================================================= /** * @file hpifit.cpp * @author Lorenz Esch <[email protected]>; * Matti Hamalainen <[email protected]> * @version 1.0 * @date March, 2017 * * @section LICENSE * * Copyright (C) 2017, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief HPIFit class defintion. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "hpifit.h" #include <fiff/fiff_dig_point_set.h> #include <utils/ioutils.h> #include <iostream> #include <fiff/fiff_cov.h> #include <fstream> //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= #include <Eigen/SVD> #include <Eigen/Dense> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QFuture> #include <QtConcurrent/QtConcurrent> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace INVERSELIB; using namespace FIFFLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= Eigen::MatrixXd pinv(Eigen::MatrixXd a) { double epsilon = std::numeric_limits<double>::epsilon(); Eigen::JacobiSVD< Eigen::MatrixXd > svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV); double tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs()(0); return svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(),0).matrix().asDiagonal() * svd.matrixU().adjoint(); } /********************************************************************************* * magnetic_dipole leadfield for a magnetic dipole in an infinite medium * The function has been compared with matlab magnetic_dipole and it gives same output *********************************************************************************/ Eigen::MatrixXd magnetic_dipole(Eigen::MatrixXd pos, Eigen::MatrixXd pnt, Eigen::MatrixXd ori) { double u0 = 1e-7; int nchan; Eigen::MatrixXd r, r2, r5, x, y, z, mx, my, mz, Tx, Ty, Tz, lf; nchan = pnt.rows(); // Shift the magnetometers so that the dipole is in the origin pnt.array().col(0) -= pos(0); pnt.array().col(1) -= pos(1); pnt.array().col(2) -= pos(2); r = pnt.array().square().rowwise().sum().sqrt(); r2 = r5 = x = y = z = mx = my = mz = Tx = Ty = Tz = lf = Eigen::MatrixXd::Zero(nchan,3); for(int i = 0;i < nchan;i++) { r2.row(i).array().fill(pow(r(i),2)); r5.row(i).array().fill(pow(r(i),5)); } for(int i = 0;i < nchan;i++) { x.row(i).array().fill(pnt(i,0)); y.row(i).array().fill(pnt(i,1)); z.row(i).array().fill(pnt(i,2)); } mx.col(0).array().fill(1); my.col(1).array().fill(1); mz.col(2).array().fill(1); Tx = 3 * x.cwiseProduct(pnt) - mx.cwiseProduct(r2); Ty = 3 * y.cwiseProduct(pnt) - my.cwiseProduct(r2); Tz = 3 * z.cwiseProduct(pnt) - mz.cwiseProduct(r2); for(int i = 0;i < nchan;i++) { lf(i,0) = Tx.row(i).dot(ori.row(i)); lf(i,1) = Ty.row(i).dot(ori.row(i)); lf(i,2) = Tz.row(i).dot(ori.row(i)); } for(int i = 0;i < nchan;i++) { for(int j = 0;j < 3;j++) { lf(i,j) = u0 * lf(i,j)/(4 * M_PI * r5(i,j)); } } return lf; } /********************************************************************************* * compute_leadfield computes a forward solution for a dipole in a a volume * conductor model. The forward solution is expressed as the leadfield * matrix (Nchan*3), where each column corresponds with the potential or field * distributions on all sensors for one of the x,y,z-orientations of the dipole. * The function has been compared with matlab ft_compute_leadfield and it gives * same output *********************************************************************************/ Eigen::MatrixXd compute_leadfield(const Eigen::MatrixXd& pos, const struct SensorInfo& sensors) { Eigen::MatrixXd pnt, ori, lf; pnt = sensors.coilpos; // position of each coil ori = sensors.coilori; // orientation of each coil lf = magnetic_dipole(pos, pnt, ori); lf = sensors.tra * lf; return lf; } /********************************************************************************* * dipfitError computes the error between measured and model data * and can be used for non-linear fitting of dipole position. * The function has been compared with matlab dipfit_error and it gives * same output *********************************************************************************/ DipFitError dipfitError(const Eigen::MatrixXd& pos, const Eigen::MatrixXd& data, const struct SensorInfo& sensors, const Eigen::MatrixXd& matProjectors) { // Variable Declaration struct DipFitError e; Eigen::MatrixXd lf, dif; // Compute lead field for a magnetic dipole in infinite vacuum lf = compute_leadfield(pos, sensors); e.moment = pinv(lf) * data; //dif = data - lf * e.moment; dif = data - matProjectors * lf * e.moment; e.error = dif.array().square().sum()/data.array().square().sum(); e.numIterations = 0; return e; } /********************************************************************************* * Compare function for sorting *********************************************************************************/ bool compare(HPISortStruct a, HPISortStruct b) { return (a.base_arr < b.base_arr); } /********************************************************************************* * fminsearch Multidimensional unconstrained nonlinear minimization (Nelder-Mead). * X = fminsearch(X0, maxiter, maxfun, display, data, sensors) starts at X0 and * attempts to find a local minimizer *********************************************************************************/ Eigen::MatrixXd fminsearch(const Eigen::MatrixXd& pos, int maxiter, int maxfun, int display, const Eigen::MatrixXd& data, const Eigen::MatrixXd& matProjectors, const struct SensorInfo& sensors, int &simplex_numitr) { double tolx, tolf, rho, chi, psi, sigma, func_evals, usual_delta, zero_term_delta, temp1, temp2; std::string header, how; int n, itercount, prnt; Eigen::MatrixXd onesn, two2np1, one2n, v, y, v1, tempX1, tempX2, xbar, xr, x, xe, xc, xcc, xin, posCopy; std::vector <double> fv, fv1; std::vector <int> idx; DipFitError tempdip, fxr, fxe, fxc, fxcc; //tolx = tolf = 1e-4; // Seok tolx = tolf = 1e-9; switch(display) { case 0: prnt = 0; break; default: prnt = 1; } header = " Iteration Func-count min f(x) Procedure"; posCopy = pos; n = posCopy.cols(); // Initialize parameters rho = 1; chi = 2; psi = 0.5; sigma = 0.5; onesn = Eigen::MatrixXd::Ones(1,n); two2np1 = one2n = Eigen::MatrixXd::Zero(1,n); for(int i = 0;i < n;i++) { two2np1(i) = 1 + i; one2n(i) = i; } v = v1 = Eigen::MatrixXd::Zero(n, n+1); fv.resize(n+1); idx.resize(n+1); fv1.resize(n+1); for(int i = 0;i < n; i++) { v(i,0) = posCopy(i); } tempdip = dipfitError(posCopy, data, sensors, matProjectors); fv[0] = tempdip.error; func_evals = 1; itercount = 0; how = ""; // Continue setting up the initial simplex. // Following improvement suggested by L.Pfeffer at Stanford usual_delta = 0.05; // 5 percent deltas for non-zero terms zero_term_delta = 0.00025; // Even smaller delta for zero elements of x xin = posCopy.transpose(); for(int j = 0;j < n;j++) { y = xin; if(y(j) != 0) { y(j) = (1 + usual_delta) * y(j); } else { y(j) = zero_term_delta; } v.col(j+1).array() = y; posCopy = y.transpose(); tempdip = dipfitError(posCopy, data, sensors, matProjectors); fv[j+1] = tempdip.error; } // Sort elements of fv std::vector<HPISortStruct> vecSortStruct; for (int i = 0; i < fv.size(); i++) { HPISortStruct structTemp; structTemp.base_arr = fv[i]; structTemp.idx = i; vecSortStruct.push_back(structTemp); } sort (vecSortStruct.begin(), vecSortStruct.end(), compare); for (int i = 0; i < vecSortStruct.size(); i++) { idx[i] = vecSortStruct[i].idx; } for (int i = 0;i < n+1;i++) { v1.col(i) = v.col(idx[i]); fv1[i] = fv[idx[i]]; } v = v1;fv = fv1; how = "initial simplex"; itercount = itercount + 1; func_evals = n + 1; tempX1 = Eigen::MatrixXd::Zero(1,n); while ((func_evals < maxfun) && (itercount < maxiter)) { for (int i = 0;i < n;i++) { tempX1(i) = abs(fv[0] - fv[i+1]); } temp1 = tempX1.maxCoeff(); tempX2 = Eigen::MatrixXd::Zero(n,n); for(int i = 0;i < n;i++) { tempX2.col(i) = v.col(i+1) - v.col(0); } tempX2 = tempX2.array().abs(); temp2 = tempX2.maxCoeff(); if((temp1 <= tolf) && (temp2 <= tolx)) { break; } xbar = v.block(0,0,n,n).rowwise().sum(); xbar /= n; xr = (1+rho) * xbar - rho * v.block(0,n,v.rows(),1); x = xr.transpose(); //std::cout << "Iteration Count: " << itercount << ":" << x << std::endl; fxr = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if (fxr.error < fv[0]) { // Calculate the expansion point xe = (1 + rho * chi) * xbar - rho * chi * v.col(v.cols()-1); x = xe.transpose(); fxe = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if(fxe.error < fxr.error) { v.col(v.cols()-1) = xe; fv[n] = fxe.error; how = "expand"; } else { v.col(v.cols()-1) = xr; fv[n] = fxr.error; how = "reflect"; } } else { if(fxr.error < fv[n-1]) { v.col(v.cols()-1) = xr; fv[n] = fxr.error; how = "reflect"; } else { // fxr.error >= fv[:,n-1] // Perform contraction if(fxr.error < fv[n]) { // Perform an outside contraction xc = (1 + psi * rho) * xbar - psi * rho * v.col(v.cols()-1); x = xc.transpose(); fxc = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals + 1; if(fxc.error <= fxr.error) { v.col(v.cols()-1) = xc; fv[n] = fxc.error; how = "contract outside"; } else { // perform a shrink how = "shrink"; } } else { xcc = (1 - psi) * xbar + psi * v.col(v.cols()-1); x = xcc.transpose(); fxcc = dipfitError(x, data, sensors, matProjectors); func_evals = func_evals+1; if(fxcc.error < fv[n]) { v.col(v.cols()-1) = xcc; fv[n] = fxcc.error; how = "contract inside"; } else { // perform a shrink how = "shrink"; } } if(how.compare("shrink") == 0) { for(int j = 1;j < n+1;j++) { v.col(j).array() = v.col(0).array() + sigma * (v.col(j).array() - v.col(0).array()); x = v.col(j).array().transpose(); tempdip = dipfitError(x,data, sensors, matProjectors); fv[j] = tempdip.error; } } } } // Sort elements of fv vecSortStruct.clear(); for (int i = 0; i < fv.size(); i++) { HPISortStruct structTemp; structTemp.base_arr = fv[i]; structTemp.idx = i; vecSortStruct.push_back(structTemp); } sort (vecSortStruct.begin(), vecSortStruct.end(), compare); for (int i = 0; i < vecSortStruct.size(); i++) { idx[i] = vecSortStruct[i].idx; } for (int i = 0;i < n+1;i++) { v1.col(i) = v.col(idx[i]); fv1[i] = fv[idx[i]]; } v = v1; fv = fv1; itercount = itercount + 1; } x = v.col(0).transpose(); // Seok simplex_numitr = itercount; return x; } /********************************************************************************* * dipfit function is adapted from Fieldtrip Software. It has been * heavily edited for use with MNE Scan Software *********************************************************************************/ void doDipfitConcurrent(FittingCoilData& lCoilData) { // Initialize variables Eigen::RowVectorXd currentCoil = lCoilData.coilPos; Eigen::VectorXd currentData = lCoilData.sensorData; SensorInfo currentSensors = lCoilData.sensorPos; int display = 0; int maxiter = 500; int simplex_numitr = 0; lCoilData.coilPos = fminsearch(currentCoil, maxiter, 2 * maxiter * currentCoil.cols(), display, currentData, lCoilData.matProjector, currentSensors, simplex_numitr); lCoilData.errorInfo = dipfitError(currentCoil, currentData, currentSensors, lCoilData.matProjector); lCoilData.errorInfo.numIterations = simplex_numitr; } //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= HPIFit::HPIFit() { } //************************************************************************************************************* void HPIFit::fitHPI(const MatrixXd& t_mat, const Eigen::MatrixXd& t_matProjectors, FiffCoordTrans& transDevHead, const QVector<int>& vFreqs, QVector<double>& vGof, FiffDigPointSet& fittedPointSet, FiffInfo::SPtr pFiffInfo, bool bDoDebug, const QString& sHPIResourceDir) { //Check if data was passed if(t_mat.rows() == 0 || t_mat.cols() == 0 ) { std::cout<<std::endl<< "HPIFit::fitHPI - No data passed. Returning."; } //Check if projector was passed if(t_matProjectors.rows() == 0 || t_matProjectors.cols() == 0 ) { std::cout<<std::endl<< "HPIFit::fitHPI - No projector passed. Returning."; } vGof.clear(); struct SensorInfo sensors; struct CoilParam coil; int numCh = pFiffInfo->nchan; int samF = pFiffInfo->sfreq; int samLoc = t_mat.cols(); // minimum samples required to localize numLoc times in a second //Get HPI coils from digitizers and set number of coils int numCoils = 0; QList<FiffDigPoint> lHPIPoints; for(int i = 0; i < pFiffInfo->dig.size(); ++i) { if(pFiffInfo->dig[i].kind == FIFFV_POINT_HPI) { numCoils++; lHPIPoints.append(pFiffInfo->dig[i]); } } //Set coil frequencies Eigen::VectorXd coilfreq(numCoils); if(vFreqs.size() >= numCoils) { for(int i = 0; i < numCoils; ++i) { coilfreq[i] = vFreqs.at(i); //std::cout<<std::endl << coilfreq[i] << "Hz"; } } else { std::cout<<std::endl<< "HPIFit::fitHPI - Not enough coil frequencies specified. Returning."; return; } // Initialize HPI coils location and moment coil.pos = Eigen::MatrixXd::Zero(numCoils,3); coil.mom = Eigen::MatrixXd::Zero(numCoils,3); coil.dpfiterror = Eigen::VectorXd::Zero(numCoils); coil.dpfitnumitr = Eigen::VectorXd::Zero(numCoils); // Generate simulated data Eigen::MatrixXd simsig(samLoc,numCoils*2); Eigen::VectorXd time(samLoc); for (int i = 0; i < samLoc; ++i) { time[i] = i*1.0/samF; } for(int i = 0; i < numCoils; ++i) { for(int j = 0; j < samLoc; ++j) { simsig(j,i) = sin(2*M_PI*coilfreq[i]*time[j]); simsig(j,i+numCoils) = cos(2*M_PI*coilfreq[i]*time[j]); } } // Create digitized HPI coil position matrix Eigen::MatrixXd headHPI(numCoils,3); // check the pFiffInfo->dig information. If dig is empty, set the headHPI is 0; if (lHPIPoints.size() > 0) { for (int i = 0; i < lHPIPoints.size(); ++i) { headHPI(i,0) = lHPIPoints.at(i).r[0]; headHPI(i,1) = lHPIPoints.at(i).r[1]; headHPI(i,2) = lHPIPoints.at(i).r[2]; } } else { for (int i = 0; i < numCoils; ++i) { headHPI(i,0) = 0; headHPI(i,1) = 0; headHPI(i,2) = 0; } } // Get the indices of inner layer channels and exclude bad channels. //TODO: Only supports babymeg and vectorview gradiometeres for hpi fitting. QVector<int> innerind(0); for (int i = 0; i < numCh; ++i) { if(pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_BABY_MAG || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T1 || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T2 || pFiffInfo->chs[i].chpos.coil_type == FIFFV_COIL_VV_PLANAR_T3) { // Check if the sensor is bad, if not append to innerind if(!(pFiffInfo->bads.contains(pFiffInfo->ch_names.at(i)))) { innerind.append(i); } } } //Create new projector based on the excluded channels, first exclude the rows then the columns MatrixXd matProjectorsRows(innerind.size(),t_matProjectors.cols()); MatrixXd matProjectorsInnerind(innerind.size(),innerind.size()); for (int i = 0; i < matProjectorsRows.rows(); ++i) { matProjectorsRows.row(i) = t_matProjectors.row(innerind.at(i)); } for (int i = 0; i < matProjectorsInnerind.cols(); ++i) { matProjectorsInnerind.col(i) = matProjectorsRows.col(innerind.at(i)); } //UTILSLIB::IOUtils::write_eigen_matrix(matProjectorsInnerind, "matProjectorsInnerind.txt"); //UTILSLIB::IOUtils::write_eigen_matrix(t_matProjectors, "t_matProjectors.txt"); // Initialize inner layer sensors sensors.coilpos = Eigen::MatrixXd::Zero(innerind.size(),3); sensors.coilori = Eigen::MatrixXd::Zero(innerind.size(),3); sensors.tra = Eigen::MatrixXd::Identity(innerind.size(),innerind.size()); for(int i = 0; i < innerind.size(); i++) { sensors.coilpos(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.r0[0]; sensors.coilpos(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.r0[1]; sensors.coilpos(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.r0[2]; sensors.coilori(i,0) = pFiffInfo->chs[innerind.at(i)].chpos.ez[0]; sensors.coilori(i,1) = pFiffInfo->chs[innerind.at(i)].chpos.ez[1]; sensors.coilori(i,2) = pFiffInfo->chs[innerind.at(i)].chpos.ez[2]; } Eigen::MatrixXd topo(innerind.size(), numCoils*2); Eigen::MatrixXd amp(innerind.size(), numCoils); Eigen::MatrixXd ampC(innerind.size(), numCoils); // Get the data from inner layer channels Eigen::MatrixXd innerdata(innerind.size(), t_mat.cols()); for(int j = 0; j < innerind.size(); ++j) { innerdata.row(j) << t_mat.row(innerind[j]); } // Calculate topo topo = innerdata * pinv(simsig).transpose(); // topo: # of good inner channel x 8 // Select sine or cosine component depending on the relative size amp = topo.leftCols(numCoils); // amp: # of good inner channel x 4 ampC = topo.rightCols(numCoils); for(int j = 0; j < numCoils; ++j) { float nS = 0.0; float nC = 0.0; for(int i = 0; i < innerind.size(); ++i) { nS += amp(i,j)*amp(i,j); nC += ampC(i,j)*ampC(i,j); } if(nC > nS) { for(int i = 0; i < innerind.size(); ++i) { amp(i,j) = ampC(i,j); } } } //Find good seed point/starting point for the coil position in 3D space //Find biggest amplitude per pickup coil (sensor) and store corresponding sensor channel index VectorXi chIdcs(numCoils); for (int j = 0; j < numCoils; j++) { double maxVal = 0; int chIdx = 0; for (int i = 0; i < amp.rows(); ++i) { if(abs(amp(i,j)) > maxVal) { maxVal = abs(amp(i,j)); if(chIdx < innerind.size()) { chIdx = innerind.at(i); } } } chIdcs(j) = chIdx; } //Generate seed point by projection the found channel position 3cm inwards Eigen::MatrixXd coilPos = Eigen::MatrixXd::Zero(numCoils,3); for (int j = 0; j < chIdcs.rows(); ++j) { int chIdx = chIdcs(j); if(chIdx < pFiffInfo->chs.size()) { double x = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[0]; double y = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[1]; double z = pFiffInfo->chs.at(chIdcs(j)).chpos.r0[2]; coilPos(j,0) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[0] * 0.03 + x; coilPos(j,1) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[1] * 0.03 + y; coilPos(j,2) = -1 * pFiffInfo->chs.at(chIdcs(j)).chpos.ez[2] * 0.03 + z; } //std::cout << "HPIFit::fitHPI - Coil " << j << " max value index " << chIdx << std::endl; } coil.pos = coilPos; coil = dipfit(coil, sensors, amp, numCoils, matProjectorsInnerind); Eigen::Matrix4d trans = computeTransformation(headHPI, coil.pos); //Eigen::Matrix4d trans = computeTransformation(coil.pos, headHPI); // Store the final result to fiff info // Set final device/head matrix and its inverse to the fiff info transDevHead.from = 1; transDevHead.to = 4; for(int r = 0; r < 4; ++r) { for(int c = 0; c < 4 ; ++c) { transDevHead.trans(r,c) = trans(r,c); } } // Also store the inverse transDevHead.invtrans = transDevHead.trans.inverse(); //Calculate GOF MatrixXd temp = coil.pos; temp.conservativeResize(coil.pos.rows(),coil.pos.cols()+1); temp.block(0,3,numCoils,1).setOnes(); temp.transposeInPlace(); MatrixXd testPos = trans * temp; MatrixXd diffPos = testPos.block(0,0,3,numCoils) - headHPI.transpose(); for(int i = 0; i < diffPos.cols(); ++i) { vGof.append(diffPos.col(i).norm()); } //Generate final fitted points and store in digitizer set for(int i = 0; i < coil.pos.rows(); ++i) { FiffDigPoint digPoint; digPoint.kind = FIFFV_POINT_EEG; digPoint.ident = i; digPoint.r[0] = coil.pos(i,0); digPoint.r[1] = coil.pos(i,1); digPoint.r[2] = coil.pos(i,2); fittedPointSet << digPoint; } if(bDoDebug) { // DEBUG HPI fitting and write debug results std::cout << std::endl << std::endl << "HPIFit::fitHPI - dpfiterror" << coil.dpfiterror << std::endl << coil.pos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - Initial seed point for HPI coils" << std::endl << coil.pos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - temp" << std::endl << temp << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - testPos" << std::endl << testPos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - Diff fitted - original" << std::endl << diffPos << std::endl; std::cout << std::endl << std::endl << "HPIFit::fitHPI - dev/head trans" << std::endl << trans << std::endl; QString sTimeStamp = QDateTime::currentDateTime().toString("yyMMdd_hhmmss"); if(!QDir(sHPIResourceDir).exists()) { QDir().mkdir(sHPIResourceDir); } UTILSLIB::IOUtils::write_eigen_matrix(coilPos, QString("%1/%2_coilPosSeed_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(coil.pos, QString("%1/%2_coilPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(headHPI, QString("%1/%2_headHPI_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXd testPosCut = testPos.transpose();//block(0,0,3,4); UTILSLIB::IOUtils::write_eigen_matrix(testPosCut, QString("%1/%2_testPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXi idx_mat(chIdcs.rows(),1); idx_mat.col(0) = chIdcs; UTILSLIB::IOUtils::write_eigen_matrix(idx_mat, QString("%1/%2_idx_mat").arg(sHPIResourceDir).arg(sTimeStamp)); MatrixXd coilFreq_mat(coilfreq.rows(),1); coilFreq_mat.col(0) = coilfreq; UTILSLIB::IOUtils::write_eigen_matrix(coilFreq_mat, QString("%1/%2_coilFreq_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(diffPos, QString("%1/%2_diffPos_mat").arg(sHPIResourceDir).arg(sTimeStamp)); UTILSLIB::IOUtils::write_eigen_matrix(amp, QString("%1/%2_amp_mat").arg(sHPIResourceDir).arg(sTimeStamp)); } } //************************************************************************************************************* CoilParam HPIFit::dipfit(struct CoilParam coil, struct SensorInfo sensors, const Eigen::MatrixXd& data, int numCoils, const Eigen::MatrixXd& t_matProjectors) { //Do this in conncurrent mode //Generate QList structure which can be handled by the QConcurrent framework QList<FittingCoilData> lCoilData; for(qint32 i = 0; i < numCoils; ++i) { FittingCoilData coilData; coilData.coilPos = coil.pos.row(i); coilData.sensorData = data.col(i); coilData.sensorPos = sensors; coilData.matProjector = t_matProjectors; lCoilData.append(coilData); } //Do the concurrent filtering if(!lCoilData.isEmpty()) { //Do sequential for(int l = 0; l < lCoilData.size(); ++l) { doDipfitConcurrent(lCoilData[l]); } // //Do concurrent // QFuture<void> future = QtConcurrent::map(lCoilData, // doDipfitConcurrent); // future.waitForFinished(); //Transform results to final coil information for(qint32 i = 0; i < lCoilData.size(); ++i) { coil.pos.row(i) = lCoilData.at(i).coilPos; coil.mom = lCoilData.at(i).errorInfo.moment.transpose(); coil.dpfiterror(i) = lCoilData.at(i).errorInfo.error; coil.dpfitnumitr(i) = lCoilData.at(i).errorInfo.numIterations; //std::cout<<std::endl<< "HPIFit::dipfit - Itr steps for coil " << i << " =" <<coil.dpfitnumitr(i); } } return coil; } //************************************************************************************************************* Eigen::Matrix4d HPIFit::computeTransformation(Eigen::MatrixXd NH, Eigen::MatrixXd BT) { Eigen::MatrixXd xdiff, ydiff, zdiff, C, Q; Eigen::Matrix4d transFinal = Eigen::Matrix4d::Identity(4,4); Eigen::Matrix4d Rot = Eigen::Matrix4d::Zero(4,4); Eigen::Matrix4d Trans = Eigen::Matrix4d::Identity(4,4); double meanx,meany,meanz,normf; for(int i = 0; i < 15; ++i) { // Calcualte mean translation for all points -> centroid of both data sets xdiff = NH.col(0) - BT.col(0); ydiff = NH.col(1) - BT.col(1); zdiff = NH.col(2) - BT.col(2); meanx = xdiff.mean(); meany = ydiff.mean(); meanz = zdiff.mean(); // Apply translation -> bring both data sets to the same center location for (int j = 0; j < BT.rows(); ++j) { BT(j,0) = BT(j,0) + meanx; BT(j,1) = BT(j,1) + meany; BT(j,2) = BT(j,2) + meanz; } // Estimate rotation component C = BT.transpose() * NH; Eigen::JacobiSVD< Eigen::MatrixXd > svd(C ,Eigen::ComputeThinU | Eigen::ComputeThinV); Q = svd.matrixU() * svd.matrixV().transpose(); //Handle special reflection case if(Q.determinant() < 0) { Q(0,2) = Q(0,2) * -1; Q(1,2) = Q(1,2) * -1; Q(2,2) = Q(2,2) * -1; } // Apply rotation on translated points BT = BT * Q; // Calculate GOF normf = (NH.transpose()-BT.transpose()).norm(); // Store rotation part to transformation matrix Rot(3,3) = 1; for(int j = 0; j < 3; ++j) { for(int k = 0; k < 3; ++k) { Rot(j,k) = Q(k,j); } } // Store translation part to transformation matrix Trans(0,3) = meanx; Trans(1,3) = meany; Trans(2,3) = meanz; // Safe rotation and translation to final matrix for next iteration step transFinal = Rot * Trans * transFinal; } return transFinal; }
35.765027
173
0.507288
13grife37
70fc1ccb1df0ebc43bda8ead109ac1b70e7eefe3
5,669
cpp
C++
src/common/commandLine.cpp
salarii/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
1
2015-01-22T11:22:19.000Z
2015-01-22T11:22:19.000Z
src/common/commandLine.cpp
salivan-ratcoin-dev-team/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
null
null
null
src/common/commandLine.cpp
salivan-ratcoin-dev-team/dims
b8008c49edd10a9ca50923b89e3b469c342d9cee
[ "MIT" ]
null
null
null
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 DiMS dev-team // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "rpcclient.h" #include "util.h" #include "json/json_spirit_value.h" #include <openssl/crypto.h> #include "common/commandLine.h" #include <boost/thread.hpp> namespace common { CCommandLine * CCommandLine::ms_instance = NULL; CCommandLine* CCommandLine::getInstance() { if ( !ms_instance ) { ms_instance = new CCommandLine(); }; return ms_instance; } void CCommandLine::reply( CMessageClass::Enum _category, std::string const & _commandResponse ) { std::string comandResponse; switch( _category ) { case CMessageClass::MC_ERROR: comandResponse = "CODE ERROR: "; break; case CMessageClass::MC_DEBUG: comandResponse = "CODE DEBUG: "; break; case CMessageClass::CMD_REQUEST: comandResponse = "COMMAND REQUEST: "; break; case CMessageClass::CMD_REPLY: comandResponse = "COMMAND REPLY: "; break; case CMessageClass::CMD_ERROR: comandResponse = "COMMAND ERROR: "; break; default: break; } addOutputMessage( comandResponse + _commandResponse ); } void CCommandLine::workLoop() { fd_set read_fds; timeval waitTime; waitTime.tv_sec = 0; waitTime.tv_usec = 0; bool promptPrinted = false; while ( 1 ) { if ( !promptPrinted ) { promptPrinted = true; std::cout << "PROMPT > "; std::cout.flush(); } std::string line; FD_ZERO(&read_fds); FD_SET( STDIN_FILENO, &read_fds ); int result = select( FD_SETSIZE, &read_fds, NULL, NULL, &waitTime ); if (result == -1 && errno != EINTR) { assert(!"Error in select"); } else if (result == -1 && errno == EINTR) { assert(!"problem"); } else { if (FD_ISSET(STDIN_FILENO, &read_fds)) { promptPrinted = false; std::getline(std::cin, line); } } if ( !line.empty() ) { request( line ); } boost::lock_guard<boost::mutex> lock( m_lock ); BOOST_FOREACH( std::string const & out, m_outputs ) { std::cout << out << "\n\n"; } m_outputs.clear(); MilliSleep(10); boost::this_thread::interruption_point(); } } bool CCommandLine::parseCommandLine( std::vector<std::string> & _args, const std::string & _strCommand ) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; BOOST_FOREACH( char const & ch, _strCommand ) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if( state == STATE_ARGUMENT ) // Space ends argument { _args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: _args.push_back( curarg ); return true; default: // ERROR to end in one of the other states return false; } } void CCommandLine::request( std::string const & _command ) { std::vector<std::string> args; if( !parseCommandLine( args, _command ) ) { reply( CMessageClass::CMD_ERROR, "Parse error: unbalanced ' or \"" ); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); reply( CMessageClass::CMD_REPLY, strPrint ); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); std::ostringstream errorStream; errorStream << code; reply(CMessageClass::CMD_ERROR, message + " (code " + errorStream.str() + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object reply( CMessageClass::CMD_ERROR, write_string( json_spirit::Value(objError), false) ); } } catch (std::exception& e) { reply( CMessageClass::CMD_ERROR, std::string("Error: ") + e.what()); } } }
23.138776
102
0.66943
salarii
cb0080971d43ed9bdd2cc1c9275497a91e86063d
2,922
hpp
C++
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
1
2019-07-25T01:42:22.000Z
2019-07-25T01:42:22.000Z
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
null
null
null
include/mitama/mana/functional/chunkify.hpp
LoliGothick/mitama-mana
32ba02356b6e2bbfdbadd4dd6f8054b2aa1af898
[ "MIT" ]
null
null
null
#ifndef MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP #define MITAMA_MANA_FUNCTIONAL_CHUNKIFY_HPP #include <mitama/mana/algorithm/chunk.hpp> #include <mitama/mana/algorithm/klisli.hpp> #include <mitama/mana/utility/apply.hpp> #include <mitama/mana/utility/peel.hpp> #include <mitama/mana/type_traits/is_tuple_like.hpp> #include <mitama/mana/meta/repack.hpp> #include <mitama/mana/core/view/view.hpp> #include <tuple> namespace mitama::mana::map_fn { template <std::size_t N> struct chunkify_map_fn { template <class Tuple, std::size_t... Indices> static constexpr auto element_type(Tuple&&, value_list<Indices...>) -> std::tuple<std::tuple_element_t<Indices, Tuple>...>; template <class Tuple> static constexpr std::size_t value = std::tuple_size_v<std::decay_t<Tuple>> / N; template <std::size_t I, class Tuple> using type = decltype(chunkify_map_fn::element_type(std::declval<Tuple>(), mana::iota<I*N, I*N + N>)); template <std::size_t I, class Tuple> static constexpr auto get(Tuple&& t) { return mana::apply([&t](auto... indices){ return std::tuple(std::get<mana::peel(indices)>(t)...); }, mana::iota<I*N, I*N + N>); } }; } namespace mitama::mana { template <std::size_t N> struct chunkify_fn { template <class... Args> auto operator()(Args&&... args) const { return mana::apply([forwarded = std::forward_as_tuple(std::forward<Args>(args)...)](auto... chunk) mutable { return std::tuple{mana::apply([&forwarded](auto... indices) mutable { return std::tuple(std::get<mana::peel(indices)>(forwarded)...); }, mana::peel(chunk))... }; }, mana::chunk<N>(mana::iota<0, sizeof...(Args)>)); } template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false> auto operator()(TupleLike&& t) const { return mana::apply([t](auto... chunk) mutable { return std::tuple{mana::apply([&t](auto... indices) mutable { return std::tuple(std::get<mana::peel(indices)>(t)...); }, mana::peel(chunk))... }; }, mana::chunk<N>(mana::iota<0, std::tuple_size_v<std::decay_t<TupleLike>>>)); } template <class... Args> auto view(Args&&... args) const { return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<Args...>>{std::forward<Args>(args)...}; } template <class TupleLike, std::enable_if_t<mana::is_tuple_like_v<std::decay_t<TupleLike>>, bool> = false> auto view(TupleLike&& t) const { return std::apply([](auto&&... args){ return _view<fn::static_, mitama::mana::map_fn::chunkify_map_fn<N>, std::tuple<decltype(args)...>>{std::forward<decltype(args)>(args)...}; }, std::forward<TupleLike>(t)); } }; template <std::size_t N> inline constexpr chunkify_fn<N> chunkify{}; } #endif // !MITAMA_MANA_FUNCTIONAL_CHUNK_HPP
38.96
150
0.644079
LoliGothick
cb022d18789e6e9500f206350d0b5990cd80f4d3
385
cpp
C++
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
OOPs/TimeUse.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
1
2021-10-05T10:09:32.000Z
2021-10-05T10:09:32.000Z
#include <bits/stdc++.h> #include "Time.cpp" using namespace std; int main() { Time t1; t1.setHour(3); t1.setMinutes(34); t1.setSeconds(54); Time t2; t2.setHour(2); t2.setMinutes(24); t2.setSeconds(35); Time t3; t3 = t1.add(t2); t1.print(); t2.print(); t3.print(); Time t4; t4 = t2.subtract(t1); t4.print(); }
14.259259
26
0.532468
Mitushi-23
cb09316a90c30dd0cdfd9be6ec24c1760760f3ad
2,592
cpp
C++
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
255
2015-01-06T15:11:26.000Z
2022-03-30T20:52:58.000Z
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
2
2018-12-18T22:50:25.000Z
2019-01-09T16:57:11.000Z
src/buffer.cpp
plenluno/libnode
9dea4f2390422e70544186df3f5c032cb4a7db08
[ "BSD-2-Clause", "MIT" ]
36
2015-03-28T03:23:57.000Z
2022-01-16T12:51:30.000Z
// Copyright (c) 2012-2014 Plenluno All rights reserved. #include <libnode/buffer.h> #include <libnode/detail/buffer.h> namespace libj { namespace node { Buffer::Ptr Buffer::create(Size length) { return Ptr(new detail::Buffer<Buffer>(length)); } Buffer::Ptr Buffer::create(const void* data, Size length) { if (!data) return null(); detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length)); const UByte* src = static_cast<const UByte*>(data); UByte* dst = static_cast<UByte*>(const_cast<void*>(buf->data())); std::copy(src, src + length, dst); return Ptr(buf); } Buffer::Ptr Buffer::create(TypedJsArray<UByte>::CPtr array) { if (!array) return null(); Size length = array->length(); detail::Buffer<Buffer>* buf(new detail::Buffer<Buffer>(length)); for (Size i = 0; i < length; i++) { buf->writeUInt8(array->getTyped(i), i); } return Ptr(buf); } template<typename T> static Buffer::Ptr createBuffer(T t, Buffer::Encoding enc) { if (!t) return Buffer::null(); std::string s; switch (enc) { case Buffer::UTF8: s = t->toStdString(); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length()); case Buffer::UTF16BE: s = t->toStdString(String::UTF16BE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 2); // delete the last null character case Buffer::UTF16LE: s = t->toStdString(String::UTF16LE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 2); // delete the last null character case Buffer::UTF32BE: s = t->toStdString(String::UTF32BE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 4); // delete the last null character case Buffer::UTF32LE: s = t->toStdString(String::UTF32LE); return Buffer::create( reinterpret_cast<const UByte*>(s.c_str()), s.length() - 4); // delete the last null character case Buffer::BASE64: return util::base64Decode(t); case Buffer::HEX: return util::hexDecode(t); default: return Buffer::null(); } } Buffer::Ptr Buffer::create(String::CPtr str, Buffer::Encoding enc) { return createBuffer<String::CPtr>(str, enc); } Buffer::Ptr Buffer::create(StringBuilder::CPtr sb, Buffer::Encoding enc) { return createBuffer<StringBuilder::CPtr>(sb, enc); } } // namespace node } // namespace libj
30.857143
74
0.615355
plenluno
cb0ac0e955faa7177b861c492357bb98f501d442
3,698
cc
C++
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
2
2016-01-22T03:10:02.000Z
2021-04-21T06:32:11.000Z
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
null
null
null
tests/unittests/test_util.cc
phuy/cef3
33449af3cfa7b43e8b0f9a7190a20def32cb8f7b
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "tests/unittests/test_util.h" #include "testing/gtest/include/gtest/gtest.h" void TestBinaryEqual(CefRefPtr<CefBinaryValue> val1, CefRefPtr<CefBinaryValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); size_t data_size = val1->GetSize(); EXPECT_EQ(data_size, val2->GetSize()); EXPECT_GT(data_size, (size_t)0); char* data1 = new char[data_size+1]; char* data2 = new char[data_size+1]; EXPECT_EQ(data_size, val1->GetData(data1, data_size, 0)); data1[data_size] = 0; EXPECT_EQ(data_size, val2->GetData(data2, data_size, 0)); data2[data_size] = 0; EXPECT_STREQ(data1, data2); delete [] data1; delete [] data2; } void TestDictionaryEqual(CefRefPtr<CefDictionaryValue> val1, CefRefPtr<CefDictionaryValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); EXPECT_EQ(val1->GetSize(), val2->GetSize()); CefDictionaryValue::KeyList keys; EXPECT_TRUE(val1->GetKeys(keys)); CefDictionaryValue::KeyList::const_iterator it = keys.begin(); for (; it != keys.end(); ++it) { CefString key = *it; EXPECT_TRUE(val2->HasKey(key)); CefValueType type = val1->GetType(key); EXPECT_EQ(type, val2->GetType(key)); switch (type) { case VTYPE_INVALID: case VTYPE_NULL: break; case VTYPE_BOOL: EXPECT_EQ(val1->GetBool(key), val2->GetBool(key)); break; case VTYPE_INT: EXPECT_EQ(val1->GetInt(key), val2->GetInt(key)); break; case VTYPE_DOUBLE: EXPECT_EQ(val1->GetDouble(key), val2->GetDouble(key)); break; case VTYPE_STRING: EXPECT_EQ(val1->GetString(key), val2->GetString(key)); break; case VTYPE_BINARY: TestBinaryEqual(val1->GetBinary(key), val2->GetBinary(key)); break; case VTYPE_DICTIONARY: TestDictionaryEqual(val1->GetDictionary(key), val2->GetDictionary(key)); break; case VTYPE_LIST: TestListEqual(val1->GetList(key), val2->GetList(key)); break; } } } void TestListEqual(CefRefPtr<CefListValue> val1, CefRefPtr<CefListValue> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); size_t size = val1->GetSize(); EXPECT_EQ(size, val2->GetSize()); for (size_t i = 0; i < size; ++i) { CefValueType type = val1->GetType(i); EXPECT_EQ(type, val2->GetType(i)); switch (type) { case VTYPE_INVALID: case VTYPE_NULL: break; case VTYPE_BOOL: EXPECT_EQ(val1->GetBool(i), val2->GetBool(i)); break; case VTYPE_INT: EXPECT_EQ(val1->GetInt(i), val2->GetInt(i)); break; case VTYPE_DOUBLE: EXPECT_EQ(val1->GetDouble(i), val2->GetDouble(i)); break; case VTYPE_STRING: EXPECT_EQ(val1->GetString(i), val2->GetString(i)); break; case VTYPE_BINARY: TestBinaryEqual(val1->GetBinary(i), val2->GetBinary(i)); break; case VTYPE_DICTIONARY: TestDictionaryEqual(val1->GetDictionary(i), val2->GetDictionary(i)); break; case VTYPE_LIST: TestListEqual(val1->GetList(i), val2->GetList(i)); break; } } } void TestProcessMessageEqual(CefRefPtr<CefProcessMessage> val1, CefRefPtr<CefProcessMessage> val2) { EXPECT_TRUE(val1.get()); EXPECT_TRUE(val2.get()); EXPECT_EQ(val1->GetName(), val2->GetName()); TestListEqual(val1->GetArgumentList(), val2->GetArgumentList()); }
29.11811
80
0.637372
phuy
cb0b7dde789b57b4cb63bad8b630a434c245d1d3
1,678
hh
C++
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-06-02T11:50:06.000Z
2018-06-02T11:50:06.000Z
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-01-17T04:16:29.000Z
2018-01-30T09:01:44.000Z
policy-decision-point/ast_preprocessor_visitor.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-11-18T20:31:54.000Z
2018-11-18T20:31:54.000Z
// Copyright 2015-2018 RWTH Aachen University // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "ast.hh" #include "policy_definition.hh" #include <algorithm> #include <boost/lexical_cast.hpp> //Visitor that preprocesses the AST class AstPreprocessorVisitor : public AstVisitor { public: //the policy definition is used to get the types of IDs, since they are initially unknown after the parsing AstPreprocessorVisitor(const PolicyDefinition &policyDefinition) : policyDefinition(policyDefinition) {} void visit(AstOperation &); void visit(AstConstant &); void visit(AstId &); void visit(AstFunction &); void visit(Ast &); private: const PolicyDefinition &policyDefinition; const static uint64_t maxNumberOfChildren = 2; //fields used to save results of a visit AstValueType resultType; //used for type checking, IDs are replaced with their real value AstOperationType parentType; //used to flip booleans with NOT parent uint64_t nodeCounter; bool flipMeaning; //used to eliminate NOTs by moving them into the relations };
37.288889
115
0.721692
SSICLOPS
cb0c4ae2df7edf3b76f081f073c4eef3bf23221e
1,349
hpp
C++
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
6
2017-11-13T02:08:50.000Z
2021-02-21T07:34:31.000Z
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
null
null
null
core/cs_basic_type.hpp
WukongGPU/WukongGPU
7810ecc1328b21230d448c6e64cc6fbd21f3b089
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2016 Shanghai Jiao Tong University. * 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. * */ #pragma once #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <vector> using namespace std; using namespace boost::archive; struct CS_Request { string type; bool use_file; string content; string cid; template <typename Archive> void serialize(Archive &ar, const unsigned int v) { ar &type; ar &use_file; ar &content; } }; struct CS_Reply { string type; string content; int column; vector<int64_t> column_table; vector<int> result_table; string cid; template <typename Archive> void serialize(Archive &ar, const unsigned int v) { ar &type; ar &content; ar &column; ar &column_table; ar &result_table; } };
22.114754
68
0.717569
WukongGPU
cb0d492f8289909d70483f319fd2aca06f0184cb
233
hpp
C++
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
null
null
null
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
null
null
null
shared/Networking/MpNetworkingEvents.hpp
EnderdracheLP/MultiplayerCore.Quest
fd680fe8eb4dffdd3459059b9058002c3ed24749
[ "MIT" ]
1
2022-03-22T11:36:32.000Z
2022-03-22T11:36:32.000Z
#pragma once #include "../Utils/event.hpp" #include "MpPacketSerializer.hpp" namespace MultiplayerCore::Networking { struct MpNetworkingEvents { static event<Networking::MpPacketSerializer*> RegisterPackets; }; }
19.416667
70
0.729614
EnderdracheLP
cb0d6b53ddd6bc26007aaa873858d9771d92043e
2,069
cpp
C++
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Common/isLocalAddress.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Common/isLocalAddress.h> #include <Core/Types.h> #include <Poco/Net/NetworkInterface.h> #include <Poco/Net/SocketAddress.h> #include <Poco/Util/Application.h> #include <cstring> namespace DB { bool isLocalAddress(const Poco::Net::SocketAddress & address) { static auto interfaces = Poco::Net::NetworkInterface::list(); return interfaces.end() != std::find_if(interfaces.begin(), interfaces.end(), [&](const Poco::Net::NetworkInterface & interface) { /** Compare the addresses without taking into account `scope`. * Theoretically, this may not be correct - depends on `route` setting * - through which interface we will actually access the specified address. */ return interface.address().length() == address.host().length() && 0 == memcmp(interface.address().addr(), address.host().addr(), address.host().length()); }); } bool isLocalAddress(const Poco::Net::SocketAddress & address, UInt16 clickhouse_port) { return clickhouse_port == address.port() && isLocalAddress(address); } size_t getHostNameDifference(const std::string & local_hostname, const std::string & host) { size_t hostname_difference = 0; for (size_t i = 0; i < std::min(local_hostname.length(), host.length()); ++i) if (local_hostname[i] != host[i]) ++hostname_difference; return hostname_difference; } } // namespace DB
36.946429
134
0.676655
solotzg
cb0fa89cbbde76c03257ca2722f09e63f855779a
2,309
cpp
C++
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
3
2018-08-30T18:14:40.000Z
2019-02-22T17:12:44.000Z
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
4
2018-05-31T10:01:25.000Z
2018-07-26T15:14:26.000Z
test/cnd_test/cnd_test.cpp
BoostGSoC18/Advanced-Intrusive
30c465125c460e4bc2a9583ce00f0f706ed23e5a
[ "BSL-1.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #include <iostream> // for std::cout #include <utility> // for std::pair #include <algorithm> // for std::for_each #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/adjacency_matrix.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> using namespace boost; #include "boost/graph/CND/cnd_function.hpp" template<typename Graph> void treesize_vertices(int cur,Graph &graph,bool visited[],int subtree_size[]) { visited[cur] = true; subtree_size[cur] = 1; typedef typename graph_traits<Graph>::adjacency_iterator adj_itr; adj_itr ai,ai_end; for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai) { if (!visited[*ai]) { treesize_vertices(*ai,graph,visited,subtree_size); subtree_size[cur]+=subtree_size[*ai]; } } } template<typename Graph> void check_centroid(int cur,Graph &graph,bool visited[],int subtree_size[],int *check) { visited[cur] = true; typedef typename graph_traits<Graph>::adjacency_iterator adj_itr; adj_itr ai,ai_end; for (boost::tie(ai, ai_end) = adjacent_vertices(cur,graph);ai != ai_end; ++ai) { if (!visited[*ai]) { if(subtree_size[*ai]>(subtree_size[cur]/2)) { *check=0; } check_centroid(*ai,graph,visited,subtree_size,check); } } } int main() { int i,n,a,b; scanf("%d",&n); typedef adjacency_list<vecS, vecS, undirectedS> Graph_list; Graph_list graph_list(n); for(i=1;i<n;i++) { scanf("%d %d",&a,&b); add_edge(a,b,graph_list); } pair<Graph_list,int> copy_graph; copy_graph=CND(graph_list,0,n); int root=copy_graph.second; bool visited[1030]; int subtree_size[1030]; for(i=0;i<n;i++) { visited[i]=false; subtree_size[i]=0; } treesize_vertices<Graph_list>(root,copy_graph.first,visited,subtree_size); int check=1; for(i=0;i<n;i++) visited[i]=false; check_centroid<Graph_list>(root,copy_graph.first,visited,subtree_size,&check); if(check) { printf("Success\n"); } return 0; }
28.158537
86
0.614985
BoostGSoC18
cb12fa9353b628206ec24432662579cd5bec6fd5
7,232
cpp
C++
src/core/cpp/scene/SceneUtility.cpp
NeroGames/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
26
2020-09-02T18:14:36.000Z
2022-02-08T18:28:36.000Z
src/core/cpp/scene/SceneUtility.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
14
2020-08-30T01:37:04.000Z
2021-07-19T20:47:29.000Z
src/core/cpp/scene/SceneUtility.cpp
sk-landry/Nero-Game-Engine
8543b8bb142738aa28bc20e929b342d3e6df066e
[ "MIT" ]
6
2020-09-02T18:14:57.000Z
2021-12-31T00:32:09.000Z
//////////////////////////////////////////////////////////// // Nero Game Engine // Copyright (c) 2016-2020 Sanou A. K. Landry //////////////////////////////////////////////////////////// ///////////////////////////HEADERS////////////////////////// //NERO #include <Nero/core/cpp/scene/SceneUtility.h> //////////////////////////////////////////////////////////// namespace nero { //////////////////////////////////////////////////////////// //QueryCallback QueryCallback::QueryCallback(const b2Vec2& point) { m_Point = point; m_Fixture = nullptr; } bool QueryCallback::ReportFixture(b2Fixture* fixture) { b2Body* body = fixture->GetBody(); if (body->GetType() == b2_dynamicBody) { bool inside = fixture->TestPoint(m_Point); if (inside) { m_Fixture = fixture; //Clean pointer body = nullptr; //We are done, terminate the query. return false; } } //Clean pointer body = nullptr; //Continue the query. return true; } QueryCallback::~QueryCallback() { m_Fixture = nullptr; } //////////////////////////////////////////////////////////// //SceneSetting SceneSetting::SceneSetting() { hz = 40.0f; viewCenter.Set(0.0f, 0.0f); gravity.Set(0.f, 10.f); velocityIterations = 8; positionIterations = 3; drawAxis = true; drawGrid = true; drawShapes = true; drawJoints = true; drawAABBs = false; drawContactPoints = false; drawContactNormals = false; drawContactImpulse = false; drawFrictionImpulse = false; drawCOMs = false; drawStats = false; drawProfile = false; enableWarmStarting = true; enableContinuous = true; enableSubStepping = false; enableSleep = true; pause = false; singleStep = false; } nlohmann::json SceneSetting::toJson() { nlohmann::json scene_setting; scene_setting["frequency"] = hz; scene_setting["view_center"] = graphics::vectorToJson<b2Vec2>(viewCenter); scene_setting["gravity"] = graphics::vectorToJson<b2Vec2>(gravity); scene_setting["velocity_iterations"] = velocityIterations; scene_setting["position_iterations"] = positionIterations; scene_setting["enable_warm_starting"] = enableWarmStarting; scene_setting["enable_continuous"] = enableContinuous; scene_setting["enable_sub_stepping"] = enableSubStepping; scene_setting["enable_sleep"] = enableSleep; scene_setting["draw_axis"] = drawAxis; scene_setting["draw_grid"] = drawGrid; scene_setting["draw_shapes"] = drawShapes; scene_setting["draw_joints"] = drawJoints; scene_setting["draw_aabbs"] = drawAABBs; scene_setting["draw_contact_points"] = drawContactPoints; scene_setting["draw_contact_normals"] = drawContactNormals; scene_setting["draw_contact_impulse"] = drawContactImpulse; scene_setting["draw_coms"] = drawCOMs; scene_setting["draw_stats"] = drawStats; scene_setting["draw_profile"] = drawProfile; return scene_setting; } SceneSetting SceneSetting::fromJson(nlohmann::json setting) { SceneSetting scene_setting; scene_setting.hz = setting["frequency"]; scene_setting.gravity = graphics::vectorFromJson<b2Vec2>(setting["gravity"]); scene_setting.viewCenter = graphics::vectorFromJson<b2Vec2>(setting["view_center"]); scene_setting.velocityIterations = setting["velocity_iterations"]; scene_setting.positionIterations = setting["position_iterations"]; scene_setting.enableWarmStarting = setting["enable_warm_starting"]; scene_setting.enableContinuous = setting["enable_continuous"]; scene_setting.enableSubStepping = setting["enable_sub_stepping"]; scene_setting.enableSleep = setting["enable_sleep"]; scene_setting.drawAxis = setting["draw_axis"]; scene_setting.drawGrid = setting["draw_grid"]; scene_setting.drawShapes = setting["draw_shapes"]; scene_setting.drawJoints = setting["draw_joints"]; scene_setting.drawAABBs = setting["draw_aabbs"]; scene_setting.drawContactPoints = setting["draw_contact_points"]; scene_setting.drawContactNormals = setting["draw_contact_normals"]; scene_setting.drawContactImpulse = setting["draw_contact_impulse"]; scene_setting.drawCOMs = setting["draw_coms"]; scene_setting.drawStats = setting["draw_stats"]; scene_setting.drawProfile = setting["draw_profile"]; return scene_setting; } //////////////////////////////////////////////////////////// //CameraSetting CameraSetting::CameraSetting() { defaultPosition.x = 0.f; defaultPosition.y = 0.f; defaultRotation = 0.f; defaultZoom = 0.f; position.x = 0.f; position.y = 0.f; rotation = 0.f; zoom = 0.f; }; nlohmann::json CameraSetting::toJson() { nlohmann::json camera_setting; camera_setting["default_position"] = {{"x", defaultPosition.x}, {"y", defaultPosition.y}}; camera_setting["default_rotation"] = defaultRotation; camera_setting["default_zoom"] = defaultZoom; camera_setting["position"] = {{"x", position.x}, {"y", position.y}}; camera_setting["rotation"] = rotation; camera_setting["zoom"] = zoom; return camera_setting; } CameraSetting CameraSetting::fromJson(nlohmann::json setting) { CameraSetting camera_setting; camera_setting.defaultPosition.x = setting["default_position"]["x"]; camera_setting.defaultPosition.y = setting["default_position"]["y"]; camera_setting.defaultRotation = setting["default_rotation"]; camera_setting.defaultZoom = setting["default_zoom"]; camera_setting.position.x = setting["position"]["x"]; camera_setting.position.y = setting["position"]["y"]; camera_setting.rotation = setting["rotation"]; camera_setting.zoom = setting["zoom"]; return camera_setting; } //////////////////////////////////////////////////////////// //Target CameraTarget::CameraTarget() { target = nullptr; offsetLeft = 150.f; offsetRight = 0.f; offsetUp = 250.f; offsetDown = 0.f; followTarget = false; } }
35.106796
98
0.53927
NeroGames
cb174c43dbb3556a123d9d3311e26c54683f224d
538
cpp
C++
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
Problems/PTA/B1008.cpp
five-5/code
9c20757b1d4a087760c51da7d3dcdcc2b17aee07
[ "Apache-2.0" ]
null
null
null
#include <iostream> #define maxn 101 int main() { int n, m; int a[maxn]; std::cin >> n >> m; for (int i = 0; i < n; ++i) { std::cin >> a[i]; } m = m % n; if (m == 0) { std::cout << a[0]; for (int i = 1; i < n; ++i) { std::cout << " " << a[i]; } } else { int start = n - m; std::cout << a[start]; for (int i = 1; i < n; ++i) { std::cout << " " << a[(start+i)%n]; } } std::cout << std::endl; return 0; }
19.925926
47
0.343866
five-5
0e157a9783dc97f2a93951437eef491917042999
540
cpp
C++
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
8
2021-02-14T13:13:27.000Z
2022-01-08T23:58:32.000Z
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
17
2021-02-28T17:03:50.000Z
2021-10-19T13:02:03.000Z
Array/Sorting/Insertion Sort/Solution_By_Shourya.cpp
surajshah123/Fork_CPP
c85ec3464382db298f2dbac443f3379dd1c1f4a6
[ "MIT" ]
15
2021-03-01T03:54:29.000Z
2021-10-19T18:29:00.000Z
#include <iostream> using namespace std; void insert_sort(int a[], int n){ int temp, k; for (int i = 1; i < n; i++){ k = i; temp = a[k]; for (int j = i - 1; j >= 0; j--){ if (a[j] > temp){ a[k] = a[j]; k--; } } a[k] = temp; } for (int i = 0; i < n; i++){ cout << a[i] << " "; } } int main(){ int n; cin >> n; int a[n]; for (int i = 0; i < n; i++){ cin >> a[i]; } insert_sort(a, n); }
18.62069
41
0.331481
surajshah123
0e15d56105e78a9c42e1d2214c2c580d4caa32ed
53
hpp
C++
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_spirit_home_karma_action_action.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/spirit/home/karma/action/action.hpp>
26.5
52
0.792453
miathedev
0e167340937c0ec900368346616cf65d0432ba4d
315
cpp
C++
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
src/body.cpp
awinabi/capybara-webkit-0.13.0
84e70bad13e9c137bdf77a2af61bbb7ab7f30a77
[ "MIT" ]
null
null
null
#include "Body.h" #include "WebPage.h" #include "WebPageManager.h" Body::Body(WebPageManager *manager, QStringList &arguments, QObject *parent) : SocketCommand(manager, arguments, parent) { } void Body::start() { QString result = page()->currentFrame()->toHtml(); emit finished(new Response(true, result)); }
26.25
122
0.720635
awinabi
0e1cd4dfd145316d3d09108749e51e5356a31259
2,220
hh
C++
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
src/include/syntax/source.hh
awfeequdng/px_cppgo
5a102fce4c919ce93af247deb68241480374bf01
[ "MIT" ]
null
null
null
#pragma once #include "common/types.hh" #include "common/utf8/rune.hh" #include "common/hex_formatter.hh" #include <vector> #include <string> #include <iostream> #include <tuple> #include <fstream> template <typename T> std::vector<T> slice(std::vector<T>& v, std::size_t low, std::size_t high = -1) { std::vector<T> vec; if (high == -1) { std::copy(v.begin() + low, v.end(), std::back_inserter(vec)); } else { std::copy(v.begin() + low, v.begin() + high, std::back_inserter(vec)); } return vec; } namespace syntax { int64_t nextSize(int64_t size); typedef void (*err_handler)(uint line, uint col, std::string msg); // The source buffer is accessed using three indices b (begin), // r (read), and e (end): // // - If b >= 0, it points to the beginning of a segment of most // recently read characters (typically a Go literal). // // - r points to the byte immediately following the most recently // read character ch, which starts at r-chw. // // - e points to the byte immediately following the last byte that // was read into the buffer. // // The buffer content is terminated at buf[e] with the sentinel // character utf8.RuneSelf. This makes it possible to test for // the common case of ASCII characters with a single 'if' (see // nextch method). // // +------ content in use -------+ // v v // buf [...read...|...segment...|ch|...unread...|s|...free...] // ^ ^ ^ ^ // | | | | // b r-chw r e // // Invariant: -1 <= b < r <= e < len(buf) && buf[e] == sentinel struct source { std::ifstream _ifs; err_handler _errh{}; std::string _buf; int64_t _b; int64_t _r; int64_t _e; int _line; int _col; common::utf8::rune_t _ch; int _chw; void init(std::string file, err_handler errh); std::pair<int, int> pos(); void error(std::string msg); void start(); void stop(); // std::string segment() { return slice(buf, b, r - chw); } std::string segment(); void rewind(); void nextch(); void fill(); }; } // namespace syntax
25.813953
81
0.569369
awfeequdng
0e1cfe242aa6f0b92124df6d11ada3782f41ea01
5,531
cpp
C++
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
//<Snippet1> #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class ListViewInsertionMarkExample: public Form { private: ListView^ myListView; public: //<Snippet2> ListViewInsertionMarkExample() { // Initialize myListView. myListView = gcnew ListView; myListView->Dock = DockStyle::Fill; myListView->View = View::LargeIcon; myListView->MultiSelect = false; myListView->ListViewItemSorter = gcnew ListViewIndexComparer; // Initialize the insertion mark. myListView->InsertionMark->Color = Color::Green; // Add items to myListView. myListView->Items->Add( "zero" ); myListView->Items->Add( "one" ); myListView->Items->Add( "two" ); myListView->Items->Add( "three" ); myListView->Items->Add( "four" ); myListView->Items->Add( "five" ); // Initialize the drag-and-drop operation when running // under Windows XP or a later operating system. if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) ) { myListView->AllowDrop = true; myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag ); myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter ); myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver ); myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave ); myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop ); } // Initialize the form. this->Text = "ListView Insertion Mark Example"; this->Controls->Add( myListView ); } private: //</Snippet2> // Starts the drag-and-drop operation when an item is dragged. void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e ) { myListView->DoDragDrop( e->Item, DragDropEffects::Move ); } // Sets the target drop effect. void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e ) { e->Effect = e->AllowedEffect; } //<Snippet3> // Moves the insertion mark as the item is dragged. void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e ) { // Retrieve the client coordinates of the mouse pointer. Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) ); // Retrieve the index of the item closest to the mouse pointer. int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint ); // Confirm that the mouse pointer is not over the dragged item. if ( targetIndex > -1 ) { // Determine whether the mouse pointer is to the left or // the right of the midpoint of the closest item and set // the InsertionMark.AppearsAfterItem property accordingly. Rectangle itemBounds = myListView->GetItemRect( targetIndex ); if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) ) { myListView->InsertionMark->AppearsAfterItem = true; } else { myListView->InsertionMark->AppearsAfterItem = false; } } // Set the location of the insertion mark. If the mouse is // over the dragged item, the targetIndex value is -1 and // the insertion mark disappears. myListView->InsertionMark->Index = targetIndex; } //</Snippet3> // Removes the insertion mark when the mouse leaves the control. void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ ) { myListView->InsertionMark->Index = -1; } // Moves the item to the location of the insertion mark. void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e ) { // Retrieve the index of the insertion mark; int targetIndex = myListView->InsertionMark->Index; // If the insertion mark is not visible, exit the method. if ( targetIndex == -1 ) { return; } // If the insertion mark is to the right of the item with // the corresponding index, increment the target index. if ( myListView->InsertionMark->AppearsAfterItem ) { targetIndex++; } // Retrieve the dragged item. ListViewItem^ draggedItem = dynamic_cast<ListViewItem^>(e->Data->GetData( ListViewItem::typeid )); // Insert a copy of the dragged item at the target index. // A copy must be inserted before the original item is removed // to preserve item index values. myListView->Items->Insert( targetIndex, dynamic_cast<ListViewItem^>(draggedItem->Clone()) ); // Remove the original copy of the dragged item. myListView->Items->Remove( draggedItem ); } // Sorts ListViewItem objects by index. ref class ListViewIndexComparer: public System::Collections::IComparer { public: virtual int Compare( Object^ x, Object^ y ) { return (dynamic_cast<ListViewItem^>(x))->Index - (dynamic_cast<ListViewItem^>(y))->Index; } }; }; [STAThread] int main() { Application::EnableVisualStyles(); Application::Run( gcnew ListViewInsertionMarkExample ); } //</Snippet1>
34.354037
175
0.661906
BohdanMosiyuk
0e2c76aecec8ee5d094920e5075b9b368b208575
7,992
cpp
C++
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
1
2022-03-09T23:29:29.000Z
2022-03-09T23:29:29.000Z
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
null
null
null
eprp/eprp.cpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
null
null
null
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include <ctype.h> #include <algorithm> #include "eprp.hpp" void Eprp::eat_comments() { while (scan_is_token(Token_id_comment) && !scan_is_end()) scan_next(); } // rule_path = (\. | alnum | / | "asdad.." | \,)+ bool Eprp::rule_path(std::string &path) { assert(!scan_is_end()); if (!(scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) || scan_is_token(Token_id_div))) return false; do { absl::StrAppend(&path, scan_text()); ast->add(Eprp_rule_path, scan_token()); bool ok = scan_next(); if (!ok) break; eat_comments(); if (scan_is_next_token(1, Token_id_colon)) break; // stop if file:foo is the next argument list } while (scan_is_token(Token_id_dot) || scan_is_token(Token_id_alnum) || scan_is_token(Token_id_string) || scan_is_token(Token_id_comma) || scan_is_token(Token_id_div)); return true; } // rule_label_path = label path bool Eprp::rule_label_path(const std::string &cmd_line, Eprp_var &next_var) { if (!(scan_is_token(Token_id_alnum) && scan_is_next_token(1, Token_id_colon))) return false; auto label = scan_text(); ast->add(Eprp_rule_label_path, scan_token()); scan_next(); // Skip alnum token scan_next(); // Skip colon token eat_comments(); if (scan_is_end()) { scan_error("the {} field in {} command has no argument", label, cmd_line); return false; } std::string path; ast->down(); bool ok = rule_path(path); ast->up(Eprp_rule_label_path); if (!ok) { if (scan_is_token(Token_id_register)) { scan_error("could not pass a register {} to a method {}", scan_text(), cmd_line); } else { scan_error("field {} with invalid value in {} command", label, cmd_line); } return false; } next_var.add(label, path); return true; } // rule_reg = reg+ bool Eprp::rule_reg(bool first) { if (!scan_is_token(Token_id_register)) return false; std::string var{scan_text()}; ast->add(Eprp_rule_reg, scan_token()); if (first) { // First in line #a |> ... if (variables.find(var) == variables.end()) { scan_error("variable {} is empty", var); return false; } last_cmd_var = variables[var]; } else { variables[var] = last_cmd_var; } scan_next(); eat_comments(); return true; } // rule_cmd_line = alnum (dot alnum)* bool Eprp::rule_cmd_line(std::string &path) { if (scan_is_end()) return false; if (!scan_is_token(Token_id_alnum)) return false; do { absl::StrAppend(&path, scan_text()); // Add the Token_id_alnum ast->add(Eprp_rule_cmd_line, scan_token()); bool ok1 = scan_next(); if (!ok1) break; if (!scan_is_token(Token_id_dot)) break; absl::StrAppend(&path, scan_text()); // Add the Token_id_dot ast->add(Eprp_rule_cmd_line, scan_token()); bool ok2 = scan_next(); if (!ok2) break; } while (scan_is_token(Token_id_alnum)); eat_comments(); return true; } // rule_cmd_full =rule_cmd_line rule_label_path* bool Eprp::rule_cmd_full() { std::string cmd_line; Eprp_var next_var; ast->down(); bool cmd_found = rule_cmd_line(cmd_line); ast->up(Eprp_rule_cmd_full); if (!cmd_found) return false; bool path_found; do { ast->down(); path_found = rule_label_path(cmd_line, next_var); ast->up(Eprp_rule_cmd_full); } while (path_found); ast->down(); run_cmd(cmd_line, next_var); ast->up(Eprp_rule_cmd_full); return true; } // rule_pipe = |> rule_cmd_or_reg bool Eprp::rule_pipe() { if (scan_is_end()) return false; if (!scan_is_token(Token_id_pipe)) return false; scan_next(); eat_comments(); ast->down(); bool try_either = rule_cmd_or_reg(false); ast->up(Eprp_rule_pipe); if (!try_either) { scan_error("after a pipe there should be a register or a command"); return false; } return true; } // rule_cmd_or_reg = rule_reg | rule_cmd_full bool Eprp::rule_cmd_or_reg(bool first) { ast->down(); bool try_reg_rule = rule_reg(first); ast->up(Eprp_rule_cmd_or_reg); if (try_reg_rule) return true; ast->down(); bool cmd_found = rule_cmd_full(); ast->up(Eprp_rule_cmd_or_reg); return cmd_found; } // rule_top = rule_cmd_or_reg(first) rule_pipe* bool Eprp::rule_top() { ast->down(); bool try_either = rule_cmd_or_reg(true); ast->up(Eprp_rule_top); if (!try_either) { scan_error("statements start with a register or a command"); return false; } // tree.add_lazy_child(1); bool try_pipe = rule_pipe(); if (!try_pipe) { if (scan_is_token(Token_id_or)) { scan_error("eprp pipe is |> not |"); return false; } else if (scan_is_end()) { return true; } else { scan_error("invalid command"); return false; } } // tree.add_lazy_child(1); while (rule_pipe()) { // tree.add_lazy_child(1); ; } return true; } // top = parse_top+ void Eprp::elaborate() { ast = std::make_unique<Ast_parser>(get_memblock(), Eprp_rule); ast->down(); while (!scan_is_end()) { eat_comments(); if (scan_is_end()) return; bool cmd = rule_top(); if (!cmd) return; } ast->up(Eprp_rule); //process_ast(); ast = nullptr; last_cmd_var.clear(); }; void Eprp::process_ast_handler(const mmap_lib::Tree_index &self, const Ast_parser_node &node) { auto txt = scan_text(node.token_entry); fmt::print("level:{} pos:{} te:{} rid:{} txt:{}\n", self.level, self.pos, node.token_entry, node.rule_id, txt); if (node.rule_id == Eprp_rule_cmd_or_reg) { std::string children_txt; // HERE: Children should iterate FAST, over all the children recursively // HERE: Move this iterate over children as a handle_command for (const auto &ti : ast->children(self)) { auto txt2 = scan_text(ast->get_data(ti).token_entry); if (ast->get_data(ti).rule_id == Eprp_rule_label_path) absl::StrAppend(&children_txt, " ", txt2, ":"); else absl::StrAppend(&children_txt, txt2); } fmt::print(" children: {}\n", children_txt); } } void Eprp::process_ast() { for(const auto &ti:ast->depth_preorder(ast->get_root())) { fmt::print("ti.level:{} ti.pos:{}\n", ti.level, ti.pos); } ast->each_bottom_up_fast(std::bind(&Eprp::process_ast_handler, this, std::placeholders::_1, std::placeholders::_2)); } void Eprp::run_cmd(const std::string &cmd, Eprp_var &var) { const auto &it = methods.find(cmd); if (it == methods.end()) { parser_error("method {} not registered", cmd); return; } const auto &m = it->second; last_cmd_var.add(var); std::string err_msg; bool err = m.check_labels(last_cmd_var, err_msg); if (err) { parser_error(err_msg); return; } #if 0 for(const auto &v:var.dict) { if (!m.has_label(v.first)) { parser_warn("method {} does not have passed label {}", cmd, v.first); } } #endif for (const auto &label : m.labels) { if (!label.second.default_value.empty() && !last_cmd_var.has_label(label.first)) last_cmd_var.add(label.first, label.second.default_value); } m.method(last_cmd_var); } const std::string &Eprp::get_command_help(const std::string &cmd) const { const auto &it = methods.find(cmd); if (it == methods.end()) { static const std::string empty = ""; return empty; } return it->second.help; } void Eprp::get_commands(std::function<void(const std::string &, const std::string &)> fn) const { for (const auto &v : methods) { fn(v.first, v.second.help); } } void Eprp::get_labels(const std::string & cmd, std::function<void(const std::string &, const std::string &, bool required)> fn) const { const auto &it = methods.find(cmd); if (it == methods.end()) return; for (const auto &v : it->second.labels) { fn(v.first, v.second.help, v.second.required); } } Eprp::Eprp() {}
24.145015
118
0.646021
milad621
0e2ef69313c2609d4b2d4d9e3e853a5dc38131e8
449
cpp
C++
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
void_data.cpp
shirishbahirat/algorithm
ec743d4c16ab4f429f22bd6f71540341b3905b3b
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int a[6] = {[4] = 29, [2] = 15}; struct node { int data; node *next; node(int d) : data(d), next(NULL) {} }; int add_node(void *data) { node *n = (node *)data; cout << n->data << endl; return 0; } int main(int argc, char const *argv[]) { node *n1 = new node(1000); add_node((void *)n1); for (int i = 0; i < 6; ++i) { cout << a[i] << " "; } cout << endl; return 0; }
11.512821
38
0.514477
shirishbahirat
0e317907bb73e475fe9114aaa47362016e00f1af
6,413
cpp
C++
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
3
2021-07-26T04:03:47.000Z
2021-08-31T15:17:29.000Z
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
null
null
null
SuperMarioBros3/IntroScene.cpp
ThienUIT/Super-Mario-Bros-3
dc14eaa6a20b17a9ec13908e7e42947662c26005
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include "IntroScene.h" #include "Textures.h" #include "Utils.h" #include "Brick.h" #include "IntroGround.h" #include "Leaf.h" #include "MushRoom.h" #include "Goomba.h" #include "Koopas.h" using namespace std; CIntroScene::CIntroScene(int id, LPCWSTR filePath) : CScene(id, filePath) { key_handler = new IntroSceneKeyHandler(this); BackGround = nullptr; Three = nullptr; Arrow = nullptr; //StartScrolling(); } void CIntroScene::_ParseSection_TEXTURES(string line) { vector<string> tokens = split(line); if (tokens.size() < 5) return; // skip invalid lines int texID = atoi(tokens[0].c_str()); wstring path = ToWSTR(tokens[1]); int R = atoi(tokens[2].c_str()); int G = atoi(tokens[3].c_str()); int B = atoi(tokens[4].c_str()); CTextures::GetInstance()->Add(texID, path.c_str(), D3DCOLOR_XRGB(R, G, B)); } void CIntroScene::_ParseSection_SPRITES(string line) { vector<string> tokens = split(line); if (tokens.size() < 6) return; // skip invalid lines int ID = atoi(tokens[0].c_str()); int l = atoi(tokens[1].c_str()); int t = atoi(tokens[2].c_str()); int r = atoi(tokens[3].c_str()); int b = atoi(tokens[4].c_str()); int texID = atoi(tokens[5].c_str()); LPDIRECT3DTEXTURE9 tex = CTextures::GetInstance()->Get(texID); if (tex == NULL) { DebugOut(L"[ERROR] Texture ID %d not found!\n", texID); return; } CSprites::GetInstance()->Add(ID, l, t, r, b, tex); } void CIntroScene::_ParseSection_ANIMATIONS(string line) { vector<string> tokens = split(line); if (tokens.size() < 3) return; // skip invalid lines - an animation must at least has 1 frame and 1 frame time //DebugOut(L"--> %s\n",ToWSTR(line).c_str()); LPANIMATION ani = new CAnimation(); int ani_id = atoi(tokens[0].c_str()); for (unsigned int i = 1; i < tokens.size(); i += 2) // why i+=2 ? sprite_id | frame_time { int sprite_id = atoi(tokens[i].c_str()); int frame_time = atoi(tokens[i + 1].c_str()); ani->Add(sprite_id, frame_time); } CAnimations::GetInstance()->Add(ani_id, ani); if (ani_id == 800) Three = ani; } void CIntroScene::_ParseSection_ANIMATION_SETS(string line) { vector<string> tokens = split(line); if (tokens.size() < 2) return; // skip invalid lines - an animation set must at least id and one animation id //DebugOut(L"--> %s\n", ToWSTR(line).c_str()); int ani_set_id = atoi(tokens[0].c_str()); LPANIMATION_SET s; if (CAnimationSets::GetInstance()->animation_sets[ani_set_id] != NULL) s = CAnimationSets::GetInstance()->animation_sets[ani_set_id]; else s = new CAnimationSet(); CAnimations* animations = CAnimations::GetInstance(); for (unsigned int i = 1; i < tokens.size(); i++) { int ani_id = atoi(tokens[i].c_str()); LPANIMATION ani = animations->Get(ani_id); s->push_back(ani); } CAnimationSets::GetInstance()->Add(ani_set_id, s); if (ani_set_id == ANISET_BACKGROUND_ID) BackGround = s; if (ani_set_id == ANISET_ARROW_ID) Arrow = s; } void CIntroScene::_ParseSection_OBJECTS(string line) { vector<string> tokens = split(line); if (tokens.size() < 3) return; // skip invalid lines - an object set must have at least id, x, y int tag = 0, option_tag_1 = 0, option_tag_2 = 0; int object_type = atoi(tokens[0].c_str()); float x = (float)atof(tokens[1].c_str()); float y = (float)atof(tokens[2].c_str()); int ani_set_id = atoi(tokens[3].c_str()); if (tokens.size() >= 5) tag = (int)atof(tokens[4].c_str()); if (tokens.size() >= 6) option_tag_1 = (int)atof(tokens[5].c_str()); if (tokens.size() >= 7) option_tag_2 = (int)atof(tokens[6].c_str()); CAnimationSets* animation_sets = CAnimationSets::GetInstance(); CGameObject* obj = NULL; switch (object_type) { case OBJECT_TYPE_GROUND: obj = new CIntroGround(); break; default: DebugOut(L"[ERR] Invalid object type: %d\n", object_type); return; } obj->SetPosition(x, y); LPANIMATION_SET ani_set = animation_sets->Get(ani_set_id); obj->SetAnimationSet(ani_set); objects.push_back(obj); } void CIntroScene::Update(DWORD dt) { if (switchTimer.ElapsedTime() >= SWITCH_TIME && switchTimer.IsStarted()) { CGame::GetInstance()->SwitchScene(WORLD_SCENE_ID); } } void CIntroScene::Load() { DebugOut(L"[INFO] Start loading scene resources from : %s \n", sceneFilePath); ifstream f; f.open(sceneFilePath); // current resource section flag int section = SCENE_SECTION_UNKNOWN; DebugOut(L"%d", section); char str[MAX_SCENE_LINE]; while (f.getline(str, MAX_SCENE_LINE)) { string line(str); if (line[0] == '#') continue; // skip comment lines if (line == "[TEXTURES]") { section = SCENE_SECTION_TEXTURES; continue; } if (line == "[SPRITES]") { section = SCENE_SECTION_SPRITES; continue; } if (line == "[ANIMATIONS]") { section = SCENE_SECTION_ANIMATIONS; continue; } if (line == "[ANIMATION_SETS]") { section = SCENE_SECTION_ANIMATION_SETS; continue; } if (line == "[OBJECTS]") { section = SCENE_SECTION_OBJECTS; continue; } if (line[0] == '[' || line == "") { section = SCENE_SECTION_UNKNOWN; continue; } // // data section // switch (section) { case SCENE_SECTION_TEXTURES: _ParseSection_TEXTURES(line); break; case SCENE_SECTION_SPRITES: _ParseSection_SPRITES(line); break; case SCENE_SECTION_ANIMATIONS: _ParseSection_ANIMATIONS(line); break; case SCENE_SECTION_ANIMATION_SETS: _ParseSection_ANIMATION_SETS(line); break; case SCENE_SECTION_OBJECTS: _ParseSection_OBJECTS(line); break; } } f.close(); CTextures::GetInstance()->Add(ID_TEX_BBOX, L"Resources\\Textures\\bbox.png", D3DCOLOR_XRGB(255, 255, 255)); DebugOut(L"[INFO] Done loading scene resources %s\n", sceneFilePath); } void CIntroScene::Render() { BackGround->at(3)->Render(0, 0); Three->Render(THREE_X, THREE_Y); for (size_t i = 0; i < objects.size(); i++) objects[i]->Render(); if (switchTimer.IsStarted()) Arrow->at(0)->Render(ARROW_X, ARROW_Y); else Arrow->at(1)->Render(ARROW_X, ARROW_Y); } void CIntroScene::Unload() { for (size_t i = 2; i < objects.size(); i++) delete objects[i]; objects.clear(); BackGround = NULL; Arrow = NULL; Three = NULL; switchTimer.Reset(); DebugOut(L"Unload Intro Scene\n"); } void IntroSceneKeyHandler::OnKeyDown(int KeyCode) { CIntroScene* intro = ((CIntroScene*)CGame::GetInstance()->GetCurrentScene()); switch (KeyCode) { case DIK_RETURN: intro->switchTimer.Start(); DebugOut(L"Enter"); break; default: break; } }
27.059072
111
0.684703
ThienUIT
0e3243e42b424f841913651fb56b4e6d859e1e8c
10,153
cpp
C++
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
test/variant_add.t.cpp
sheehamj13/task
67ed9cadfcbccf1f1071fc1b04cde61a2aba2f69
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2013 - 2015, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <iostream> #include <test.h> #include <Variant.h> #include <Context.h> Context context; #define EPSILON 0.001 //////////////////////////////////////////////////////////////////////////////// int main (int, char**) { UnitTest t (80); Variant v0 (true); Variant v1 (42); Variant v2 (3.14); Variant v3 ("foo"); Variant v4 (1234567890, Variant::type_date); Variant v5 (1200, Variant::type_duration); // boolean + boolean -> ERROR try {Variant v00 = v0 + v0; t.fail ("true + true --> error");} catch (...) {t.pass ("true + true --> error");} // boolean + integer -> integer Variant v01 = v0 + v1; t.is (v01.type (), Variant::type_integer, "true + 42 --> integer"); t.is (v01.get_integer (), 43, "true + 42 --> 43"); // boolean + real -> real Variant v02 = v0 + v2; t.is (v02.type (), Variant::type_real, "true + 3.14 --> real"); t.is (v02.get_real (), 4.14, EPSILON, "true + 3.14 --> 4.14"); // boolean + string -> string Variant v03 = v0 + v3; t.is (v03.type (), Variant::type_string, "true + foo --> string"); t.is (v03.get_string (), "truefoo", "true + foo --> truefoo"); // boolean + date -> date Variant v04 = v0 + v4; t.is (v04.type (), Variant::type_date, "true + 1234567890 --> date"); t.is (v04.get_date (), "1234567891", "true + 1234567890 --> 1234567891"); // boolean + duration -> duration Variant v05 = v0 + v5; t.is (v05.type (), Variant::type_duration, "true + 1200 --> duration"); t.is (v05.get_duration (), "1201", "true + 1200 --> 1201"); // integer + boolean -> integer Variant v10 = v1 + v0; t.is (v10.type (), Variant::type_integer, "42 + true --> integer"); t.is (v10.get_integer (), 43, "42 + true --> 43"); // integer + integer -> integer Variant v11 = v1 + v1; t.is (v11.type (), Variant::type_integer, "42 + 42 --> integer"); t.is (v11.get_integer (), 84, "42 + 42 --> 84"); // integer + real -> real Variant v12 = v1 + v2; t.is (v12.type (), Variant::type_real, "42 + 3.14 --> real"); t.is (v12.get_real (), 45.14, EPSILON, "42 + 3.14 --> 45.14"); // integer + string -> string Variant v13 = v1 + v3; t.is (v13.type (), Variant::type_string, "42 + foo --> string"); t.is (v13.get_string (), "42foo", "42 + foo --> 42foo"); // integer + date -> date Variant v14 = v1 + v4; t.is (v14.type (), Variant::type_date, "42 + 1234567890 --> date"); t.is (v14.get_date (), 1234567932, "42 + 1234567890 --> 1234567932"); // integer + duration -> duration Variant v15 = v1 + v5; t.is (v15.type (), Variant::type_duration, "42 + 1200 --> duration"); t.is (v15.get_duration (), 1242, "42 + 1200 --> 1242"); // real + boolean -> real Variant v20 = v2 + v0; t.is (v20.type (), Variant::type_real, "3.14 + true --> real"); t.is (v20.get_real (), 4.14, EPSILON, "3.14 + true --> 4.14"); // real + integer -> real Variant v21 = v2 + v1; t.is (v21.type (), Variant::type_real, "3.14 + 42 --> real"); t.is (v21.get_real (), 45.14, EPSILON, "3.14 + 42 --> 45.14"); // real + real -> real Variant v22 = v2 + v2; t.is (v22.type (), Variant::type_real, "3.14 + 3.14 --> real"); t.is (v22.get_real (), 6.28, EPSILON, "3.14 + 3.14 --> 6.28"); // real + string -> string Variant v23 = v2 + v3; t.is (v23.type (), Variant::type_string, "3.14 + foo --> string"); t.is (v23.get_string (), "3.14foo", "3.14 + foo --> 3.14foo"); // real + date -> date Variant v24 = v2 + v4; t.is (v24.type (), Variant::type_date, "3.14 + 1234567890 --> date"); t.is (v24.get_date (), 1234567893, "3.14 + 1234567890 --> 1234567893"); // real + duration -> duration Variant v25 = v2 + v5; t.is (v25.type (), Variant::type_duration, "3.14 + 1200 --> duration"); t.is (v25.get_duration (), 1203, "3.14 + 1200 --> 1203"); // string + boolean -> string Variant v30 = v3 + v0; t.is (v30.type (), Variant::type_string, "foo + true --> string"); t.is (v30.get_string (), "footrue", "foo + true --> footrue"); // string + integer -> string Variant v31 = v3 + v1; t.is (v31.type (), Variant::type_string, "foo + 42 --> string"); t.is (v31.get_string (), "foo42", "foo + 42 --> foo42"); // string + real -> string Variant v32 = v3 + v2; t.is (v32.type (), Variant::type_string, "foo + 3.14 --> string"); t.is (v32.get_string (), "foo3.14", "foo + 3.14 --> foo3.14"); // string + string -> string Variant v33 = v3 + v3; t.is (v33.type (), Variant::type_string, "foo + foo --> string"); t.is (v33.get_string (), "foofoo", "foo + foo --> foofoo"); // string + date -> string Variant v34 = v3 + v4; t.is (v34.type (), Variant::type_string, "foo + 1234567890 --> string"); std::string s = v34.get_string (); t.is ((int)s[7], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[10], (int)'-', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[13], (int)'T', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[16], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s[19], (int)':', "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); t.is ((int)s.length (), 22, "foo + 1234567890 --> fooYYYY-MM-DDThh:mm:ss"); // string + duration -> string Variant v35 = v3 + v5; t.is (v35.type (), Variant::type_string, "foo + 1200 --> string"); t.is (v35.get_string (), "fooPT20M", "foo + 1200 --> fooPT20M"); // date + boolean -> date Variant v40 = v4 + v0; t.is (v40.type (), Variant::type_date, "1234567890 + true --> date"); t.is (v40.get_date (), 1234567891, "1234567890 + true --> 1234567891"); // date + integer -> date Variant v41 = v4 + v1; t.is (v41.type (), Variant::type_date, "1234567890 + 42 --> date"); t.is (v41.get_date (), 1234567932, "1234567890 + 42 --> 1234567932"); // date + real -> date Variant v42 = v4 + v2; t.is (v42.type (), Variant::type_date, "1234567890 + 3.14 --> date"); t.is (v42.get_date (), 1234567893, "1234567890 + 3.14 --> 1234567893"); // date + string -> string Variant v43 = v4 + v3; t.is (v43.type (), Variant::type_string, "1234567890 + foo --> string"); s = v43.get_string (); t.is ((int)s[4], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[7], (int)'-', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[10], (int)'T', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[13], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s[16], (int)':', "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); t.is ((int)s.length (), 22, "1234567890 + foo --> YYYY-MM-DDThh:mm:ssfoo"); // date + date -> ERROR try {Variant v44 = v4 + v4; t.fail ("1234567890 + 1234567890 --> error");} catch (...) {t.pass ("1234567890 + 1234567890 --> error");} // date + duration -> date Variant v45 = v4 + v5; t.is (v45.type (), Variant::type_date, "1234567890 + 1200 --> date"); t.is (v45.get_date (), 1234569090, "1234567890 + 1200 --> 1234569090"); // duration + boolean -> duration Variant v50 = v5 + v0; t.is (v50.type (), Variant::type_duration, "1200 + true --> duration"); t.is (v50.get_duration (), 1201, "1200 + true --> 1201"); // duration + integer -> duration Variant v51 = v5 + v1; t.is (v51.type (), Variant::type_duration, "1200 + 42 --> duration"); t.is (v51.get_duration (), 1242, "1200 + 42 --> 1242"); // duration + real -> duration Variant v52 = v5 + v2; t.is (v52.type (), Variant::type_duration, "1200 + 3.14 --> duration"); t.is (v52.get_duration (), 1203, "1200 + 3.14 --> 1203"); // duration + string -> string Variant v53 = v5 + v3; t.is (v53.type (), Variant::type_string, "1200 + foo --> string"); t.is (v53.get_string (), "PT20Mfoo", "1200 + foo --> PT20Mfoo"); // duration + date -> date Variant v54 = v5 + v4; t.is (v54.type (), Variant::type_date, "1200 + 1234567890 --> date"); t.is (v54.get_date (), 1234569090, "1200 + 1234567890 --> 1234569090"); // duration + duration -> duration Variant v55 = v5 + v5; t.is (v55.type (), Variant::type_duration, "1200 + 1200 --> duration"); t.is (v55.get_duration (), 2400, "1200 + 1200 --> 2400"); return 0; } ////////////////////////////////////////////////////////////////////////////////
41.781893
92
0.547424
sheehamj13
0e33ea5cfe8ffe7b19dfe9e067fc572c542facfe
9,190
cpp
C++
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
1
2021-11-26T13:23:39.000Z
2021-11-26T13:23:39.000Z
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
null
null
null
Source/Model/Writer/NMR_ModelWriter_3MF_Native.cpp
qmuntal/lib3mf
ad82d2f17bd37b942635c9cc7a33e4ea060b7adf
[ "BSD-2-Clause" ]
null
null
null
/*++ Copyright (C) 2018 3MF Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Abstract: NMR_ModelWriter_3MF_Native.cpp implements the platform independent 3MF Model Writer Class. This model writer exports the in memory represenation into a 3MF file, using LibZ and a native XML writer implementation. --*/ #include "Model/Writer/NMR_ModelWriter_3MF_Native.h" #include "Model/Classes/NMR_ModelConstants.h" #include "Model/Classes/NMR_ModelAttachment.h" #include "Model/Classes/NMR_ModelTextureAttachment.h" #include "Model/Classes/NMR_ModelSliceResource.h" #include "Common/Platform/NMR_ImportStream.h" #include "Common/NMR_Exception.h" #include "Common/Platform/NMR_XmlWriter.h" #include "Common/Platform/NMR_XmlWriter_Native.h" #include "Common/Platform/NMR_ImportStream_Unique_Memory.h" #include "Common/Platform/NMR_ExportStream_Memory.h" #include "Common/NMR_StringUtils.h" #include "Common/3MF_ProgressMonitor.h" #include <functional> #include <sstream> namespace NMR { CModelWriter_3MF_Native::CModelWriter_3MF_Native(_In_ PModel pModel) : CModelWriter_3MF(pModel) { m_nRelationIDCounter = 0; m_pModel = nullptr; } // These are OPC dependent functions void CModelWriter_3MF_Native::createPackage(_In_ CModel * pModel) { __NMRASSERT(pModel != nullptr); m_pModel = pModel; m_nRelationIDCounter = 0; } void CModelWriter_3MF_Native::releasePackage() { m_pModel = nullptr; } void CModelWriter_3MF_Native::writePackageToStream(_In_ PExportStream pStream) { if (pStream.get() == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_pModel == nullptr) throw CNMRException(NMR_ERROR_NOMODELTOWRITE); // Write Model Stream POpcPackageWriter pPackageWriter = std::make_shared<COpcPackageWriter>(pStream); POpcPackagePart pModelPart = pPackageWriter->addPart(PACKAGE_3D_MODEL_URI); PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(pModelPart->getExportStream()); if (!m_pProgressMonitor->Progress(0.01, ProgressIdentifier::PROGRESS_WRITEROOTMODEL)) throw CNMRException(NMR_USERABORTED); writeModelStream(pXMLWriter.get(), m_pModel); // add Root relationships pPackageWriter->addRootRelationship(generateRelationShipID(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pModelPart.get()); PModelAttachment pPackageThumbnail = m_pModel->getPackageThumbnail(); if (pPackageThumbnail.get() != nullptr) { // create Package Thumbnail Part POpcPackagePart pThumbnailPart = pPackageWriter->addPart(pPackageThumbnail->getPathURI()); PExportStream pExportStream = pThumbnailPart->getExportStream(); // Copy data PImportStream pPackageThumbnailStream = pPackageThumbnail->getStream(); pPackageThumbnailStream->seekPosition(0, true); pExportStream->copyFrom(pPackageThumbnailStream.get(), pPackageThumbnailStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); // add root relationship pPackageWriter->addRootRelationship(generateRelationShipID(), pPackageThumbnail->getRelationShipType(), pThumbnailPart.get()); } if (!m_pProgressMonitor->Progress(0.5, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS)) throw CNMRException(NMR_USERABORTED); // add slicestacks that reference other files m_pProgressMonitor->PushLevel(0.5, 0.85); addSlicerefAttachments(m_pModel); m_pProgressMonitor->PopLevel(); // add Attachments if (!m_pProgressMonitor->Progress(0.85, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS)) throw CNMRException(NMR_USERABORTED); m_pProgressMonitor->PushLevel(0.85, 0.99); addAttachments(m_pModel, pPackageWriter, pModelPart); m_pProgressMonitor->PopLevel(); if (!m_pProgressMonitor->Progress(0.99, ProgressIdentifier::PROGRESS_WRITECONTENTTYPES)) throw CNMRException(NMR_USERABORTED); // add Content Types pPackageWriter->addContentType(PACKAGE_3D_RELS_EXTENSION, PACKAGE_3D_RELS_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_MODEL_EXTENSION, PACKAGE_3D_MODEL_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_TEXTURE_EXTENSION, PACKAGE_TEXTURE_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_PNG_EXTENSION, PACKAGE_PNG_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_JPEG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); pPackageWriter->addContentType(PACKAGE_3D_JPG_EXTENSION, PACKAGE_JPG_CONTENT_TYPE); std::map<std::string, std::string> CustomContentTypes = m_pModel->getCustomContentTypes(); std::map<std::string, std::string>::iterator iContentTypeIterator; for (iContentTypeIterator = CustomContentTypes.begin(); iContentTypeIterator != CustomContentTypes.end(); iContentTypeIterator++) { if (!m_pModel->contentTypeIsDefault(iContentTypeIterator->first)) { pPackageWriter->addContentType(iContentTypeIterator->first, iContentTypeIterator->second); } } } std::string CModelWriter_3MF_Native::generateRelationShipID() { // Create Unique ID String std::stringstream sStream; sStream << "rel" << m_nRelationIDCounter; m_nRelationIDCounter++; return sStream.str(); } void CModelWriter_3MF_Native::addSlicerefAttachments(_In_ CModel *pModel) { __NMRASSERT(pModel != nullptr); nfUint32 nCount = pModel->getSliceStackCount(); if (nCount > 0) { nfUint32 nIndex; for (nIndex = 0; nIndex < nCount; nIndex++) { if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITENONROOTMODELS)) throw CNMRException(NMR_USERABORTED); CModelSliceStackResource* pSliceStackResource = dynamic_cast<CModelSliceStackResource*>(pModel->getSliceStackResource(nIndex).get()); CSliceStack* pSliceStack = pSliceStackResource->getSliceStack().get(); if (pSliceStack->usesSliceRef()) { PExportStreamMemory p = std::make_shared<CExportStreamMemory>(); PXmlWriter_Native pXMLWriter = std::make_shared<CXmlWriter_Native>(p); writeSlicestackStream(pXMLWriter.get(), pModel, pSliceStackResource); PImportStream pStream = std::make_shared<CImportStream_Unique_Memory>(p->getData(), p->getDataSize()); // check, whether that's already in here PModelAttachment pSliceRefAttachment = m_pModel->findModelAttachment(pSliceStackResource->sliceRefPath()); if (pSliceRefAttachment.get() != nullptr) { if (pSliceRefAttachment->getRelationShipType() != PACKAGE_START_PART_RELATIONSHIP_TYPE) throw CNMRException(NMR_ERROR_DUPLICATEATTACHMENTPATH); pSliceRefAttachment->setStream(pStream); } else m_pModel->addAttachment(pSliceStackResource->sliceRefPath(), PACKAGE_START_PART_RELATIONSHIP_TYPE, pStream); } } } } void CModelWriter_3MF_Native::addAttachments(_In_ CModel * pModel, _In_ POpcPackageWriter pPackageWriter, _In_ POpcPackagePart pModelPart) { __NMRASSERT(pModel != nullptr); __NMRASSERT(pModelPart.get() != nullptr); __NMRASSERT(pPackageWriter.get() != nullptr); nfUint32 nCount = pModel->getAttachmentCount(); nfUint32 nIndex; if (nCount > 0) { for (nIndex = 0; nIndex < nCount; nIndex++) { if (!m_pProgressMonitor->Progress(double(nIndex) / nCount, ProgressIdentifier::PROGRESS_WRITEATTACHMENTS)) throw CNMRException(NMR_USERABORTED); PModelAttachment pAttachment = pModel->getModelAttachment(nIndex); PImportStream pStream = pAttachment->getStream(); std::string sPath = fnIncludeLeadingPathDelimiter(pAttachment->getPathURI()); std::string sRelationShipType = pAttachment->getRelationShipType(); if (pStream.get() == nullptr) throw CNMRException(NMR_ERROR_INVALIDPARAM); // create Texture Part POpcPackagePart pAttachmentPart = pPackageWriter->addPart(sPath); PExportStream pExportStream = pAttachmentPart->getExportStream(); // Copy data pStream->seekPosition(0, true); pExportStream->copyFrom(pStream.get(), pStream->retrieveSize(), MODELWRITER_NATIVE_BUFFERSIZE); // add relationships pModelPart->addRelationship(generateRelationShipID(), sRelationShipType.c_str(), pAttachmentPart->getURI()); } } } }
40.844444
139
0.783134
qmuntal
0e389f04c7c038d92b3fa332cfb5950e71b90f27
321
cpp
C++
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
3
2020-12-17T19:35:27.000Z
2021-09-29T09:34:51.000Z
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
null
null
null
src/actions/action.cpp
Spark-NF/organizer
d8bcd459f8bebcb76d07ce3a125246944d1a1824
[ "Apache-2.0" ]
1
2019-06-18T17:34:16.000Z
2019-06-18T17:34:16.000Z
#include "action.h" Action::Action(QString name, QKeySequence shortcut, bool terminal) : m_name(name), m_shortcut(shortcut), m_terminal(terminal) {} QString Action::name() const { return m_name; } QKeySequence Action::shortcut() const { return m_shortcut; } bool Action::terminal() const { return m_terminal; }
13.956522
66
0.732087
Spark-NF
0e3ac1f2b7da5a645ffa48ed25eb3dc94b4788ec
1,325
cpp
C++
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
Source/controls/menu_controls.cpp
julealgon/devilutionX
0c8e4edba1521a78d993a7eceba8bc1df7e28fd5
[ "Unlicense" ]
null
null
null
#include "controls/menu_controls.h" #include "DiabloUI/diabloui.h" #include "controls/remap_keyboard.h" #include "utils/sdl_compat.h" namespace devilution { MenuAction GetMenuAction(const SDL_Event &event) { if (event.type == SDL_KEYDOWN) { auto sym = event.key.keysym.sym; remap_keyboard_key(&sym); switch (sym) { case SDLK_UP: return MenuAction_UP; case SDLK_DOWN: return MenuAction_DOWN; case SDLK_TAB: if ((SDL_GetModState() & KMOD_SHIFT) != 0) return MenuAction_UP; else return MenuAction_DOWN; case SDLK_PAGEUP: return MenuAction_PAGE_UP; case SDLK_PAGEDOWN: return MenuAction_PAGE_DOWN; case SDLK_RETURN: { const Uint8 *state = SDLC_GetKeyState(); if (state[SDLC_KEYSTATE_LALT] == 0 && state[SDLC_KEYSTATE_RALT] == 0) { return MenuAction_SELECT; } break; } case SDLK_KP_ENTER: return MenuAction_SELECT; case SDLK_SPACE: if (!textInputActive) { return MenuAction_SELECT; } break; case SDLK_DELETE: return MenuAction_DELETE; case SDLK_LEFT: return MenuAction_LEFT; case SDLK_RIGHT: return MenuAction_RIGHT; case SDLK_ESCAPE: return MenuAction_BACK; default: break; } } return MenuAction_NONE; } // namespace devilution } // namespace devilution
22.457627
75
0.687547
julealgon
0e3e0ea60c16aa6aa2ce5a7a33fdc3f93013a929
956
cpp
C++
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2019-10-02T11:10:08.000Z
2019-10-02T11:10:08.000Z
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
null
null
null
examples/undocumented/libshogun/library_hash.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2020-06-02T09:15:40.000Z
2020-06-02T09:15:40.000Z
#include <shogun/lib/Hash.h> #include <stdio.h> using namespace shogun; int main(int argc, char** argv) { uint8_t array[4]={0,1,2,3}; printf("hash(0)=%0x\n", CHash::MurmurHash3(&array[0], 1, 0xDEADBEAF)); printf("hash(1)=%0x\n", CHash::MurmurHash3(&array[1], 1, 0xDEADBEAF)); printf("hash(2)=%0x\n", CHash::MurmurHash3(&array[0], 2, 0xDEADBEAF)); printf("hash(3)=%0x\n", CHash::MurmurHash3(&array[0], 4, 0xDEADBEAF)); uint32_t h = 0xDEADBEAF; uint32_t carry = 0; CHash::IncrementalMurmurHash3(&h, &carry, &array[0], 1); printf("inc_hash(0)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[1], 1); printf("inc_hash(1)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[2], 1); printf("inc_hash(2)=%0x\n", h); CHash::IncrementalMurmurHash3(&h, &carry, &array[3], 1); printf("inc_hash(3)=%0x\n", h); h = CHash::FinalizeIncrementalMurmurHash3(h, carry, 4); printf("Final inc_hash(3)=%0x\n", h); return 0; }
30.83871
71
0.65272
Arpit2601
0e3fe2ad88d6866a4396df74bbfbf4539acaabc3
4,279
cpp
C++
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
1
2021-08-16T15:39:56.000Z
2021-08-16T15:39:56.000Z
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
28
2020-10-26T07:29:15.000Z
2022-03-31T01:06:49.000Z
src/widgets/settingspages/IgnoresPage.cpp
NilsIrl/chatterino2
b7e86a8de66e53876d7a71376c43529597ee6c12
[ "MIT" ]
null
null
null
#include "IgnoresPage.hpp" #include "Application.hpp" #include "controllers/accounts/AccountController.hpp" #include "controllers/ignores/IgnoreController.hpp" #include "controllers/ignores/IgnoreModel.hpp" #include "providers/twitch/TwitchAccount.hpp" #include "singletons/Settings.hpp" #include "util/LayoutCreator.hpp" #include "widgets/helper/EditableModelView.hpp" #include <QCheckBox> #include <QGroupBox> #include <QHeaderView> #include <QLabel> #include <QListView> #include <QPushButton> #include <QTableView> #include <QVBoxLayout> // clang-format off #define INFO "/ignore <user> in chat ignores a user.\n/unignore <user> in chat unignores a user.\nYou can also click on a user to open the usercard." // clang-format on namespace chatterino { static void addPhrasesTab(LayoutCreator<QVBoxLayout> box); static void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> box, QStringListModel &model); IgnoresPage::IgnoresPage() { LayoutCreator<IgnoresPage> layoutCreator(this); auto layout = layoutCreator.setLayoutType<QVBoxLayout>(); auto tabs = layout.emplace<QTabWidget>(); addPhrasesTab(tabs.appendTab(new QVBoxLayout, "Messages")); addUsersTab(*this, tabs.appendTab(new QVBoxLayout, "Users"), this->userListModel_); } void addPhrasesTab(LayoutCreator<QVBoxLayout> layout) { layout.emplace<QLabel>("Ignore messages based certain patterns."); EditableModelView *view = layout .emplace<EditableModelView>( (new IgnoreModel(nullptr)) ->initialized(&getSettings()->ignoredMessages)) .getElement(); view->setTitles( {"Pattern", "Regex", "Case Sensitive", "Block", "Replacement"}); view->getTableView()->horizontalHeader()->setSectionResizeMode( QHeaderView::Fixed); view->getTableView()->horizontalHeader()->setSectionResizeMode( 0, QHeaderView::Stretch); view->addRegexHelpLink(); QTimer::singleShot(1, [view] { view->getTableView()->resizeColumnsToContents(); view->getTableView()->setColumnWidth(0, 200); }); view->addButtonPressed.connect([] { getSettings()->ignoredMessages.append( IgnorePhrase{"my pattern", false, false, getSettings()->ignoredPhraseReplace.getValue(), true}); }); } void addUsersTab(IgnoresPage &page, LayoutCreator<QVBoxLayout> users, QStringListModel &userModel) { auto label = users.emplace<QLabel>(INFO); label->setWordWrap(true); users.append(page.createCheckBox("Enable twitch ignored users", getSettings()->enableTwitchIgnoredUsers)); auto anyways = users.emplace<QHBoxLayout>().withoutMargin(); { anyways.emplace<QLabel>("Show messages from ignored users anyways:"); auto combo = anyways.emplace<QComboBox>().getElement(); combo->addItems( {"Never", "If you are Moderator", "If you are Broadcaster"}); auto &setting = getSettings()->showIgnoredUsersMessages; setting.connect( [combo](const int value) { combo->setCurrentIndex(value); }); QObject::connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), [&setting](int index) { if (index != -1) setting = index; }); anyways->addStretch(1); } /*auto addremove = users.emplace<QHBoxLayout>().withoutMargin(); { auto add = addremove.emplace<QPushButton>("Ignore user"); auto remove = addremove.emplace<QPushButton>("Unignore User"); addremove->addStretch(1); }*/ users.emplace<QLabel>("List of ignored users:"); users.emplace<QListView>()->setModel(&userModel); } void IgnoresPage::onShow() { auto app = getApp(); auto user = app->accounts->twitch.getCurrent(); if (user->isAnon()) { return; } QStringList users; for (const auto &ignoredUser : user->getIgnores()) { users << ignoredUser.name; } users.sort(Qt::CaseInsensitive); this->userListModel_.setStringList(users); } } // namespace chatterino
31.932836
149
0.643842
NilsIrl
0e4124b1bc075ab6fb060d145653ac4bbaa95360
2,218
cc
C++
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/film.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Zhehang Ding 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 "core/film.h" #include <math.h> #include <fstream> #include <sstream> namespace qjulia { CPU_AND_CUDA Point2f GenerateCameraCoords(Point2f src, Size size) { Float c = src[1]; Float r= src[0]; Float ss = (Float)(size.width < size.height ? size.width : size.height - 1); Float x = (c - (size.width - 1) * 0.5f) / ss; Float y = ((size.height - 1) * 0.5f - r) / ss; return {x, y}; } /* void SaveToPPM(const std::string &filename, const Film &film, Float scale) { int w = film.Width(); int h = film.Height(); std::vector<unsigned char> buf(w * h * 3); auto *p = buf.data(); for (int i = 0; i < (w * h); ++i) { const auto &sp = film.At(i); for (int ch = 0; ch < 3; ++ch) { *(p++) = std::min(255, std::max(0, (int)std::round(sp[ch] * scale))); } } std::ostringstream header_stream; header_stream << "P6 " << w << ' ' << h << ' ' << 255 << '\n'; std::string header = header_stream.str(); std::ofstream file_stream(filename, std::ofstream::binary); file_stream.write(header.c_str(), header.size()); file_stream.write(reinterpret_cast<const char*>(buf.data()), buf.size()); }*/ }
33.606061
78
0.693417
zhehangd
0e41a058de70310d29a28a408d1cb8afa336e1aa
336
cpp
C++
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-23T16:06:39.000Z
2021-09-23T16:06:39.000Z
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
null
null
null
practical 7/task5.cpp
sahilnegi30/C-PLUS-
bd8d9ce79e5ae36b9f8d5e4c88949455dc4a6339
[ "MIT" ]
1
2021-09-24T15:10:07.000Z
2021-09-24T15:10:07.000Z
#include<iostream> using namespace std; int main() { int b[3][3]; int a [3] [3]={1,2,3,4,5,6,7,8,9}; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { b[i][j]=a[2-i] [2-j]; } } for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cout<<b[i][j]<<" "; } cout<<endl; } return 0; }
14.608696
36
0.39881
sahilnegi30
0e424e511af987030f273557f62e14989f01ba2a
851
cpp
C++
src/keyboard.cpp
astrellon/simple-snake
3dbe1f2af1afe31d3cef8bcc995d9150beafa1b2
[ "MIT" ]
1
2020-06-26T07:51:45.000Z
2020-06-26T07:51:45.000Z
src/keyboard.cpp
astrellon/starter-sfml
3679e76c01275d07fa9af5ead92a5d41c6fccfea
[ "MIT" ]
null
null
null
src/keyboard.cpp
astrellon/starter-sfml
3679e76c01275d07fa9af5ead92a5d41c6fccfea
[ "MIT" ]
null
null
null
#include "keyboard.hpp" #include <algorithm> namespace town { Keyboard::KeyList Keyboard::_KeysUp; Keyboard::KeyList Keyboard::_KeysDown; bool Keyboard::isKeyPressed(sf::Keyboard::Key key) { return sf::Keyboard::isKeyPressed(key); } bool Keyboard::isKeyUp(sf::Keyboard::Key key) { return std::find(_KeysUp.begin(), _KeysUp.end(), key) != _KeysUp.end(); } bool Keyboard::isKeyDown(sf::Keyboard::Key key) { return std::find(_KeysDown.begin(), _KeysDown.end(), key) != _KeysDown.end(); } void Keyboard::resetKeys() { _KeysUp.clear(); _KeysDown.clear(); } void Keyboard::setKeyUp(sf::Keyboard::Key key) { _KeysUp.push_back(key); } void Keyboard::setKeyDown(sf::Keyboard::Key key) { _KeysDown.push_back(key); } }
21.275
85
0.60517
astrellon
0e46f42529f2eed7cb5196249fed406637d1f5d6
5,032
hpp
C++
src/controls/TreeViewModelAdaptor.hpp
oclero/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
5
2021-07-19T19:57:41.000Z
2021-09-25T01:41:13.000Z
src/controls/TreeViewModelAdaptor.hpp
chiefstone/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
2
2021-09-25T08:35:49.000Z
2021-09-25T11:14:49.000Z
src/controls/TreeViewModelAdaptor.hpp
chiefstone/luna
00bd5736e7bab57daa5d622bcd5379992ca6505c
[ "MIT" ]
3
2021-08-20T10:19:12.000Z
2021-09-25T10:46:40.000Z
#pragma once #include <QSet> #include <QPointer> #include <QAbstractItemModel> #include <QItemSelectionModel> #include <QPersistentModelIndex> class TreeViewModelAdaptor : public QAbstractItemModel { Q_OBJECT Q_PROPERTY(QAbstractItemModel* model READ model WRITE setModel NOTIFY modelChanged) Q_PROPERTY(QModelIndex rootIndex READ rootIndex WRITE setRootIndex RESET resetRootIndex NOTIFY rootIndexChanged) struct TreeItem; public: explicit TreeViewModelAdaptor(QObject* parent = nullptr); QAbstractItemModel* model() const; const QModelIndex& rootIndex() const; void setRootIndex(const QModelIndex& idx); void resetRootIndex(); QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; QModelIndex parent(const QModelIndex& child) const; int rowCount(const QModelIndex& parent = QModelIndex()) const; int columnCount(const QModelIndex& parent = QModelIndex()) const; enum { DepthRole = Qt::UserRole - 5, ExpandedRole, HasChildrenRole, HasSiblingRole, ModelIndexRole, }; QHash<int, QByteArray> roleNames() const; QVariant data(const QModelIndex&, int role) const; bool setData(const QModelIndex& index, const QVariant& value, int role); QVariant headerData(int section, Qt::Orientation orientation, int role) const; void clearModelData(); bool isVisible(const QModelIndex& index); bool childrenVisible(const QModelIndex& index); QModelIndex mapToModel(const QModelIndex& index) const; QModelIndex mapFromModel(const QModelIndex& index) const; QModelIndex mapToModel(int row) const; Q_INVOKABLE QItemSelection selectionForRowRange(const QModelIndex& fromIndex, const QModelIndex& toIndex) const; void showModelTopLevelItems(bool doInsertRows = true); void showModelChildItems( const TreeItem& parent, int start, int end, bool doInsertRows = true, bool doExpandPendingRows = true); int itemIndex(const QModelIndex& index) const; void expandPendingRows(bool doInsertRows = true); int lastChildIndex(const QModelIndex& index); void removeVisibleRows(int startIndex, int endIndex, bool doRemoveRows = true); void dump() const; bool testConsistency(bool dumpOnFail = false) const; using QAbstractItemModel::hasChildren; signals: void modelChanged(QAbstractItemModel* model); void rootIndexChanged(); void expanded(const QModelIndex& index); void collapsed(const QModelIndex& index); public slots: void expand(const QModelIndex&); void collapse(const QModelIndex&); void setModel(QAbstractItemModel* model); bool isExpanded(const QModelIndex&) const; bool isExpanded(int row) const; bool hasChildren(int row) const; bool hasSiblings(int row) const; int depthAtRow(int row) const; void expandRow(int n); void collapseRow(int n); private slots: void modelHasBeenDestroyed(); void modelHasBeenReset(); void modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRigth, const QVector<int>& roles); void modelLayoutAboutToBeChanged( const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint); void modelLayoutChanged(const QList<QPersistentModelIndex>& parents, QAbstractItemModel::LayoutChangeHint hint); void modelRowsAboutToBeInserted(const QModelIndex& parent, int start, int end); void modelRowsAboutToBeMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd, const QModelIndex& destinationParent, int destinationRow); void modelRowsAboutToBeRemoved(const QModelIndex& parent, int start, int end); void modelRowsInserted(const QModelIndex& parent, int start, int end); void modelRowsMoved(const QModelIndex& sourceParent, int sourceStart, int sourceEnd, const QModelIndex& destinationParent, int destinationRow); void modelRowsRemoved(const QModelIndex& parent, int start, int end); private: struct TreeItem { QPersistentModelIndex index; int depth; bool expanded; explicit TreeItem(const QModelIndex& idx = {}, int d = 0, int e = false) : index(idx) , depth(d) , expanded(e) {} inline bool operator==(const TreeItem& other) const { return this->index == other.index; } }; struct DataChangedParams { QModelIndex topLeft; QModelIndex bottomRight; QVector<int> roles; }; struct SignalFreezer { SignalFreezer(TreeViewModelAdaptor* parent) : parent(parent) { parent->enableSignalAggregation(); } ~SignalFreezer() { parent->disableSignalAggregation(); } private: TreeViewModelAdaptor* parent; }; void enableSignalAggregation(); void disableSignalAggregation(); bool isAggregatingSignals() const; void queueDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int>& roles); void emitQueuedSignals(); QPointer<QAbstractItemModel> _model = nullptr; QPersistentModelIndex _rootIndex; QList<TreeItem> _items; QSet<QPersistentModelIndex> _expandedItems; QList<TreeItem*> _itemsToExpand; mutable int _lastItemIndex = 0; bool _visibleRowsMoved = false; int _signalAggregatorStack = 0; QVector<DataChangedParams> _queuedDataChanged; int _column = 0; };
32.464516
113
0.783386
oclero
0e4a59069b9151279c3ec782557d638585c2baa2
381
hpp
C++
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
1
2017-10-06T02:01:59.000Z
2017-10-06T02:01:59.000Z
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
1
2016-01-24T04:05:04.000Z
2016-01-25T14:43:35.000Z
EyeOfSauronDHTMonitor/tests/test_esdhttp.hpp
zhaishuai/EyeOfSauronDHTMonitor
5f4fdb6056f54c13b7f47821bb714c1a041f5f16
[ "MIT" ]
null
null
null
// // test_esdhttp.hpp // EyeOfSauronDHTMonitor // // Created by shuaizhai on 4/25/16. // Copyright © 2016 com.dhtMonitor.www. All rights reserved. // #ifndef test_esdhttp_hpp #define test_esdhttp_hpp #include <stdio.h> #include "ESDHttpUtility.hpp" #include "ESDHttpProtocol.hpp" namespace test_esdhttp { void test_esdhttp(); } #endif /* test_esdhttp_hpp */
16.565217
61
0.711286
zhaishuai
0e4c8eb8d1f3f06e805a435f4d9027e443b1ca1d
31,177
cpp
C++
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
exportGOAT/release/windows/obj/src/polymod/backends/PolymodAssetLibrary.cpp
SamuraiOfSecrets/Goatmeal-Time-v0.2
7b89cbaf6895495b90ee1a5679e9cc696a7fbb53
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.5 #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_haxe_io_Encoding #include <haxe/io/Encoding.h> #endif #ifndef INCLUDED_polymod_backends_IBackend #include <polymod/backends/IBackend.h> #endif #ifndef INCLUDED_polymod_backends_PolymodAssetLibrary #include <polymod/backends/PolymodAssetLibrary.h> #endif #ifndef INCLUDED_polymod_format_ParseRules #include <polymod/format/ParseRules.h> #endif #ifndef INCLUDED_polymod_fs_SysFileSystem #include <polymod/fs/SysFileSystem.h> #endif #ifndef INCLUDED_polymod_util_Util #include <polymod/util/Util.h> #endif #ifndef INCLUDED_sys_FileSystem #include <sys/FileSystem.h> #endif #ifndef INCLUDED_sys_io_File #include <sys/io/File.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_41154335dca776f0_63_new,"polymod.backends.PolymodAssetLibrary","new",0xd3ebdd3c,"polymod.backends.PolymodAssetLibrary.new","polymod/backends/PolymodAssetLibrary.hx",63,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_88_destroy,"polymod.backends.PolymodAssetLibrary","destroy",0x1f3bd7d6,"polymod.backends.PolymodAssetLibrary.destroy","polymod/backends/PolymodAssetLibrary.hx",88,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_95_mergeAndAppendText,"polymod.backends.PolymodAssetLibrary","mergeAndAppendText",0xf742862a,"polymod.backends.PolymodAssetLibrary.mergeAndAppendText","polymod/backends/PolymodAssetLibrary.hx",95,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_101_getExtensionType,"polymod.backends.PolymodAssetLibrary","getExtensionType",0x9080a107,"polymod.backends.PolymodAssetLibrary.getExtensionType","polymod/backends/PolymodAssetLibrary.hx",101,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_114_getTextDirectly,"polymod.backends.PolymodAssetLibrary","getTextDirectly",0x8a3e4055,"polymod.backends.PolymodAssetLibrary.getTextDirectly","polymod/backends/PolymodAssetLibrary.hx",114,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_136_exists,"polymod.backends.PolymodAssetLibrary","exists",0xbb428280,"polymod.backends.PolymodAssetLibrary.exists","polymod/backends/PolymodAssetLibrary.hx",136,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_137_getText,"polymod.backends.PolymodAssetLibrary","getText",0x1a32273f,"polymod.backends.PolymodAssetLibrary.getText","polymod/backends/PolymodAssetLibrary.hx",137,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_138_getBytes,"polymod.backends.PolymodAssetLibrary","getBytes",0x81aeed99,"polymod.backends.PolymodAssetLibrary.getBytes","polymod/backends/PolymodAssetLibrary.hx",138,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_139_getPath,"polymod.backends.PolymodAssetLibrary","getPath",0x178a4037,"polymod.backends.PolymodAssetLibrary.getPath","polymod/backends/PolymodAssetLibrary.hx",139,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_141_list,"polymod.backends.PolymodAssetLibrary","list",0x99265002,"polymod.backends.PolymodAssetLibrary.list","polymod/backends/PolymodAssetLibrary.hx",141,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_144_listModFiles,"polymod.backends.PolymodAssetLibrary","listModFiles",0x114a5677,"polymod.backends.PolymodAssetLibrary.listModFiles","polymod/backends/PolymodAssetLibrary.hx",144,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_166_check,"polymod.backends.PolymodAssetLibrary","check",0x391094a4,"polymod.backends.PolymodAssetLibrary.check","polymod/backends/PolymodAssetLibrary.hx",166,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_177_getType,"polymod.backends.PolymodAssetLibrary","getType",0x1a414d4c,"polymod.backends.PolymodAssetLibrary.getType","polymod/backends/PolymodAssetLibrary.hx",177,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_187_checkDirectly,"polymod.backends.PolymodAssetLibrary","checkDirectly",0xba101aba,"polymod.backends.PolymodAssetLibrary.checkDirectly","polymod/backends/PolymodAssetLibrary.hx",187,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_211_file,"polymod.backends.PolymodAssetLibrary","file",0x952f0220,"polymod.backends.PolymodAssetLibrary.file","polymod/backends/PolymodAssetLibrary.hx",211,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_231__checkExists,"polymod.backends.PolymodAssetLibrary","_checkExists",0xbf011669,"polymod.backends.PolymodAssetLibrary._checkExists","polymod/backends/PolymodAssetLibrary.hx",231,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_246_init,"polymod.backends.PolymodAssetLibrary","init",0x972e6eb4,"polymod.backends.PolymodAssetLibrary.init","polymod/backends/PolymodAssetLibrary.hx",246,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_260_initExtensions,"polymod.backends.PolymodAssetLibrary","initExtensions",0x4b48d7e8,"polymod.backends.PolymodAssetLibrary.initExtensions","polymod/backends/PolymodAssetLibrary.hx",260,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_287__extensionSet,"polymod.backends.PolymodAssetLibrary","_extensionSet",0x73b0841e,"polymod.backends.PolymodAssetLibrary._extensionSet","polymod/backends/PolymodAssetLibrary.hx",287,0xd1edfd94) HX_LOCAL_STACK_FRAME(_hx_pos_41154335dca776f0_294_initMod,"polymod.backends.PolymodAssetLibrary","initMod",0xc63f886e,"polymod.backends.PolymodAssetLibrary.initMod","polymod/backends/PolymodAssetLibrary.hx",294,0xd1edfd94) namespace polymod{ namespace backends{ void PolymodAssetLibrary_obj::__construct( ::Dynamic params){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_63_new) HXLINE( 71) this->parseRules = null(); HXLINE( 70) this->ignoredFiles = null(); HXLINE( 69) this->dirs = null(); HXLINE( 76) this->backend = ::Dynamic(params->__Field(HX_("backend",14,bc,87,fb),::hx::paccDynamic)); HXLINE( 77) this->backend->__SetField(HX_("polymodLibrary",a5,49,05,cb),::hx::ObjectPtr<OBJ_>(this),::hx::paccDynamic); HXLINE( 78) this->dirs = ( (::Array< ::String >)(params->__Field(HX_("dirs",86,66,69,42),::hx::paccDynamic)) ); HXLINE( 79) this->parseRules = ( ( ::polymod::format::ParseRules)(params->__Field(HX_("parseRules",c4,aa,37,1b),::hx::paccDynamic)) ); HXLINE( 80) ::Array< ::String > _hx_tmp; HXDLIN( 80) if (::hx::IsNotNull( params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic) )) { HXLINE( 80) _hx_tmp = ( (::Array< ::String >)(params->__Field(HX_("ignoredFiles",05,36,92,57),::hx::paccDynamic)) )->copy(); } else { HXLINE( 80) _hx_tmp = ::Array_obj< ::String >::__new(0); } HXDLIN( 80) this->ignoredFiles = _hx_tmp; HXLINE( 81) this->extensions = ( ( ::haxe::ds::StringMap)(params->__Field(HX_("extensionMap",5d,28,7a,23),::hx::paccDynamic)) ); HXLINE( 82) ::polymod::backends::IBackend_obj::clearCache(this->backend); HXLINE( 83) this->init(); } Dynamic PolymodAssetLibrary_obj::__CreateEmpty() { return new PolymodAssetLibrary_obj; } void *PolymodAssetLibrary_obj::_hx_vtable = 0; Dynamic PolymodAssetLibrary_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< PolymodAssetLibrary_obj > _hx_result = new PolymodAssetLibrary_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool PolymodAssetLibrary_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6eaea9ac; } void PolymodAssetLibrary_obj::destroy(){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_88_destroy) HXDLIN( 88) if (::hx::IsNotNull( this->backend )) { HXLINE( 90) ::polymod::backends::IBackend_obj::destroy(this->backend); } } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,destroy,(void)) ::String PolymodAssetLibrary_obj::mergeAndAppendText(::String id,::String modText){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_95_mergeAndAppendText) HXLINE( 96) modText = ::polymod::util::Util_obj::mergeAndAppendText(modText,id,this->dirs,this->getTextDirectly_dyn(),this->parseRules); HXLINE( 97) return modText; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,mergeAndAppendText,return ) ::String PolymodAssetLibrary_obj::getExtensionType(::String ext){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_101_getExtensionType) HXLINE( 102) ext = ext.toLowerCase(); HXLINE( 103) if ((this->extensions->exists(ext) == false)) { HXLINE( 103) return HX_("BYTES",4b,40,86,3b); } HXLINE( 104) return this->extensions->get_string(ext); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getExtensionType,return ) ::String PolymodAssetLibrary_obj::getTextDirectly(::String id,::String __o_directory){ ::String directory = __o_directory; if (::hx::IsNull(__o_directory)) directory = HX_("",00,00,00,00); HX_STACKFRAME(&_hx_pos_41154335dca776f0_114_getTextDirectly) HXLINE( 115) ::haxe::io::Bytes bytes = null(); HXLINE( 116) if (this->checkDirectly(id,directory)) { HXLINE( 118) ::String path = this->file(id,directory); HXDLIN( 118) if (!(::sys::FileSystem_obj::exists(path))) { HXLINE( 118) bytes = null(); } else { HXLINE( 118) bytes = ::sys::io::File_obj::getBytes(path); } } else { HXLINE( 122) bytes = ::polymod::backends::IBackend_obj::getBytes(this->backend,id); } HXLINE( 125) if (::hx::IsNull( bytes )) { HXLINE( 127) return null(); } else { HXLINE( 131) return bytes->getString(0,bytes->length,null()); } HXLINE( 125) return null(); } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,getTextDirectly,return ) bool PolymodAssetLibrary_obj::exists(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_136_exists) HXDLIN( 136) return ::polymod::backends::IBackend_obj::exists(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,exists,return ) ::String PolymodAssetLibrary_obj::getText(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_137_getText) HXDLIN( 137) return ::polymod::backends::IBackend_obj::getText(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getText,return ) ::haxe::io::Bytes PolymodAssetLibrary_obj::getBytes(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_138_getBytes) HXDLIN( 138) return ::polymod::backends::IBackend_obj::getBytes(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getBytes,return ) ::String PolymodAssetLibrary_obj::getPath(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_139_getPath) HXDLIN( 139) return ::polymod::backends::IBackend_obj::getPath(this->backend,id); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getPath,return ) ::Array< ::String > PolymodAssetLibrary_obj::list(::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_141_list) HXDLIN( 141) return ::polymod::backends::IBackend_obj::list(this->backend,type); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,list,return ) ::Array< ::String > PolymodAssetLibrary_obj::listModFiles(::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_144_listModFiles) HXLINE( 145) ::Array< ::String > items = ::Array_obj< ::String >::__new(0); HXLINE( 147) { HXLINE( 147) ::Dynamic id = this->type->keys(); HXDLIN( 147) while(( (bool)(id->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 147) ::String id1 = ( (::String)(id->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) ); HXLINE( 149) bool _hx_tmp; HXDLIN( 149) if ((id1.indexOf(HX_("_append",79,f3,4a,fe),null()) != 0)) { HXLINE( 149) _hx_tmp = (id1.indexOf(HX_("_merge",f9,e9,ad,01),null()) == 0); } else { HXLINE( 149) _hx_tmp = true; } HXDLIN( 149) if (_hx_tmp) { HXLINE( 149) continue; } HXLINE( 150) bool _hx_tmp1; HXDLIN( 150) bool _hx_tmp2; HXDLIN( 150) if (::hx::IsNotNull( type )) { HXLINE( 150) _hx_tmp2 = (type == HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 150) _hx_tmp2 = true; } HXDLIN( 150) if (!(_hx_tmp2)) { HXLINE( 150) _hx_tmp1 = this->check(id1,type); } else { HXLINE( 150) _hx_tmp1 = true; } HXDLIN( 150) if (_hx_tmp1) { HXLINE( 152) items->push(id1); } } } HXLINE( 156) return items; } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,listModFiles,return ) bool PolymodAssetLibrary_obj::check(::String id,::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_166_check) HXLINE( 167) bool exists = this->_checkExists(id); HXLINE( 168) bool _hx_tmp; HXDLIN( 168) bool _hx_tmp1; HXDLIN( 168) if (exists) { HXLINE( 168) _hx_tmp1 = ::hx::IsNotNull( type ); } else { HXLINE( 168) _hx_tmp1 = false; } HXDLIN( 168) if (_hx_tmp1) { HXLINE( 168) _hx_tmp = (type != HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 168) _hx_tmp = false; } HXDLIN( 168) if (_hx_tmp) { HXLINE( 170) ::String otherType = this->type->get_string(id); HXLINE( 171) bool exists1; HXDLIN( 171) bool exists2; HXDLIN( 171) if ((otherType != type)) { HXLINE( 171) exists2 = (otherType == HX_("BYTES",4b,40,86,3b)); } else { HXLINE( 171) exists2 = true; } HXDLIN( 171) if (!(exists2)) { HXLINE( 171) exists1 = ::hx::IsNull( otherType ); } else { HXLINE( 171) exists1 = true; } HXDLIN( 171) if (!(exists1)) { HXLINE( 171) exists = (otherType == HX_("",00,00,00,00)); } else { HXLINE( 171) exists = true; } } HXLINE( 173) return exists; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,check,return ) ::String PolymodAssetLibrary_obj::getType(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_177_getType) HXLINE( 178) bool exists = this->_checkExists(id); HXLINE( 179) if (exists) { HXLINE( 181) return this->type->get_string(id); } HXLINE( 183) return null(); } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,getType,return ) bool PolymodAssetLibrary_obj::checkDirectly(::String id,::String dir){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_187_checkDirectly) HXLINE( 188) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 189) bool _hx_tmp; HXDLIN( 189) if (::hx::IsNotNull( dir )) { HXLINE( 189) _hx_tmp = (dir == HX_("",00,00,00,00)); } else { HXLINE( 189) _hx_tmp = true; } HXDLIN( 189) if (_hx_tmp) { HXLINE( 191) return ::sys::FileSystem_obj::exists(id); } else { HXLINE( 195) ::String thePath = ::polymod::util::Util_obj::uCombine(::Array_obj< ::String >::__new(3)->init(0,dir)->init(1,::polymod::util::Util_obj::sl())->init(2,id)); HXLINE( 196) if (::sys::FileSystem_obj::exists(thePath)) { HXLINE( 198) return true; } } HXLINE( 201) return false; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,checkDirectly,return ) ::String PolymodAssetLibrary_obj::file(::String id,::String __o_theDir){ ::String theDir = __o_theDir; if (::hx::IsNull(__o_theDir)) theDir = HX_("",00,00,00,00); HX_STACKFRAME(&_hx_pos_41154335dca776f0_211_file) HXLINE( 212) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 213) if ((theDir != HX_("",00,00,00,00))) { HXLINE( 215) return ::polymod::util::Util_obj::pathJoin(theDir,id); } HXLINE( 218) ::String theFile = HX_("",00,00,00,00); HXLINE( 219) { HXLINE( 219) int _g = 0; HXDLIN( 219) ::Array< ::String > _g1 = this->dirs; HXDLIN( 219) while((_g < _g1->length)){ HXLINE( 219) ::String d = _g1->__get(_g); HXDLIN( 219) _g = (_g + 1); HXLINE( 221) ::String thePath = ::polymod::util::Util_obj::pathJoin(d,id); HXLINE( 222) if (::sys::FileSystem_obj::exists(thePath)) { HXLINE( 224) theFile = thePath; } } } HXLINE( 227) return theFile; } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,file,return ) bool PolymodAssetLibrary_obj::_checkExists(::String id){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_231__checkExists) HXLINE( 232) bool _hx_tmp; HXDLIN( 232) if ((this->ignoredFiles->length > 0)) { HXLINE( 232) _hx_tmp = (this->ignoredFiles->indexOf(id,null()) != -1); } else { HXLINE( 232) _hx_tmp = false; } HXDLIN( 232) if (_hx_tmp) { HXLINE( 232) return false; } HXLINE( 233) bool exists = false; HXLINE( 234) id = ::polymod::backends::IBackend_obj::stripAssetsPrefix(this->backend,id); HXLINE( 235) { HXLINE( 235) int _g = 0; HXDLIN( 235) ::Array< ::String > _g1 = this->dirs; HXDLIN( 235) while((_g < _g1->length)){ HXLINE( 235) ::String d = _g1->__get(_g); HXDLIN( 235) _g = (_g + 1); HXLINE( 237) if (::sys::FileSystem_obj::exists(::polymod::util::Util_obj::pathJoin(d,id))) { HXLINE( 239) exists = true; } } } HXLINE( 242) return exists; } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,_checkExists,return ) void PolymodAssetLibrary_obj::init(){ HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_246_init) HXLINE( 247) this->type = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 248) this->initExtensions(); HXLINE( 249) if (::hx::IsNull( this->parseRules )) { HXLINE( 249) this->parseRules = ::polymod::format::ParseRules_obj::getDefault(); } HXLINE( 250) if (::hx::IsNotNull( this->dirs )) { HXLINE( 252) int _g = 0; HXDLIN( 252) ::Array< ::String > _g1 = this->dirs; HXDLIN( 252) while((_g < _g1->length)){ HXLINE( 252) ::String d = _g1->__get(_g); HXDLIN( 252) _g = (_g + 1); HXLINE( 254) this->initMod(d); } } } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,init,(void)) void PolymodAssetLibrary_obj::initExtensions(){ HX_GC_STACKFRAME(&_hx_pos_41154335dca776f0_260_initExtensions) HXLINE( 261) this->extensions = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 262) this->_extensionSet(HX_("mp3",70,17,53,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 263) this->_extensionSet(HX_("ogg",4f,94,54,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 264) this->_extensionSet(HX_("wav",2c,a1,5a,00),HX_("AUDIO_GENERIC",2e,f6,26,23)); HXLINE( 265) this->_extensionSet(HX_("jpg",e1,d0,50,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 266) this->_extensionSet(HX_("png",a9,5c,55,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 267) this->_extensionSet(HX_("gif",04,84,4e,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 268) this->_extensionSet(HX_("tga",8e,5f,58,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 269) this->_extensionSet(HX_("bmp",45,bc,4a,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 270) this->_extensionSet(HX_("tif",51,61,58,00),HX_("IMAGE",3b,57,57,3b)); HXLINE( 271) this->_extensionSet(HX_("tiff",f5,c5,fc,4c),HX_("IMAGE",3b,57,57,3b)); HXLINE( 272) this->_extensionSet(HX_("txt",70,6e,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 273) this->_extensionSet(HX_("xml",d7,6d,5b,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 274) this->_extensionSet(HX_("json",28,42,68,46),HX_("TEXT",ad,94,ba,37)); HXLINE( 275) this->_extensionSet(HX_("csv",c6,83,4b,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 276) this->_extensionSet(HX_("tsv",17,6a,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 277) this->_extensionSet(HX_("mpf",a3,17,53,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 278) this->_extensionSet(HX_("tsx",19,6a,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 279) this->_extensionSet(HX_("tmx",df,64,58,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 280) this->_extensionSet(HX_("vdf",78,e1,59,00),HX_("TEXT",ad,94,ba,37)); HXLINE( 281) this->_extensionSet(HX_("ttf",e6,6a,58,00),HX_("FONT",cf,25,81,2e)); HXLINE( 282) this->_extensionSet(HX_("otf",a1,9f,54,00),HX_("FONT",cf,25,81,2e)); } HX_DEFINE_DYNAMIC_FUNC0(PolymodAssetLibrary_obj,initExtensions,(void)) void PolymodAssetLibrary_obj::_extensionSet(::String str,::String type){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_287__extensionSet) HXDLIN( 287) if ((this->extensions->exists(str) == false)) { HXLINE( 289) this->extensions->set(str,type); } } HX_DEFINE_DYNAMIC_FUNC2(PolymodAssetLibrary_obj,_extensionSet,(void)) void PolymodAssetLibrary_obj::initMod(::String d){ HX_STACKFRAME(&_hx_pos_41154335dca776f0_294_initMod) HXLINE( 295) if (::hx::IsNull( d )) { HXLINE( 295) return; } HXLINE( 297) ::Array< ::String > all = null(); HXLINE( 299) bool _hx_tmp; HXDLIN( 299) if ((d != HX_("",00,00,00,00))) { HXLINE( 299) _hx_tmp = ::hx::IsNull( d ); } else { HXLINE( 299) _hx_tmp = true; } HXDLIN( 299) if (_hx_tmp) { HXLINE( 301) all = ::Array_obj< ::String >::__new(0); } HXLINE( 304) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 306) if (::sys::FileSystem_obj::exists(d)) { HXLINE( 308) all = ::polymod::fs::SysFileSystem_obj::readDirectoryRecursive(d); } else { HXLINE( 312) all = ::Array_obj< ::String >::__new(0); } } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic msg = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 317) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown((((HX_("ModAssetLibrary._initMod(",b4,86,f3,80) + d) + HX_(") failed : ",72,52,be,0b)) + ::Std_obj::string(msg)))); } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 319) { HXLINE( 319) int _g = 0; HXDLIN( 319) while((_g < all->length)){ HXLINE( 319) ::String f = all->__get(_g); HXDLIN( 319) _g = (_g + 1); HXLINE( 321) int doti = ::polymod::util::Util_obj::uLastIndexOf(f,HX_(".",2e,00,00,00),null()); HXLINE( 322) ::String ext; HXDLIN( 322) if ((doti != -1)) { HXLINE( 322) ext = f.substring((doti + 1),null()); } else { HXLINE( 322) ext = HX_("",00,00,00,00); } HXLINE( 323) ext = ext.toLowerCase(); HXLINE( 324) ::String assetType = this->getExtensionType(ext); HXLINE( 325) this->type->set(f,assetType); } } } HX_DEFINE_DYNAMIC_FUNC1(PolymodAssetLibrary_obj,initMod,(void)) ::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__new( ::Dynamic params) { ::hx::ObjectPtr< PolymodAssetLibrary_obj > __this = new PolymodAssetLibrary_obj(); __this->__construct(params); return __this; } ::hx::ObjectPtr< PolymodAssetLibrary_obj > PolymodAssetLibrary_obj::__alloc(::hx::Ctx *_hx_ctx, ::Dynamic params) { PolymodAssetLibrary_obj *__this = (PolymodAssetLibrary_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(PolymodAssetLibrary_obj), true, "polymod.backends.PolymodAssetLibrary")); *(void **)__this = PolymodAssetLibrary_obj::_hx_vtable; __this->__construct(params); return __this; } PolymodAssetLibrary_obj::PolymodAssetLibrary_obj() { } void PolymodAssetLibrary_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(PolymodAssetLibrary); HX_MARK_MEMBER_NAME(backend,"backend"); HX_MARK_MEMBER_NAME(type,"type"); HX_MARK_MEMBER_NAME(dirs,"dirs"); HX_MARK_MEMBER_NAME(ignoredFiles,"ignoredFiles"); HX_MARK_MEMBER_NAME(parseRules,"parseRules"); HX_MARK_MEMBER_NAME(extensions,"extensions"); HX_MARK_END_CLASS(); } void PolymodAssetLibrary_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(backend,"backend"); HX_VISIT_MEMBER_NAME(type,"type"); HX_VISIT_MEMBER_NAME(dirs,"dirs"); HX_VISIT_MEMBER_NAME(ignoredFiles,"ignoredFiles"); HX_VISIT_MEMBER_NAME(parseRules,"parseRules"); HX_VISIT_MEMBER_NAME(extensions,"extensions"); } ::hx::Val PolymodAssetLibrary_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"type") ) { return ::hx::Val( type ); } if (HX_FIELD_EQ(inName,"dirs") ) { return ::hx::Val( dirs ); } if (HX_FIELD_EQ(inName,"list") ) { return ::hx::Val( list_dyn() ); } if (HX_FIELD_EQ(inName,"file") ) { return ::hx::Val( file_dyn() ); } if (HX_FIELD_EQ(inName,"init") ) { return ::hx::Val( init_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"check") ) { return ::hx::Val( check_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"exists") ) { return ::hx::Val( exists_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"backend") ) { return ::hx::Val( backend ); } if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); } if (HX_FIELD_EQ(inName,"getText") ) { return ::hx::Val( getText_dyn() ); } if (HX_FIELD_EQ(inName,"getPath") ) { return ::hx::Val( getPath_dyn() ); } if (HX_FIELD_EQ(inName,"getType") ) { return ::hx::Val( getType_dyn() ); } if (HX_FIELD_EQ(inName,"initMod") ) { return ::hx::Val( initMod_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"getBytes") ) { return ::hx::Val( getBytes_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"parseRules") ) { return ::hx::Val( parseRules ); } if (HX_FIELD_EQ(inName,"extensions") ) { return ::hx::Val( extensions ); } break; case 12: if (HX_FIELD_EQ(inName,"ignoredFiles") ) { return ::hx::Val( ignoredFiles ); } if (HX_FIELD_EQ(inName,"listModFiles") ) { return ::hx::Val( listModFiles_dyn() ); } if (HX_FIELD_EQ(inName,"_checkExists") ) { return ::hx::Val( _checkExists_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"checkDirectly") ) { return ::hx::Val( checkDirectly_dyn() ); } if (HX_FIELD_EQ(inName,"_extensionSet") ) { return ::hx::Val( _extensionSet_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"initExtensions") ) { return ::hx::Val( initExtensions_dyn() ); } break; case 15: if (HX_FIELD_EQ(inName,"getTextDirectly") ) { return ::hx::Val( getTextDirectly_dyn() ); } break; case 16: if (HX_FIELD_EQ(inName,"getExtensionType") ) { return ::hx::Val( getExtensionType_dyn() ); } break; case 18: if (HX_FIELD_EQ(inName,"mergeAndAppendText") ) { return ::hx::Val( mergeAndAppendText_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val PolymodAssetLibrary_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"type") ) { type=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } if (HX_FIELD_EQ(inName,"dirs") ) { dirs=inValue.Cast< ::Array< ::String > >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"backend") ) { backend=inValue.Cast< ::Dynamic >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"parseRules") ) { parseRules=inValue.Cast< ::polymod::format::ParseRules >(); return inValue; } if (HX_FIELD_EQ(inName,"extensions") ) { extensions=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 12: if (HX_FIELD_EQ(inName,"ignoredFiles") ) { ignoredFiles=inValue.Cast< ::Array< ::String > >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void PolymodAssetLibrary_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("backend",14,bc,87,fb)); outFields->push(HX_("type",ba,f2,08,4d)); outFields->push(HX_("dirs",86,66,69,42)); outFields->push(HX_("ignoredFiles",05,36,92,57)); outFields->push(HX_("parseRules",c4,aa,37,1b)); outFields->push(HX_("extensions",14,7c,70,89)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo PolymodAssetLibrary_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(PolymodAssetLibrary_obj,backend),HX_("backend",14,bc,87,fb)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,type),HX_("type",ba,f2,08,4d)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,dirs),HX_("dirs",86,66,69,42)}, {::hx::fsObject /* ::Array< ::String > */ ,(int)offsetof(PolymodAssetLibrary_obj,ignoredFiles),HX_("ignoredFiles",05,36,92,57)}, {::hx::fsObject /* ::polymod::format::ParseRules */ ,(int)offsetof(PolymodAssetLibrary_obj,parseRules),HX_("parseRules",c4,aa,37,1b)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(PolymodAssetLibrary_obj,extensions),HX_("extensions",14,7c,70,89)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *PolymodAssetLibrary_obj_sStaticStorageInfo = 0; #endif static ::String PolymodAssetLibrary_obj_sMemberFields[] = { HX_("backend",14,bc,87,fb), HX_("type",ba,f2,08,4d), HX_("dirs",86,66,69,42), HX_("ignoredFiles",05,36,92,57), HX_("parseRules",c4,aa,37,1b), HX_("extensions",14,7c,70,89), HX_("destroy",fa,2c,86,24), HX_("mergeAndAppendText",86,bb,89,90), HX_("getExtensionType",63,87,3c,56), HX_("getTextDirectly",79,59,58,bb), HX_("exists",dc,1d,e0,bf), HX_("getText",63,7c,7c,1f), HX_("getBytes",f5,17,6f,1d), HX_("getPath",5b,95,d4,1c), HX_("list",5e,1c,b3,47), HX_("listModFiles",d3,de,44,5a), HX_("check",c8,98,b6,45), HX_("getType",70,a2,8b,1f), HX_("checkDirectly",de,e2,4c,4c), HX_("file",7c,ce,bb,43), HX_("_checkExists",c5,9e,fb,07), HX_("init",10,3b,bb,45), HX_("initExtensions",44,2f,3b,ae), HX_("_extensionSet",42,4c,ed,05), HX_("initMod",92,dd,89,cb), ::String(null()) }; ::hx::Class PolymodAssetLibrary_obj::__mClass; void PolymodAssetLibrary_obj::__register() { PolymodAssetLibrary_obj _hx_dummy; PolymodAssetLibrary_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("polymod.backends.PolymodAssetLibrary",4a,cf,f5,08); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(PolymodAssetLibrary_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< PolymodAssetLibrary_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = PolymodAssetLibrary_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = PolymodAssetLibrary_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace polymod } // end namespace backends
44.411681
253
0.687077
SamuraiOfSecrets
0e5292bed843dd33e904a5cb5caddc5068c38910
24,442
cpp
C++
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
src/common/DecFloat.cpp
sas9mba/FB-ISQL-autopadding
033393aa80de4274ed9469767464e9b189b26838
[ "Condor-1.1" ]
null
null
null
/* * PROGRAM: Decimal 64 & 128 type. * MODULE: DecFloat.cpp * DESCRIPTION: Floating point with decimal exponent. * * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by Alex Peshkov * for the Firebird Open Source RDBMS project. * * Copyright (c) 2016 Alex Peshkov <peshkoff at mail dot ru> * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. * * */ #include "firebird.h" #include "DecFloat.h" #include "StatusArg.h" #include "gen/iberror.h" extern "C" { #include "../../extern/decNumber/decimal128.h" #include "../../extern/decNumber/decimal64.h" #include "../../extern/decNumber/decNumber.h" } #include <stdlib.h> #include <string.h> #include <float.h> using namespace Firebird; namespace { struct Dec2fb { USHORT decError; ISC_STATUS fbError; }; Dec2fb dec2fb[] = { { DEC_IEEE_754_Division_by_zero, isc_decfloat_divide_by_zero }, { DEC_IEEE_754_Inexact, isc_decfloat_inexact_result }, { DEC_IEEE_754_Invalid_operation, isc_decfloat_invalid_operation }, { DEC_IEEE_754_Overflow, isc_decfloat_overflow }, { DEC_IEEE_754_Underflow, isc_decfloat_underflow }, { 0, 0 } }; class DecimalContext : public decContext { public: DecimalContext(const Decimal64*, DecimalStatus ds) : decSt(ds) { init(DEC_INIT_DECIMAL64); } DecimalContext(const Decimal128Base*, DecimalStatus ds) : decSt(ds) { init(DEC_INIT_DECIMAL128); } ~DecimalContext() NOEXCEPT_ARG(false) { // Typically exceptions should better be not thrown from destructors. // But in our case there should never be any exception raised inside // Decimal64/128 functions - C library never throw, i.e. dtor will // be never called due to exception processing. // Therefore checking status in destructor is safe. checkForExceptions(); } void checkForExceptions() { USHORT unmaskedExceptions = decSt.decExtFlag & decContextGetStatus(this); if (!unmaskedExceptions) return; decContextZeroStatus(this); for (Dec2fb* e = dec2fb; e->decError; ++e) { // Arg::Gds(isc_arith_except) as first vector element ? if (e->decError & unmaskedExceptions) Arg::Gds(e->fbError).raise(); } } private: DecimalStatus decSt; void init(int kind) { decContextDefault(this, kind); fb_assert(decSt.roundingMode < USHORT(DEC_ROUND_MAX)); enum rounding rMode = rounding(decSt.roundingMode); decContextSetRounding(this, rMode); traps = 0; // do not raise SIGFPE } }; const CDecimal128 dmax(DBL_MAX, DecimalStatus(0)), dmin(-DBL_MAX, DecimalStatus(0)); const CDecimal128 dzup(DBL_MIN, DecimalStatus(0)), dzlw(-DBL_MIN, DecimalStatus(0)); const CDecimal128 i64max(MAX_SINT64, DecimalStatus(0)), i64min(MIN_SINT64, DecimalStatus(0)); const CDecimal128 c1(1); unsigned digits(const unsigned pMax, unsigned char* const coeff, int& exp) { for (unsigned i = 0; i < pMax; ++i) { if (coeff[i]) { if (i) { memmove(coeff, &coeff[i], pMax - i); memset(&coeff[pMax - i], 0, i); exp -= i; } i = pMax - i; while (!coeff[i - 1]) { fb_assert(i > 0); --i; } return i; } } return 0; } void make(ULONG* key, const unsigned pMax, const int bias, const unsigned decSize, unsigned char* coeff, int sign, int exp) { // normalize coeff & exponent unsigned dig = digits(pMax, coeff, exp); // exponent bias and sign if (!dig) { exp = 0; sign = 0; } else { exp += (bias + 2); if (sign) exp = -exp; } *key++ = exp; // convert to SLONG fb_assert(pMax / 9 < decSize / sizeof(int)); memset(key, 0, decSize); for (unsigned i = 0; i < pMax; ++i) { unsigned c = i / 9; key[c] *= 10; key[c] += (sign ? 9 - coeff[i] : coeff[i]); } } void grab(ULONG* key, const unsigned pMax, const int bias, const unsigned decSize, unsigned char* bcd, int& sign, int& exp) { exp = *key++; sign = 0; // parse exp if (exp < 0) { sign = DECFLOAT_Sign; exp = -exp; } if (exp != 0) exp -= (bias + 2); // convert from SLONG for (int i = pMax; i--;) { int c = i / 9; bcd[i] = key[c] % 10; key[c] /= 10; if (sign) bcd[i] = 9 - bcd[i]; } // normalize for (unsigned i = pMax; i--; ) { if (bcd[i]) { if (i < pMax - 1) { memmove(&bcd[pMax - 1 - i], bcd, i + 1); memset(bcd, 0, pMax - 1 - i); exp += (pMax - 1 - i); } break; } } } } // anonymous namespace namespace Firebird { void Decimal64::setScale(DecimalStatus decSt, int scale) { if (scale) { DecimalContext context(this, decSt); scale += decDoubleGetExponent(&dec); decDoubleSetExponent(&dec, &context, scale); } } #if SIZEOF_LONG < 8 Decimal64 Decimal64::set(int value, DecimalStatus decSt, int scale) { return set(SLONG(value), decSt, scale); } #endif Decimal64 Decimal64::set(SLONG value, DecimalStatus decSt, int scale) { decDoubleFromInt32(&dec, value); setScale(decSt, -scale); return *this; } Decimal64 Decimal64::set(DecimalFixed value, DecimalStatus decSt, int scale) { Decimal128 tmp; tmp.set(value, decSt, scale); *this = tmp.toDecimal64(decSt); return *this; } Decimal64 Decimal64::set(SINT64 value, DecimalStatus decSt, int scale) { { char s[30]; // for sure enough for int64 sprintf(s, "%" SQUADFORMAT, value); DecimalContext context(this, decSt); decDoubleFromString(&dec, s, &context); } setScale(decSt, -scale); return *this; } Decimal64 Decimal64::set(const char* value, DecimalStatus decSt) { DecimalContext context(this, decSt); decDoubleFromString(&dec, value, &context); return *this; } Decimal64 Decimal64::set(double value, DecimalStatus decSt) { char s[50]; sprintf(s, "%.016e", value); DecimalContext context(this, decSt); decDoubleFromString(&dec, s, &context); return *this; } void Decimal64::toString(DecimalStatus decSt, unsigned length, char* to) const { DecimalContext context(this, decSt); if (length) { --length; char s[IDecFloat16::STRING_SIZE]; memset(s, 0, sizeof(s)); decDoubleToString(&dec, s); if (strlen(s) > length) decContextSetStatus(&context, DEC_Invalid_operation); else length = strlen(s); memcpy(to, s, length + 1); } else decContextSetStatus(&context, DEC_Invalid_operation); } void Decimal64::toString(string& to) const { to.grow(IDecFloat16::STRING_SIZE); toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps to.recalculate_length(); } UCHAR* Decimal64::getBytes() { return dec.bytes; } Decimal64 Decimal64::abs() const { Decimal64 rc; decDoubleCopyAbs(&rc.dec, &dec); return rc; } Decimal64 Decimal64::ceil(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING); return rc; } Decimal64 Decimal64::floor(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR); return rc; } int Decimal64::compare(DecimalStatus decSt, Decimal64 tgt) const { DecimalStatus cmpStatus(decSt); cmpStatus.decExtFlag &= ~DEC_IEEE_754_Invalid_operation; DecimalContext context(this, cmpStatus); decDouble r; decDoubleCompare(&r, &dec, &tgt.dec, &context); return decDoubleToInt32(&r, &context, DEC_ROUND_HALF_UP); } bool Decimal64::isInf() const { switch (decDoubleClass(&dec)) { case DEC_CLASS_NEG_INF: case DEC_CLASS_POS_INF: return true; } return false; } bool Decimal64::isNan() const { switch (decDoubleClass(&dec)) { case DEC_CLASS_SNAN: case DEC_CLASS_QNAN: return true; } return false; } int Decimal64::sign() const { if (decDoubleIsZero(&dec)) return 0; if (decDoubleIsSigned(&dec)) return -1; return 1; } #ifdef DEV_BUILD int Decimal64::show() { decDoubleShow(&dec, ""); return 0; } #endif Decimal64 Decimal64::neg() const { Decimal64 rc; decDoubleCopyNegate(&rc.dec, &dec); return rc; } void Decimal64::makeKey(ULONG* key) const { unsigned char coeff[DECDOUBLE_Pmax]; int sign = decDoubleGetCoefficient(&dec, coeff); int exp = decDoubleGetExponent(&dec); make(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), coeff, sign, exp); } void Decimal64::grabKey(ULONG* key) { int exp, sign; unsigned char bcd[DECDOUBLE_Pmax]; grab(key, DECDOUBLE_Pmax, DECDOUBLE_Bias, sizeof(dec), bcd, sign, exp); decDoubleFromBCD(&dec, exp, bcd, sign); } Decimal64 Decimal64::quantize(DecimalStatus decSt, Decimal64 op2) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleQuantize(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal64 Decimal64::normalize(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal64 rc; decDoubleReduce(&rc.dec, &dec, &context); return rc; } short Decimal64::totalOrder(Decimal64 op2) const { decDouble r; decDoubleCompareTotal(&r, &dec, &op2.dec); fb_assert(!decDoubleIsNaN(&r)); DecimalContext context2(this, 0); return decDoubleToInt32(&r, &context2, DEC_ROUND_HALF_UP); } /* * decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values. * COMPARE_DECFLOAT (X, Y) * 0 - X == Y * 1 - X < Y * 2 - X > Y * 3 - values unordered */ short Decimal64::decCompare(Decimal64 op2) const { if (decDoubleIsNaN(&dec) || decDoubleIsNaN(&op2.dec)) return 3; switch (totalOrder(op2)) { case -1: return 1; case 0: return 0; case 1: return 2; default: fb_assert(false); } // warning silencer return 3; } Decimal128 Decimal128::set(Decimal64 d64) { decDoubleToWider(&d64.dec, &dec); return *this; } #if SIZEOF_LONG < 8 Decimal128 Decimal128::set(int value, DecimalStatus decSt, int scale) { return set(SLONG(value), decSt, scale); } #endif Decimal128 Decimal128::set(SLONG value, DecimalStatus decSt, int scale) { decQuadFromInt32(&dec, value); setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(DecimalFixed value, DecimalStatus decSt, int scale) { *this = value; setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(SINT64 value, DecimalStatus decSt, int scale) { { int high = value >> 32; unsigned low = value & 0xFFFFFFFF; DecimalContext context(this, decSt); decQuad pow2_32; decQuadFromString(&pow2_32, "4294967296", &context); decQuad up, down; decQuadFromInt32(&up, high); decQuadFromUInt32(&down, low); decQuadFMA(&dec, &up, &pow2_32, &down, &context); } setScale(decSt, -scale); return *this; } Decimal128 Decimal128::set(const char* value, DecimalStatus decSt) { DecimalContext context(this, decSt); decQuadFromString(&dec, value, &context); return *this; } Decimal128 Decimal128::set(double value, DecimalStatus decSt) { char s[50]; sprintf(s, "%.016e", value); DecimalContext context(this, decSt); decQuadFromString(&dec, s, &context); return *this; } DecimalFixed DecimalFixed::set(SLONG value) { decQuadFromInt32(&dec, value); return *this; } DecimalFixed DecimalFixed::set(SINT64 value) { int high = value >> 32; unsigned low = value & 0xFFFFFFFF; DecimalContext context(this, DecimalStatus(0)); decQuad pow2_32; decQuadFromString(&pow2_32, "4294967296", &context); decQuad up, down; decQuadFromInt32(&up, high); decQuadFromUInt32(&down, low); decQuadFMA(&dec, &up, &pow2_32, &down, &context); return *this; } DecimalFixed DecimalFixed::set(const char* value, int scale, DecimalStatus decSt) { { // scope for 'context' DecimalContext context(this, decSt); decQuadFromString(&dec, value, &context); } exactInt(decSt, scale); return *this; } DecimalFixed DecimalFixed::set(double value, int scale, DecimalStatus decSt) { char s[50]; sprintf(s, "%18.016e", value); { // scope for 'context' DecimalContext context(this, decSt); decQuadFromString(&dec, s, &context); } exactInt(decSt, scale); return *this; } void DecimalFixed::exactInt(DecimalStatus decSt, int scale) { setScale(decSt, -scale); DecimalContext context(this, decSt); decQuadToIntegralExact(&dec, &dec, &context); decQuadQuantize(&dec, &dec, &c1.dec, &context); } Decimal128 Decimal128::operator=(Decimal64 d64) { decDoubleToWider(&d64.dec, &dec); return *this; } int Decimal128::toInteger(DecimalStatus decSt, int scale) const { Decimal128 tmp(*this); tmp.setScale(decSt, -scale); DecimalContext context(this, decSt); enum rounding rMode = decContextGetRounding(&context); return decQuadToInt32(&tmp.dec, &context, rMode); } int DecimalFixed::toInteger(DecimalStatus decSt) const { DecimalContext context(this, decSt); enum rounding rMode = decContextGetRounding(&context); return decQuadToInt32(&dec, &context, rMode); } void Decimal128::toString(DecimalStatus decSt, unsigned length, char* to) const { DecimalContext context(this, decSt); if (length) { --length; char s[IDecFloat34::STRING_SIZE]; memset(s, 0, sizeof(s)); decQuadToString(&dec, s); if (strlen(s) > length) decContextSetStatus(&context, DEC_Invalid_operation); else length = strlen(s); memcpy(to, s, length + 1); } else decContextSetStatus(&context, DEC_Invalid_operation); } void Decimal128::toString(string& to) const { to.grow(IDecFloat34::STRING_SIZE); toString(DecimalStatus(0), to.length(), to.begin()); // provide long enough string, i.e. no traps to.recalculate_length(); } Decimal128 DecimalFixed::scaled128(DecimalStatus decSt, int scale) const { Decimal128 tmp; tmp.set(*this, decSt, -scale); return tmp; } void DecimalFixed::toString(DecimalStatus decSt, int scale, unsigned length, char* to) const { scaled128(decSt, scale).toString(decSt, length, to); } void DecimalFixed::toString(DecimalStatus decSt, int scale, string& to) const { scaled128(decSt, scale).toString(to); } double Decimal128Base::toDouble(DecimalStatus decSt) const { DecimalContext context(this, decSt); if (compare(decSt, dmin) < 0 || compare(decSt, dmax) > 0) decContextSetStatus(&context, DEC_Overflow); else if ((!decQuadIsZero(&dec)) && compare(decSt, dzlw) > 0 && compare(decSt, dzup) < 0) { decContextSetStatus(&context, DEC_Underflow); return 0.0; } else { char s[IDecFloat34::STRING_SIZE]; decQuadToString(&dec, s); return atof(s); } return 0.0; } SINT64 Decimal128::toInt64(DecimalStatus decSt, int scale) const { static CDecimal128 quant(1); Decimal128 wrk(*this); wrk.setScale(decSt, -scale); wrk = wrk.quantize(decSt, quant); if (wrk.compare(decSt, i64min) < 0 || wrk.compare(decSt, i64max) > 0) { DecimalContext context(this, decSt); decContextSetStatus(&context, DEC_Invalid_operation); return 0; // in case of no trap on invalid operation } unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&wrk.dec, coeff); SINT64 rc = 0; for (int i = 0; i < DECQUAD_Pmax; ++i) { rc *= 10; if (sign) rc -= coeff[i]; else rc += coeff[i]; } return rc; } SINT64 DecimalFixed::toInt64(DecimalStatus decSt) const { if (compare(decSt, i64min) < 0 || compare(decSt, i64max) > 0) { DecimalContext context(this, decSt); decContextSetStatus(&context, DEC_Invalid_operation); return 0; // in case of no trap on invalid operation } unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&dec, coeff); SINT64 rc = 0; for (int i = 0; i < DECQUAD_Pmax; ++i) { rc *= 10; if (sign) rc -= coeff[i]; else rc += coeff[i]; } return rc; } UCHAR* Decimal128Base::getBytes() { return dec.bytes; } Decimal64 Decimal128Base::toDecimal64(DecimalStatus decSt) const { Decimal64 rc; DecimalContext context(this, decSt); decDoubleFromWider(&rc.dec, &dec, &context); return rc; } void Decimal128Base::setScale(DecimalStatus decSt, int scale) { if (scale) { DecimalContext context(this, decSt); scale += decQuadGetExponent(&dec); decQuadSetExponent(&dec, &context, scale); } } int Decimal128Base::compare(DecimalStatus decSt, Decimal128Base tgt) const { DecimalContext context(this, decSt); decQuad r; decQuadCompare(&r, &dec, &tgt.dec, &context); return decQuadToInt32(&r, &context, DEC_ROUND_HALF_UP); } bool Decimal128Base::isInf() const { switch(decQuadClass(&dec)) { case DEC_CLASS_NEG_INF: case DEC_CLASS_POS_INF: return true; } return false; } bool Decimal128Base::isNan() const { switch(decQuadClass(&dec)) { case DEC_CLASS_SNAN: case DEC_CLASS_QNAN: return true; } return false; } int Decimal128Base::sign() const { if (decQuadIsZero(&dec)) return 0; if (decQuadIsSigned(&dec)) return -1; return 1; } Decimal128 Decimal128::ceil(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_CEILING); return rc; } Decimal128 Decimal128::floor(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadToIntegralValue(&rc.dec, &dec, &context, DEC_ROUND_FLOOR); return rc; } #ifdef DEV_BUILD int Decimal128Base::show() { decQuadShow(&dec, ""); return 0; } #endif Decimal128 Decimal128::abs() const { Decimal128 rc; decQuadCopyAbs(&rc.dec, &dec); return rc; } Decimal128 Decimal128::neg() const { Decimal128 rc; decQuadCopyNegate(&rc.dec, &dec); return rc; } Decimal128 Decimal128::add(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadAdd(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::sub(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadSubtract(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::mul(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadMultiply(&rc.dec, &dec, &op2.dec, &context); return rc; } DecimalFixed DecimalFixed::abs() const { DecimalFixed rc; decQuadCopyAbs(&rc.dec, &dec); return rc; } DecimalFixed DecimalFixed::neg() const { DecimalFixed rc; decQuadCopyNegate(&rc.dec, &dec); return rc; } DecimalFixed DecimalFixed::add(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadAdd(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } DecimalFixed DecimalFixed::sub(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadSubtract(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } DecimalFixed DecimalFixed::mul(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadMultiply(&rc.dec, &dec, &op2.dec, &context); context.checkForExceptions(); decQuadQuantize(&rc.dec, &rc.dec, &c1.dec, &context); return rc; } Decimal128 Decimal128::div(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadDivide(&rc.dec, &dec, &op2.dec, &context); return rc; } DecimalFixed DecimalFixed::div(DecimalStatus decSt, DecimalFixed op2, int scale) const { DecimalContext context(this, decSt); DecimalFixed rc; // first divide with full decfloat precision decQuadDivide(&rc.dec, &dec, &op2.dec, &context); // next re-scale & int-ize rc.exactInt(decSt, scale); return rc; } DecimalFixed DecimalFixed::mod(DecimalStatus decSt, DecimalFixed op2) const { DecimalContext context(this, decSt); DecimalFixed rc; decQuadRemainder(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::fma(DecimalStatus decSt, Decimal128 op2, Decimal128 op3) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadFMA(&rc.dec, &op2.dec, &op3.dec, &dec, &context); return rc; } Decimal128 Decimal128::sqrt(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberSquareRoot(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::pow(DecimalStatus decSt, Decimal128 op2) const { decNumber dn, dn2; decQuadToNumber(&dec, &dn); decQuadToNumber(&op2.dec, &dn2); DecimalContext context(this, decSt); decNumberPower(&dn, &dn, &dn2, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::ln(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberLn(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } Decimal128 Decimal128::log10(DecimalStatus decSt) const { decNumber dn; decQuadToNumber(&dec, &dn); DecimalContext context(this, decSt); decNumberLog10(&dn, &dn, &context); Decimal128 rc; decQuadFromNumber(&rc.dec, &dn, &context); return rc; } void Decimal128Base::makeKey(ULONG* key) const { unsigned char coeff[DECQUAD_Pmax]; int sign = decQuadGetCoefficient(&dec, coeff); int exp = decQuadGetExponent(&dec); make(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), coeff, sign, exp); } void Decimal128Base::grabKey(ULONG* key) { int exp, sign; unsigned char bcd[DECQUAD_Pmax]; grab(key, DECQUAD_Pmax, DECQUAD_Bias, sizeof(dec), bcd, sign, exp); decQuadFromBCD(&dec, exp, bcd, sign); } ULONG Decimal128Base::getIndexKeyLength() { return 17; } ULONG Decimal128Base::makeIndexKey(vary* buf) { unsigned char coeff[DECQUAD_Pmax + 2]; int sign = decQuadGetCoefficient(&dec, coeff); int exp = decQuadGetExponent(&dec); const int bias = DECQUAD_Bias; const unsigned pMax = DECQUAD_Pmax; // normalize coeff & exponent unsigned dig = digits(pMax, coeff, exp); // exponent bias and sign exp += (bias + 1); if (!dig) exp = 0; if (sign) exp = -exp; exp += 2 * (bias + 1); // make it positive fb_assert(exp >= 0 && exp < 64 * 1024); // encode exp char* k = buf->vary_string; *k++ = exp >> 8; *k++ = exp & 0xff; // invert negative unsigned char* const end = &coeff[dig]; if (sign && dig) { fb_assert(end[-1]); --end[-1]; for (unsigned char* p = coeff; p < end; ++p) *p = 9 - *p; } // Some 0's in the end - caller, do not forget to reserve additional space on stack end[0] = end[1] = 0; // Avoid bad data in k in case when coeff is zero *k = 0; // Shifts for moving 10-bit values to bytes buffer struct ShiftTable { UCHAR rshift, lshift; }; static ShiftTable table[4] = { { 2, 6 }, { 4, 4 }, { 6, 2 }, { 8, 0 } }; // compress coeff - 3 decimal digits (999) per 10 bits (1023) unsigned char* p = coeff; for (ShiftTable* t = table; p < end; p += 3) { USHORT val = p[0] * 100 + p[1] * 10 + p[2]; fb_assert(val < 1000); // 1024, 10 bit *k |= (val >> t->rshift); ++k; *k = (val << t->lshift); if (!t->lshift) { ++k; *k = 0; t = table; } else ++t; } if (*k) ++k; // done buf->vary_length = k - buf->vary_string; return buf->vary_length; } Decimal128 Decimal128::quantize(DecimalStatus decSt, Decimal128 op2) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadQuantize(&rc.dec, &dec, &op2.dec, &context); return rc; } Decimal128 Decimal128::normalize(DecimalStatus decSt) const { DecimalContext context(this, decSt); Decimal128 rc; decQuadReduce(&rc.dec, &dec, &context); return rc; } short Decimal128::totalOrder(Decimal128 op2) const { decQuad r; decQuadCompareTotal(&r, &dec, &op2.dec); fb_assert(!decQuadIsNaN(&r)); DecimalContext context2(this, 0); return decQuadToInt32(&r, &context2, DEC_ROUND_HALF_UP); } /* * decCompare() implements SQL function COMPARE_DECFLOAT() which has non-traditional return values. * COMPARE_DECFLOAT (X, Y) * 0 - X == Y * 1 - X < Y * 2 - X > Y * 3 - values unordered */ short Decimal128::decCompare(Decimal128 op2) const { if (decQuadIsNaN(&dec) || decQuadIsNaN(&op2.dec)) return 3; switch (totalOrder(op2)) { case -1: return 1; case 0: return 0; case 1: return 2; default: fb_assert(false); } // warning silencer return 3; } } // namespace Firebird
20.678511
99
0.699247
sas9mba
0e5508065b0d797d1fe9131d259423bc02830e86
1,161
cpp
C++
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
5
2021-04-30T14:30:20.000Z
2022-03-27T09:58:24.000Z
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
4
2021-06-15T10:52:10.000Z
2021-12-15T10:25:21.000Z
src/sconelib/scone/measures/JointLoadMeasure.cpp
alexxlzhou/scone-core
4a071626e5ee7ba253e72a973d4d214fa6e30cf5
[ "Apache-2.0" ]
2
2021-05-02T13:38:19.000Z
2021-07-22T19:37:07.000Z
/* ** JointLoadMeasure.cpp ** ** Copyright (C) 2013-2019 Thomas Geijtenbeek and contributors. All rights reserved. ** ** This file is part of SCONE. For more information, see http://scone.software. */ #include "JointLoadMeasure.h" #include "scone/model/Model.h" namespace scone { JointLoadMeasure::JointLoadMeasure( const PropNode& props, Params& par, const Model& model, const Location& loc ) : Measure( props, par, model, loc ), RangePenalty( props ), joint_load(), joint( *FindByName( model.GetJoints(), props.get< String >( "joint" ) ) ) { INIT_PROP( props, method, 1 ); } double JointLoadMeasure::ComputeResult( const Model& model ) { return RangePenalty<Real>::GetResult(); } bool JointLoadMeasure::UpdateMeasure( const Model& model, double timestamp ) { joint_load = joint.GetLoad(); AddSample( timestamp, joint_load ); return false; } scone::String JointLoadMeasure::GetClassSignature() const { return ""; } void JointLoadMeasure::StoreData( Storage< Real >::Frame& frame, const StoreDataFlags& flags ) const { // #todo: store joint load value frame[ joint.GetName() + ".load_penalty" ] = GetLatest(); } }
24.1875
116
0.701981
alexxlzhou
0e576d935bdfc6164bafd14477acb0af56ca1832
20,328
hh
C++
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
4
2016-01-26T06:03:13.000Z
2020-02-08T04:09:17.000Z
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
89
2016-01-24T22:09:34.000Z
2020-03-25T08:33:43.000Z
dune/xt/la/solver/fasp.hh
dune-community/dune-xt-la
2c3119fcc3798b14aa3c9228aed0e1ae8ee4ebcc
[ "BSD-2-Clause" ]
2
2018-04-09T11:52:25.000Z
2020-02-08T04:10:27.000Z
// This file is part of the dune-xt-la project: // https://github.com/dune-community/dune-xt-la // Copyright 2009-2018 dune-xt-la developers and contributors. All rights reserved. // License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // or GPL-2.0+ (http://opensource.org/licenses/gpl-license) // with "runtime exception" (http://www.dune-project.org/license.html) // Authors: // Felix Schindler (2013 - 2014, 2016 - 2017) // Rene Milk (2013, 2015 - 2016, 2018) // Tobias Leibner (2017) #ifndef DUNE_XT_LA_SOLVER_FASP_HH #define DUNE_XT_LA_SOLVER_FASP_HH #if HAVE_FASP # if HAVE_EIGEN extern "C" { # include "fasp_functs.h" } # include <dune/xt/la/container/eigen.hh> # include "interface.hh" namespace Dune { namespace XT { namespace LA { template <class ElementImp> class AmgSolver<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> : public SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> { public: typedef SolverInterface<Dune::XT::LA::EigenRowMajorSparseMatrix<ElementImp>, Dune::XT::LA::EigenDenseVector<ElementImp>> BaseType; typedef typename BaseType::MatrixType MatrixType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::ScalarType ScalarType; static Dune::ParameterTree defaultSettings() { Dune::ParameterTree description = BaseType::defaultIterativeSettings(); // these parameters were taken from the init.dat that Ludmil gave me... description["input_param.print_level"] = "3"; description["input_param.output_type"] = "0"; description["input_param.workdir"] = "./"; description["input_param.problem_num"] = "14 "; description["input_param.solver_type"] = "1"; description["input_param.precond_type"] = "2"; description["input_param.stop_type"] = "1"; description["input_param.itsolver_tol"] = "1.000000e-10"; description["input_param.itsolver_maxit"] = "1000"; description["input_param.restart"] = "20"; description["input_param.ILU_type"] = "1"; description["input_param.ILU_lfil"] = "0"; description["input_param.ILU_droptol"] = "1.000000e-01"; description["input_param.ILU_relax"] = "9.000000e-01"; description["input_param.ILU_permtol"] = "1.000000e-03"; description["input_param.Schwarz_mmsize"] = "200"; description["input_param.Schwarz_maxlvl"] = "2"; description["input_param.Schwarz_type"] = "1"; description["input_param.AMG_type"] = "1"; description["input_param.AMG_levels"] = "20"; description["input_param.AMG_cycle_type"] = "1"; description["input_param.AMG_smoother"] = "2"; description["input_param.AMG_relaxation"] = "1.100000e+00"; description["input_param.AMG_polynomial_degree"] = "3"; description["input_param.AMG_presmooth_iter"] = "2"; description["input_param.AMG_postsmooth_iter"] = "2"; description["input_param.AMG_coarse_dof"] = "100"; description["input_param.AMG_tol"] = "1.000000e-08"; description["input_param.AMG_maxit"] = "1"; description["input_param.AMG_ILU_levels"] = "0"; description["input_param.AMG_coarse_scaling"] = "0"; description["input_param.AMG_amli_degree"] = "2"; description["input_param.AMG_nl_amli_krylov_type"] = "6"; description["input_param.AMG_schwarz_levels"] = "0"; description["input_param.AMG_coarsening_type"] = "1"; description["input_param.AMG_interpolation_type"] = "1"; description["input_param.AMG_strong_threshold"] = "3.000000e-01"; description["input_param.AMG_truncation_threshold"] = "4.000000e-01"; description["input_param.AMG_max_row_sum"] = "9.000000e-01"; description["input_param.AMG_strong_coupled"] = "8.000000e-02"; description["input_param.AMG_max_aggregation"] = "20"; description["input_param.AMG_tentative_smooth"] = "6.700000e-01"; description["input_param.AMG_smooth_filter"] = "0"; description["itsolver_param.itsolver_type"] = "1"; description["itsolver_param.precond_type"] = "2"; description["itsolver_param.stop_type"] = "1"; description["itsolver_param.maxit"] = "1000"; description["itsolver_param.tol"] = "1.000000e-10"; description["itsolver_param.restart"] = "20"; description["itsolver_param.print_level"] = "3"; description["AMG_param.AMG_type"] = "1"; description["AMG_param.print_level"] = "3"; description["AMG_param.maxit"] = "1"; description["AMG_param.tol"] = "1.000000e-08"; description["AMG_param.max_levels"] = "20"; description["AMG_param.coarse_dof"] = "100"; description["AMG_param.cycle_type"] = "1"; description["AMG_param.smoother"] = "2"; description["AMG_param.smooth_order"] = "1"; description["AMG_param.presmooth_iter"] = "2"; description["AMG_param.postsmooth_iter"] = "2"; description["AMG_param.relaxation"] = "1.100000e+00"; description["AMG_param.polynomial_degree"] = "3"; description["AMG_param.coarse_scaling"] = "0"; description["AMG_param.amli_degree"] = "2"; description["AMG_param.amli_coef"] = "1.100000e+00"; description["AMG_param.nl_amli_krylov_type"] = "6"; description["AMG_param.coarsening_type"] = "1"; description["AMG_param.interpolation_type"] = "1"; description["AMG_param.strong_threshold"] = "3.000000e-01"; description["AMG_param.max_row_sum"] = "9.000000e-01"; description["AMG_param.truncation_threshold"] = "4.000000e-01"; description["AMG_param.strong_coupled"] = "8.000000e-02"; description["AMG_param.max_aggregation"] = "20"; description["AMG_param.tentative_smooth"] = "6.700000e-01"; description["AMG_param.smooth_filter"] = "0"; description["AMG_param.ILU_levels"] = "0"; description["AMG_param.ILU_type"] = "1"; description["AMG_param.ILU_lfil"] = "0"; description["AMG_param.ILU_droptol"] = "1.000000e-01"; description["AMG_param.ILU_relax"] = "9.000000e-01"; description["AMG_param.ILU_permtol"] = "1.000000e-03"; description["AMG_param.schwarz_levels"] = "0"; description["AMG_param.schwarz_mmsize"] = "200"; description["AMG_param.schwarz_maxlvl"] = "2"; description["AMG_param.schwarz_type"] = "1"; description["ILU_param.print_level"] = "3"; description["ILU_param.ILU_type"] = "1"; description["ILU_param.ILU_lfil"] = "0"; description["ILU_param.ILU_droptol"] = "1.000000e-01"; description["ILU_param.ILU_relax"] = "9.000000e-01"; description["ILU_param.ILU_permtol"] = "1.000000e-03"; description["Schwarz_param.print_level"] = "3"; description["Schwarz_param.schwarz_type"] = "1"; description["Schwarz_param.schwarz_maxlvl"] = "2"; description["Schwarz_param.schwarz_mmsize"] = "200"; return description; } // Dune::ParameterTree defaultSettings() /** * \attention There is a const_cast inside, in order to forward non-const pointers to fasp. I hope they do not * touch the matrix, but who knows... */ virtual size_t apply(const MatrixType& _systemMatrix, const VectorType& _rhsVector, VectorType& solutionVector, const Dune::ParameterTree description = defaultSettings()) const { const size_t maxIter = description.get<size_t>("maxIter"); const ScalarType precision = description.get<ScalarType>("precision"); // init system matrix and right hand side MatrixType& systemMatrix = const_cast<MatrixType&>(_systemMatrix); VectorType& rhsVector = const_cast<VectorType&>(_rhsVector); dCSRmat A; A.row = systemMatrix.rows(); A.col = systemMatrix.cols(); A.nnz = systemMatrix.backend().nonZeros(); A.IA = systemMatrix.backend().outerIndexPtr(); A.JA = systemMatrix.backend().innerIndexPtr(); A.val = systemMatrix.backend().valuePtr(); dvector f, x; f.row = rhsVector.size(); f.val = rhsVector.backend().data(); x.row = rhsVector.backend().rows(); x.val = solutionVector.backend().data(); // init parameters input_param inparam = initInputParams(maxIter, precision, description); itsolver_param itparam = initItsolverParams(maxIter, precision, description); AMG_param amgparam = initAMGParams(1, precision, description); // the 1 is on purpose! ILU_param iluparam = initIluParams(maxIter, precision, description); Schwarz_param swzparam = initSchwarzParams(maxIter, precision, description); // call fasp (this is taken from the fasp example test) int status = -1; // Preconditioned Krylov methods if (inparam.solver_type >= 1 && inparam.solver_type <= 20) { // Using no preconditioner for Krylov iterative methods if (inparam.precond_type == PREC_NULL) { status = fasp_solver_dcsr_krylov(&A, &f, &x, &itparam); } // Using diag(A) as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_DIAG) { status = fasp_solver_dcsr_krylov_diag(&A, &f, &x, &itparam); } // Using AMG as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_AMG || inparam.precond_type == PREC_FMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); status = fasp_solver_dcsr_krylov_amg(&A, &f, &x, &itparam, &amgparam); } // Using ILU as preconditioner for Krylov iterative methods Q: Need to change! else if (inparam.precond_type == PREC_ILU) { if (inparam.print_level > PRINT_NONE) fasp_param_ilu_print(&iluparam); status = fasp_solver_dcsr_krylov_ilu(&A, &f, &x, &itparam, &iluparam); } // Using Schwarz as preconditioner for Krylov iterative methods else if (inparam.precond_type == PREC_SCHWARZ) { if (inparam.print_level > PRINT_NONE) fasp_param_schwarz_print(&swzparam); status = fasp_solver_dcsr_krylov_schwarz(&A, &f, &x, &itparam, &swzparam); } else { printf("### ERROR: Wrong preconditioner type %d!!!\n", inparam.precond_type); status = ERROR_SOLVER_PRECTYPE; } } // AMG as the iterative solver else if (inparam.solver_type == SOLVER_AMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); fasp_solver_amg(&A, &f, &x, &amgparam); } // Full AMG as the iterative solver else if (inparam.solver_type == SOLVER_FMG) { if (inparam.print_level > PRINT_NONE) fasp_param_amg_print(&amgparam); fasp_solver_famg(&A, &f, &x, &amgparam); } else { DUNE_THROW(Dune::RangeError, "### ERROR: Wrong solver type: " << inparam.solver_type << "!"); status = ERROR_SOLVER_TYPE; } if (status > 0) return 0; else return 3; } // ... apply(...) private: input_param initInputParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { input_param inputParam; inputParam.print_level = description.get<int>("input_param.print_level", 0); inputParam.output_type = description.get<int>("input_param.output_type", 0); // inputParam.workdir = description.get< char >("input_param.workdir", '.'); inputParam.problem_num = 14; inputParam.solver_type = description.get<int>("input_param.solver_type", 1); inputParam.precond_type = description.get<int>("input_param.precond_type", 2); inputParam.stop_type = description.get<int>("input_param.stop_type", 1); inputParam.itsolver_tol = precision; inputParam.itsolver_maxit = maxIter; inputParam.restart = description.get<int>("input_param.restart", 20); inputParam.ILU_type = description.get<int>("input_param.ILU_type", 1); inputParam.ILU_lfil = description.get<int>("input_param.ILU_lfil", 0); inputParam.ILU_droptol = description.get<double>("input_param.ILU_droptol", 1.000000e-01); inputParam.ILU_relax = description.get<double>("input_param.ILU_relax", 9.000000e-01); inputParam.ILU_permtol = description.get<double>("input_param.ILU_permtol", 1.000000e-03); inputParam.Schwarz_mmsize = description.get<int>("input_param.Schwarz_mmsize", 200); inputParam.Schwarz_maxlvl = description.get<int>("input_param.Schwarz_maxlvl", 2); inputParam.Schwarz_type = description.get<int>("input_param.Schwarz_type", 1); inputParam.AMG_type = description.get<int>("input_param.AMG_type", 1); inputParam.AMG_levels = description.get<int>("input_param.AMG_levels", 20); inputParam.AMG_cycle_type = description.get<int>("input_param.AMG_cycle_type", 1); inputParam.AMG_smoother = description.get<int>("input_param.AMG_smoother", 2); inputParam.AMG_relaxation = description.get<double>("input_param.AMG_relaxation", 1.100000e+00); inputParam.AMG_polynomial_degree = description.get<int>("input_param.AMG_polynomial_degree", 3); inputParam.AMG_presmooth_iter = description.get<int>("input_param.AMG_presmooth_iter", 2); inputParam.AMG_postsmooth_iter = description.get<int>("input_param.AMG_postsmooth_iter", 2); inputParam.AMG_coarse_dof = description.get<int>("input_param.AMG_coarse_dof", 100); inputParam.AMG_tol = description.get<double>("input_param.AMG_tol", 1.000000e-08); inputParam.AMG_maxit = description.get<int>("input_param.AMG_maxit", 1); inputParam.AMG_ILU_levels = description.get<int>("input_param.AMG_ILU_levels", 0); inputParam.AMG_coarse_scaling = description.get<int>("input_param.AMG_coarse_scaling", 0); inputParam.AMG_amli_degree = description.get<int>("input_param.AMG_amli_degree", 2); inputParam.AMG_nl_amli_krylov_type = description.get<int>("input_param.AMG_nl_amli_krylov_type", 6); inputParam.AMG_schwarz_levels = description.get<int>("input_param.AMG_schwarz_levels", 0); inputParam.AMG_coarsening_type = description.get<int>("input_param.AMG_coarsening_type", 1); inputParam.AMG_interpolation_type = description.get<int>("input_param.AMG_interpolation_type", 1); inputParam.AMG_strong_threshold = description.get<double>("input_param.AMG_strong_threshold", 3.000000e-01); inputParam.AMG_truncation_threshold = description.get<double>("input_param.AMG_truncation_threshold", 4.000000e-01); inputParam.AMG_max_row_sum = description.get<double>("input_param.AMG_max_row_sum", 9.000000e-01); inputParam.AMG_strong_coupled = description.get<double>("input_param.AMG_strong_coupled", 8.000000e-02); inputParam.AMG_max_aggregation = description.get<int>("input_param.AMG_max_aggregation", 20); inputParam.AMG_tentative_smooth = description.get<double>("input_param.AMG_tentative_smooth", 6.700000e-01); inputParam.AMG_smooth_filter = description.get<int>("input_param.AMG_smooth_filter", 0); return inputParam; } // ... initInputParams(...) itsolver_param initItsolverParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { itsolver_param itsolverParams; itsolverParams.itsolver_type = description.get<int>("itsolver_param.itsolver_type", 1); itsolverParams.precond_type = description.get<int>("itsolver_param.precond_type", 2); itsolverParams.stop_type = description.get<int>("itsolver_param.stop_type", 1); itsolverParams.maxit = maxIter; itsolverParams.tol = precision; itsolverParams.restart = description.get<int>("itsolver_param.restart", 20); itsolverParams.print_level = description.get<int>("itsolver_param.print_level", 0); return itsolverParams; } // ... initItsolverParams(...) AMG_param initAMGParams(const size_t& maxIter, const ScalarType& precision, const Dune::ParameterTree& description) const { AMG_param amgParams; amgParams.AMG_type = description.get<int>("AMG_param.AMG_type", 1); amgParams.print_level = description.get<int>("AMG_param.print_level", 0); amgParams.maxit = maxIter; amgParams.tol = precision; amgParams.max_levels = description.get<int>("AMG_param.max_levels", 20); amgParams.coarse_dof = description.get<int>("AMG_param.coarse_dof", 100); amgParams.cycle_type = description.get<int>("AMG_param.cycle_type", 1); amgParams.smoother = description.get<int>("AMG_param.smoother", 2); amgParams.smooth_order = description.get<int>("AMG_param.smooth_order", 1); amgParams.presmooth_iter = description.get<int>("AMG_param.presmooth_iter", 2); amgParams.postsmooth_iter = description.get<int>("AMG_param.postsmooth_iter", 2); amgParams.relaxation = description.get<double>("AMG_param.relaxation", 1.1); amgParams.polynomial_degree = description.get<int>("AMG_param.polynomial_degree", 3); amgParams.coarse_scaling = description.get<int>("AMG_param.coarse_scaling", 0); amgParams.amli_degree = description.get<int>("AMG_param.amli_degree", 2); double tmp = description.get<double>("AMG_param.amli_coef", 1.1); amgParams.amli_coef = &tmp; amgParams.nl_amli_krylov_type = description.get<int>("AMG_param.nl_amli_krylov_type", 6); amgParams.coarsening_type = description.get<int>("AMG_param.coarsening_type", 1); amgParams.interpolation_type = description.get<int>("AMG_param.interpolation_type", 1); amgParams.strong_threshold = description.get<double>("AMG_param.strong_threshold", 3.e-1); amgParams.max_row_sum = description.get<double>("AMG_param.max_row_sum", 9.0e-1); amgParams.truncation_threshold = description.get<double>("AMG_param.truncation_threshold", 1.0e-1); amgParams.strong_coupled = description.get<double>("AMG_param.strong_coupled", 8.0e-2); amgParams.max_aggregation = description.get<int>("AMG_param.max_aggregation", 20); amgParams.tentative_smooth = description.get<double>("AMG_param.tentative_smooth", 6.7e-1); amgParams.smooth_filter = description.get<int>("AMG_param.smooth_filter", 0); amgParams.ILU_levels = description.get<int>("AMG_param.ILU_levels", 0); amgParams.ILU_type = description.get<int>("AMG_param.ILU_type", 1); amgParams.ILU_lfil = description.get<int>("AMG_param.ILU_lfil", 0); amgParams.ILU_droptol = description.get<double>("AMG_param.ILU_droptol", 1.0e-1); amgParams.ILU_relax = description.get<double>("AMG_param.ILU_relax", 9.0e-1); amgParams.ILU_permtol = description.get<double>("AMG_param.ILU_permtol", 1.0e-3); amgParams.schwarz_levels = description.get<int>("AMG_param.schwarz_levels", 0); amgParams.schwarz_mmsize = description.get<int>("AMG_param.schwarz_mmsize", 200); amgParams.schwarz_maxlvl = description.get<int>("AMG_param.schwarz_maxlvl", 2); amgParams.schwarz_type = description.get<int>("AMG_param.schwarz_type", 1); return amgParams; } // ... initAMGParams(...) ILU_param initIluParams(const size_t& /*maxIter*/, const ScalarType& /*precision*/, const Dune::ParameterTree& description) const { ILU_param iluParams; iluParams.print_level = description.get<int>("ILU_param.print_level", 0); iluParams.ILU_type = description.get<int>("ILU_param.ILU_type", 1); iluParams.ILU_lfil = description.get<int>("ILU_param.ILU_lfil", 0); iluParams.ILU_droptol = description.get<double>("ILU_param.ILU_droptol", 1.0e-1); iluParams.ILU_relax = description.get<double>("ILU_param.ILU_relax", 9.0e-1); iluParams.ILU_permtol = description.get<double>("ILU_param.ILU_permtol", 1.0e-3); return iluParams; } // ... initIluParams(...) Schwarz_param initSchwarzParams(const size_t& /*maxIter*/, const ScalarType& /*precision*/, const Dune::ParameterTree& description) const { Schwarz_param schwarzParams; schwarzParams.print_level = description.get<int>("schwarzParams.print_level", 0); schwarzParams.schwarz_type = description.get<int>("schwarzParams.schwarz_type", 1); schwarzParams.schwarz_maxlvl = description.get<int>("schwarzParams.schwarz_maxlvl", 2); schwarzParams.schwarz_mmsize = description.get<int>("schwarzParams.schwarz_mmsize", 200); return schwarzParams; } // ... initSchwarzParams(...) }; // class AmgSolver } // namespace LA } // namespace XT } // namespace Dune # endif // HAVE_EIGEN #endif // HAVE_FASP #endif // DUNE_XT_LA_SOLVER_FASP_HH
53.635884
120
0.711531
dune-community
0e58ac0f89a74345cbb8d4ba7f6b0084e0a13a64
2,277
cpp
C++
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
3
2019-02-25T10:13:57.000Z
2020-11-11T14:46:14.000Z
my_vulkan/texture_sampler.cpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
#include "texture_sampler.hpp" #include "utils.hpp" namespace my_vulkan { texture_sampler_t::texture_sampler_t(VkDevice device, filter_mode_t filter_mode) : _device{device} { VkFilter filter; switch(filter_mode) { case filter_mode_t::linear: filter = VK_FILTER_LINEAR; break; case filter_mode_t::nearest: filter = VK_FILTER_NEAREST; break; case filter_mode_t::cubic: filter = VK_FILTER_CUBIC_IMG; break; } VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.pNext = 0; samplerInfo.flags = 0; samplerInfo.magFilter = filter; samplerInfo.minFilter = filter; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; vk_require( vkCreateSampler(device, &samplerInfo, nullptr, &_sampler), "creating texture sampler" ); } texture_sampler_t::texture_sampler_t(texture_sampler_t&& other) noexcept : _device{0} { *this = std::move(other); } texture_sampler_t& texture_sampler_t::operator=(texture_sampler_t&& other) noexcept { cleanup(); _sampler = other._sampler; std::swap(_device, other._device); return *this; } texture_sampler_t::~texture_sampler_t() { cleanup(); } void texture_sampler_t::cleanup() { if (_device) { vkDestroySampler(_device, _sampler, nullptr); _device = 0; } } VkSampler texture_sampler_t::get() { return _sampler; } }
29.571429
87
0.625823
pixelwise
0e5b6811ac90710d35f50afa1cb894e3193535a4
5,624
cc
C++
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
11
2015-11-10T09:56:37.000Z
2021-02-09T02:10:45.000Z
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
40
2015-01-08T12:16:37.000Z
2016-06-08T19:41:03.000Z
service/testing/epoll_test.cc
datacratic/soa
74eeda506feb522de9181aac4a5543c7766e600e
[ "Apache-2.0" ]
10
2015-01-05T21:46:46.000Z
2021-09-26T10:07:07.000Z
/* epoll_test.cc Wolfgang Sourdeau, 17 November 2014 Copyright (c) 2014 Datacratic. All rights reserved. Assumption tests for epoll */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <fcntl.h> #include <unistd.h> #include <sys/epoll.h> #include <atomic> #include <iostream> #include <thread> #include <boost/test/unit_test.hpp> #include <jml/arch/exception.h> #include <jml/arch/futex.h> #include <jml/arch/timers.h> #include <jml/utils/exc_assert.h> using namespace std; namespace { #if 1 /* Assumption test - this disproves the race condition initially suspected * with EPOLLONESHOT in the following scenario: - armed fd - (data received) - epoll_wait returns due to armed fd and data received - read fd - (data received) - rearmed fd - epoll_wait waits indefinitely due to data emitted before fd rearmed fd */ void thread1Fn(atomic<int> & stage, int epollFd, int pipeFds[2]) { uint32_t readData; struct epoll_event armEvent, event; armEvent.events = EPOLLIN | EPOLLONESHOT; ::fprintf(stderr, "thread 1: arming fd\n"); int rc = ::epoll_ctl(epollFd, EPOLL_CTL_ADD, pipeFds[0], &armEvent); if (rc == -1) { throw ML::Exception(errno, "epoll_ctl"); } stage = 1; ML::futex_wake(stage); ::fprintf(stderr, "thread 1: waiting 1\n"); while (true) { rc = ::epoll_wait(epollFd, &event, 1, -1); if (rc == -1) { if (errno == EINTR) { continue; } throw ML::Exception(errno, "epoll_wait"); } break; } ::fprintf(stderr, "thread 1: reading 1\n"); rc = ::read(pipeFds[0], &readData, sizeof(readData)); if (rc == -1) { throw ML::Exception(errno, "read"); } ExcAssertEqual(rc, sizeof(readData)); ExcAssertEqual(readData, 1); ML::sleep(1.0); ::fprintf(stderr, "thread 1: reading 2\n"); rc = ::read(pipeFds[0], &readData, sizeof(readData)); if (rc == -1) { throw ML::Exception(errno, "read"); } ExcAssertEqual(rc, sizeof(readData)); ExcAssertEqual(readData, 0x1fffffff); ML::sleep(1.0); rc = ::read(pipeFds[0], &readData, sizeof(readData)); ExcAssert(rc == -1); ExcAssert(errno == EWOULDBLOCK); stage = 2; ML::futex_wake(stage); ::fprintf(stderr, "thread 1: data read, awaiting final notification from thread" " 2\n"); while (stage.load() != 3) { ML::futex_wait(stage, 2); } ::fprintf(stderr, "thread 1: notified of final payload from thread 2\n"); ML::sleep(1.0); ::fprintf(stderr, "thread 1: rearming\n"); rc = ::epoll_ctl(epollFd, EPOLL_CTL_MOD, pipeFds[0], &armEvent); if (rc == -1) { throw ML::Exception(errno, "epoll_ctl"); } ::fprintf(stderr, "thread 1: epoll_wait for final payload\n"); while (true) { rc = ::epoll_wait(epollFd, &event, 1, 2000); if (rc == -1) { if (errno == EINTR) { continue; } throw ML::Exception(errno, "epoll_wait"); } else if (rc == 0) ::fprintf(stderr, "thread 1: second epoll wait has no event\n"); else if (rc > 0) ::fprintf(stderr, "thread 1: second epoll wait has %d events\n", rc); break; } /* This proves that the data written in thread 2 was properly received despite being sent before the rearming of our end of the pipe. */ BOOST_CHECK_EQUAL(rc, 1); } void thread2Fn(atomic<int> & stage, int epollFd, int pipeFds[2]) { ::fprintf(stderr, "thread 2: initial wait for thread1\n"); while (stage.load() != 1) { ML::futex_wait(stage, 0); } uint32_t writeData(1); int rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 1 written\n"); writeData = 0x1fffffff; rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 2 written\n"); ::fprintf(stderr, "thread 2: waiting thread 1\n"); while (stage.load() != 2) { ML::futex_wait(stage, 1); } ::fprintf(stderr, "thread 2: thread1 done reading, writing again\n"); writeData = 0x12345678; rc = ::write(pipeFds[1], &writeData, sizeof(writeData)); if (rc == -1) { throw ML::Exception(errno, "write"); } ExcAssert(rc == sizeof(writeData)); ::fprintf(stderr, "thread 2: payload 3 written\n"); ::fprintf(stderr, "thread 2: writing complete, notifying thread 1\n"); stage++; ML::futex_wake(stage); } } BOOST_AUTO_TEST_CASE( test_epolloneshot ) { int epollFd = ::epoll_create(666); if (epollFd == -1) { throw ML::Exception(errno, "epoll_create"); } int pipeFds[2]; if (::pipe2(pipeFds, O_NONBLOCK) == -1) { throw ML::Exception(errno, "pipe2"); } atomic<int> stage(0); /* receiving thread */ auto thread1Lda = [&] () { thread1Fn(stage, epollFd, pipeFds); ::fprintf(stderr, "thread1 done\n"); }; thread thread1(thread1Lda); /* sending thread */ auto thread2Lda = [&] () { thread2Fn(stage, epollFd, pipeFds); ::fprintf(stderr, "thread 2 done\n"); }; thread thread2(thread2Lda); thread2.join(); thread1.join(); ::close(pipeFds[0]); ::close(pipeFds[1]); ::close(epollFd); } #endif
26.403756
76
0.590683
datacratic
0e5ef653e2f5d7b0a25571e20bd63aca77ba7b3b
3,617
cpp
C++
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
43
2017-08-09T04:03:38.000Z
2018-07-17T15:25:32.000Z
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
3
2018-01-23T06:44:41.000Z
2018-05-29T19:22:41.000Z
Sources/Fonts/FontType.cpp
Equilibrium-Games/Flounder
1bd67dc8c2c2ebee2ca95f0cabb40b926f747fcf
[ "MIT" ]
6
2017-11-03T10:48:20.000Z
2018-04-28T21:44:59.000Z
#include "FontType.hpp" #include <tiny_msdf.hpp> #include <ft2build.h> #include FT_FREETYPE_H #include "Files/Files.hpp" #include "Resources/Resources.hpp" #include "Graphics/Graphics.hpp" namespace acid { static const std::wstring_view NEHE = L" \t\r\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\"!`?'.,;:()[]{}<>|/@\\^$-%+=#_&~*"; template<typename T> constexpr double F26DOT6_TO_DOUBLE(T x) { return 1.0 / 64.0 * double(x); } std::shared_ptr<FontType> FontType::Create(const Node &node) { if (auto resource = Resources::Get()->Find<FontType>(node)) return resource; auto result = std::make_shared<FontType>("", 0, false); Resources::Get()->Add(node, std::dynamic_pointer_cast<Resource>(result)); node >> *result; result->Load(); return result; } std::shared_ptr<FontType> FontType::Create(const std::filesystem::path &filename, std::size_t size) { FontType temp(filename, size, false); Node node; node << temp; return Create(node); } FontType::FontType(std::filesystem::path filename, std::size_t size, bool load) : filename(std::move(filename)), size(size) { if (load) FontType::Load(); } FontType::~FontType() { Close(); } const Node &operator>>(const Node &node, FontType &fontType) { node["filename"].Get(fontType.filename); node["size"].Get(fontType.size); return node; } Node &operator<<(Node &node, const FontType &fontType) { node["filename"].Set(fontType.filename); node["size"].Set(fontType.size); return node; } void FontType::Open() { if (auto error = FT_Init_FreeType(&library)) throw std::runtime_error("Freetype failed to initialize"); auto fileLoaded = Files::Read(filename); if (!fileLoaded) { Log::Error("Font could not be loaded: ", filename, '\n'); return; } if (FT_New_Memory_Face(library, reinterpret_cast<FT_Byte *>(fileLoaded->data()), static_cast<FT_Long>(fileLoaded->size()), 0, &face) != 0) throw std::runtime_error("Freetype failed to create face from memory"); // Multiply pixel size by 64 as FreeType uses points instead of pixels internally. if (FT_Set_Char_Size(face, size * 64, size * 64, 96, 96) != 0) throw std::runtime_error("Freetype failed to set char size"); } void FontType::Close() { if (!IsOpen()) return; FT_Done_Face(face); face = nullptr; FT_Done_FreeType(library); library = nullptr; } void FontType::Load() { if (filename.empty()) return; #ifdef ACID_DEBUG auto debugStart = Time::Now(); #endif Open(); auto layerCount = NEHE.size(); //image = std::make_unique<Image2dArray>(Vector2ui(size, size), layerCount, VK_FORMAT_R32G32B32A32_SFLOAT); tinymsdf::Bitmap<float, 4> mtsdf(size, size); glyphs.resize(glyphs.size() + layerCount); for (auto c : NEHE) { bool success = !tinymsdf::GenerateMTSDF(mtsdf, face, c); auto id = indices.size(); indices[c] = id; glyphs[id].advance = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiAdvance); glyphs[id].x = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingX); glyphs[id].y = F26DOT6_TO_DOUBLE(face->glyph->metrics.horiBearingY); glyphs[id].w = F26DOT6_TO_DOUBLE(face->glyph->metrics.width); glyphs[id].h = F26DOT6_TO_DOUBLE(face->glyph->metrics.height); glyphs[id].pxRange = 2; //if (success) // image->SetPixels(mtsdf.pixels, id); } Close(); #ifdef ACID_DEBUG Log::Out("Font Type ", filename, " loaded ", glyphs.size(), " glyphs in ", (Time::Now() - debugStart).AsMilliseconds<float>(), "ms\n"); #endif } std::optional<FontType::Glyph> FontType::GetGlyph(wchar_t ascii) const { auto it = indices.find(ascii); if (it != indices.end()) { return glyphs[it->second]; } return std::nullopt; } }
26.40146
145
0.697263
Equilibrium-Games
0e606b0a8a475b3df31cfe975fe752e36b16ddd0
855
cpp
C++
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
day-9-6-1.cpp
duasong111/c_lang_learn
4a939204a9d12a1fd0a6ca4ff36ed3bfdfb97482
[ "BSD-2-Clause" ]
null
null
null
/* 求四名同学在三次考试中的成绩 */ #include <stdio.h> void mat_add(const int a[4][3], const int b[4][3], int c[4][3]); void mat_print(const int m[4][3]); int main(void) { int sore1[4][3] = { {23, 13,23}, {23, 67, 89}, {34, 56, 67}, {89,98, 32} }; int sore2[4][3] = { {93, 43,33}, {23, 63, 82}, {34, 66, 87}, {69,93, 39} }; int sum[4][3]; mat_add(sore1, sore2, sum); printf("第一次考试的分数\n"); mat_print(sore1); printf("第二次考试的分数\n"); mat_print(sore2); puts("总分"); mat_print(sum); return 0; } void mat_add(const int a[4][3], const int b[4][3], int c[4][3]) { int i, j; for (i = 0; i < 4; i++) for (j = 0; j < 3; j++) c[i][j] = a[i][j] + b[i][j]; // 那个也是这个样子吗? } void mat_print(const int m[4][3]) { int i, j; for (i = 0; i < 4; i++) { for (j = 0; j < 3; j++) printf("%4d", m[i][j]); putchar('\n'); } }
21.923077
77
0.493567
duasong111
0e6616c096e92c2c85f7599f6a5a81dfc094f72b
3,273
cpp
C++
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
16
2021-09-14T14:19:08.000Z
2022-02-02T23:51:04.000Z
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
10
2021-09-15T17:51:26.000Z
2022-01-20T11:22:26.000Z
src/python_bindings.cpp
johnlees/mandrake
f34deb1aeed730041398923c1c0d6e6d5ccb9611
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
1
2021-09-28T14:44:12.000Z
2021-09-28T14:44:12.000Z
// 2021 John Lees, Gerry Tonkin-Hill, Zhirong Yang // See LICENSE files #include "pairsnp.hpp" #include "sound.hpp" #include "wtsne.hpp" #include <pybind11/stl.h> namespace py = pybind11; PYBIND11_MODULE(SCE, m) { m.doc() = "Stochastic cluster embedding"; m.attr("version") = VERSION_INFO; // Results class (need to define here to be able to return this type) py::class_<sce_results, std::shared_ptr<sce_results>>(m, "sce_result") .def(py::init<const bool, const size_t, const uint64_t>()) .def("animated", &sce_results::is_animated) .def("n_frames", &sce_results::n_frames) .def("get_eq", &sce_results::get_eq) .def("get_embedding", &sce_results::get_embedding) .def("get_embedding_frame", &sce_results::get_embedding_frame, py::arg("frame")); // Exported functions m.def("wtsne", &wtsne, py::return_value_policy::take_ownership, "Run stochastic cluster embedding", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("n_workers") = 128, py::arg("n_threads") = 1, py::arg("seed") = 1); m.def("pairsnp", &pairsnp, py::return_value_policy::take_ownership, "Run pairsnp", py::arg("fasta"), py::arg("n_threads"), py::arg("dist"), py::arg("knn")); m.def("gen_audio", &sample_wave, py::return_value_policy::take_ownership, "Generate audio for animation", py::arg("frequencies"), py::arg("duration"), py::arg("sample_rate"), py::arg("n_threads")); #ifdef GPU_AVAILABLE // NOTE: python always uses fp64 so cannot easily template these (which // would just give one function name exported but with different type // prototypes). To do this would require numpy (python)/Eigen (C++) which // support both precisions. But easier just to stick with List (python)/ // std::vector (C++) and allow fp64->fp32 conversion when called // Use fp64 for double precision (slower, more accurate) m.def("wtsne_gpu_fp64", &wtsne_gpu<double>, py::return_value_policy::take_ownership, "Run stochastic cluster embedding with CUDA", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128, py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("cpu_threads") = 1, py::arg("device_id") = 0, py::arg("seed") = 1); // Use fp32 for single precision (faster, less accurate) m.def("wtsne_gpu_fp32", &wtsne_gpu<float>, py::return_value_policy::take_ownership, "Run stochastic cluster embedding with CUDA", py::arg("I_vec"), py::arg("J_vec"), py::arg("dist_vec"), py::arg("weights"), py::arg("perplexity"), py::arg("maxIter"), py::arg("blockSize") = 128, py::arg("n_workers") = 128, py::arg("nRepuSamp") = 5, py::arg("eta0") = 1, py::arg("bInit") = 0, py::arg("animated") = false, py::arg("cpu_threads") = 1, py::arg("device_id") = 0, py::arg("seed") = 1); #endif }
46.098592
79
0.62542
johnlees
0e66dadb9b0faf7b9e13c7b977595fcdd3541173
897
hpp
C++
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/version.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_CORE_VERSION_HPP_ #define BE_CORE_VERSION_HPP_ #include "macros.hpp" #define BE_CORE_VERSION_MAJOR 0 #define BE_CORE_VERSION_MINOR 1 #define BE_CORE_VERSION_REV 32 /*!! include('common/version', 'BE_CORE', 'bengine') !! 6 */ /* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */ #define BE_CORE_VERSION (BE_CORE_VERSION_MAJOR * 100000 + BE_CORE_VERSION_MINOR * 1000 + BE_CORE_VERSION_REV) #define BE_CORE_VERSION_STRING "bengine " BE_STRINGIFY(BE_CORE_VERSION_MAJOR) "." BE_STRINGIFY(BE_CORE_VERSION_MINOR) "." BE_STRINGIFY(BE_CORE_VERSION_REV) /* ######################### END OF GENERATED CODE ######################### */ #define BE_COPYRIGHT "Copyright (C) 2012-2017 Magic / More Magic, B. Crist" #define BE_LICENSE "Distributed under the MIT license as part of bengine" #define BE_URL "https://github.com/magicmoremagic/bengine" #endif
39
155
0.702341
magicmoremagic
0e68cf0eb44496c1dcb61eaaa213e80b23c2f918
26,546
cpp
C++
cross/cocos2d/cocos/2d/platform/android/nativeactivity.cpp
yobiya/tdd_game_sample
d3605c13f1fd97cd3929d5d3054f603edde839db
[ "MIT" ]
20
2015-01-04T03:15:01.000Z
2020-08-14T00:48:34.000Z
cocos2d/cocos/2d/platform/android/nativeactivity.cpp
kobakei/CCLocalNotification
c47ad6ff96409857ee6637892cc2618c1daf7ffa
[ "Apache-2.0" ]
null
null
null
cocos2d/cocos/2d/platform/android/nativeactivity.cpp
kobakei/CCLocalNotification
c47ad6ff96409857ee6637892cc2618c1daf7ffa
[ "Apache-2.0" ]
5
2015-06-15T02:26:05.000Z
2021-10-04T06:57:49.000Z
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "nativeactivity.h" #include <jni.h> #include <errno.h> #include <EGL/egl.h> #include <GLES/gl.h> #include <android/sensor.h> #include <android/log.h> #include <android_native_app_glue.h> #include <android/configuration.h> #include <pthread.h> #include <chrono> #include "CCDirector.h" #include "CCApplication.h" #include "CCEventType.h" #include "CCFileUtilsAndroid.h" #include "jni/JniHelper.h" #include "CCEGLView.h" #include "CCDrawingPrimitives.h" #include "CCShaderCache.h" #include "CCTextureCache.h" #include "CCEventDispatcher.h" #include "CCEventAcceleration.h" #include "CCEventKeyboard.h" #include "CCEventCustom.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOG_RENDER_DEBUG(...) // #define LOG_RENDER_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #define LOG_EVENTS_DEBUG(...) // #define LOG_EVENTS_DEBUG(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) /* For debug builds, always enable the debug traces in this library */ #ifndef NDEBUG # define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "cocos2dx/nativeactivity.cpp", __VA_ARGS__)) #else # define LOGV(...) ((void)0) #endif void cocos_android_app_init(struct android_app* app); /** * Our saved state data. */ struct saved_state { float angle; int32_t x; int32_t y; }; /** * Shared state for our app. */ struct engine { struct android_app* app; ASensorManager* sensorManager; const ASensor* accelerometerSensor; ASensorEventQueue* sensorEventQueue; int animating; EGLDisplay display; EGLSurface surface; EGLContext context; int32_t width; int32_t height; struct saved_state state; }; static bool isContentRectChanged = false; static std::chrono::steady_clock::time_point timeRectChanged; static struct engine engine; static char* editboxText = NULL; extern EditTextCallback s_pfEditTextCallback; extern void* s_ctx; extern "C" { JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) { jsize size = env->GetArrayLength(text); pthread_mutex_lock(&(engine.app->mutex)); if (size > 0) { jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0); char* pBuf = (char*)malloc(size+1); if (pBuf != NULL) { memcpy(pBuf, data, size); pBuf[size] = '\0'; editboxText = pBuf; } env->ReleaseByteArrayElements(text, data, 0); } else { char* pBuf = (char*)malloc(1); pBuf[0] = '\0'; editboxText = pBuf; } pthread_cond_broadcast(&engine.app->cond); pthread_mutex_unlock(&(engine.app->mutex)); } } typedef struct cocos_dimensions { int w; int h; } cocos_dimensions; static void cocos_init(cocos_dimensions d, struct android_app* app) { LOGI("cocos_init(...)"); pthread_t thisthread = pthread_self(); LOGI("pthread_self() = %X", thisthread); cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager); if (!cocos2d::Director::getInstance()->getOpenGLView()) { cocos2d::EGLView *view = cocos2d::EGLView::getInstance(); view->setFrameSize(d.w, d.h); cocos_android_app_init(app); cocos2d::Application::getInstance()->run(); } else { cocos2d::GL::invalidateStateCache(); cocos2d::ShaderCache::getInstance()->reloadDefaultShaders(); cocos2d::DrawPrimitives::init(); cocos2d::VolatileTextureMgr::reloadAllTextures(); cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent); cocos2d::Director::getInstance()->setGLDefaultValues(); } } /** * Initialize an EGL context for the current display. */ static cocos_dimensions engine_init_display(struct engine* engine) { cocos_dimensions r; r.w = -1; r.h = -1; // initialize OpenGL ES and EGL /* * Here specify the attributes of the desired configuration. * Below, we select an EGLConfig with at least 8 bits per color * component compatible with on-screen windows */ const EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_BLUE_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_RED_SIZE, 5, EGL_DEPTH_SIZE, 16, EGL_STENCIL_SIZE, 8, EGL_NONE }; EGLint w, h, dummy, format; EGLint numConfigs; EGLConfig config; EGLSurface surface; EGLContext context; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(display, 0, 0); /* Here, the application chooses the configuration it desires. In this * sample, we have a very simplified selection process, where we pick * the first EGLConfig that matches our criteria */ eglChooseConfig(display, attribs, &config, 1, &numConfigs); /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). * As soon as we picked a EGLConfig, we can safely reconfigure the * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); surface = eglCreateWindowSurface(display, config, engine->app->window, NULL); const EGLint eglContextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; context = eglCreateContext(display, config, NULL, eglContextAttrs); if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) { LOGW("Unable to eglMakeCurrent"); return r; } eglQuerySurface(display, surface, EGL_WIDTH, &w); eglQuerySurface(display, surface, EGL_HEIGHT, &h); engine->display = display; engine->context = context; engine->surface = surface; engine->width = w; engine->height = h; engine->state.angle = 0; r.w = w; r.h = h; return r; } /** * Invoke the dispatching of the next bunch of Runnables in the Java-Land */ static bool s_methodInitialized = false; static void dispatch_pending_runnables() { static cocos2d::JniMethodInfo info; if (!s_methodInitialized) { s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo( info, "org/cocos2dx/lib/Cocos2dxHelper", "dispatchPendingRunnables", "()V" ); if (!s_methodInitialized) { LOGW("Unable to dispatch pending Runnables!"); return; } } info.env->CallStaticVoidMethod(info.classID, info.methodID); } /** * Just the current frame in the display. */ static void engine_draw_frame(struct engine* engine) { LOG_RENDER_DEBUG("engine_draw_frame(...)"); pthread_t thisthread = pthread_self(); LOG_RENDER_DEBUG("pthread_self() = %X", thisthread); if (engine->display == NULL) { // No display. LOGW("engine_draw_frame : No display."); return; } dispatch_pending_runnables(); cocos2d::Director::getInstance()->mainLoop(); LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()"); /* // Just fill the screen with a color. */ /* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */ /* ((float)engine->state.y)/engine->height, 1); */ /* glClear(GL_COLOR_BUFFER_BIT); */ if (s_pfEditTextCallback && editboxText) { s_pfEditTextCallback(editboxText, s_ctx); free(editboxText); editboxText = NULL; } eglSwapBuffers(engine->display, engine->surface); } /** * Tear down the EGL context currently associated with the display. */ static void engine_term_display(struct engine* engine) { if (engine->display != EGL_NO_DISPLAY) { eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (engine->context != EGL_NO_CONTEXT) { eglDestroyContext(engine->display, engine->context); } if (engine->surface != EGL_NO_SURFACE) { eglDestroySurface(engine->display, engine->surface); } eglTerminate(engine->display); } engine->animating = 0; engine->display = EGL_NO_DISPLAY; engine->context = EGL_NO_CONTEXT; engine->surface = EGL_NO_SURFACE; } /* * Get X, Y positions and ID's for all pointers */ static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) { int pointerCount = AMotionEvent_getPointerCount(event); for(int i = 0; i < pointerCount; ++i) { ids[i] = AMotionEvent_getPointerId(event, i); xs[i] = AMotionEvent_getX(event, i); ys[i] = AMotionEvent_getY(event, i); } } /* * Handle Touch Inputs */ static int32_t handle_touch_input(AInputEvent *event) { pthread_t thisthread = pthread_self(); LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread); switch(AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK) { case AMOTION_EVENT_ACTION_DOWN: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN"); int pointerId = AMotionEvent_getPointerId(event, 0); float xP = AMotionEvent_getX(event,0); float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_POINTER_DOWN: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN"); int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; int pointerId = AMotionEvent_getPointerId(event, pointerIndex); float xP = AMotionEvent_getX(event,pointerIndex); float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_MOVE: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE"); int pointerCount = AMotionEvent_getPointerCount(event); int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys); return 1; } break; case AMOTION_EVENT_ACTION_UP: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP"); int pointerId = AMotionEvent_getPointerId(event, 0); float xP = AMotionEvent_getX(event,0); float yP = AMotionEvent_getY(event,0); LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n", xP, yP, pointerId); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_POINTER_UP: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP"); int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; int pointerId = AMotionEvent_getPointerId(event, pointerIndex); float xP = AMotionEvent_getX(event,pointerIndex); float yP = AMotionEvent_getY(event,pointerIndex); LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n", xP, yP, pointerIndex); float x = xP; float y = yP; cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y); return 1; } break; case AMOTION_EVENT_ACTION_CANCEL: { LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL"); int pointerCount = AMotionEvent_getPointerCount(event); int ids[pointerCount]; float xs[pointerCount], ys[pointerCount]; getTouchPos(event, ids, xs, ys); cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys); return 1; } break; default: LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE"); return 0; break; } } /* * Handle Key Inputs */ static int32_t handle_key_input(AInputEvent *event) { if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) { auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); switch (AKeyEvent_getKeyCode(event)) { case AKEYCODE_BACK: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); dispatcher->dispatchEvent(&event); } return 1; case AKEYCODE_MENU: { cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); dispatcher->dispatchEvent(&event); } return 1; default: break; } } return 0; } /** * Process the next input event. */ static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) { pthread_t thisthread = pthread_self(); LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread); struct engine* engine = (struct engine*)app->userData; if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) { engine->animating = 1; engine->state.x = AMotionEvent_getX(event, 0); engine->state.y = AMotionEvent_getY(event, 0); return handle_touch_input(event); } else return handle_key_input(event); return 0; } void enableAccelerometerJni(void) { LOGI("enableAccelerometerJni()"); if (engine.accelerometerSensor != NULL) { ASensorEventQueue_enableSensor(engine.sensorEventQueue, engine.accelerometerSensor); // Set a default sample rate // We'd like to get 60 events per second (in us). ASensorEventQueue_setEventRate(engine.sensorEventQueue, engine.accelerometerSensor, (1000L/60)*1000); } } void disableAccelerometerJni(void) { LOGI("disableAccelerometerJni()"); if (engine.accelerometerSensor != NULL) { ASensorEventQueue_disableSensor(engine.sensorEventQueue, engine.accelerometerSensor); } } void setAccelerometerIntervalJni(float interval) { LOGI("setAccelerometerIntervalJni(%f)", interval); // We'd like to get 60 events per second (in us). ASensorEventQueue_setEventRate(engine.sensorEventQueue, engine.accelerometerSensor, interval * 1000000L); } /** * Process the next main command. */ static void engine_handle_cmd(struct android_app* app, int32_t cmd) { struct engine* engine = (struct engine*)app->userData; switch (cmd) { case APP_CMD_SAVE_STATE: // The system has asked us to save our current state. Do so. engine->app->savedState = malloc(sizeof(struct saved_state)); *((struct saved_state*)engine->app->savedState) = engine->state; engine->app->savedStateSize = sizeof(struct saved_state); break; case APP_CMD_INIT_WINDOW: // The window is being shown, get it ready. if (engine->app->window != NULL) { cocos_dimensions d = engine_init_display(engine); if ((d.w > 0) && (d.h > 0)) { cocos2d::JniHelper::setJavaVM(app->activity->vm); cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz); // call Cocos2dxHelper.init() cocos2d::JniMethodInfo ccxhelperInit; if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit, "org/cocos2dx/lib/Cocos2dxHelper", "init", "(Landroid/app/Activity;)V")) { LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED"); } ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID, ccxhelperInit.methodID, app->activity->clazz); cocos_init(d, app); } engine->animating = 1; engine_draw_frame(engine); } break; case APP_CMD_TERM_WINDOW: // The window is being hidden or closed, clean it up. engine_term_display(engine); break; case APP_CMD_GAINED_FOCUS: if (cocos2d::Director::getInstance()->getOpenGLView()) { cocos2d::Application::getInstance()->applicationWillEnterForeground(); engine->animating = 1; } break; case APP_CMD_LOST_FOCUS: { cocos2d::Application::getInstance()->applicationDidEnterBackground(); cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND); cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent); // Also stop animating. engine->animating = 0; engine_draw_frame(engine); } break; } } static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) { timeRectChanged = std::chrono::steady_clock::now(); isContentRectChanged = true; } static void process_input(struct android_app* app, struct android_poll_source* source) { AInputEvent* event = NULL; int processed = 0; while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) { LOGV("New input event: type=%d\n", AInputEvent_getType(event)); if (AInputQueue_preDispatchEvent(app->inputQueue, event)) { continue; } int32_t handled = 0; if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event); AInputQueue_finishEvent(app->inputQueue, event, handled); processed = 1; } if (processed == 0) { LOGE("Failure reading next input event: %s\n", strerror(errno)); } } /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state) { // Make sure glue isn't stripped. app_dummy(); memset(&engine, 0, sizeof(engine)); state->userData = &engine; state->onAppCmd = engine_handle_cmd; state->onInputEvent = engine_handle_input; state->inputPollSource.process = process_input; engine.app = state; // Prepare to monitor accelerometer engine.sensorManager = ASensorManager_getInstance(); engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager, ASENSOR_TYPE_ACCELEROMETER); engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager, state->looper, LOOPER_ID_USER, NULL, NULL); if (state->savedState != NULL) { // We are starting with a previous saved state; restore from it. engine.state = *(struct saved_state*)state->savedState; } // Screen size change support state->activity->callbacks->onContentRectChanged = onContentRectChanged; // loop waiting for stuff to do. while (1) { // Read all pending events. int ident; int events; struct android_poll_source* source; // If not animating, we will block forever waiting for events. // If animating, we loop until all events are read, then continue // to draw the next frame of animation. while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events, (void**)&source)) >= 0) { // Process this event. if (source != NULL) { source->process(state, source); } // If a sensor has data, process it now. if (ident == LOOPER_ID_USER) { if (engine.accelerometerSensor != NULL) { ASensorEvent event; while (ASensorEventQueue_getEvents(engine.sensorEventQueue, &event, 1) > 0) { LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f", event.acceleration.x, event.acceleration.y, event.acceleration.z); AConfiguration* _currentconf = AConfiguration_new(); AConfiguration_fromAssetManager(_currentconf, state->activity->assetManager); static int32_t _orientation = AConfiguration_getOrientation(_currentconf); if (ACONFIGURATION_ORIENTATION_LAND != _orientation) { // ACONFIGURATION_ORIENTATION_ANY // ACONFIGURATION_ORIENTATION_PORT // ACONFIGURATION_ORIENTATION_SQUARE cocos2d::Acceleration acc; acc.x = -event.acceleration.x/10; acc.y = -event.acceleration.y/10; acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&accEvent); } else { // ACONFIGURATION_ORIENTATION_LAND // swap x and y parameters cocos2d::Acceleration acc; acc.x = event.acceleration.y/10; acc.y = -event.acceleration.x/10; acc.z = event.acceleration.z/10; acc.timestamp = 0; cocos2d::EventAcceleration accEvent(acc); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher(); dispatcher->dispatchEvent(&accEvent); } } } } // Check if we are exiting. if (state->destroyRequested != 0) { engine_term_display(&engine); memset(&engine, 0, sizeof(engine)); s_methodInitialized = false; return; } } if (engine.animating) { // Done with events; draw next animation frame. engine.state.angle += .01f; if (engine.state.angle > 1) { engine.state.angle = 0; } // Drawing is throttled to the screen update rate, so there // is no need to do timing here. LOG_RENDER_DEBUG("android_main : engine.animating"); engine_draw_frame(&engine); } else { LOG_RENDER_DEBUG("android_main : !engine.animating"); } // Check if screen size changed if (isContentRectChanged) { std::chrono::duration<int, std::milli> duration( std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged)); // Wait about 30 ms to get new width and height. Without waiting we can get old values sometime if (duration.count() > 30) { isContentRectChanged = false; int32_t newWidth = ANativeWindow_getWidth(engine.app->window); int32_t newHeight = ANativeWindow_getHeight(engine.app->window); cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight); } } } }
35.206897
137
0.616515
yobiya
0e696d20715dc73afc4ae5c530b3ee4f16dbade6
106
cpp
C++
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
27
2015-09-03T18:41:03.000Z
2022-01-17T20:38:54.000Z
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
null
null
null
Engine/Math/Ray3D.cpp
techmatt/Provincial
3e636570d7ef359b823cb0dab3c5f8c3f1cb36b2
[ "MIT" ]
8
2015-02-23T10:04:30.000Z
2020-09-04T10:56:22.000Z
/* Ray3D.cpp Written by Matthew Fisher a 3D ray represented by an origin point and a direction vector. */
17.666667
63
0.764151
techmatt
0e6aa6bb823ed1ac4ac96db47326af50a653daa5
87,738
cpp
C++
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
grid-test/export/macos/obj/src/hscript/Interp.cpp
VehpuS/learning-haxe-and-haxeflixel
cb18c074720656797beed7333eeaced2cf323337
[ "Apache-2.0" ]
null
null
null
// Generated by Haxe 4.1.4 #include <hxcpp.h> #ifndef INCLUDED_IntIterator #include <IntIterator.h> #endif #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_ds_BalancedTree #include <haxe/ds/BalancedTree.h> #endif #ifndef INCLUDED_haxe_ds_EnumValueMap #include <haxe/ds/EnumValueMap.h> #endif #ifndef INCLUDED_haxe_ds_IntMap #include <haxe/ds/IntMap.h> #endif #ifndef INCLUDED_haxe_ds_ObjectMap #include <haxe/ds/ObjectMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_hscript_CType #include <hscript/CType.h> #endif #ifndef INCLUDED_hscript_Const #include <hscript/Const.h> #endif #ifndef INCLUDED_hscript_Error #include <hscript/Error.h> #endif #ifndef INCLUDED_hscript_Expr #include <hscript/Expr.h> #endif #ifndef INCLUDED_hscript_Interp #include <hscript/Interp.h> #endif #ifndef INCLUDED_hscript__Interp_Stop #include <hscript/_Interp/Stop.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_f37559d470356c9e_53_new,"hscript.Interp","new",0xf7e71101,"hscript.Interp.new","hscript/Interp.hx",53,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_64_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",64,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_74_resetVariables,"hscript.Interp","resetVariables",0x6cebf7e7,"hscript.Interp.resetVariables","hscript/Interp.hx",74,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_87_posInfos,"hscript.Interp","posInfos",0x444859d0,"hscript.Interp.posInfos","hscript/Interp.hx",87,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_97_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",97,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_98_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",98,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_99_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",99,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_100_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",100,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_101_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",101,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_102_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",102,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_103_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",103,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_104_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",104,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_105_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",105,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_106_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",106,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_107_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",107,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_108_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",108,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_109_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",109,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_110_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",110,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_111_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",111,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_112_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",112,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_113_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",113,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_114_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",114,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_115_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",115,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_117_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",117,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_118_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",118,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_119_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",119,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_120_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",120,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_121_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",121,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_122_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",122,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_123_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",123,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_124_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",124,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_125_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",125,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_126_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",126,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_127_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",127,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_128_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",128,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_90_initOps,"hscript.Interp","initOps",0xe1420823,"hscript.Interp.initOps","hscript/Interp.hx",90,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_131_assign,"hscript.Interp","assign",0xca66602e,"hscript.Interp.assign","hscript/Interp.hx",131,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_160_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",160,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_158_assignOp,"hscript.Interp","assignOp",0xf8e18cef,"hscript.Interp.assignOp","hscript/Interp.hx",158,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_163_evalAssignOp,"hscript.Interp","evalAssignOp",0xa46efc2b,"hscript.Interp.evalAssignOp","hscript/Interp.hx",163,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_199_increment,"hscript.Interp","increment",0x1e81f590,"hscript.Interp.increment","hscript/Interp.hx",199,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_246_execute,"hscript.Interp","execute",0xe1c3af56,"hscript.Interp.execute","hscript/Interp.hx",246,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_258_exprReturn,"hscript.Interp","exprReturn",0x8cfbf144,"hscript.Interp.exprReturn","hscript/Interp.hx",258,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_273_duplicate,"hscript.Interp","duplicate",0x8d9a10ec,"hscript.Interp.duplicate","hscript/Interp.hx",273,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_285_restore,"hscript.Interp","restore",0x80670c6f,"hscript.Interp.restore","hscript/Interp.hx",285,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_293_error,"hscript.Interp","error",0xe68736a9,"hscript.Interp.error","hscript/Interp.hx",293,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_301_rethrow,"hscript.Interp","rethrow",0x0be155b4,"hscript.Interp.rethrow","hscript/Interp.hx",301,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_305_resolve,"hscript.Interp","resolve",0x7d16b80d,"hscript.Interp.resolve","hscript/Interp.hx",305,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_315_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",315,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_410_expr,"hscript.Interp","expr",0xec634974,"hscript.Interp.expr","hscript/Interp.hx",410,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_583_doWhileLoop,"hscript.Interp","doWhileLoop",0x813d4b4b,"hscript.Interp.doWhileLoop","hscript/Interp.hx",583,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_600_whileLoop,"hscript.Interp","whileLoop",0xce1b3216,"hscript.Interp.whileLoop","hscript/Interp.hx",600,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_616_makeIterator,"hscript.Interp","makeIterator",0x634d013b,"hscript.Interp.makeIterator","hscript/Interp.hx",616,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_626_forLoop,"hscript.Interp","forLoop",0xdf1ff72e,"hscript.Interp.forLoop","hscript/Interp.hx",626,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_646_isMap,"hscript.Interp","isMap",0x34ae9fb3,"hscript.Interp.isMap","hscript/Interp.hx",646,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_650_getMapValue,"hscript.Interp","getMapValue",0x1594fb8c,"hscript.Interp.getMapValue","hscript/Interp.hx",650,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_654_setMapValue,"hscript.Interp","setMapValue",0x20020298,"hscript.Interp.setMapValue","hscript/Interp.hx",654,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_657_get,"hscript.Interp","get",0xf7e1c137,"hscript.Interp.get","hscript/Interp.hx",657,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_673_set,"hscript.Interp","set",0xf7eadc43,"hscript.Interp.set","hscript/Interp.hx",673,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_680_fcall,"hscript.Interp","fcall",0x6ff6aee5,"hscript.Interp.fcall","hscript/Interp.hx",680,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_684_call,"hscript.Interp","call",0xeaff64dd,"hscript.Interp.call","hscript/Interp.hx",684,0xf078416e) HX_LOCAL_STACK_FRAME(_hx_pos_f37559d470356c9e_687_cnew,"hscript.Interp","cnew",0xeb093c1c,"hscript.Interp.cnew","hscript/Interp.hx",687,0xf078416e) namespace hscript{ void Interp_obj::__construct(){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_53_new) HXLINE( 55) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 59) this->declared = ::Array_obj< ::Dynamic>::__new(); HXLINE( 60) this->resetVariables(); HXLINE( 61) this->initOps(); } Dynamic Interp_obj::__CreateEmpty() { return new Interp_obj; } void *Interp_obj::_hx_vtable = 0; Dynamic Interp_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< Interp_obj > _hx_result = new Interp_obj(); _hx_result->__construct(); return _hx_result; } bool Interp_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2a95eb9f; } void Interp_obj::resetVariables(){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_64_resetVariables) HXDLIN( 64) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 66) this->variables = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 71) { HXLINE( 71) ::Dynamic value = null(); HXDLIN( 71) this->variables->set(HX_("null",87,9e,0e,49),value); } HXLINE( 72) this->variables->set(HX_("true",4e,a7,03,4d),true); HXLINE( 73) this->variables->set(HX_("false",a3,35,4f,fb),false); HXLINE( 74) { HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,_gthis) HXARGC(1) void _hx_run(::cpp::VirtualArray el){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_74_resetVariables) HXLINE( 75) ::Dynamic inf = _gthis->posInfos(); HXLINE( 76) ::Dynamic v = el->shift(); HXLINE( 77) if ((el->get_length() > 0)) { HXLINE( 77) inf->__SetField(HX_("customParams",d7,51,18,ed),el,::hx::paccDynamic); } HXLINE( 78) ::Dynamic value = ::haxe::Log_obj::trace; HXDLIN( 78) value(::Std_obj::string(v),inf); } HX_END_LOCAL_FUNC1((void)) HXLINE( 74) ::Dynamic this1 = this->variables; HXDLIN( 74) ( ( ::haxe::ds::StringMap)(this1) )->set(HX_("trace",85,8e,1f,16),::Reflect_obj::makeVarArgs( ::Dynamic(new _hx_Closure_0(_gthis)))); } } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,resetVariables,(void)) ::Dynamic Interp_obj::posInfos(){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_87_posInfos) HXDLIN( 87) return ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("fileName",e7,5a,43,62),HX_("hscript",73,8c,18,2c)) ->setFixed(1,HX_("lineNumber",dd,81,22,76),0)); } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,posInfos,return ) void Interp_obj::initOps(){ HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_0, ::hscript::Interp,me) HXARGC(2) ::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_97_initOps) HXLINE( 97) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 97) return (_hx_tmp + me->expr(e2)); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_1, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_98_initOps) HXLINE( 98) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 98) return (( (Float)(_hx_tmp) ) - ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_2, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_99_initOps) HXLINE( 99) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 99) return (( (Float)(_hx_tmp) ) * ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_3, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_100_initOps) HXLINE( 100) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 100) return (( (Float)(_hx_tmp) ) / ( (Float)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_4, ::hscript::Interp,me) HXARGC(2) Float _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_101_initOps) HXLINE( 101) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 101) return ::hx::Mod(_hx_tmp,me->expr(e2)); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_5, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_102_initOps) HXLINE( 102) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 102) return (( (int)(_hx_tmp) ) & ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_6, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_103_initOps) HXLINE( 103) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 103) return (( (int)(_hx_tmp) ) | ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_7, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_104_initOps) HXLINE( 104) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 104) return (( (int)(_hx_tmp) ) ^ ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_8, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_105_initOps) HXLINE( 105) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 105) return (( (int)(_hx_tmp) ) << ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_9, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_106_initOps) HXLINE( 106) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 106) return (( (int)(_hx_tmp) ) >> ( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_10, ::hscript::Interp,me) HXARGC(2) int _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_107_initOps) HXLINE( 107) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 107) return ::hx::UShr(( (int)(_hx_tmp) ),( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_11, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_108_initOps) HXLINE( 108) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 108) return ::hx::IsEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_12, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_109_initOps) HXLINE( 109) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 109) return ::hx::IsNotEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_13, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_110_initOps) HXLINE( 110) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 110) return ::hx::IsGreaterEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_14, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_111_initOps) HXLINE( 111) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 111) return ::hx::IsLessEq( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_15, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_112_initOps) HXLINE( 112) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 112) return ::hx::IsGreater( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_16, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_113_initOps) HXLINE( 113) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 113) return ::hx::IsLess( _hx_tmp,me->expr(e2) ); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_17, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_114_initOps) HXLINE( 114) if (::hx::IsNotEq( me->expr(e1),true )) { HXLINE( 114) return ::hx::IsEq( me->expr(e2),true ); } else { HXLINE( 114) return true; } HXDLIN( 114) return false; } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_18, ::hscript::Interp,me) HXARGC(2) bool _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_115_initOps) HXLINE( 115) if (::hx::IsEq( me->expr(e1),true )) { HXLINE( 115) return ::hx::IsEq( me->expr(e2),true ); } else { HXLINE( 115) return false; } HXDLIN( 115) return false; } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_19, ::hscript::Interp,me) HXARGC(2) ::IntIterator _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_117_initOps) HXLINE( 117) ::Dynamic _hx_tmp = me->expr(e1); HXDLIN( 117) return ::IntIterator_obj::__alloc( HX_CTX ,( (int)(_hx_tmp) ),( (int)(me->expr(e2)) )); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_20) HXARGC(2) ::Dynamic _hx_run( ::Dynamic v1, ::Dynamic v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_118_initOps) HXLINE( 118) return (v1 + v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_21) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_119_initOps) HXLINE( 119) return (v1 - v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_22) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_120_initOps) HXLINE( 120) return (v1 * v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_23) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_121_initOps) HXLINE( 121) return (v1 / v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_24) HXARGC(2) Float _hx_run(Float v1,Float v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_122_initOps) HXLINE( 122) return ::hx::Mod(v1,v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_25) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_123_initOps) HXLINE( 123) return (v1 & v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_26) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_124_initOps) HXLINE( 124) return (v1 | v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_27) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_125_initOps) HXLINE( 125) return (v1 ^ v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_28) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_126_initOps) HXLINE( 126) return (v1 << v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_29) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_127_initOps) HXLINE( 127) return (v1 >> v2); } HX_END_LOCAL_FUNC2(return) HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_30) HXARGC(2) int _hx_run(int v1,int v2){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_128_initOps) HXLINE( 128) return ::hx::UShr(v1,v2); } HX_END_LOCAL_FUNC2(return) HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_90_initOps) HXLINE( 91) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 93) this->binops = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 97) this->binops->set(HX_("+",2b,00,00,00), ::Dynamic(new _hx_Closure_0(me))); HXLINE( 98) this->binops->set(HX_("-",2d,00,00,00), ::Dynamic(new _hx_Closure_1(me))); HXLINE( 99) this->binops->set(HX_("*",2a,00,00,00), ::Dynamic(new _hx_Closure_2(me))); HXLINE( 100) this->binops->set(HX_("/",2f,00,00,00), ::Dynamic(new _hx_Closure_3(me))); HXLINE( 101) this->binops->set(HX_("%",25,00,00,00), ::Dynamic(new _hx_Closure_4(me))); HXLINE( 102) this->binops->set(HX_("&",26,00,00,00), ::Dynamic(new _hx_Closure_5(me))); HXLINE( 103) this->binops->set(HX_("|",7c,00,00,00), ::Dynamic(new _hx_Closure_6(me))); HXLINE( 104) this->binops->set(HX_("^",5e,00,00,00), ::Dynamic(new _hx_Closure_7(me))); HXLINE( 105) this->binops->set(HX_("<<",80,34,00,00), ::Dynamic(new _hx_Closure_8(me))); HXLINE( 106) this->binops->set(HX_(">>",40,36,00,00), ::Dynamic(new _hx_Closure_9(me))); HXLINE( 107) this->binops->set(HX_(">>>",fe,41,2f,00), ::Dynamic(new _hx_Closure_10(me))); HXLINE( 108) this->binops->set(HX_("==",60,35,00,00), ::Dynamic(new _hx_Closure_11(me))); HXLINE( 109) this->binops->set(HX_("!=",fc,1c,00,00), ::Dynamic(new _hx_Closure_12(me))); HXLINE( 110) this->binops->set(HX_(">=",3f,36,00,00), ::Dynamic(new _hx_Closure_13(me))); HXLINE( 111) this->binops->set(HX_("<=",81,34,00,00), ::Dynamic(new _hx_Closure_14(me))); HXLINE( 112) this->binops->set(HX_(">",3e,00,00,00), ::Dynamic(new _hx_Closure_15(me))); HXLINE( 113) this->binops->set(HX_("<",3c,00,00,00), ::Dynamic(new _hx_Closure_16(me))); HXLINE( 114) this->binops->set(HX_("||",80,6c,00,00), ::Dynamic(new _hx_Closure_17(me))); HXLINE( 115) this->binops->set(HX_("&&",40,21,00,00), ::Dynamic(new _hx_Closure_18(me))); HXLINE( 116) this->binops->set(HX_("=",3d,00,00,00),this->assign_dyn()); HXLINE( 117) this->binops->set(HX_("...",ee,0f,23,00), ::Dynamic(new _hx_Closure_19(me))); HXLINE( 118) this->assignOp(HX_("+=",b2,25,00,00), ::Dynamic(new _hx_Closure_20())); HXLINE( 119) this->assignOp(HX_("-=",70,27,00,00), ::Dynamic(new _hx_Closure_21())); HXLINE( 120) this->assignOp(HX_("*=",d3,24,00,00), ::Dynamic(new _hx_Closure_22())); HXLINE( 121) this->assignOp(HX_("/=",2e,29,00,00), ::Dynamic(new _hx_Closure_23())); HXLINE( 122) this->assignOp(HX_("%=",78,20,00,00), ::Dynamic(new _hx_Closure_24())); HXLINE( 123) this->assignOp(HX_("&=",57,21,00,00), ::Dynamic(new _hx_Closure_25())); HXLINE( 124) this->assignOp(HX_("|=",41,6c,00,00), ::Dynamic(new _hx_Closure_26())); HXLINE( 125) this->assignOp(HX_("^=",1f,52,00,00), ::Dynamic(new _hx_Closure_27())); HXLINE( 126) this->assignOp(HX_("<<=",bd,bb,2d,00), ::Dynamic(new _hx_Closure_28())); HXLINE( 127) this->assignOp(HX_(">>=",fd,41,2f,00), ::Dynamic(new _hx_Closure_29())); HXLINE( 128) this->assignOp(HX_(">>>=",7f,7c,2a,29), ::Dynamic(new _hx_Closure_30())); } HX_DEFINE_DYNAMIC_FUNC0(Interp_obj,initOps,(void)) ::Dynamic Interp_obj::assign( ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_131_assign) HXLINE( 132) ::Dynamic v = this->expr(e2); HXLINE( 133) switch((int)(e1->_hx_getIndex())){ case (int)1: { HXLINE( 134) ::String id = e1->_hx_getString(0); HXDLIN( 134) { HXLINE( 135) ::Dynamic l = this->locals->get(id); HXLINE( 136) if (::hx::IsNull( l )) { HXLINE( 137) this->variables->set(id,v); } else { HXLINE( 139) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } } break; case (int)5: { HXLINE( 140) ::String f = e1->_hx_getString(1); HXDLIN( 140) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 141) v = this->set(this->expr(e),f,v); } break; case (int)16: { HXLINE( 142) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 142) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 142) { HXLINE( 143) ::Dynamic arr = this->expr(e); HXLINE( 144) ::Dynamic index1 = this->expr(index); HXLINE( 145) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 146) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 149) arr->__SetItem(( (int)(index1) ),v); } } } break; default:{ HXLINE( 153) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(HX_("=",3d,00,00,00)); HXDLIN( 153) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } } HXLINE( 155) return v; } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assign,return ) void Interp_obj::assignOp(::String op, ::Dynamic fop){ HX_BEGIN_LOCAL_FUNC_S3(::hx::LocalFunc,_hx_Closure_0,::String,op, ::hscript::Interp,me, ::Dynamic,fop) HXARGC(2) ::Dynamic _hx_run( ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_160_assignOp) HXLINE( 160) return me->evalAssignOp(op,fop,e1,e2); } HX_END_LOCAL_FUNC2(return) HX_STACKFRAME(&_hx_pos_f37559d470356c9e_158_assignOp) HXLINE( 159) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 160) this->binops->set(op, ::Dynamic(new _hx_Closure_0(op,me,fop))); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,assignOp,(void)) ::Dynamic Interp_obj::evalAssignOp(::String op, ::Dynamic fop, ::hscript::Expr e1, ::hscript::Expr e2){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_163_evalAssignOp) HXLINE( 164) ::Dynamic v; HXLINE( 165) switch((int)(e1->_hx_getIndex())){ case (int)1: { HXLINE( 166) ::String id = e1->_hx_getString(0); HXDLIN( 166) { HXLINE( 167) ::Dynamic l = this->locals->get(id); HXLINE( 168) ::Dynamic v1 = this->expr(e1); HXDLIN( 168) v = fop(v1,this->expr(e2)); HXLINE( 169) if (::hx::IsNull( l )) { HXLINE( 170) this->variables->set(id,v); } else { HXLINE( 172) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } } break; case (int)5: { HXLINE( 173) ::String f = e1->_hx_getString(1); HXDLIN( 173) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 173) { HXLINE( 174) ::Dynamic obj = this->expr(e); HXLINE( 175) ::Dynamic v1 = this->get(obj,f); HXDLIN( 175) v = fop(v1,this->expr(e2)); HXLINE( 176) v = this->set(obj,f,v); } } break; case (int)16: { HXLINE( 177) ::hscript::Expr index = e1->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 177) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXDLIN( 177) { HXLINE( 178) ::Dynamic arr = this->expr(e); HXLINE( 179) ::Dynamic index1 = this->expr(index); HXLINE( 180) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 181) ::Dynamic v1 = ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1); HXDLIN( 181) v = fop(v1,this->expr(e2)); HXLINE( 182) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 185) ::Dynamic arr1 = arr->__GetItem(( (int)(index1) )); HXDLIN( 185) v = fop(arr1,this->expr(e2)); HXLINE( 186) arr->__SetItem(( (int)(index1) ),v); } } } break; default:{ HXLINE( 189) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 189) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } } HXLINE( 191) return v; } HX_DEFINE_DYNAMIC_FUNC4(Interp_obj,evalAssignOp,return ) ::Dynamic Interp_obj::increment( ::hscript::Expr e,bool prefix,int delta){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_199_increment) HXDLIN( 199) switch((int)(e->_hx_getIndex())){ case (int)1: { HXLINE( 200) ::String id = e->_hx_getString(0); HXLINE( 201) ::Dynamic l = this->locals->get(id); HXLINE( 202) ::Dynamic v; HXDLIN( 202) if (::hx::IsNull( l )) { HXLINE( 202) v = this->variables->get(id); } else { HXLINE( 202) v = ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic)); } HXLINE( 203) if (prefix) { HXLINE( 204) v = (v + delta); HXLINE( 205) if (::hx::IsNull( l )) { HXLINE( 205) this->variables->set(id,v); } else { HXLINE( 205) l->__SetField(HX_("r",72,00,00,00),v,::hx::paccDynamic); } } else { HXLINE( 207) if (::hx::IsNull( l )) { HXLINE( 207) this->variables->set(id,(v + delta)); } else { HXLINE( 207) l->__SetField(HX_("r",72,00,00,00),(v + delta),::hx::paccDynamic); } } HXLINE( 208) return v; } break; case (int)5: { HXLINE( 209) ::String f = e->_hx_getString(1); HXDLIN( 209) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 210) ::Dynamic obj = this->expr(e1); HXLINE( 211) ::Dynamic v = this->get(obj,f); HXLINE( 212) if (prefix) { HXLINE( 213) v = (v + delta); HXLINE( 214) this->set(obj,f,v); } else { HXLINE( 216) this->set(obj,f,(v + delta)); } HXLINE( 217) return v; } break; case (int)16: { HXLINE( 218) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 218) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 219) ::Dynamic arr = this->expr(e1); HXLINE( 220) ::Dynamic index1 = this->expr(index); HXLINE( 221) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 222) int v = ( (int)(::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1)) ); HXLINE( 223) if (prefix) { HXLINE( 224) v = (v + delta); HXLINE( 225) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,v); } else { HXLINE( 228) ::haxe::IMap_obj::set( ::hx::interface_check(arr,0x09c2bd39),index1,(v + delta)); } HXLINE( 230) return v; } else { HXLINE( 233) int v = ( (int)(arr->__GetItem(( (int)(index1) ))) ); HXLINE( 234) if (prefix) { HXLINE( 235) v = (v + delta); HXLINE( 236) arr->__SetItem(( (int)(index1) ),v); } else { HXLINE( 238) arr->__SetItem(( (int)(index1) ),(v + delta)); } HXLINE( 239) return v; } } break; default:{ HXLINE( 242) ::String e; HXDLIN( 242) if ((delta > 0)) { HXLINE( 242) e = HX_("++",a0,25,00,00); } else { HXLINE( 242) e = HX_("--",60,27,00,00); } HXDLIN( 242) ::hscript::Error e1 = ::hscript::Error_obj::EInvalidOp(e); HXDLIN( 242) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e1)); } } HXLINE( 199) return null(); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,increment,return ) ::Dynamic Interp_obj::execute( ::hscript::Expr expr){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_246_execute) HXLINE( 247) this->depth = 0; HXLINE( 249) this->locals = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 253) this->declared = ::Array_obj< ::Dynamic>::__new(); HXLINE( 254) return this->exprReturn(expr); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,execute,return ) ::Dynamic Interp_obj::exprReturn( ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_258_exprReturn) HXDLIN( 258) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 259) return this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 258) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop e = _g1; HXLINE( 261) switch((int)(e->_hx_getIndex())){ case (int)0: { HXLINE( 262) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid break",b6,ee,24,9d))); } break; case (int)1: { HXLINE( 263) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid continue",d0,6a,b7,3f))); } break; case (int)2: { HXLINE( 265) ::Dynamic v = this->returnValue; HXLINE( 266) this->returnValue = null(); HXLINE( 267) return v; } break; } } else { HXDLIN( 258) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } HXDLIN( 258) return null(); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,exprReturn,return ) ::haxe::ds::StringMap Interp_obj::duplicate( ::haxe::ds::StringMap h){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_273_duplicate) HXLINE( 275) ::haxe::ds::StringMap h2 = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); HXLINE( 279) { HXLINE( 279) ::Dynamic k = h->keys(); HXDLIN( 279) while(( (bool)(k->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 279) ::String k1 = ( (::String)(k->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) ); HXLINE( 280) h2->set(k1,h->get(k1)); } } HXLINE( 281) return h2; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,duplicate,return ) void Interp_obj::restore(int old){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_285_restore) HXDLIN( 285) while((this->declared->length > old)){ HXLINE( 286) ::Dynamic d = this->declared->pop(); HXLINE( 287) this->locals->set(( (::String)(d->__Field(HX_("n",6e,00,00,00),::hx::paccDynamic)) ), ::Dynamic(d->__Field(HX_("old",a7,98,54,00),::hx::paccDynamic))); } } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,restore,(void)) ::Dynamic Interp_obj::error( ::hscript::Error e,::hx::Null< bool > __o_rethrow){ bool rethrow = __o_rethrow.Default(false); HX_STACKFRAME(&_hx_pos_f37559d470356c9e_293_error) HXDLIN( 293) if (rethrow) { HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } else { HXDLIN( 293) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXDLIN( 293) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,error,return ) void Interp_obj::rethrow( ::Dynamic e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_301_rethrow) HXDLIN( 301) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,rethrow,(void)) ::Dynamic Interp_obj::resolve(::String id){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_305_resolve) HXLINE( 306) ::Dynamic l = this->locals->get(id); HXLINE( 307) if (::hx::IsNotNull( l )) { HXLINE( 308) return ::Dynamic(l->__Field(HX_("r",72,00,00,00),::hx::paccDynamic)); } HXLINE( 309) ::Dynamic v = this->variables->get(id); HXLINE( 310) bool _hx_tmp; HXDLIN( 310) if (::hx::IsNull( v )) { HXLINE( 310) _hx_tmp = !(this->variables->exists(id)); } else { HXLINE( 310) _hx_tmp = false; } HXDLIN( 310) if (_hx_tmp) { HXLINE( 311) ::hscript::Error e = ::hscript::Error_obj::EUnknownVariable(id); HXDLIN( 311) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 312) return v; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,resolve,return ) ::Dynamic Interp_obj::expr( ::hscript::Expr e){ HX_GC_STACKFRAME(&_hx_pos_f37559d470356c9e_315_expr) HXDLIN( 315) ::hscript::Interp _gthis = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 320) switch((int)(e->_hx_getIndex())){ case (int)0: { HXLINE( 321) ::hscript::Const c = e->_hx_getObject(0).StaticCast< ::hscript::Const >(); HXLINE( 322) switch((int)(c->_hx_getIndex())){ case (int)0: { HXLINE( 323) int v = c->_hx_getInt(0); HXDLIN( 323) return v; } break; case (int)1: { HXLINE( 324) Float f = c->_hx_getFloat(0); HXDLIN( 324) return f; } break; case (int)2: { HXLINE( 325) ::String s = c->_hx_getString(0); HXDLIN( 325) return s; } break; } } break; case (int)1: { HXLINE( 330) ::String id = e->_hx_getString(0); HXLINE( 331) return this->resolve(id); } break; case (int)2: { HXLINE( 332) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >(); HXDLIN( 332) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 332) ::String n = e->_hx_getString(0); HXLINE( 333) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 333) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 334) { HXLINE( 334) ::Dynamic this1 = this->locals; HXDLIN( 334) ::Dynamic value; HXDLIN( 334) if (::hx::IsNull( e1 )) { HXLINE( 334) value = null(); } else { HXLINE( 334) value = this->expr(e1); } HXDLIN( 334) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),value))); } HXLINE( 335) return null(); } break; case (int)3: { HXLINE( 336) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 337) return this->expr(e1); } break; case (int)4: { HXLINE( 338) ::Array< ::Dynamic> exprs = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 339) int old = this->declared->length; HXLINE( 340) ::Dynamic v = null(); HXLINE( 341) { HXLINE( 341) int _g = 0; HXDLIN( 341) while((_g < exprs->length)){ HXLINE( 341) ::hscript::Expr e = exprs->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 341) _g = (_g + 1); HXLINE( 342) v = this->expr(e); } } HXLINE( 343) this->restore(old); HXLINE( 344) return v; } break; case (int)5: { HXLINE( 345) ::String f = e->_hx_getString(1); HXDLIN( 345) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 346) return this->get(this->expr(e1),f); } break; case (int)6: { HXLINE( 347) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 347) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 347) ::String op = e->_hx_getString(0); HXLINE( 348) ::Dynamic fop = this->binops->get(op); HXLINE( 349) if (::hx::IsNull( fop )) { HXLINE( 349) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 349) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 350) return fop(e1,e2); } break; case (int)7: { HXLINE( 351) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 351) bool prefix = e->_hx_getBool(1); HXDLIN( 351) ::String op = e->_hx_getString(0); HXLINE( 352) ::String _hx_switch_0 = op; if ( (_hx_switch_0==HX_("!",21,00,00,00)) ){ HXLINE( 354) return ::hx::IsNotEq( this->expr(e1),true ); HXDLIN( 354) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("++",a0,25,00,00)) ){ HXLINE( 358) return this->increment(e1,prefix,1); HXDLIN( 358) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("-",2d,00,00,00)) ){ HXLINE( 356) return -(this->expr(e1)); HXDLIN( 356) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("--",60,27,00,00)) ){ HXLINE( 360) return this->increment(e1,prefix,-1); HXDLIN( 360) goto _hx_goto_51; } if ( (_hx_switch_0==HX_("~",7e,00,00,00)) ){ HXLINE( 365) return ~(( (int)(this->expr(e1)) )); HXDLIN( 365) goto _hx_goto_51; } /* default */{ HXLINE( 368) ::hscript::Error e = ::hscript::Error_obj::EInvalidOp(op); HXDLIN( 368) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } _hx_goto_51:; } break; case (int)8: { HXLINE( 370) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 370) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 371) ::cpp::VirtualArray args = ::cpp::VirtualArray_obj::__new(); HXLINE( 372) { HXLINE( 372) int _g = 0; HXDLIN( 372) while((_g < params->length)){ HXLINE( 372) ::hscript::Expr p = params->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 372) _g = (_g + 1); HXLINE( 373) args->push(this->expr(p)); } } HXLINE( 375) if ((e1->_hx_getIndex() == 5)) { HXLINE( 376) ::String f = e1->_hx_getString(1); HXDLIN( 376) ::hscript::Expr e = e1->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 377) ::Dynamic obj = this->expr(e); HXLINE( 378) if (::hx::IsNull( obj )) { HXLINE( 378) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 378) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 379) return this->fcall(obj,f,args); } else { HXLINE( 381) return this->call(null(),this->expr(e1),args); } } break; case (int)9: { HXLINE( 383) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 383) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 383) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 384) if (::hx::IsEq( this->expr(econd),true )) { HXLINE( 384) return this->expr(e1); } else { HXLINE( 384) if (::hx::IsNull( e2 )) { HXLINE( 384) return null(); } else { HXLINE( 384) return this->expr(e2); } } } break; case (int)10: { HXLINE( 385) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 385) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 386) this->whileLoop(econd,e1); HXLINE( 387) return null(); } break; case (int)11: { HXLINE( 391) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 391) ::hscript::Expr it = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 391) ::String v = e->_hx_getString(0); HXLINE( 392) this->forLoop(v,it,e1); HXLINE( 393) return null(); } break; case (int)12: { HXLINE( 395) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SBreak_dyn())); } break; case (int)13: { HXLINE( 397) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SContinue_dyn())); } break; case (int)14: { HX_BEGIN_LOCAL_FUNC_S7(::hx::LocalFunc,_hx_Closure_0,::String,name, ::hscript::Expr,fexpr, ::hscript::Interp,_gthis,int,minParams, ::hscript::Interp,me,::Array< ::Dynamic>,params, ::haxe::ds::StringMap,capturedLocals) HXARGC(1) ::Dynamic _hx_run(::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_410_expr) HXLINE( 411) int f; HXDLIN( 411) if (::hx::IsNull( args )) { HXLINE( 411) f = 0; } else { HXLINE( 411) f = args->get_length(); } HXDLIN( 411) if ((f != params->length)) { HXLINE( 412) if ((args->get_length() < minParams)) { HXLINE( 413) ::String str = (((HX_("Invalid number of parameters. Got ",cb,2b,d9,b1) + args->get_length()) + HX_(", required ",ed,0c,66,93)) + minParams); HXLINE( 414) if (::hx::IsNotNull( name )) { HXLINE( 414) str = (str + ((HX_(" for function '",f6,90,ab,a0) + name) + HX_("'",27,00,00,00))); } HXLINE( 415) ::hscript::Error e = ::hscript::Error_obj::ECustom(str); HXDLIN( 415) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 418) ::cpp::VirtualArray args2 = ::cpp::VirtualArray_obj::__new(0); HXLINE( 419) int extraParams = (args->get_length() - minParams); HXLINE( 420) int pos = 0; HXLINE( 421) { HXLINE( 421) int _g = 0; HXDLIN( 421) while((_g < params->length)){ HXLINE( 421) ::Dynamic p = params->__get(_g); HXDLIN( 421) _g = (_g + 1); HXLINE( 422) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) { HXLINE( 423) if ((extraParams > 0)) { HXLINE( 424) pos = (pos + 1); HXDLIN( 424) args2->push(args->__get((pos - 1))); HXLINE( 425) extraParams = (extraParams - 1); } else { HXLINE( 427) args2->push(null()); } } else { HXLINE( 429) pos = (pos + 1); HXDLIN( 429) args2->push(args->__get((pos - 1))); } } } HXLINE( 430) args = args2; } HXLINE( 432) ::haxe::ds::StringMap old = me->locals; HXDLIN( 432) int depth = me->depth; HXLINE( 433) me->depth++; HXLINE( 434) me->locals = me->duplicate(capturedLocals); HXLINE( 435) { HXLINE( 435) int _g = 0; HXDLIN( 435) int _g1 = params->length; HXDLIN( 435) while((_g < _g1)){ HXLINE( 435) _g = (_g + 1); HXDLIN( 435) int i = (_g - 1); HXLINE( 436) me->locals->set(( (::String)(params->__get(i)->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) ), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),args->__get(i)))); } } HXLINE( 437) ::Dynamic r = null(); HXLINE( 438) if (_gthis->inTry) { HXLINE( 439) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 440) r = me->exprReturn(fexpr); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic e = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 442) me->locals = old; HXLINE( 443) me->depth = depth; HXLINE( 447) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } else { HX_STACK_DO_THROW(_hx_e); } } } else { HXLINE( 451) r = me->exprReturn(fexpr); } HXLINE( 452) me->locals = old; HXLINE( 453) me->depth = depth; HXLINE( 454) return r; } HX_END_LOCAL_FUNC1(return) HXLINE( 401) ::hscript::CType _g = e->_hx_getObject(3).StaticCast< ::hscript::CType >(); HXDLIN( 401) ::String name = e->_hx_getString(2); HXDLIN( 401) ::hscript::Expr fexpr = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 401) ::Array< ::Dynamic> params = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 402) ::haxe::ds::StringMap capturedLocals = this->duplicate(this->locals); HXLINE( 403) ::hscript::Interp me = ::hx::ObjectPtr<OBJ_>(this); HXLINE( 404) bool hasOpt = false; HXDLIN( 404) int minParams = 0; HXLINE( 405) { HXLINE( 405) int _g1 = 0; HXDLIN( 405) while((_g1 < params->length)){ HXLINE( 405) ::Dynamic p = params->__get(_g1); HXDLIN( 405) _g1 = (_g1 + 1); HXLINE( 406) if (( (bool)(p->__Field(HX_("opt",33,9c,54,00),::hx::paccDynamic)) )) { HXLINE( 407) hasOpt = true; } else { HXLINE( 409) minParams = (minParams + 1); } } } HXLINE( 410) ::Dynamic f = ::Dynamic(new _hx_Closure_0(name,fexpr,_gthis,minParams,me,params,capturedLocals)); HXLINE( 456) ::Dynamic f1 = ::Reflect_obj::makeVarArgs(f); HXLINE( 457) if (::hx::IsNotNull( name )) { HXLINE( 458) if ((this->depth == 0)) { HXLINE( 460) this->variables->set(name,f1); } else { HXLINE( 463) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 463) ::String name1 = name; HXDLIN( 463) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),name1) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(name)))); HXLINE( 464) ::Dynamic ref = ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),f1)); HXLINE( 465) this->locals->set(name,ref); HXLINE( 466) capturedLocals->set(name,ref); } } HXLINE( 469) return f1; } break; case (int)15: { HXLINE( 398) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 399) ::Dynamic _hx_tmp; HXDLIN( 399) if (::hx::IsNull( e1 )) { HXLINE( 399) _hx_tmp = null(); } else { HXLINE( 399) _hx_tmp = this->expr(e1); } HXDLIN( 399) this->returnValue = _hx_tmp; HXLINE( 400) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::hscript::_Interp::Stop_obj::SReturn_dyn())); } break; case (int)16: { HXLINE( 512) ::hscript::Expr index = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 512) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 513) ::Dynamic arr = this->expr(e1); HXLINE( 514) ::Dynamic index1 = this->expr(index); HXLINE( 515) if (::Std_obj::isOfType(arr,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) ))) { HXLINE( 516) return ::haxe::IMap_obj::get( ::hx::interface_check(arr,0x09c2bd39),index1); } else { HXLINE( 519) return arr->__GetItem(( (int)(index1) )); } } break; case (int)17: { HXLINE( 470) ::Array< ::Dynamic> arr = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 471) bool _hx_tmp; HXDLIN( 471) if ((arr->length > 0)) { HXLINE( 471) ::hscript::Expr _g = arr->__get(0).StaticCast< ::hscript::Expr >(); HXDLIN( 471) if ((_g->_hx_getIndex() == 6)) { HXLINE( 471) ::hscript::Expr _g1 = _g->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 471) ::hscript::Expr _g2 = _g->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 471) if ((_g->_hx_getString(0) == HX_("=>",61,35,00,00))) { HXLINE( 471) _hx_tmp = true; } else { HXLINE( 471) _hx_tmp = false; } } else { HXLINE( 471) _hx_tmp = false; } } else { HXLINE( 471) _hx_tmp = false; } HXDLIN( 471) if (_hx_tmp) { HXLINE( 472) bool isAllString = true; HXLINE( 473) bool isAllInt = true; HXLINE( 474) bool isAllObject = true; HXLINE( 475) bool isAllEnum = true; HXLINE( 476) ::cpp::VirtualArray keys = ::cpp::VirtualArray_obj::__new(0); HXLINE( 477) ::cpp::VirtualArray values = ::cpp::VirtualArray_obj::__new(0); HXLINE( 478) { HXLINE( 478) int _g = 0; HXDLIN( 478) while((_g < arr->length)){ HXLINE( 478) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 478) _g = (_g + 1); HXLINE( 479) if ((e->_hx_getIndex() == 6)) { HXLINE( 480) if ((e->_hx_getString(0) == HX_("=>",61,35,00,00))) { HXLINE( 480) ::hscript::Expr eValue = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 480) ::hscript::Expr eKey = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 480) { HXLINE( 481) ::Dynamic key = this->expr(eKey); HXLINE( 482) ::Dynamic value = this->expr(eValue); HXLINE( 483) if (isAllString) { HXLINE( 483) isAllString = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< ::String >()) )); } else { HXLINE( 483) isAllString = false; } HXLINE( 484) if (isAllInt) { HXLINE( 484) isAllInt = ::Std_obj::isOfType(key,( ( ::Dynamic)(::hx::ClassOf< int >()) )); } else { HXLINE( 484) isAllInt = false; } HXLINE( 485) if (isAllObject) { HXLINE( 485) isAllObject = ::Reflect_obj::isObject(key); } else { HXLINE( 485) isAllObject = false; } HXLINE( 486) if (isAllEnum) { HXLINE( 486) isAllEnum = ::Reflect_obj::isEnumValue(key); } else { HXLINE( 486) isAllEnum = false; } HXLINE( 487) keys->push(key); HXLINE( 488) values->push(value); } } else { HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5))); } } else { HXLINE( 490) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("=> expected",17,e5,65,e5))); } } } HXLINE( 493) ::Dynamic map; HXLINE( 494) if (isAllInt) { HXLINE( 493) map = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); } else { HXLINE( 495) if (isAllString) { HXLINE( 493) map = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } else { HXLINE( 496) if (isAllEnum) { HXLINE( 493) map = ::haxe::ds::EnumValueMap_obj::__alloc( HX_CTX ); } else { HXLINE( 497) if (isAllObject) { HXLINE( 493) map = ::haxe::ds::ObjectMap_obj::__alloc( HX_CTX ); } else { HXLINE( 498) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Inconsistent key types",af,4f,50,a9))); } } } } HXLINE( 500) { HXLINE( 500) int _g1 = 0; HXDLIN( 500) int _g2 = keys->get_length(); HXDLIN( 500) while((_g1 < _g2)){ HXLINE( 500) _g1 = (_g1 + 1); HXDLIN( 500) int n = (_g1 - 1); HXLINE( 501) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),keys->__get(n),values->__get(n)); } } HXLINE( 503) return map; } else { HXLINE( 506) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new(); HXLINE( 507) { HXLINE( 507) int _g = 0; HXDLIN( 507) while((_g < arr->length)){ HXLINE( 507) ::hscript::Expr e = arr->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 507) _g = (_g + 1); HXLINE( 508) a->push(this->expr(e)); } } HXLINE( 510) return a; } } break; case (int)18: { HXLINE( 521) ::Array< ::Dynamic> params = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 521) ::String cl = e->_hx_getString(0); HXLINE( 522) ::cpp::VirtualArray a = ::cpp::VirtualArray_obj::__new(); HXLINE( 523) { HXLINE( 523) int _g = 0; HXDLIN( 523) while((_g < params->length)){ HXLINE( 523) ::hscript::Expr e = params->__get(_g).StaticCast< ::hscript::Expr >(); HXDLIN( 523) _g = (_g + 1); HXLINE( 524) a->push(this->expr(e)); } } HXLINE( 525) return this->cnew(cl,a); } break; case (int)19: { HXLINE( 526) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 527) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(this->expr(e1))); } break; case (int)20: { HXLINE( 528) ::hscript::CType _g = e->_hx_getObject(2).StaticCast< ::hscript::CType >(); HXDLIN( 528) ::hscript::Expr ecatch = e->_hx_getObject(3).StaticCast< ::hscript::Expr >(); HXDLIN( 528) ::String n = e->_hx_getString(1); HXDLIN( 528) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 529) int old = this->declared->length; HXLINE( 530) bool oldTry = this->inTry; HXLINE( 531) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 532) this->inTry = true; HXLINE( 533) ::Dynamic v = this->expr(e1); HXLINE( 534) this->restore(old); HXLINE( 535) this->inTry = oldTry; HXLINE( 536) return v; } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 531) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 538) this->inTry = oldTry; HXLINE( 539) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } else { HXLINE( 1) ::Dynamic err = _g1; HXLINE( 542) this->restore(old); HXLINE( 543) this->inTry = oldTry; HXLINE( 545) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 545) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 546) this->locals->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),err))); HXLINE( 547) ::Dynamic v = this->expr(ecatch); HXLINE( 548) this->restore(old); HXLINE( 549) return v; } } else { HX_STACK_DO_THROW(_hx_e); } } } break; case (int)21: { HXLINE( 551) ::Array< ::Dynamic> fl = e->_hx_getObject(0).StaticCast< ::Array< ::Dynamic> >(); HXLINE( 552) ::Dynamic o = ::Dynamic(::hx::Anon_obj::Create(0)); HXLINE( 553) { HXLINE( 553) int _g = 0; HXDLIN( 553) while((_g < fl->length)){ HXLINE( 553) ::Dynamic f = fl->__get(_g); HXDLIN( 553) _g = (_g + 1); HXLINE( 554) ::String f1 = ( (::String)(f->__Field(HX_("name",4b,72,ff,48),::hx::paccDynamic)) ); HXDLIN( 554) this->set(o,f1,this->expr(f->__Field(HX_("e",65,00,00,00),::hx::paccDynamic))); } } HXLINE( 555) return o; } break; case (int)22: { HXLINE( 556) ::hscript::Expr e2 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 556) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 556) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 557) if (::hx::IsEq( this->expr(econd),true )) { HXLINE( 557) return this->expr(e1); } else { HXLINE( 557) return this->expr(e2); } } break; case (int)23: { HXLINE( 558) ::hscript::Expr def = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXDLIN( 558) ::Array< ::Dynamic> cases = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 558) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 559) ::Dynamic val = this->expr(e1); HXLINE( 560) bool match = false; HXLINE( 561) { HXLINE( 561) int _g = 0; HXDLIN( 561) while((_g < cases->length)){ HXLINE( 561) ::Dynamic c = cases->__get(_g); HXDLIN( 561) _g = (_g + 1); HXLINE( 562) { HXLINE( 562) int _g1 = 0; HXDLIN( 562) ::Array< ::Dynamic> _g2 = ( (::Array< ::Dynamic>)(c->__Field(HX_("values",e2,03,b7,4f),::hx::paccDynamic)) ); HXDLIN( 562) while((_g1 < _g2->length)){ HXLINE( 562) ::hscript::Expr v = _g2->__get(_g1).StaticCast< ::hscript::Expr >(); HXDLIN( 562) _g1 = (_g1 + 1); HXLINE( 563) if (::hx::IsEq( this->expr(v),val )) { HXLINE( 564) match = true; HXLINE( 565) goto _hx_goto_62; } } _hx_goto_62:; } HXLINE( 567) if (match) { HXLINE( 568) val = this->expr(c->__Field(HX_("expr",35,fd,1d,43),::hx::paccDynamic)); HXLINE( 569) goto _hx_goto_61; } } _hx_goto_61:; } HXLINE( 572) if (!(match)) { HXLINE( 573) if (::hx::IsNull( def )) { HXLINE( 573) val = null(); } else { HXLINE( 573) val = this->expr(def); } } HXLINE( 574) return val; } break; case (int)24: { HXLINE( 388) ::hscript::Expr e1 = e->_hx_getObject(1).StaticCast< ::hscript::Expr >(); HXDLIN( 388) ::hscript::Expr econd = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 389) this->doWhileLoop(econd,e1); HXLINE( 390) return null(); } break; case (int)25: { HXLINE( 575) ::Array< ::Dynamic> _g = e->_hx_getObject(1).StaticCast< ::Array< ::Dynamic> >(); HXDLIN( 575) ::String _g1 = e->_hx_getString(0); HXDLIN( 575) ::hscript::Expr e1 = e->_hx_getObject(2).StaticCast< ::hscript::Expr >(); HXLINE( 576) return this->expr(e1); } break; case (int)26: { HXLINE( 577) ::hscript::CType _g = e->_hx_getObject(1).StaticCast< ::hscript::CType >(); HXDLIN( 577) ::hscript::Expr e1 = e->_hx_getObject(0).StaticCast< ::hscript::Expr >(); HXLINE( 578) return this->expr(e1); } break; } HXLINE( 320) return null(); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,expr,return ) void Interp_obj::doWhileLoop( ::hscript::Expr econd, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_583_doWhileLoop) HXLINE( 584) int old = this->declared->length; HXLINE( 585) while(true){ HXLINE( 586) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 587) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 586) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 589) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 591) goto _hx_goto_65; } break; case (int)1: { } break; case (int)2: { HXLINE( 592) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 586) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 585) if (!(::hx::IsEq( this->expr(econd),true ))) { HXLINE( 585) goto _hx_goto_65; } } _hx_goto_65:; HXLINE( 597) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,doWhileLoop,(void)) void Interp_obj::whileLoop( ::hscript::Expr econd, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_600_whileLoop) HXLINE( 601) int old = this->declared->length; HXLINE( 602) while(::hx::IsEq( this->expr(econd),true )){ HXLINE( 603) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 604) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 603) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 606) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 608) goto _hx_goto_67; } break; case (int)1: { } break; case (int)2: { HXLINE( 609) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 603) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } } _hx_goto_67:; HXLINE( 613) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,whileLoop,(void)) ::Dynamic Interp_obj::makeIterator( ::Dynamic v){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_616_makeIterator) HXLINE( 620) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 620) v = v->__Field(HX_("iterator",ee,49,9a,93),::hx::paccDynamic)(); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } } else { HX_STACK_DO_THROW(_hx_e); } } HXLINE( 622) bool _hx_tmp; HXDLIN( 622) if (::hx::IsNotNull( v->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic) )) { HXLINE( 622) _hx_tmp = ::hx::IsNull( v->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic) ); } else { HXLINE( 622) _hx_tmp = true; } HXDLIN( 622) if (_hx_tmp) { HXLINE( 622) ::hscript::Error e = ::hscript::Error_obj::EInvalidIterator(v); HXDLIN( 622) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 623) return v; } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,makeIterator,return ) void Interp_obj::forLoop(::String n, ::hscript::Expr it, ::hscript::Expr e){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_626_forLoop) HXLINE( 627) int old = this->declared->length; HXLINE( 628) ::Array< ::Dynamic> _hx_tmp = this->declared; HXDLIN( 628) _hx_tmp->push( ::Dynamic(::hx::Anon_obj::Create(2) ->setFixed(0,HX_("n",6e,00,00,00),n) ->setFixed(1,HX_("old",a7,98,54,00),this->locals->get(n)))); HXLINE( 629) ::Dynamic it1 = this->makeIterator(this->expr(it)); HXLINE( 630) while(( (bool)(it1->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){ HXLINE( 631) { HXLINE( 631) ::Dynamic this1 = this->locals; HXDLIN( 631) ( ( ::haxe::ds::StringMap)(this1) )->set(n, ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("r",72,00,00,00),it1->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()))); } HXLINE( 632) try { HX_STACK_CATCHABLE( ::Dynamic, 0); HXLINE( 633) this->expr(e); } catch( ::Dynamic _hx_e) { if (_hx_e.IsClass< ::Dynamic >() ){ HX_STACK_BEGIN_CATCH ::Dynamic _g = _hx_e; HXLINE( 1) { HXLINE( 1) null(); } HXDLIN( 1) ::Dynamic _g1 = ::haxe::Exception_obj::caught(_g)->unwrap(); HXLINE( 632) if (::Std_obj::isOfType(_g1,::hx::ClassOf< ::hscript::_Interp::Stop >())) { HXLINE( 1) ::hscript::_Interp::Stop err = _g1; HXLINE( 635) switch((int)(err->_hx_getIndex())){ case (int)0: { HXLINE( 637) goto _hx_goto_70; } break; case (int)1: { } break; case (int)2: { HXLINE( 638) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(err)); } break; } } else { HXLINE( 632) HX_STACK_DO_THROW(_g); } } else { HX_STACK_DO_THROW(_hx_e); } } } _hx_goto_70:; HXLINE( 642) this->restore(old); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,forLoop,(void)) bool Interp_obj::isMap( ::Dynamic o){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_646_isMap) HXDLIN( 646) return ::Std_obj::isOfType(o,( ( ::Dynamic)(::hx::ClassOf< ::haxe::IMap >()) )); } HX_DEFINE_DYNAMIC_FUNC1(Interp_obj,isMap,return ) ::Dynamic Interp_obj::getMapValue( ::Dynamic map, ::Dynamic key){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_650_getMapValue) HXDLIN( 650) return ::haxe::IMap_obj::get( ::hx::interface_check(map,0x09c2bd39),key); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,getMapValue,return ) void Interp_obj::setMapValue( ::Dynamic map, ::Dynamic key, ::Dynamic value){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_654_setMapValue) HXDLIN( 654) ::haxe::IMap_obj::set( ::hx::interface_check(map,0x09c2bd39),key,value); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,setMapValue,(void)) ::Dynamic Interp_obj::get( ::Dynamic o,::String f){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_657_get) HXLINE( 658) if (::hx::IsNull( o )) { HXLINE( 658) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 658) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 659) return ::Reflect_obj::getProperty(o,f); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,get,return ) ::Dynamic Interp_obj::set( ::Dynamic o,::String f, ::Dynamic v){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_673_set) HXLINE( 674) if (::hx::IsNull( o )) { HXLINE( 674) ::hscript::Error e = ::hscript::Error_obj::EInvalidAccess(f); HXDLIN( 674) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(e)); } HXLINE( 675) ::Reflect_obj::setProperty(o,f,v); HXLINE( 676) return v; } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,set,return ) ::Dynamic Interp_obj::fcall( ::Dynamic o,::String f,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_680_fcall) HXDLIN( 680) return this->call(o,this->get(o,f),args); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,fcall,return ) ::Dynamic Interp_obj::call( ::Dynamic o, ::Dynamic f,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_684_call) HXDLIN( 684) return ::Reflect_obj::callMethod(o,f,args); } HX_DEFINE_DYNAMIC_FUNC3(Interp_obj,call,return ) ::Dynamic Interp_obj::cnew(::String cl,::cpp::VirtualArray args){ HX_STACKFRAME(&_hx_pos_f37559d470356c9e_687_cnew) HXLINE( 688) ::hx::Class c = ::Type_obj::resolveClass(cl); HXLINE( 689) if (::hx::IsNull( c )) { HXLINE( 689) c = this->resolve(cl); } HXLINE( 690) return ::Type_obj::createInstance(c,args); } HX_DEFINE_DYNAMIC_FUNC2(Interp_obj,cnew,return ) ::hx::ObjectPtr< Interp_obj > Interp_obj::__new() { ::hx::ObjectPtr< Interp_obj > __this = new Interp_obj(); __this->__construct(); return __this; } ::hx::ObjectPtr< Interp_obj > Interp_obj::__alloc(::hx::Ctx *_hx_ctx) { Interp_obj *__this = (Interp_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(Interp_obj), true, "hscript.Interp")); *(void **)__this = Interp_obj::_hx_vtable; __this->__construct(); return __this; } Interp_obj::Interp_obj() { } void Interp_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Interp); HX_MARK_MEMBER_NAME(variables,"variables"); HX_MARK_MEMBER_NAME(locals,"locals"); HX_MARK_MEMBER_NAME(binops,"binops"); HX_MARK_MEMBER_NAME(depth,"depth"); HX_MARK_MEMBER_NAME(inTry,"inTry"); HX_MARK_MEMBER_NAME(declared,"declared"); HX_MARK_MEMBER_NAME(returnValue,"returnValue"); HX_MARK_END_CLASS(); } void Interp_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(variables,"variables"); HX_VISIT_MEMBER_NAME(locals,"locals"); HX_VISIT_MEMBER_NAME(binops,"binops"); HX_VISIT_MEMBER_NAME(depth,"depth"); HX_VISIT_MEMBER_NAME(inTry,"inTry"); HX_VISIT_MEMBER_NAME(declared,"declared"); HX_VISIT_MEMBER_NAME(returnValue,"returnValue"); } ::hx::Val Interp_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"get") ) { return ::hx::Val( get_dyn() ); } if (HX_FIELD_EQ(inName,"set") ) { return ::hx::Val( set_dyn() ); } break; case 4: if (HX_FIELD_EQ(inName,"expr") ) { return ::hx::Val( expr_dyn() ); } if (HX_FIELD_EQ(inName,"call") ) { return ::hx::Val( call_dyn() ); } if (HX_FIELD_EQ(inName,"cnew") ) { return ::hx::Val( cnew_dyn() ); } break; case 5: if (HX_FIELD_EQ(inName,"depth") ) { return ::hx::Val( depth ); } if (HX_FIELD_EQ(inName,"inTry") ) { return ::hx::Val( inTry ); } if (HX_FIELD_EQ(inName,"error") ) { return ::hx::Val( error_dyn() ); } if (HX_FIELD_EQ(inName,"isMap") ) { return ::hx::Val( isMap_dyn() ); } if (HX_FIELD_EQ(inName,"fcall") ) { return ::hx::Val( fcall_dyn() ); } break; case 6: if (HX_FIELD_EQ(inName,"locals") ) { return ::hx::Val( locals ); } if (HX_FIELD_EQ(inName,"binops") ) { return ::hx::Val( binops ); } if (HX_FIELD_EQ(inName,"assign") ) { return ::hx::Val( assign_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"initOps") ) { return ::hx::Val( initOps_dyn() ); } if (HX_FIELD_EQ(inName,"execute") ) { return ::hx::Val( execute_dyn() ); } if (HX_FIELD_EQ(inName,"restore") ) { return ::hx::Val( restore_dyn() ); } if (HX_FIELD_EQ(inName,"rethrow") ) { return ::hx::Val( rethrow_dyn() ); } if (HX_FIELD_EQ(inName,"resolve") ) { return ::hx::Val( resolve_dyn() ); } if (HX_FIELD_EQ(inName,"forLoop") ) { return ::hx::Val( forLoop_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"declared") ) { return ::hx::Val( declared ); } if (HX_FIELD_EQ(inName,"posInfos") ) { return ::hx::Val( posInfos_dyn() ); } if (HX_FIELD_EQ(inName,"assignOp") ) { return ::hx::Val( assignOp_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"variables") ) { return ::hx::Val( variables ); } if (HX_FIELD_EQ(inName,"increment") ) { return ::hx::Val( increment_dyn() ); } if (HX_FIELD_EQ(inName,"duplicate") ) { return ::hx::Val( duplicate_dyn() ); } if (HX_FIELD_EQ(inName,"whileLoop") ) { return ::hx::Val( whileLoop_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"exprReturn") ) { return ::hx::Val( exprReturn_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"returnValue") ) { return ::hx::Val( returnValue ); } if (HX_FIELD_EQ(inName,"doWhileLoop") ) { return ::hx::Val( doWhileLoop_dyn() ); } if (HX_FIELD_EQ(inName,"getMapValue") ) { return ::hx::Val( getMapValue_dyn() ); } if (HX_FIELD_EQ(inName,"setMapValue") ) { return ::hx::Val( setMapValue_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"evalAssignOp") ) { return ::hx::Val( evalAssignOp_dyn() ); } if (HX_FIELD_EQ(inName,"makeIterator") ) { return ::hx::Val( makeIterator_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"resetVariables") ) { return ::hx::Val( resetVariables_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val Interp_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"depth") ) { depth=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"inTry") ) { inTry=inValue.Cast< bool >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"locals") ) { locals=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } if (HX_FIELD_EQ(inName,"binops") ) { binops=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"declared") ) { declared=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"variables") ) { variables=inValue.Cast< ::haxe::ds::StringMap >(); return inValue; } break; case 11: if (HX_FIELD_EQ(inName,"returnValue") ) { returnValue=inValue.Cast< ::Dynamic >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Interp_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("variables",b7,e2,62,82)); outFields->push(HX_("locals",a8,74,bf,59)); outFields->push(HX_("binops",cb,59,16,ed)); outFields->push(HX_("depth",03,f1,29,d7)); outFields->push(HX_("inTry",56,82,08,be)); outFields->push(HX_("declared",fa,58,bc,c4)); outFields->push(HX_("returnValue",a1,4c,95,3e)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo Interp_obj_sMemberStorageInfo[] = { {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,variables),HX_("variables",b7,e2,62,82)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,locals),HX_("locals",a8,74,bf,59)}, {::hx::fsObject /* ::haxe::ds::StringMap */ ,(int)offsetof(Interp_obj,binops),HX_("binops",cb,59,16,ed)}, {::hx::fsInt,(int)offsetof(Interp_obj,depth),HX_("depth",03,f1,29,d7)}, {::hx::fsBool,(int)offsetof(Interp_obj,inTry),HX_("inTry",56,82,08,be)}, {::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(Interp_obj,declared),HX_("declared",fa,58,bc,c4)}, {::hx::fsObject /* ::Dynamic */ ,(int)offsetof(Interp_obj,returnValue),HX_("returnValue",a1,4c,95,3e)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *Interp_obj_sStaticStorageInfo = 0; #endif static ::String Interp_obj_sMemberFields[] = { HX_("variables",b7,e2,62,82), HX_("locals",a8,74,bf,59), HX_("binops",cb,59,16,ed), HX_("depth",03,f1,29,d7), HX_("inTry",56,82,08,be), HX_("declared",fa,58,bc,c4), HX_("returnValue",a1,4c,95,3e), HX_("resetVariables",e8,46,d3,dc), HX_("posInfos",11,82,2e,5a), HX_("initOps",02,63,8b,cb), HX_("assign",2f,46,06,4c), HX_("assignOp",30,b5,c7,0e), HX_("evalAssignOp",ec,d8,94,19), HX_("increment",2f,06,ff,31), HX_("execute",35,0a,0d,cc), HX_("exprReturn",c5,6b,ed,86), HX_("duplicate",8b,21,17,a1), HX_("restore",4e,67,b0,6a), HX_("error",c8,cb,29,73), HX_("rethrow",93,b0,2a,f6), HX_("resolve",ec,12,60,67), HX_("expr",35,fd,1d,43), HX_("doWhileLoop",aa,01,97,3a), HX_("whileLoop",b5,42,98,e1), HX_("makeIterator",fc,dd,72,d8), HX_("forLoop",0d,52,69,c9), HX_("isMap",d2,34,51,c1), HX_("getMapValue",eb,b1,ee,ce), HX_("setMapValue",f7,b8,5b,d9), HX_("get",96,80,4e,00), HX_("set",a2,9b,57,00), HX_("fcall",04,44,99,fc), HX_("call",9e,18,ba,41), HX_("cnew",dd,ef,c3,41), ::String(null()) }; ::hx::Class Interp_obj::__mClass; void Interp_obj::__register() { Interp_obj _hx_dummy; Interp_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("hscript.Interp",8f,7c,f0,9a); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(Interp_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< Interp_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Interp_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Interp_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace hscript
45.063174
243
0.593745
VehpuS
0e6f241d5b39be52ee550570a5563c2a42aa7e27
3,998
cpp
C++
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
driver/src/visitor/ScopedModifier.cpp
pranavsubramani/Birch
0a4bb698ed44353c8e8b93d234f2941d7511683c
[ "Apache-2.0" ]
null
null
null
/** * @file */ #include "src/visitor/ScopedModifier.hpp" birch::ScopedModifier::ScopedModifier(Package* currentPackage, Class* currentClass) : ContextualModifier(currentPackage, currentClass), inMember(0), inGlobal(0) { if (currentPackage) { scopes.push_back(currentPackage->scope); if (currentClass) { scopes.push_back(currentClass->scope); } } } birch::ScopedModifier::~ScopedModifier() { // } birch::Package* birch::ScopedModifier::modify(Package* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Expression* birch::ScopedModifier::modify(LambdaFunction* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Expression* birch::ScopedModifier::modify(Member* o) { o->left = o->left->accept(this); ++inMember; o->right = o->right->accept(this); --inMember; return o; } birch::Expression* birch::ScopedModifier::modify(Global* o) { ++inGlobal; o->single = o->single->accept(this); --inGlobal; return o; } birch::Statement* birch::ScopedModifier::modify(MemberFunction* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Function* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(BinaryOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(UnaryOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Program* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(AssignmentOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(ConversionOperator* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Class* o) { this->currentClass = o; scopes.push_back(o->scope); o->typeParams = o->typeParams->accept(this); o->base = o->base->accept(this); scopes.push_back(o->initScope); o->params = o->params->accept(this); o->args = o->args->accept(this); scopes.pop_back(); o->braces = o->braces->accept(this); scopes.pop_back(); this->currentClass = nullptr; return o; } birch::Statement* birch::ScopedModifier::modify(If* o) { scopes.push_back(o->scope); o->cond = o->cond->accept(this); o->braces = o->braces->accept(this); scopes.pop_back(); scopes.push_back(o->falseScope); o->falseBraces = o->falseBraces->accept(this); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(For* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Parallel* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(While* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(DoWhile* o) { scopes.push_back(o->scope); o->braces = o->braces->accept(this); scopes.pop_back(); o->cond = o->cond->accept(this); return o; } birch::Statement* birch::ScopedModifier::modify(With* o) { scopes.push_back(o->scope); ContextualModifier::modify(o); scopes.pop_back(); return o; } birch::Statement* birch::ScopedModifier::modify(Block* o) { scopes.push_back(o->scope); o->braces = o->braces->accept(this); scopes.pop_back(); return o; }
23.656805
72
0.690595
pranavsubramani
0e6f7fd5bbea687cc6ca4a486d5a07f877207dab
3,380
cc
C++
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/mraft/floyd/example/simple/t1.cc
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include <pthread.h> #include <signal.h> #include <iostream> #include <string> #include "floyd/include/floyd.h" #include "slash/include/testutil.h" using namespace floyd; uint64_t NowMicros() { struct timeval tv; gettimeofday(&tv, NULL); return static_cast<uint64_t>(tv.tv_sec) * 1000000 + tv.tv_usec; } Floyd *f1, *f2, *f3, *f4, *f5; std::string keystr[1001000]; std::string valstr[1001000]; int val_size = 128; int thread_num = 4; int item_num = 10000; void *fun(void *arg) { int i = 1; Floyd *p; if (f1->IsLeader()) { p = f1; } else if (f2->IsLeader()) { p = f2; } else if (f3->IsLeader()) { p = f3; } else if (f4->IsLeader()) { p = f4; } else { p = f5; } while (i--) { for (int j = 0; j < item_num; j++) { p->Write(keystr[j], valstr[j]); } } } int main(int argc, char * argv[]) { if (argc > 1) { thread_num = atoi(argv[1]); } if (argc > 2) { val_size = atoi(argv[2]); } if (argc > 3) { item_num = atoi(argv[3]); } printf("multi threads test to get performance thread num %d key size %d item number %d\n", thread_num, val_size, item_num); Options op1("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8901, "./data1/"); slash::Status s = Floyd::Open(op1, &f1); printf("%s\n", s.ToString().c_str()); Options op2("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8902, "./data2/"); s = Floyd::Open(op2, &f2); printf("%s\n", s.ToString().c_str()); Options op3("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8903, "./data3/"); s = Floyd::Open(op3, &f3); printf("%s\n", s.ToString().c_str()); Options op4("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8904, "./data4/"); s = Floyd::Open(op4, &f4); printf("%s\n", s.ToString().c_str()); Options op5("127.0.0.1:8901,127.0.0.1:8902,127.0.0.1:8903,127.0.0.1:8904,127.0.0.1:8905", "127.0.0.1", 8905, "./data5/"); s = Floyd::Open(op5, &f5); printf("%s\n", s.ToString().c_str()); std::string msg; int i = 10; uint64_t st = NowMicros(), ed; for (int i = 0; i < item_num; i++) { keystr[i] = slash::RandomString(32); } for (int i = 0; i < item_num; i++) { valstr[i] = slash::RandomString(val_size); } while (1) { if (f1->HasLeader()) { f1->GetServerStatus(&msg); printf("%s\n", msg.c_str()); break; } printf("electing leader... sleep 2s\n"); sleep(2); } pthread_t pid[24]; st = NowMicros(); for (int i = 0; i < thread_num; i++) { pthread_create(&pid[i], NULL, fun, NULL); } for (int i = 0; i < thread_num; i++) { pthread_join(pid[i], NULL); } ed = NowMicros(); printf("write %d datas cost time microsecond(us) %ld, qps %llu\n", item_num * thread_num, ed - st, item_num * thread_num * 1000000LL / (ed - st)); getchar(); delete f2; delete f3; delete f4; delete f5; delete f1; return 0; }
27.04
148
0.595266
fasShare
0e702dca9016f0b45aac2e65410bd313a18e8745
34,122
hpp
C++
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/spirit/home/support/char_encoding/unicode/uppercase_table.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman 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) AUTOGENERATED. DO NOT EDIT!!! ==============================================================================*/ #include <boost/cstdint.hpp> namespace boost { namespace spirit { namespace ucd { namespace detail { static const ::boost::uint8_t uppercase_stage1[] = { 0, 1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 8, 9, 6, 10, 6, 6, 11, 6, 6, 6, 6, 6, 6, 6, 12, 13, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 14, 15, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 16, 6, 6, 6, 6, 17, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}; static const ::boost::uint32_t uppercase_stage2[] = { // block 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, 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, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 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, 924, 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, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 0, 216, 217, 218, 219, 220, 221, 222, 376, // block 1 0, 256, 0, 258, 0, 260, 0, 262, 0, 264, 0, 266, 0, 268, 0, 270, 0, 272, 0, 274, 0, 276, 0, 278, 0, 280, 0, 282, 0, 284, 0, 286, 0, 288, 0, 290, 0, 292, 0, 294, 0, 296, 0, 298, 0, 300, 0, 302, 0, 73, 0, 306, 0, 308, 0, 310, 0, 0, 313, 0, 315, 0, 317, 0, 319, 0, 321, 0, 323, 0, 325, 0, 327, 0, 0, 330, 0, 332, 0, 334, 0, 336, 0, 338, 0, 340, 0, 342, 0, 344, 0, 346, 0, 348, 0, 350, 0, 352, 0, 354, 0, 356, 0, 358, 0, 360, 0, 362, 0, 364, 0, 366, 0, 368, 0, 370, 0, 372, 0, 374, 0, 0, 377, 0, 379, 0, 381, 83, 579, 0, 0, 386, 0, 388, 0, 0, 391, 0, 0, 0, 395, 0, 0, 0, 0, 0, 401, 0, 0, 502, 0, 0, 0, 408, 573, 0, 0, 0, 544, 0, 0, 416, 0, 418, 0, 420, 0, 0, 423, 0, 0, 0, 0, 428, 0, 0, 431, 0, 0, 0, 435, 0, 437, 0, 0, 440, 0, 0, 0, 444, 0, 503, 0, 0, 0, 0, 0, 452, 452, 0, 455, 455, 0, 458, 458, 0, 461, 0, 463, 0, 465, 0, 467, 0, 469, 0, 471, 0, 473, 0, 475, 398, 0, 478, 0, 480, 0, 482, 0, 484, 0, 486, 0, 488, 0, 490, 0, 492, 0, 494, 0, 0, 497, 497, 0, 500, 0, 0, 0, 504, 0, 506, 0, 508, 0, 510, // block 2 0, 512, 0, 514, 0, 516, 0, 518, 0, 520, 0, 522, 0, 524, 0, 526, 0, 528, 0, 530, 0, 532, 0, 534, 0, 536, 0, 538, 0, 540, 0, 542, 0, 0, 0, 546, 0, 548, 0, 550, 0, 552, 0, 554, 0, 556, 0, 558, 0, 560, 0, 562, 0, 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, 0, 0, 0, 577, 0, 0, 0, 0, 582, 0, 584, 0, 586, 0, 588, 0, 590, 11375, 11373, 0, 385, 390, 0, 393, 394, 0, 399, 0, 400, 0, 0, 0, 0, 403, 0, 0, 404, 0, 0, 0, 0, 407, 406, 0, 11362, 0, 0, 0, 412, 0, 11374, 413, 0, 0, 415, 0, 0, 0, 0, 0, 0, 0, 11364, 0, 0, 422, 0, 0, 425, 0, 0, 0, 0, 430, 580, 433, 434, 581, 0, 0, 0, 0, 0, 439, 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, 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, // block 3 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, 0, 0, 0, 0, 921, 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, 880, 0, 882, 0, 0, 0, 886, 0, 0, 0, 1021, 1022, 1023, 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, 902, 904, 905, 906, 0, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 931, 931, 932, 933, 934, 935, 936, 937, 938, 939, 908, 910, 911, 0, 914, 920, 0, 0, 0, 934, 928, 975, 0, 984, 0, 986, 0, 988, 0, 990, 0, 992, 0, 994, 0, 996, 0, 998, 0, 1000, 0, 1002, 0, 1004, 0, 1006, 922, 929, 1017, 0, 0, 917, 0, 0, 1015, 0, 0, 1018, 0, 0, 0, 0, // block 4 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, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 0, 1120, 0, 1122, 0, 1124, 0, 1126, 0, 1128, 0, 1130, 0, 1132, 0, 1134, 0, 1136, 0, 1138, 0, 1140, 0, 1142, 0, 1144, 0, 1146, 0, 1148, 0, 1150, 0, 1152, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1162, 0, 1164, 0, 1166, 0, 1168, 0, 1170, 0, 1172, 0, 1174, 0, 1176, 0, 1178, 0, 1180, 0, 1182, 0, 1184, 0, 1186, 0, 1188, 0, 1190, 0, 1192, 0, 1194, 0, 1196, 0, 1198, 0, 1200, 0, 1202, 0, 1204, 0, 1206, 0, 1208, 0, 1210, 0, 1212, 0, 1214, 0, 0, 1217, 0, 1219, 0, 1221, 0, 1223, 0, 1225, 0, 1227, 0, 1229, 1216, 0, 1232, 0, 1234, 0, 1236, 0, 1238, 0, 1240, 0, 1242, 0, 1244, 0, 1246, 0, 1248, 0, 1250, 0, 1252, 0, 1254, 0, 1256, 0, 1258, 0, 1260, 0, 1262, 0, 1264, 0, 1266, 0, 1268, 0, 1270, 0, 1272, 0, 1274, 0, 1276, 0, 1278, // block 5 0, 1280, 0, 1282, 0, 1284, 0, 1286, 0, 1288, 0, 1290, 0, 1292, 0, 1294, 0, 1296, 0, 1298, 0, 1300, 0, 1302, 0, 1304, 0, 1306, 0, 1308, 0, 1310, 0, 1312, 0, 1314, 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, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 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, 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, // block 6 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, 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, 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, 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, // block 7 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, 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, 42877, 0, 0, 0, 11363, 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, 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, // block 8 0, 7680, 0, 7682, 0, 7684, 0, 7686, 0, 7688, 0, 7690, 0, 7692, 0, 7694, 0, 7696, 0, 7698, 0, 7700, 0, 7702, 0, 7704, 0, 7706, 0, 7708, 0, 7710, 0, 7712, 0, 7714, 0, 7716, 0, 7718, 0, 7720, 0, 7722, 0, 7724, 0, 7726, 0, 7728, 0, 7730, 0, 7732, 0, 7734, 0, 7736, 0, 7738, 0, 7740, 0, 7742, 0, 7744, 0, 7746, 0, 7748, 0, 7750, 0, 7752, 0, 7754, 0, 7756, 0, 7758, 0, 7760, 0, 7762, 0, 7764, 0, 7766, 0, 7768, 0, 7770, 0, 7772, 0, 7774, 0, 7776, 0, 7778, 0, 7780, 0, 7782, 0, 7784, 0, 7786, 0, 7788, 0, 7790, 0, 7792, 0, 7794, 0, 7796, 0, 7798, 0, 7800, 0, 7802, 0, 7804, 0, 7806, 0, 7808, 0, 7810, 0, 7812, 0, 7814, 0, 7816, 0, 7818, 0, 7820, 0, 7822, 0, 7824, 0, 7826, 0, 7828, 0, 0, 0, 0, 0, 7776, 0, 0, 0, 0, 0, 7840, 0, 7842, 0, 7844, 0, 7846, 0, 7848, 0, 7850, 0, 7852, 0, 7854, 0, 7856, 0, 7858, 0, 7860, 0, 7862, 0, 7864, 0, 7866, 0, 7868, 0, 7870, 0, 7872, 0, 7874, 0, 7876, 0, 7878, 0, 7880, 0, 7882, 0, 7884, 0, 7886, 0, 7888, 0, 7890, 0, 7892, 0, 7894, 0, 7896, 0, 7898, 0, 7900, 0, 7902, 0, 7904, 0, 7906, 0, 7908, 0, 7910, 0, 7912, 0, 7914, 0, 7916, 0, 7918, 0, 7920, 0, 7922, 0, 7924, 0, 7926, 0, 7928, 0, 7930, 0, 7932, 0, 7934, // block 9 7944, 7945, 7946, 7947, 7948, 7949, 7950, 7951, 0, 0, 0, 0, 0, 0, 0, 0, 7960, 7961, 7962, 7963, 7964, 7965, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7976, 7977, 7978, 7979, 7980, 7981, 7982, 7983, 0, 0, 0, 0, 0, 0, 0, 0, 7992, 7993, 7994, 7995, 7996, 7997, 7998, 7999, 0, 0, 0, 0, 0, 0, 0, 0, 8008, 8009, 8010, 8011, 8012, 8013, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8025, 0, 8027, 0, 8029, 0, 8031, 0, 0, 0, 0, 0, 0, 0, 0, 8040, 8041, 8042, 8043, 8044, 8045, 8046, 8047, 0, 0, 0, 0, 0, 0, 0, 0, 8122, 8123, 8136, 8137, 8138, 8139, 8154, 8155, 8184, 8185, 8170, 8171, 8186, 8187, 0, 0, 8072, 8073, 8074, 8075, 8076, 8077, 8078, 8079, 0, 0, 0, 0, 0, 0, 0, 0, 8088, 8089, 8090, 8091, 8092, 8093, 8094, 8095, 0, 0, 0, 0, 0, 0, 0, 0, 8104, 8105, 8106, 8107, 8108, 8109, 8110, 8111, 0, 0, 0, 0, 0, 0, 0, 0, 8120, 8121, 0, 8124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 921, 0, 0, 0, 0, 8140, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8152, 8153, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8168, 8169, 0, 0, 0, 8172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8188, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 10 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8498, 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, 8544, 8545, 8546, 8547, 8548, 8549, 8550, 8551, 8552, 8553, 8554, 8555, 8556, 8557, 8558, 8559, 0, 0, 0, 0, 8579, 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, 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, // block 11 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9398, 9399, 9400, 9401, 9402, 9403, 9404, 9405, 9406, 9407, 9408, 9409, 9410, 9411, 9412, 9413, 9414, 9415, 9416, 9417, 9418, 9419, 9420, 9421, 9422, 9423, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 12 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, 11264, 11265, 11266, 11267, 11268, 11269, 11270, 11271, 11272, 11273, 11274, 11275, 11276, 11277, 11278, 11279, 11280, 11281, 11282, 11283, 11284, 11285, 11286, 11287, 11288, 11289, 11290, 11291, 11292, 11293, 11294, 11295, 11296, 11297, 11298, 11299, 11300, 11301, 11302, 11303, 11304, 11305, 11306, 11307, 11308, 11309, 11310, 0, 0, 11360, 0, 0, 0, 570, 574, 0, 11367, 0, 11369, 0, 11371, 0, 0, 0, 0, 0, 0, 11378, 0, 0, 11381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11392, 0, 11394, 0, 11396, 0, 11398, 0, 11400, 0, 11402, 0, 11404, 0, 11406, 0, 11408, 0, 11410, 0, 11412, 0, 11414, 0, 11416, 0, 11418, 0, 11420, 0, 11422, 0, 11424, 0, 11426, 0, 11428, 0, 11430, 0, 11432, 0, 11434, 0, 11436, 0, 11438, 0, 11440, 0, 11442, 0, 11444, 0, 11446, 0, 11448, 0, 11450, 0, 11452, 0, 11454, 0, 11456, 0, 11458, 0, 11460, 0, 11462, 0, 11464, 0, 11466, 0, 11468, 0, 11470, 0, 11472, 0, 11474, 0, 11476, 0, 11478, 0, 11480, 0, 11482, 0, 11484, 0, 11486, 0, 11488, 0, 11490, 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, // block 13 4256, 4257, 4258, 4259, 4260, 4261, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277, 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285, 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293, 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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // block 14 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, 42560, 0, 42562, 0, 42564, 0, 42566, 0, 42568, 0, 42570, 0, 42572, 0, 42574, 0, 42576, 0, 42578, 0, 42580, 0, 42582, 0, 42584, 0, 42586, 0, 42588, 0, 42590, 0, 0, 0, 42594, 0, 42596, 0, 42598, 0, 42600, 0, 42602, 0, 42604, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42624, 0, 42626, 0, 42628, 0, 42630, 0, 42632, 0, 42634, 0, 42636, 0, 42638, 0, 42640, 0, 42642, 0, 42644, 0, 42646, 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, 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, // block 15 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, 42786, 0, 42788, 0, 42790, 0, 42792, 0, 42794, 0, 42796, 0, 42798, 0, 0, 0, 42802, 0, 42804, 0, 42806, 0, 42808, 0, 42810, 0, 42812, 0, 42814, 0, 42816, 0, 42818, 0, 42820, 0, 42822, 0, 42824, 0, 42826, 0, 42828, 0, 42830, 0, 42832, 0, 42834, 0, 42836, 0, 42838, 0, 42840, 0, 42842, 0, 42844, 0, 42846, 0, 42848, 0, 42850, 0, 42852, 0, 42854, 0, 42856, 0, 42858, 0, 42860, 0, 42862, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42873, 0, 42875, 0, 0, 42878, 0, 42880, 0, 42882, 0, 42884, 0, 42886, 0, 0, 0, 0, 42891, 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, 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, // block 16 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, 65313, 65314, 65315, 65316, 65317, 65318, 65319, 65320, 65321, 65322, 65323, 65324, 65325, 65326, 65327, 65328, 65329, 65330, 65331, 65332, 65333, 65334, 65335, 65336, 65337, 65338, 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, 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, 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, // block 17 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, 66560, 66561, 66562, 66563, 66564, 66565, 66566, 66567, 66568, 66569, 66570, 66571, 66572, 66573, 66574, 66575, 66576, 66577, 66578, 66579, 66580, 66581, 66582, 66583, 66584, 66585, 66586, 66587, 66588, 66589, 66590, 66591, 66592, 66593, 66594, 66595, 66596, 66597, 66598, 66599, 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, 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, 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}; inline ::boost::uint32_t uppercase_lookup(::boost::uint32_t ch) { ::boost::uint32_t block_offset = uppercase_stage1[ch / 256] * 256; return uppercase_stage2[block_offset + ch % 256]; } } // namespace detail } // namespace ucd } // namespace spirit } // namespace boost
69.636735
80
0.370523
henrywarhurst
0e70deb4357fff835a0badeff42683287d3c0720
677
cpp
C++
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
44
2016-05-11T06:41:14.000Z
2021-12-20T13:45:41.000Z
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
null
null
null
solutions/1066/union_find.cpp
buptlxb/hihoCoder
1995bdfda29d4dab98c002870ef0bc138bc37ce7
[ "Apache-2.0" ]
10
2016-06-25T08:55:20.000Z
2018-07-06T05:52:53.000Z
#include <iostream> #include <map> using namespace std; map<string, string> s; string represent(string n1) { if (s[n1].empty() || s[n1] == n1) { s[n1] = n1; } else { s[n1] = represent(s[n1]); } return s[n1]; } void merge(string n1, string n2) { s[represent(n1)] = represent(n2); } string find(string n1, string n2) { return represent(n1) == represent(n2) ? "yes" : "no"; } int main(void) { int n; cin >> n; int op; string n1, n2; for (int i = 0; i < n; ++i) { cin >> op >> n1 >> n2; if (op) cout << find(n1, n2) << endl; else merge(n1, n2); } return 0; }
15.744186
57
0.487445
buptlxb
0e740451d792f20641256e992647134aab9abfd4
767
cpp
C++
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
foo_dsp_effect/main.cpp
jpbattaille/foobar2000-plugins
2e52c26a9ab5e65091338e600a2c433d8b600704
[ "Unlicense" ]
null
null
null
#include "../SDK/foobar2000.h" #include "SoundTouch/SoundTouch.h" #include "dsp_guids.h" #define MYVERSION "0.42" static pfc::string_formatter g_get_component_about() { pfc::string_formatter about; about << "A special effect DSP for foobar2000.\n"; about << "Written by mudlord ([email protected]).\n"; about << "Portions by Jon Watte, Jezar Wakefield, Chris Snowhill.\n"; about << "Using SoundTouch library version " << SOUNDTOUCH_VERSION << "\n"; about << "SoundTouch (c) Olli Parviainen\n"; about << "\n"; about << "License: https://github.com/mudlord/foobar2000-plugins/blob/master/LICENSE.md"; return about; } DECLARE_COMPONENT_VERSION_COPY( "Effect DSP", MYVERSION, g_get_component_about() ); VALIDATE_COMPONENT_FILENAME("foo_dsp_effect.dll");
29.5
90
0.73794
jpbattaille
0e748b03089134f5aa06d6003fdd1e9c31123648
975
cpp
C++
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/350div2/D1/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } const int N = 1000 + 10; int dp[N][N]; int main(int argc, char *argv[]) { int n, k; while (scanf("%d%d", &n, &k) == 2) { int a[n]; for (int i = 0; i < n; ++i) { scanf("%d", a + i); } int b[n]; for (int i = 0; i < n; ++i) { scanf("%d", b + i); } int c = 0; while (true) { for (int i = 0; i < n; ++i) { if (a[i] > b[i]) { k -= abs(b[i] - a[i]); b[i] = a[i]; } } if (k < 0) break; ++c; for (int i = 0; i < n; ++i) { b[i] -= a[i]; } } printf("%d\n", c); } return 0; }
17.105263
49
0.434872
Johniel
0e76e7a7228402d1f5fabcccc065d0865184bfd1
11,207
cpp
C++
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
187
2021-05-22T07:56:34.000Z
2022-03-30T20:23:16.000Z
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
48
2021-05-25T01:46:49.000Z
2022-03-23T21:32:54.000Z
src/Core/Bindings/obe/Input/Input.cpp
lukefelsberg/ObEngine
a0385df4944adde7c1c8073ead15419286c70019
[ "MIT" ]
11
2021-05-24T07:01:33.000Z
2022-03-07T12:08:48.000Z
#include <Bindings/obe/Input/Input.hpp> #include <Input/InputAction.hpp> #include <Input/InputButton.hpp> #include <Input/InputButtonMonitor.hpp> #include <Input/InputButtonState.hpp> #include <Input/InputCondition.hpp> #include <Input/InputManager.hpp> #include <Input/InputType.hpp> #include <Bindings/Config.hpp> namespace obe::Input::Bindings { void LoadEnumMouseWheelScrollDirection(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::MouseWheelScrollDirection>("MouseWheelScrollDirection", { { "Up", obe::Input::MouseWheelScrollDirection::Up }, { "Down", obe::Input::MouseWheelScrollDirection::Down }, { "Left", obe::Input::MouseWheelScrollDirection::Left }, { "Right", obe::Input::MouseWheelScrollDirection::Right } }); } void LoadEnumAxisThresholdDirection(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::AxisThresholdDirection>("AxisThresholdDirection", { { "Less", obe::Input::AxisThresholdDirection::Less }, { "More", obe::Input::AxisThresholdDirection::More } }); } void LoadEnumInputButtonState(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::InputButtonState>("InputButtonState", { { "Idle", obe::Input::InputButtonState::Idle }, { "Hold", obe::Input::InputButtonState::Hold }, { "Pressed", obe::Input::InputButtonState::Pressed }, { "Released", obe::Input::InputButtonState::Released }, { "LAST__", obe::Input::InputButtonState::LAST__ } }); } void LoadEnumInputType(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.new_enum<obe::Input::InputType>("InputType", { { "Alpha", obe::Input::InputType::Alpha }, { "Numeric", obe::Input::InputType::Numeric }, { "NumericNP", obe::Input::InputType::NumericNP }, { "Arrows", obe::Input::InputType::Arrows }, { "Functions", obe::Input::InputType::Functions }, { "Mouse", obe::Input::InputType::Mouse }, { "Others", obe::Input::InputType::Others }, { "GamepadButton", obe::Input::InputType::GamepadButton }, { "GamepadAxis", obe::Input::InputType::GamepadAxis }, { "ScrollWheel", obe::Input::InputType::ScrollWheel } }); } void LoadClassInputAction(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputAction> bindInputAction = InputNamespace.new_usertype<obe::Input::InputAction>("InputAction", sol::call_constructor, sol::constructors<obe::Input::InputAction( obe::Event::EventGroup*, const std::string&)>(), sol::base_classes, sol::bases<obe::Types::Identifiable>()); bindInputAction["addCondition"] = &obe::Input::InputAction::addCondition; bindInputAction["addContext"] = &obe::Input::InputAction::addContext; bindInputAction["check"] = &obe::Input::InputAction::check; bindInputAction["clearConditions"] = &obe::Input::InputAction::clearConditions; bindInputAction["getContexts"] = &obe::Input::InputAction::getContexts; bindInputAction["getInterval"] = &obe::Input::InputAction::getInterval; bindInputAction["getRepeat"] = &obe::Input::InputAction::getRepeat; bindInputAction["setInterval"] = &obe::Input::InputAction::setInterval; bindInputAction["setRepeat"] = &obe::Input::InputAction::setRepeat; bindInputAction["update"] = &obe::Input::InputAction::update; bindInputAction["getInvolvedButtons"] = &obe::Input::InputAction::getInvolvedButtons; bindInputAction["enable"] = &obe::Input::InputAction::enable; bindInputAction["disable"] = &obe::Input::InputAction::disable; bindInputAction["isEnabled"] = &obe::Input::InputAction::isEnabled; } void LoadClassInputButton(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputButton> bindInputButton = InputNamespace.new_usertype< obe::Input::InputButton>("InputButton", sol::call_constructor, sol::constructors<obe::Input::InputButton(sf::Keyboard::Key, const std::string&, const std::string&, obe::Input::InputType), obe::Input::InputButton(sf::Mouse::Button, const std::string&), obe::Input::InputButton(unsigned int, unsigned int, const std::string&), obe::Input::InputButton(unsigned int, sf::Joystick::Axis, std::pair<obe::Input::AxisThresholdDirection, float>, const std::string&), obe::Input::InputButton(obe::Input::MouseWheelScrollDirection, const std::string&), obe::Input::InputButton(const obe::Input::InputButton&)>()); bindInputButton["reload"] = &obe::Input::InputButton::reload; bindInputButton["getAxisPosition"] = &obe::Input::InputButton::getAxisPosition; bindInputButton["getWheelDelta"] = &obe::Input::InputButton::getWheelDelta; bindInputButton["getKey"] = &obe::Input::InputButton::getKey; bindInputButton["getName"] = &obe::Input::InputButton::getName; bindInputButton["getType"] = &obe::Input::InputButton::getType; bindInputButton["is"] = &obe::Input::InputButton::is; bindInputButton["isPressed"] = &obe::Input::InputButton::isPressed; bindInputButton["isWritable"] = &obe::Input::InputButton::isWritable; } void LoadClassInputButtonMonitor(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputButtonMonitor> bindInputButtonMonitor = InputNamespace.new_usertype<obe::Input::InputButtonMonitor>("InputButtonMonitor", sol::call_constructor, sol::constructors<obe::Input::InputButtonMonitor(obe::Input::InputButton&)>()); bindInputButtonMonitor["getButton"] = &obe::Input::InputButtonMonitor::getButton; bindInputButtonMonitor["getState"] = &obe::Input::InputButtonMonitor::getState; bindInputButtonMonitor["update"] = &obe::Input::InputButtonMonitor::update; bindInputButtonMonitor["checkForRefresh"] = &obe::Input::InputButtonMonitor::checkForRefresh; } void LoadClassInputCondition(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputCondition> bindInputCondition = InputNamespace.new_usertype<obe::Input::InputCondition>("InputCondition", sol::call_constructor, sol::constructors<obe::Input::InputCondition()>()); bindInputCondition["addCombinationElement"] = &obe::Input::InputCondition::addCombinationElement; bindInputCondition["check"] = &obe::Input::InputCondition::check; bindInputCondition["clear"] = &obe::Input::InputCondition::clear; bindInputCondition["enable"] = &obe::Input::InputCondition::enable; bindInputCondition["disable"] = &obe::Input::InputCondition::disable; bindInputCondition["isEnabled"] = &obe::Input::InputCondition::isEnabled; } void LoadClassInputManager(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); sol::usertype<obe::Input::InputManager> bindInputManager = InputNamespace.new_usertype<obe::Input::InputManager>("InputManager", sol::call_constructor, sol::constructors<obe::Input::InputManager(obe::Event::EventNamespace&)>(), sol::base_classes, sol::bases<obe::Types::Togglable>()); bindInputManager["actionExists"] = &obe::Input::InputManager::actionExists; bindInputManager["addContext"] = &obe::Input::InputManager::addContext; bindInputManager["getAction"] = &obe::Input::InputManager::getAction; bindInputManager["getContexts"] = &obe::Input::InputManager::getContexts; bindInputManager["clear"] = &obe::Input::InputManager::clear; bindInputManager["clearContexts"] = &obe::Input::InputManager::clearContexts; bindInputManager["configure"] = &obe::Input::InputManager::configure; bindInputManager["removeContext"] = &obe::Input::InputManager::removeContext; bindInputManager["setContext"] = &obe::Input::InputManager::setContext; bindInputManager["update"] = &obe::Input::InputManager::update; bindInputManager["getInput"] = &obe::Input::InputManager::getInput; bindInputManager["getInputs"] = sol::overload( static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)()>( &obe::Input::InputManager::getInputs), static_cast<std::vector<obe::Input::InputButton*> (obe::Input::InputManager::*)( obe::Input::InputType)>(&obe::Input::InputManager::getInputs)); bindInputManager["getPressedInputs"] = &obe::Input::InputManager::getPressedInputs; bindInputManager["monitor"] = sol::overload( static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)( const std::string&)>(&obe::Input::InputManager::monitor), static_cast<obe::Input::InputButtonMonitorPtr (obe::Input::InputManager::*)( obe::Input::InputButton&)>(&obe::Input::InputManager::monitor)); bindInputManager["requireRefresh"] = &obe::Input::InputManager::requireRefresh; bindInputManager["initializeGamepads"] = &obe::Input::InputManager::initializeGamepads; bindInputManager["initializeGamepad"] = &obe::Input::InputManager::initializeGamepad; } void LoadFunctionInputButtonStateToString(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function( "inputButtonStateToString", &obe::Input::inputButtonStateToString); } void LoadFunctionStringToInputButtonState(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function( "stringToInputButtonState", &obe::Input::stringToInputButtonState); } void LoadFunctionInputTypeToString(sol::state_view state) { sol::table InputNamespace = state["obe"]["Input"].get<sol::table>(); InputNamespace.set_function("inputTypeToString", &obe::Input::inputTypeToString); } };
61.917127
100
0.640582
lukefelsberg
0e83d914251a5f8264a56b23eb54bbc1ee284629
407
cpp
C++
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0200/50/258a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <string> void answer(const std::string& v) { std::cout << v << '\n'; } void solve(std::string& a) { const size_t n = a.length(); size_t i = 0; while (i < n && a[i] == '1') ++i; if (i == n) a.pop_back(); else a.erase(i, 1); answer(a); } int main() { std::string a; std::cin >> a; solve(a); return 0; }
11.628571
33
0.461916
actium
0e8a8c778db01a6a05843c460625f9b2cae3a6ce
35,596
cpp
C++
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
Board.cpp
micheleasara/Chess-Cpp17
0477826a182056879457a0493844a8c9141166e0
[ "MIT" ]
null
null
null
#include "Board.hpp" #include "Zobrist.hpp" #include "Rook.hpp" #include "Bishop.hpp" #include "Queen.hpp" #include "Knight.hpp" #include "King.hpp" #include "Pawn.hpp" #include <iostream> #include <stdexcept> #include <iomanip> #include <sstream> /// Defines the number of squares the king travels to castle. int constexpr CASTLE_DISTANCE = 2; /// Defines the horizontal printing space used for a square of the board. int constexpr H_PRINT_SIZE = 15; namespace Chess { struct Board::PastMove { PastMove(Board const& board, Coordinates const& source, Coordinates const& destination, bool sourceMoved, std::unique_ptr<Piece> removedPiece = nullptr): PastMove(board, source, destination, sourceMoved, std::move(removedPiece), destination) {} PastMove(Board const& board, Coordinates const& source, Coordinates const& destination, bool sourceMoved, std::unique_ptr<Piece> capturedPiece, Coordinates const& capturedCoords): source(source), destination(destination), sourceMovedStatus(sourceMoved), removedPieceCoords(capturedCoords), removedPiece(std::move(capturedPiece)), isWhiteTurn(board.isWhiteTurn), promotionSource(board.promotionSource), boardHashCount(board.boardHashCount), countSincePawnMoveOrCapture(board.countSincePawnMoveOrCapture), threeFoldRepetition(board.threeFoldRepetition), insufficientMaterial(board.insufficientMaterial) {} Coordinates source; Coordinates destination; bool sourceMovedStatus = false; Coordinates removedPieceCoords; std::unique_ptr<Piece> removedPiece = nullptr; bool isWhiteTurn = false; std::optional<Coordinates> promotionSource; std::unordered_map<int, size_t> boardHashCount; int countSincePawnMoveOrCapture = 0; bool threeFoldRepetition = false; std::unordered_set<std::reference_wrapper<Piece>, PieceRefHasher> insufficientMaterial; }; Coordinates Board::stringToCoordinates(std::string_view coord) { if (coord.size() != 2) { throw std::invalid_argument(std::string(coord) + std::string(" is an invalid coordinate pair. Size must be 2")); } if (coord[0] < MIN_COLUMN || coord[0] > MAX_COLUMN) { throw std::out_of_range(std::string(coord) + std::string(" is an invalid coordinate pair. Column must be within ") + MIN_COLUMN + std::string(" and ") + MAX_COLUMN); } if (coord[1] < MIN_ROW || coord[1] > MAX_ROW) { throw std::out_of_range(std::string(coord) + std::string(" is an invalid coordinate pair. Row must be within ") + MIN_ROW + std::string(" and ") + MAX_ROW); } return Coordinates(static_cast<int>(coord[0] - MIN_COLUMN), static_cast<int>(coord[1] - MIN_ROW)); } std::string Board::coordinatesToString(Coordinates const& coord) { if (coord.column > MAX_COL_NUM || coord.row > MAX_ROW_NUM || coord.column < 0 || coord.row < 0) { throw std::out_of_range("Coordinates are beyond the board limits"); } return std::string(1, static_cast<char>(coord.column + MIN_COLUMN)) + std::string(1, static_cast<char>(coord.row + MIN_ROW)); } bool Board::areWithinLimits(Coordinates const& coord) { char row = static_cast<char>(coord.row) + MIN_ROW; char col = static_cast<char>(coord.column) + MIN_COLUMN; return (row >= MIN_ROW && row <= MAX_ROW && col >= MIN_COLUMN && col <= MAX_COLUMN); } bool Board::areInSameRow(Coordinates const& coord1, Coordinates const& coord2) { return (coord1.row == coord2.row); } bool Board::areInSameColumn(Coordinates const& coord1, Coordinates const& coord2) { return (coord1.column == coord2.column); } bool Board::areInSameDiagonal(Coordinates const& coord1, Coordinates const& coord2) { return (abs(coord1.column - coord2.column) == abs(coord1.row - coord2.row)); } Colour Board::currentPlayer() const { return isWhiteTurn ? Colour::White : Colour::Black; } bool Board::isGameOver() const { return m_isGameOver; } Board::Board(): Board(std::make_unique<ZobristHasher>()) {} Board::Board(std::unique_ptr<BoardHasher> hasher): hasher(std::move(hasher)) { if (this->hasher == nullptr) { throw std::invalid_argument("The board hasher cannot be null"); } initializePiecesInStandardPos(); } Board::Board(std::vector<Coordinates> const& whitePawns, std::vector<Coordinates> const& whiteRooks, std::vector<Coordinates> const& whiteKnights, std::vector<Coordinates> const& whiteBishops, std::vector<Coordinates> const& whiteQueens, Coordinates const& whiteKing, std::vector<Coordinates> const& blackPawns, std::vector<Coordinates> const& blackRooks, std::vector<Coordinates> const& blackKnights, std::vector<Coordinates> const& blackBishops, std::vector<Coordinates> const& blackQueens, Coordinates const& blackKing): hasher(std::make_unique<ZobristHasher>(whitePawns, whiteRooks, whiteKnights, whiteBishops, whiteQueens, whiteKing, blackPawns, blackRooks, blackKnights, blackBishops, blackQueens, blackKing)) { std::array<Colour, 2> colours = {Colour::White, Colour::Black}; for (auto const& colour : colours) { initializePawns(colour == Colour::White ? whitePawns : blackPawns, colour); initializeRooks(colour == Colour::White ? whiteRooks : blackRooks, colour); initializeKnights(colour == Colour::White ? whiteKnights : blackKnights, colour); initializeBishops(colour == Colour::White ? whiteBishops : blackBishops, colour); initializeQueens(colour == Colour::White ? whiteQueens : blackQueens, colour); initializeKing(colour == Colour::White ? whiteKing : blackKing, colour); } checkGameState(); } Board::Board(Board&& other) noexcept { operator=(std::move(other)); } Board& Board::operator=(Board&& other) noexcept { m_isGameOver = other.m_isGameOver; isWhiteTurn = other.isWhiteTurn; promotionSource = std::move(other.promotionSource); board = std::move(other.board); kings = std::move(other.kings); hasher = std::move(other.hasher); boardHashCount = std::move(other.boardHashCount);; threeFoldRepetition = other.threeFoldRepetition; countSincePawnMoveOrCapture = other.threeFoldRepetition; insufficientMaterial = std::move(other.insufficientMaterial); movesHistory = std::move(other.movesHistory); for (auto& column: board) { for (auto& piece: column) { if (piece != nullptr) { // assign existing pieces to the current Board object piece->setBoard(*this); } } } for (auto& pastMove : movesHistory) { if (pastMove.removedPiece) { // assign removed pieces to the current Board object pastMove.removedPiece->setBoard(*this); } } return *this; } void Board::initializePawns(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Pawn>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Pawn::WHITE_STD_INIT : Pawn::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }); auto promotionRow = (colour == Colour::White) ? MAX_ROW_NUM : 0; for (auto const& coord : coords) { if (coord.row == promotionRow) { if (promotionSource.has_value()) { throw std::invalid_argument("Only one pawn can be positioned for " "promotion in any given turn"); } promotionSource = coord; } } } void Board::initializeRooks(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Rook>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Rook::WHITE_STD_INIT : Rook::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }); } void Board::initializeKnights(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Knight>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Knight::WHITE_STD_INIT : Knight::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }, [this](auto& piece) { insufficientMaterial.emplace(piece); } ); } void Board::initializeBishops(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Bishop>(coords, colour, [&](Coordinates const& coord) { auto& coords = (colour == Colour::White ? Bishop::WHITE_STD_INIT : Bishop::BLACK_STD_INIT); return std::find(coords.begin(), coords.end(), coord) != coords.end(); }, [this](auto& piece) { insufficientMaterial.emplace(piece); } ); } void Board::initializeQueens(std::vector<Coordinates> const& coords, Colour colour) { initializePieces<Queen>(coords, colour, [&](Coordinates const& coord) { return coord == (colour == Colour::White ? Queen::WHITE_STD_INIT : Queen::BLACK_STD_INIT); }); } void Board::initializeKing(Coordinates const& coords, Colour colour) { initializePieces<King>({coords}, colour, [&](Coordinates const& coord) { return coord == (colour == Colour::White ? King::WHITE_STD_INIT : King::BLACK_STD_INIT); }, [&](King& king) { insufficientMaterial.emplace(king); kings.emplace(colour, king); }); } template <typename Chessman, typename Predicate> void Board::initializePieces(std::vector<Coordinates> const& coords, Colour colour, Predicate&& isStandardStartingPos) { initializePieces<Chessman>(coords, colour, isStandardStartingPos, [](auto const&) {}); } template <typename Chessman, typename Predicate, typename Callable> void Board::initializePieces(std::vector<Coordinates> const& coords, Colour colour, Predicate&& isStandardStartingPos, Callable&& finalActions) { for (auto const& coord : coords) { if (!areWithinLimits(coord)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(coord) != nullptr) { throw std::invalid_argument("Cannot initialize board with two or more" " pieces in the same coordinates"); } auto chessman = std::make_unique<Chessman>(colour, *this); if (!isStandardStartingPos(coord)) { chessman->setMovedStatus(true); } finalActions(*chessman); board[coord.column][coord.row] = std::move(chessman); } } bool Board::drawCanBeClaimed() const { // 50 moves rule is to be intended as 50 by each player, so 100 in total here return (threeFoldRepetition || countSincePawnMoveOrCapture >= 100) && !promotionPending(); } void Board::claimDraw() { if (drawCanBeClaimed()) { m_isGameOver = true; } } void Board::initializePiecesInStandardPos() { std::array<Colour, 2> colours = {Colour::White, Colour::Black}; for (auto const& colour : colours) { initializePawns(colour == Colour::White ? Pawn::WHITE_STD_INIT : Pawn::BLACK_STD_INIT, colour); initializeRooks(colour == Colour::White ? Rook::WHITE_STD_INIT : Rook::BLACK_STD_INIT, colour); initializeKnights(colour == Colour::White ? Knight::WHITE_STD_INIT : Knight::BLACK_STD_INIT, colour); initializeBishops(colour == Colour::White ? Bishop::WHITE_STD_INIT : Bishop::BLACK_STD_INIT, colour); initializeQueens({colour == Colour::White ? Queen::WHITE_STD_INIT : Queen::BLACK_STD_INIT}, colour); initializeKing(colour == Colour::White ? King::WHITE_STD_INIT : King::BLACK_STD_INIT, colour); } } void Board::reset() { countSincePawnMoveOrCapture = 0; hasher->reset(); promotionSource.reset(); boardHashCount.clear(); isWhiteTurn = true; m_isGameOver = false; threeFoldRepetition = false; for (auto& column : board) { for (auto& piece : column) { piece.reset(); } } kings.clear(); movesHistory.clear(); insufficientMaterial.clear(); initializePiecesInStandardPos(); } MoveResult Board::move(std::string_view src, std::string_view destination) { Coordinates sourceCoord; Coordinates targetCoord; try { sourceCoord = stringToCoordinates(src); targetCoord = stringToCoordinates(destination); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } return move(sourceCoord, targetCoord); } MoveResult Board::move(Coordinates const& src, Coordinates const& destination) { if (at(src) == nullptr) { std::string sourceStr; try { sourceStr = Board::coordinatesToString(src); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } std::stringstream ss; ss << "There is no piece at position " << sourceStr; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::NO_SOURCE_PIECE); } return board[src.column][src.row]->move(src, destination); } void Board::ensurePieceIsAtSource(Piece const& piece, Coordinates const& source) const { if (&piece != at(source)) { throw std::logic_error("Piece is not at the specified source coordinates"); } } MoveResult Board::move(Pawn& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this, &piece] (Coordinates const& source, Coordinates const& destination) { if (isValidEnPassant(piece, source, destination)) { auto toCaptureRow = (destination.row == 2) ? 3 : MAX_ROW_NUM - 3; Coordinates toCapture(destination.column, toCaptureRow); auto& srcPiecePtr = board[source.column][source.row]; movesHistory.emplace_back(*this, source, destination, srcPiecePtr->getMovedStatus(), std::move(board[toCapture.column][toCapture.row]), toCapture); srcPiecePtr->setMovedStatus(true); board[destination.column][destination.row] = std::move(srcPiecePtr); } else { recordAndMove(source, destination); } if ((piece.getColour() == Colour::White && destination.row == MAX_ROW_NUM) || (piece.getColour() == Colour::Black && destination.row == 0)) { promotionSource = destination; } countSincePawnMoveOrCapture = 0; }); } MoveResult Board::move(PromotionPiece& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this] (Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); countSincePawnMoveOrCapture++; }); } MoveResult Board::move(King& piece, Coordinates const& source, Coordinates const& destination) { ensurePieceIsAtSource(piece, source); return move(source, destination, [this] (Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); countSincePawnMoveOrCapture++; }); } template <typename Callable> MoveResult Board::move(Coordinates const& source, Coordinates const& destination, Callable&& mover) { ensureGameNotOver(); ensureNoPromotionNeeded(); auto& piece = *(board[source.column][source.row]); ensurePlayerCanMovePiece(piece); auto gameState = MoveResult::GameState::NORMAL; if (auto castlingType = tryCastling(source, destination)) { countSincePawnMoveOrCapture++; gameState = checkGameState(); togglePlayer(); return MoveResult(gameState, *castlingType); } if (!piece.isNormalMove(source, destination)) { std::string sourceStr, targetStr; try { sourceStr = coordinatesToString(source); targetStr = coordinatesToString(destination); } catch (std::exception const& e) { throw InvalidMove(e.what(), InvalidMove::ErrorCode::INVALID_COORDINATES); } std::stringstream ss; ss << piece << " cannot move from " << sourceStr << " to " << targetStr; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::PIECE_LOGIC_ERROR); } // may need to restore count if move causes self check auto tmpCount = countSincePawnMoveOrCapture; mover(source, destination); if (isInCheck(currentPlayer())) { std::stringstream ss; promotionSource.reset(); revertLastPieceMovement(); movesHistory.pop_back(); countSincePawnMoveOrCapture = tmpCount; ss << (isWhiteTurn? "White" : "Black") << "'s move is invalid as they would be in check"; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::CHECK_ERROR); } auto& lastMove = movesHistory.back(); if (lastMove.destination != lastMove.removedPieceCoords) { // en passant hasher->removed(lastMove.removedPieceCoords); } hasher->pieceMoved(source, destination); std::optional<std::string> capturedPieceName; if (lastMove.removedPiece != nullptr) { countSincePawnMoveOrCapture = 0; capturedPieceName = lastMove.removedPiece->name(); } if (promotionPending()) { gameState = MoveResult::GameState::AWAITING_PROMOTION; } else { hasher->togglePlayer(); auto hash = hasher->hash(); boardHashCount[hash]++; gameState = checkGameState(); if (boardHashCount.at(hash) >= 3) { threeFoldRepetition = true; } togglePlayer(); } if (capturedPieceName) { return MoveResult(gameState, *capturedPieceName); } return MoveResult(gameState); } void Board::ensureGameNotOver() { if (m_isGameOver) { throw InvalidMove("Game is already over, please reset", InvalidMove::ErrorCode::GAME_OVER); } } void Board::ensurePlayerCanMovePiece(Piece const& piece) { auto pieceColour = piece.getColour(); if ((pieceColour == Colour::Black && isWhiteTurn) || (pieceColour == Colour::White && !isWhiteTurn)) { std::stringstream ss; ss << "It is not " << (isWhiteTurn ? "Black" : "White"); ss << "'s turn to move"; throw InvalidMove(ss.str(), InvalidMove::ErrorCode::WRONG_TURN); } } bool Board::promotionPending() const { return promotionSource.has_value(); } void Board::ensureNoPromotionNeeded() { if (promotionPending()) { throw InvalidMove("Promote pawn before continuing", InvalidMove::ErrorCode::PENDING_PROMOTION); } } MoveResult::GameState Board::checkGameState() { Colour enemyColour; enemyColour = isWhiteTurn ? Colour::Black : Colour::White; bool inCheck = isInCheck(enemyColour); bool hasMoves = hasMovesLeft(enemyColour); if (inCheck && !hasMoves) { m_isGameOver = true; return MoveResult::GameState::OPPONENT_IN_CHECKMATE; } else if (!inCheck && !hasMoves) { m_isGameOver = true; return MoveResult::GameState::STALEMATE; } else if (countSincePawnMoveOrCapture >= 150) { // 75 by each player m_isGameOver = true; return MoveResult::GameState::SEVENTYFIVE_MOVES_DRAW; } else if (boardHashCount.count(hasher->hash()) && boardHashCount.at(hasher->hash()) >= 5) { m_isGameOver = true; return MoveResult::GameState::FIVEFOLD_REPETITION_DRAW; } else if (!sufficientMaterial()) { m_isGameOver = true; return MoveResult::GameState::INSUFFICIENT_MATERIAL_DRAW; } else if (inCheck && hasMoves) { return MoveResult::GameState::OPPONENT_IN_CHECK; } return MoveResult::GameState::NORMAL; } void Board::togglePlayer() { isWhiteTurn = !isWhiteTurn; } std::optional<CastlingType> getCastlingType(Coordinates const& source, Coordinates const& target) { if (source != King::WHITE_STD_INIT && source != King::BLACK_STD_INIT) { return std::nullopt; } // in castling, row is always the king's if (target.row != source.row) { return std::nullopt; } int colOffset = source.column - target.column; if (colOffset == -CASTLE_DISTANCE) { return CastlingType::KingSide; } else if (colOffset == CASTLE_DISTANCE) { return CastlingType::QueenSide; } return std::nullopt; } std::optional<CastlingType> Board::tryCastling(Coordinates const& source, Coordinates const& target) { auto castlingTypeOpt = getCastlingType(source, target); if (!castlingTypeOpt) { return std::nullopt; } auto castlingType = castlingTypeOpt.value(); int dir = 0; // column directionality for castling Coordinates rookTarget, rookSource; if (castlingType == CastlingType::KingSide) { rookSource = Coordinates(MAX_COL_NUM, source.row); rookTarget = Coordinates(MAX_COL_NUM - 2, source.row); dir = 1; } else { rookSource = Coordinates(0, source.row); rookTarget = Coordinates(3, source.row); dir = -1; } if (at(rookSource) == nullptr || at(source) == nullptr) { return std::nullopt; } if (!isFreeRow(source, target.column) || at(target) != nullptr) { return std::nullopt; } if (at(rookSource)->getMovedStatus() || at(source)->getMovedStatus()) { return std::nullopt; } if (isInCheck(at(source)->getColour())) { return std::nullopt; } // check if king's path is under attack for (auto coord = Coordinates(source.column + dir, source.row); coord.column != target.column; coord.column += dir) { if (isSuicide(source, coord)) { return std::nullopt; } } // simulate castling and abort if it ends up in a check recordAndMove(rookSource, rookTarget); recordAndMove(source, target); if (isInCheck(at(target)->getColour())) { revertLastPieceMovement(); movesHistory.pop_back(); revertLastPieceMovement(); movesHistory.pop_back(); return std::nullopt; } hasher->pieceMoved(rookSource, rookTarget); hasher->pieceMoved(source, target); hasher->togglePlayer(); boardHashCount[hasher->hash()]++; return castlingType; } bool Board::sufficientMaterial() const { std::vector<std::reference_wrapper<Piece>> whites; std::vector<std::reference_wrapper<Piece>> blacks; for (auto& column: board) { for (auto& piecePtr: column) { if (piecePtr == nullptr) { continue; } if (piecePtr->getColour() == Colour::White) { whites.emplace_back(*piecePtr); } else { blacks.emplace_back(*piecePtr); } } } if (whites.size() > 2 || blacks.size() > 2) { return true; } for (auto const& white : whites) { if (insufficientMaterial.count(white) == 0) { return true; } } for (auto const& black : blacks) { if (insufficientMaterial.count(black) == 0) { return true; } } return false; } bool Board::isFreeColumn(Coordinates const& source, int limitRow) const { if (source.row == limitRow) { throw std::invalid_argument("source row and limitRow cannot be equal"); } // figure out directionality int dir = (source.row > limitRow) ? -1: 1; Coordinates src = source; for (int row = src.row + dir; row != limitRow; row += dir) { src.row = row; if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } bool Board::isFreeRow(Coordinates const& source, int limitCol) const { if (source.column == limitCol) { throw std::invalid_argument("source column and limitCol cannot be equal"); } // figure out directionality int dir = (source.column > limitCol) ? -1 : 1; Coordinates src = source; for (int column = src.column+dir; column != limitCol; column += dir) { src.column = column; if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } bool Board::isDiagonalFree(Coordinates const& source, Coordinates const& destination) const { if (source == destination) { throw std::invalid_argument("source and destination cannot be equal"); } if (!areInSameDiagonal(source, destination)) { throw std::invalid_argument("source and destination are" " not in the same diagonal"); } // figure out directionality int rowAdd = (source.row > destination.row)? -1 : 1; int columnAdd = (source.column > destination.column)? -1 : 1; // this will not check the extremes, as intended Coordinates src = source; for (src = Coordinates(src.column + columnAdd, src.row + rowAdd); src != destination; src.row += rowAdd, src.column += columnAdd) { if (!areWithinLimits(src)) { throw std::invalid_argument("Coordinates go beyond the board limits"); } if (at(src)) { return false; } } return true; } Piece const* Board::at(Coordinates const& coord) const { return board.at(coord.column).at(coord.row).get(); } std::optional<Coordinates> Board::getPieceCoordinates(Piece const& piece) const { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { if (board[i][j].get() == &piece) { return Coordinates(i, j); } } } return std::nullopt; } bool Board::isInCheck(Colour kingColour) const { if (auto kingCoord = getPieceCoordinates(kings.at(kingColour))) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { auto& piece = board[i][j]; // check if an enemy piece can move where the king is if (piece != nullptr && piece->getColour() != kingColour && piece->isNormalMove(Coordinates(i,j), *kingCoord)) { return true; } } } return false; } throw std::logic_error("Attempted to find non-existent king while looking " "for a check."); } bool Board::hasMovesLeft(Colour colour) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { if (board[i][j] == nullptr || board[i][j]->getColour() != colour) { continue; } auto srcCoord = Coordinates(i, j); if (pieceHasMovesLeft(srcCoord)) { return true; } } } // tried all possible moves and check is unavoidable return false; } bool Board::pieceHasMovesLeft(Coordinates const& srcCoord) { for (size_t i = 0; i < board.size(); i++) { for (size_t j = 0; j < board[i].size(); j++) { Coordinates targetCoord(i, j); if (at(srcCoord)->isNormalMove(srcCoord, targetCoord) && !isSuicide(srcCoord, targetCoord)) { return true; } } } return false; } void Board::recordAndMove(Coordinates const& source, Coordinates const& destination) { auto& pieceDest = board[destination.column][destination.row]; auto& pieceSrc = board[source.column][source.row]; if (pieceDest != nullptr) { movesHistory.emplace_back(*this, source, destination, pieceSrc->getMovedStatus(), std::move(pieceDest)); } else { movesHistory.emplace_back(*this, source, destination, pieceSrc->getMovedStatus()); } pieceSrc->setMovedStatus(true); pieceDest = std::move(pieceSrc); } bool Board::isSuicide(Coordinates const& source, Coordinates const& destination) { recordAndMove(source, destination); bool check = isInCheck(at(destination)->getColour()); revertLastPieceMovement(); movesHistory.pop_back(); return check; } void Board::undoLastMove() { if (movesHistory.size() > 0) { auto srcMoved = movesHistory.back().sourceMovedStatus; auto castling = getCastlingType(movesHistory.back().source, movesHistory.back().destination); // castling and promotion are stored as 2 moves if ((castling.has_value() && !srcMoved) || movesHistory.back().source == movesHistory.back().destination) { revertLastPieceMovement(); movesHistory.pop_back(); hasher->restorePreviousHash(); } revertLastPieceMovement(); auto& lastMove = movesHistory.back(); m_isGameOver = false; isWhiteTurn = lastMove.isWhiteTurn; promotionSource = lastMove.promotionSource; boardHashCount = lastMove.boardHashCount; countSincePawnMoveOrCapture = lastMove.countSincePawnMoveOrCapture; threeFoldRepetition = lastMove.threeFoldRepetition; insufficientMaterial = lastMove.insufficientMaterial; movesHistory.pop_back(); hasher->restorePreviousHash(); } } void Board::revertLastPieceMovement() { auto& lastMove = movesHistory.back(); auto& source = lastMove.source; auto& dest = lastMove.destination; board[source.column][source.row] = std::move(board[dest.column][dest.row]); board[source.column][source.row] ->setMovedStatus(lastMove.sourceMovedStatus); if (lastMove.removedPiece != nullptr) { Coordinates target = dest; if (lastMove.removedPieceCoords != lastMove.destination) { // en passant target = lastMove.removedPieceCoords; } board[target.column][target.row] = std::move(lastMove.removedPiece); } } bool Board::isValidEnPassant(Pawn const& pawn, Coordinates const& source, Coordinates const& destination) const { if (&pawn != at(source) || movesHistory.empty()) { return false; } auto& lastMove = movesHistory.back(); auto lastMoveColour = lastMove.isWhiteTurn ? Colour::White : Colour::Black; if (lastMove.sourceMovedStatus || pawn.getColour() == lastMoveColour) { return false; } auto& lastMoveDest = lastMove.destination; if (source.row != lastMoveDest.row || abs(source.column - lastMoveDest.column) != 1) { return false; } auto& lastMoveSrc = lastMove.source; if (destination.column != lastMoveSrc.column) { return false; } if (lastMoveSrc.row == 1 && lastMoveDest.row == 3 && destination.row == 2) { return true; } if (lastMoveSrc.row == MAX_ROW_NUM - 1 && lastMoveDest.row == MAX_ROW_NUM - 3 && destination.row == MAX_ROW_NUM - 2) { return true; } return false; } std::optional<MoveResult> Board::promote(PromotionOption piece) { if (!promotionSource) { return std::nullopt; } auto& source = *promotionSource; auto& piecePtr = board[source.column][source.row]; auto moved = piecePtr->getMovedStatus(); movesHistory.emplace_back(*this, source, source, moved, std::move(piecePtr)); piecePtr = std::move(buildPromotionPiece(piece)); if (piece == PromotionOption::Knight || piece == PromotionOption::Bishop) { insufficientMaterial.emplace(*piecePtr); } promotionSource.reset(); auto state = checkGameState(); hasher->replacedWithPromotion(source, piece, currentPlayer()); togglePlayer(); hasher->togglePlayer(); return MoveResult(state); } std::unique_ptr<PromotionPiece> Board::buildPromotionPiece( PromotionOption piece) { switch (piece) { case PromotionOption::Queen: return std::make_unique<Queen>(currentPlayer(), *this); case PromotionOption::Knight: return std::make_unique<Knight>(currentPlayer(), *this); case PromotionOption::Bishop: return std::make_unique<Bishop>(currentPlayer(), *this); case PromotionOption::Rook: return std::make_unique<Rook>(currentPlayer(), *this); default: throw std::logic_error("Promotion not correctly implemented"); } } void printBottomLines(std::ostream& out) { out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { out << std::setw(H_PRINT_SIZE) << "|"; } out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { for (int i = 0; i < H_PRINT_SIZE - 1; i++) { out << '-'; } out << '|'; } } void printColumnLegend(std::ostream& out) { for (char ch = Board::MIN_COLUMN; ch <= Board::MAX_COLUMN; ch++) { out << std::setw((std::streamsize)H_PRINT_SIZE / 2 + 1) << ch; out << std::setw(H_PRINT_SIZE / 2) << " "; } } void printTopLine(std::ostream& out) { out << "\n|"; for (int j = 0; j <= Board::MAX_COL_NUM; j++) { out << std::setw(H_PRINT_SIZE) << '|'; } out << "\n|"; } std::ostream& operator<<(std::ostream& out, Board const& board) { for (int r = board.MAX_ROW_NUM; r >= 0; r--) { printTopLine(out); for (int c = 0; c <= board.MAX_ROW_NUM; c++) { Coordinates iterCoord(c, r); if (auto piece = board.at(iterCoord)) { out << std::right; out << std::setw((std::streamsize)H_PRINT_SIZE - 1); out << *piece << '|'; } else { out << std::setw(H_PRINT_SIZE) << "|"; } if (c == board.MAX_ROW_NUM) { out << " " << r+1; } } printBottomLines(out); } out << "\n"; printColumnLegend(out); return out << "\n\n"; } Board::~Board() = default; }
34.226923
86
0.607428
micheleasara
0e90229439f494fc42492a2ccb9a05b7dc714448
3,048
hpp
C++
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
include/nonstd/memory_pool.hpp
ortfero/mandalang
b6097dbbb2a16d474ea1a3064f2f66c9195601fc
[ "MIT" ]
null
null
null
#pragma once #include <forward_list> #include <memory> namespace nonstd { template<typename T> class memory_pool { public: using size_type = std::size_t; static constexpr auto default_page_size = 512u; private: union block { alignas(T) char space[sizeof(T)]; block* next; }; block* head_{nullptr}; size_type page_size_{default_page_size}; std::forward_list<std::unique_ptr<block[]>> pages_; public: memory_pool(size_type page_size = default_page_size) noexcept: page_size_{page_size} { } memory_pool(memory_pool const&) = delete; memory_pool& operator = (memory_pool const&) = delete; memory_pool(memory_pool&& other) noexcept: head_{other.head_}, page_size_{other.page_size_}, pages_{std::move(other.pages_)} { other.head_ = nullptr; } memory_pool& operator = (memory_pool&& other) noexcept { head_ = other.head_; other.head_ = nullptr; page_size_ = other.page_size_; pages_ = std::move(other.pages_); return *this; } ~memory_pool() { auto* each_block = head_; // construct all free blocks in current page while(each_block != nullptr) { auto* next_block = each_block->next; new(each_block->space) T; each_block = next_block; } // destruct all pages for(auto& each_page: pages_) { auto* begin = each_page.get(); auto* end = each_page.get() + page_size_; for(auto* each_block = begin; each_block != end; ++each_block) reinterpret_cast<T*>(each_block->space)->~T(); } } template<typename... Types> T* create(Types&&... arguments) { return new(allocate()) T(std::forward<Types>(arguments)...); } void destroy(T* object) noexcept { object->~T(); free(reinterpret_cast<block*>(object)); } private: char* allocate() { if(!head_) add_page(); char* block = head_->space; head_ = head_->next; return block; } void free(block* block) noexcept { block->next = head_; head_ = block; } void add_page() { auto new_page = std::make_unique<block[]>(page_size_); auto* begin = new_page.get(); auto* end = new_page.get() + page_size_ - 1; for(auto* each_block = begin; each_block != end; ++each_block) { each_block->next = (each_block + 1); } end->next = nullptr; head_ = begin; pages_.emplace_front(std::move(new_page)); } }; // memory_pool } // namespace nonstd
29.307692
97
0.510499
ortfero
0e91f4d7c8d303add464be9d61b35efbd8310885
214
hpp
C++
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
3
2021-08-31T17:51:01.000Z
2021-11-13T16:22:25.000Z
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
null
null
null
nacl/math/combinatorics/multinomial.hpp
ToxicPie/NaCl
8cb50bacc25f2b99a33fb5938ea4ec9906d8d65c
[ "MIT" ]
null
null
null
/// source: KACTL // ways to permute v[i] ll multinomial(vi &v) { ll c = 1, m = v.empty() ? 1 : v[0]; for (int i = 1; i < v.size(); i++) for (int j = 0; i < v[i]; j++) c = c * ++m / (j + 1); return c; }
21.4
57
0.443925
ToxicPie
0e952527ddedcfd90a971a26e758d4102609edfa
3,064
cpp
C++
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
5
2021-06-16T06:24:29.000Z
2022-03-10T03:41:44.000Z
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
1
2020-10-14T14:20:58.000Z
2020-10-14T14:20:58.000Z
gEarth.Pack/oepOGRFeatureSourceOptions.cpp
songgod/gEarth
e4ea0fa15a40f08481c7ea7e42e6f4ace8659984
[ "MIT" ]
2
2021-06-16T06:24:32.000Z
2021-08-02T09:05:42.000Z
#include "stdafx.h" #include "oepOGRFeatureSourceOptions.h" using namespace gEarthPack; using namespace osgEarth::Drivers; oepOGRFeatureSourceOptions::oepOGRFeatureSourceOptions() { bind(new OGRFeatureOptions(),true); } void gEarthPack::oepOGRFeatureSourceOptions::binded() { _geometryConfig = gcnew oepConfig(); _geometryConfig->bind(as<OGRFeatureOptions>()->geometryConfig()); _query = gcnew oepQuery(); _query->bind(as<OGRFeatureOptions>()->query()); } void gEarthPack::oepOGRFeatureSourceOptions::unbinded() { _geometryConfig->unbind(); _query->unbind(); } String^ oepOGRFeatureSourceOptions::Url::get() { return Str2Cli(as<OGRFeatureOptions>()->url()->full()); } void oepOGRFeatureSourceOptions::Url::set(String^ p) { as<OGRFeatureOptions>()->url() = Str2Std(p); NotifyChanged("Url"); } String^ oepOGRFeatureSourceOptions::Connection::get() { return Str2Cli(as<OGRFeatureOptions>()->connection().value()); } void oepOGRFeatureSourceOptions::Connection::set(String^ p) { as<OGRFeatureOptions>()->connection() = Str2Std(p); } String^ oepOGRFeatureSourceOptions::OgrDriver::get() { return Str2Cli(as<OGRFeatureOptions>()->ogrDriver().value()); } void oepOGRFeatureSourceOptions::OgrDriver::set(String^ p) { as<OGRFeatureOptions>()->ogrDriver() = Str2Std(p); NotifyChanged("OgrDriver"); } bool oepOGRFeatureSourceOptions::BuildSpatialIndex::get() { return as<OGRFeatureOptions>()->buildSpatialIndex().value(); } void oepOGRFeatureSourceOptions::BuildSpatialIndex::set(bool p) { as<OGRFeatureOptions>()->buildSpatialIndex() = p; NotifyChanged("BuildSpatialIndex"); } bool oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::get() { return as<OGRFeatureOptions>()->forceRebuildSpatialIndex().value(); } void oepOGRFeatureSourceOptions::ForceRebuildSpatialIndex::set(bool p) { as<OGRFeatureOptions>()->forceRebuildSpatialIndex() = p; NotifyChanged("ForceRebuildSpatialIndex"); } oepConfig^ oepOGRFeatureSourceOptions::GeometryConfig::get() { return _geometryConfig; } void oepOGRFeatureSourceOptions::GeometryConfig::set(oepConfig^ p) { OGRFeatureOptions* to = as<OGRFeatureOptions>(); if (to != NULL && p != nullptr) { to->geometryConfig() = *(p->as<Config>()); NotifyChanged("GeometryConfig"); } } String^ oepOGRFeatureSourceOptions::GeometryUrl::get() { return Str2Cli(as<OGRFeatureOptions>()->geometryUrl().value()); } void oepOGRFeatureSourceOptions::GeometryUrl::set(String^ p) { as<OGRFeatureOptions>()->geometryUrl() = Str2Std(p); NotifyChanged("GeometryUrl"); } String^ oepOGRFeatureSourceOptions::Layer::get() { return Str2Cli(as<OGRFeatureOptions>()->layer().value()); } void oepOGRFeatureSourceOptions::Layer::set(String^ p) { as<OGRFeatureOptions>()->layer() = Str2Std(p); NotifyChanged("Layer"); } oepQuery^ oepOGRFeatureSourceOptions::Query::get() { return _query; } void oepOGRFeatureSourceOptions::Query::set(oepQuery^ p) { OGRFeatureOptions* to = as<OGRFeatureOptions>(); if (to != NULL && p != nullptr) { to->query() = *(p->as<osgEarth::Query>()); NotifyChanged("Query"); } }
23.037594
70
0.741841
songgod
0e95c6b5977ed0492064f44464d749de3eb1fc06
8,949
cpp
C++
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
ODIN_II/SRC/lib_blocks/hard_blocks.cpp
rding2454/IndeStudy
c27be794bc2ce5ada93b16c92569a4bcafc8a21c
[ "MIT" ]
null
null
null
/* 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 <stdlib.h> #include <stdio.h> #include <string.h> #include "types.h" #include "globals.h" #include "hard_blocks.h" #include "memories.h" STRING_CACHE *hard_block_names = NULL; void cache_hard_block_names(); t_model_ports *get_model_port(t_model_ports *ports, const char *name) { while (ports && strcmp(ports->name, name)) ports = ports->next; return ports; } void cache_hard_block_names() { t_model *hard_blocks = NULL; hard_blocks = Arch.models; hard_block_names = sc_new_string_cache(); while (hard_blocks) { sc_add_string(hard_block_names, hard_blocks->name); hard_blocks = hard_blocks->next; } } void register_hard_blocks() { cache_hard_block_names(); single_port_rams = find_hard_block("single_port_ram"); dual_port_rams = find_hard_block("dual_port_ram"); if (single_port_rams) { t_model_ports *hb_ports; if (configuration.split_memory_width) { hb_ports = get_model_port(single_port_rams->inputs, "data"); hb_ports->size = 1; hb_ports = get_model_port(single_port_rams->outputs, "out"); hb_ports->size = 1; } int split_depth = get_sp_ram_split_depth(); hb_ports = get_model_port(single_port_rams->inputs, "addr"); hb_ports->size = split_depth; } if (dual_port_rams) { t_model_ports *hb_ports; if (configuration.split_memory_width) { hb_ports = get_model_port(dual_port_rams->inputs, "data1"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->inputs, "data2"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->outputs, "out1"); hb_ports->size = 1; hb_ports = get_model_port(dual_port_rams->outputs, "out2"); hb_ports->size = 1; } int split_depth = get_dp_ram_split_depth(); hb_ports = get_model_port(dual_port_rams->inputs, "addr1"); hb_ports->size = split_depth; hb_ports = get_model_port(dual_port_rams->inputs, "addr2"); hb_ports->size = split_depth; } } void deregister_hard_blocks() { sc_free_string_cache(hard_block_names); return; } t_model* find_hard_block(const char *name) { t_model *hard_blocks; hard_blocks = Arch.models; while (hard_blocks) if (!strcmp(hard_blocks->name, name)) return hard_blocks; else hard_blocks = hard_blocks->next; return NULL; } void define_hard_block(nnode_t *node, short /*type*/, FILE *out) { int i, j; int index, port; int count; char buffer[MAX_BUF]; /* Assert that every hard block has at least an input and output */ oassert(node->input_port_sizes[0] > 0); oassert(node->output_port_sizes[0] > 0); //IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in define_add_function and define_mult_function) if(strcmp(node->related_ast_node->children[0]->types.identifier, "multiply") == 0 || strcmp(node->related_ast_node->children[0]->types.identifier, "adder") == 0) return; count = fprintf(out, "\n.subckt "); count--; count += fprintf(out, "%s", node->related_ast_node->children[0]->types.identifier); /* print the input port mappings */ port = index = 0; for (i = 0; i < node->num_input_pins; i++) { /* Check that the input pin is driven */ if (node->input_pins[i]->net->driver_pin == NULL) { printf("Signal %s is not driven. Odin will terminate.\n", node->input_pins[i]->name); exit(1); } if (node->input_port_sizes[port] == 1) j = sprintf(buffer, " %s=%s", node->input_pins[i]->mapping, node->input_pins[i]->net->driver_pin->node->name); else { if (node->input_pins[i]->net->driver_pin->name != NULL) j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->name); else j = sprintf(buffer, " %s[%d]=%s", node->input_pins[i]->mapping, index, node->input_pins[i]->net->driver_pin->node->name); } if (count + j > 79) { fprintf(out, "\\\n"); count = 0; } count += fprintf(out, "%s", buffer); index++; if (node->input_port_sizes[port] == index) { index = 0; port++; } } /* print the output port mappings */ port = index = 0; for (i = 0; i < node->num_output_pins; i++) { if (node->output_port_sizes[port] != 1) j = sprintf(buffer, " %s[%d]=%s", node->output_pins[i]->mapping, index, node->output_pins[i]->name); else j = sprintf(buffer, " %s=%s", node->output_pins[i]->mapping, node->output_pins[i]->name); if (count + j > 79) { fprintf(out, "\\\n"); count = 0; } count += fprintf(out, "%s", buffer); index++; if (node->output_port_sizes[port] == index) { index = 0; port++; } } count += fprintf(out, "\n\n"); return; } void output_hard_blocks(FILE *out) { t_model_ports *hb_ports; t_model *hard_blocks; char buffer[MAX_BUF]; int count; int i; oassert(out != NULL); hard_blocks = Arch.models; while (hard_blocks != NULL) { if (hard_blocks->used == 1) /* Hard Block is utilized */ { //IF the hard_blocks is an adder or a multiplier, we ignore it.(Already print out in add_the_blackbox_for_adds and add_the_blackbox_for_mults) if(strcmp(hard_blocks->name, "adder") == 0 ||strcmp(hard_blocks->name, "multiply") == 0) { hard_blocks = hard_blocks->next; break; } fprintf(out, "\n.model %s\n", hard_blocks->name); count = fprintf(out, ".inputs"); hb_ports = hard_blocks->inputs; while (hb_ports != NULL) { for (i = 0; i < hb_ports->size; i++) { if (hb_ports->size == 1) count = count + sprintf(buffer, " %s", hb_ports->name); else count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i); if (count >= 78) count = fprintf(out, " \\\n%s", buffer) - 3; else fprintf(out, "%s", buffer); } hb_ports = hb_ports->next; } count = fprintf(out, "\n.outputs") - 1; hb_ports = hard_blocks->outputs; while (hb_ports != NULL) { for (i = 0; i < hb_ports->size; i++) { if (hb_ports->size == 1) count = count + sprintf(buffer, " %s", hb_ports->name); else count = count + sprintf(buffer, " %s[%d]", hb_ports->name, i); if (count >= 78) count = fprintf(out, " \\\n%s", buffer) - 3; else fprintf(out, "%s", buffer); } hb_ports = hb_ports->next; } fprintf(out, "\n.blackbox\n.end\n\n"); } hard_blocks = hard_blocks->next; } return; } void instantiate_hard_block(nnode_t *node, short mark, netlist_t * /*netlist*/) { int i, port, index; port = index = 0; /* Give names to the output pins */ for (i = 0; i < node->num_output_pins; i++) { if (node->output_pins[i]->name == NULL) node->output_pins[i]->name = make_full_ref_name(node->name, NULL, NULL, node->output_pins[i]->mapping, -1); index++; if (node->output_port_sizes[port] == index) { index = 0; port++; } } node->traverse_visited = mark; return; } int hard_block_port_size(t_model *hb, char *pname) { t_model_ports *tmp; if (hb == NULL) return 0; /* Indicates that the port size is different for this hard block * depending on the instance of the hard block. May want to extend * this list of blocks in the future. */ if ((strcmp(hb->name, "single_port_ram") == 0) || (strcmp(hb->name, "dual_port_ram") == 0)) { return -1; } tmp = hb->inputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->size; else tmp = tmp->next; tmp = hb->outputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->size; else tmp = tmp->next; return 0; } enum PORTS hard_block_port_direction(t_model *hb, char *pname) { t_model_ports *tmp; if (hb == NULL) return ERR_PORT; tmp = hb->inputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->dir; else tmp = tmp->next; tmp = hb->outputs; while (tmp != NULL) if ((tmp->name != NULL) && (strcmp(tmp->name, pname) == 0)) return tmp->dir; else tmp = tmp->next; return ERR_PORT; }
24.45082
162
0.659403
rding2454
0e9c8fe4bc86416da5460816edad2fc7822048c5
4,887
cxx
C++
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/src/BarGroup.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// // "$Id: BarGroup.cxx 5895 2007-06-08 18:17:53Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "[email protected]". // // Based on Frametab V2 contributed by Curtis Edwards ([email protected]) #include <fltk/BarGroup.h> #include <fltk/Box.h> #include <fltk/events.h> #include <fltk/damage.h> #include <fltk/draw.h> using namespace fltk; static void revert(Style *s) { s->box_ = THIN_UP_BOX; //s->box_ = FLAT_BOX; s->color_ = GRAY75; s->labelsize_ = 10; } static NamedStyle style("BarGroup", revert, &BarGroup::default_style); NamedStyle* BarGroup::default_style = &::style; BarGroup::BarGroup(int x, int y, int w, int h, const char* title, bool begin) : Group(x, y, w, h, title, begin) { resizable(0); style(default_style); open_ = true; highlighted = false; pushed = false; glyph_size_ = 10; saved_size = h; align(ALIGN_INSIDE); } void BarGroup::glyph_box(Rectangle& r) const { int z = open_ ? glyph_size_ : saved_size; int w = this->w(); int h = this->h(); if (horizontal()) w = z; else h = z; r.set(0,0,w,h); //box()->inset(r); } int BarGroup::handle(int event) { Rectangle r; switch (event) { case ENTER: case MOVE: if (takesevents()) { glyph_box(r); bool hl = event_inside(r); if (hl != highlighted) { highlighted = hl; if (highlight_color()) redraw(DAMAGE_HIGHLIGHT); } if (hl) {fltk::belowmouse(this); return 1;} } break; case LEAVE: if (highlighted) { highlighted = false; redraw(DAMAGE_HIGHLIGHT); } break; case PUSH: glyph_box(r); if (event_inside(r)) { pushed = highlighted = true; redraw(DAMAGE_HIGHLIGHT); return true; } break; case DRAG: glyph_box(r); if (event_inside(r)) { if (!pushed) { pushed = highlighted = true; redraw(DAMAGE_HIGHLIGHT); } } else { if (pushed) { pushed = false; redraw(DAMAGE_HIGHLIGHT); } } return true; case RELEASE: if (pushed) { opened(!open_); pushed = false; highlighted = event_inside(fltk::Rectangle(glyph_size_, glyph_size_)); redraw(DAMAGE_HIGHLIGHT); do_callback(); } else if (highlighted) { highlighted = false; redraw(DAMAGE_HIGHLIGHT); } return true; case SHORTCUT: return Group::handle(event); } if (open_) return Group::handle(event); else return 0; } void BarGroup::draw() { if (open_) { if (damage() & ~DAMAGE_HIGHLIGHT) { // make it not draw the inside label: //int saved = flags(); align(ALIGN_TOP); Group::draw(); //flags(saved); } } else if (damage() & ~(DAMAGE_CHILD|DAMAGE_HIGHLIGHT)) { clear_flag(HIGHLIGHT); draw_box(); // draw the label inside it: Rectangle r(w(),h()); Flags flags = this->flags(); drawstyle(style(), flags|OUTPUT); box()->inset(r); if (horizontal()) { r.x(saved_size); r.w(r.w()-saved_size); flags &= ~(ALIGN_TOP|ALIGN_BOTTOM); flags |= ALIGN_LEFT|ALIGN_INSIDE; } else { r.y(saved_size); r.h(r.h()-saved_size); } draw_label(r, flags); } // draw the open/close button: if (damage() & (DAMAGE_EXPOSE|DAMAGE_HIGHLIGHT|DAMAGE_ALL)) { Flags flags = OUTPUT; if (pushed) flags |= PUSHED; if (highlighted) flags |= HIGHLIGHT; drawstyle(style(), flags); Rectangle r; glyph_box(r); draw_glyph(ALIGN_INSIDE|(horizontal()?ALIGN_RIGHT:ALIGN_BOTTOM), r); } } bool BarGroup::opened(bool v) { if (open_) { if (v) return false; open_ = false; if (horizontal()) { // horizontal saved_size = h(); Widget::resize(w(), glyph_size_); } else { saved_size = w(); Widget::resize(glyph_size_, h()); } } else { if (!v) return false; open_ = true; if (horizontal()) // horizontal Widget::resize(w(), saved_size); else Widget::resize(saved_size, h()); } relayout(); redraw(); return true; } // Don't move widgets around while we are closed! void BarGroup::layout() { if (open_) Group::layout(); else Widget::layout(); }
25.321244
77
0.631062
MarioHenze
0e9d4c3a1b86afe141b80004ce034c337eddf851
1,764
cpp
C++
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
5
2020-09-17T08:15:14.000Z
2021-06-17T08:35:51.000Z
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
null
null
null
UnitTests/Test_Registry_SetBinaryValue.cpp
ossewawiel/LibWinRegUtil
602e391b521685deec809e0ae3ae97376025ffe4
[ "MIT" ]
4
2019-12-29T00:58:23.000Z
2022-01-27T12:58:36.000Z
#include "stdafx.h" #include "Test_Registry.h" #include "TUtils.h" #include "TConstants.h" using namespace std; using namespace WinReg; using namespace TConst; TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_valid_parameters_values_expect_no_exception) { try { Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1); vector<BYTE> vucRegVal{ Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME) }; for (const auto &val : vucRegVal) //{ // wcout << L"[ VALUE ] " << val << endl; //} ASSERT_EQ(vucRegVal, VUC_TESTVAL_1) << "[ FAILED ] vucRegVal is not equal to VUC_TESTVAL_1"; Registry::SetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_2); vucRegVal = Registry::GetBinaryValue(eHKey::eHKeyUsers, WS_TEST_SUBKEY, WS_BINARY_VALUENAME); //for (const auto &val : vucRegVal) //{ // wcout << L"[ VALUE ] " << val << endl; //} ASSERT_EQ(vucRegVal, VUC_TESTVAL_2) << "[ FAILED ] vwsRegVal is not equal to VUC_TESTVAL_1"; } catch (exception &ex) { ASSERT_TRUE(false) << "[EXCEPTION ] " << TUtils::ErrMsg(ex); } catch (...) { ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception"; } } TEST_F(Test_Registry_SetSBinaryValue, when_calling_setbinaryvalue_with_invalid_hkey_expect_exception) { try { Registry::SetBinaryValue(eHKey::eHkeyNotDefined, WS_TEST_SUBKEY, WS_BINARY_VALUENAME, VUC_TESTVAL_1); ASSERT_FALSE(true) << "[ FAILED ] Expected an exception"; } catch (exception &ex) { ASSERT_TRUE(TUtils::InString(TUtils::ErrMsg(ex), WS_INVALID_PARAM_VALUE)) << "[EXCEPTION ] " << TUtils::ErrMsg(ex); } catch (...) { ASSERT_TRUE(false) << "[EXCEPTION ] Unknown exception"; } }
32.072727
117
0.722222
ossewawiel
0e9f0bbc6f5fd102b02a814a405756e7927f998c
367
cpp
C++
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
Practice/C++/pattern program.cpp
Sohelr360/my_codes
9bdd28f62d3850aad8f8af2a253ba66138a7057c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int i,j; for (i = 7; i >=1; i--) { for (j = 1; j <= i; j++) { cout<<'S'; } cout<<endl; } for(i = 2; i <= 7; i++) { for (j = 1;j <= i; j++) { cout<<'S'; } cout<<endl; } }
15.956522
33
0.280654
Sohelr360
0e9f7a1add03fde6e828841efdea7f695012598d
93,533
cpp
C++
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
8
2018-11-27T15:43:22.000Z
2020-04-27T08:53:49.000Z
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
null
null
null
src/omnicore/mdex.cpp
TradeLayer/TradeLayer
2f1ea1d64870a34703d2f5d230830238c3923691
[ "MIT" ]
null
null
null
#include "omnicore/mdex.h" #include "omnicore/errors.h" #include "omnicore/log.h" #include "omnicore/omnicore.h" #include "omnicore/rules.h" #include "omnicore/sp.h" #include "omnicore/tx.h" #include "omnicore/uint256_extensions.h" #include "arith_uint256.h" #include "chain.h" #include "tinyformat.h" #include "uint256.h" #include "omnicore/tradelayer_matrices.h" #include "omnicore/externfns.h" #include "omnicore/operators_algo_clearing.h" #include "validation.h" #include <univalue.h> #include <boost/lexical_cast.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/rational.hpp> #include <openssl/sha.h> #include <assert.h> #include <stdint.h> #include <iostream> #include <fstream> #include <limits> #include <map> #include <set> #include <string> typedef boost::multiprecision::cpp_dec_float_100 dec_float; typedef boost::multiprecision::checked_int128_t int128_t; using namespace mastercore; //! Number of digits of unit price #define DISPLAY_PRECISION_LEN 50 //! Global map for price and order data md_PropertiesMap mastercore::metadex; extern volatile uint64_t marketPrice; extern volatile int idx_q; extern int64_t factorE; extern uint64_t marketP[NPTYPES]; extern int expirationAchieve; extern std::vector<std::map<std::string, std::string>> path_ele; extern int n_cols; extern int n_rows; extern MatrixTLS *pt_ndatabase; md_PricesMap* mastercore::get_Prices(uint32_t prop) { md_PropertiesMap::iterator it = metadex.find(prop); if (it != metadex.end()) return &(it->second); return (md_PricesMap*) NULL; } md_Set* mastercore::get_Indexes(md_PricesMap* p, rational_t price) { md_PricesMap::iterator it = p->find(price); if (it != p->end()) return &(it->second); return (md_Set*) NULL; } /********************************************************/ /** New things for Contracts */ cd_PropertiesMap mastercore::contractdex; cd_PricesMap *mastercore::get_PricesCd(uint32_t prop) { cd_PropertiesMap::iterator it = contractdex.find(prop); if (it != contractdex.end()) return &(it->second); return (cd_PricesMap*) NULL; } cd_Set *mastercore::get_IndexesCd(cd_PricesMap *p, uint64_t price) { cd_PricesMap::iterator it = p->find(price); if (it != p->end()) return &(it->second); return (cd_Set*) NULL; } void mastercore::LoopBiDirectional(cd_PricesMap* const ppriceMap, uint8_t trdAction, MatchReturnType &NewReturn, CMPContractDex* const pnew, const uint32_t propertyForSale) { cd_PricesMap::iterator it_fwdPrices; cd_PricesMap::reverse_iterator it_bwdPrices; std::vector<std::map<std::string, std::string>>::iterator it_path_ele; /** Calling for settlement algorithm when the expiration date has been achieved */ if ( expirationAchieve ) { PrintToLog("expirationAchieve: %d\n", expirationAchieve); // PrintToConsole("Path for Settlement:\n"); // for (it_path_ele = path_ele.begin(); it_path_ele != path_ele.end(); ++it_path_ele) printing_edges_database(*it_path_ele); // cout << "\n"; pt_ndatabase = new MatrixTLS(path_ele.size(), n_cols); MatrixTLS &ndatabase = *pt_ndatabase; MatrixTLS M_file(path_ele.size(), n_cols); fillingMatrix(M_file, ndatabase, path_ele); n_rows = size(M_file, 0); PrintToLog("Matrix for Settlement: dim = (%d, %d)\n\n", n_rows, n_cols); printing_matrix(M_file); cout << "\n\n"; PrintToLog("\nCalling the Settlement Algorithm:\n\n"); settlement_algorithm_fifo(M_file); } if ( trdAction == BUY ) { for (it_fwdPrices = ppriceMap->begin(); it_fwdPrices != ppriceMap->end(); ++it_fwdPrices) { const uint64_t sellerPrice = it_fwdPrices->first; if ( pnew->getEffectivePrice() < sellerPrice ) continue; x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn); } } else { for (it_bwdPrices = ppriceMap->rbegin(); it_bwdPrices != ppriceMap->rend(); ++it_bwdPrices) { const uint64_t sellerPrice = it_bwdPrices->first; if ( pnew->getEffectivePrice() > sellerPrice ) continue; x_TradeBidirectional(it_fwdPrices, it_bwdPrices, trdAction, pnew, sellerPrice, propertyForSale, NewReturn); } } } void mastercore::x_TradeBidirectional(typename cd_PricesMap::iterator &it_fwdPrices, typename cd_PricesMap::reverse_iterator &it_bwdPrices, uint8_t trdAction, CMPContractDex* const pnew, const uint64_t sellerPrice, const uint32_t propertyForSale, MatchReturnType &NewReturn) { cd_Set* const pofferSet = trdAction == BUY ? &(it_fwdPrices->second) : &(it_bwdPrices->second); /** At good (single) price level and property iterate over offers looking at all parameters to find the match */ cd_Set::iterator offerIt = pofferSet->begin(); while ( offerIt != pofferSet->end() ) /** Specific price, check all properties */ { const CMPContractDex* const pold = &(*offerIt); assert(pold->getEffectivePrice() == sellerPrice); std::string tradeStatus = pold->getEffectivePrice() == sellerPrice ? "Matched" : "NoMatched"; /** Match Conditions */ bool boolProperty = pold->getProperty() != propertyForSale; bool boolTrdAction = pold->getTradingAction() == pnew->getTradingAction(); bool boolEffPrice = pnew->getEffectivePrice() != pold->getEffectivePrice(); bool boolAddresses = pold->getAddr() == pnew->getAddr(); if ( findTrueValue(boolProperty, boolTrdAction, boolEffPrice, boolAddresses) ) { ++offerIt; continue; } idx_q += 1; const int idx_qp = idx_q; PrintToLog("Checking idx_q = %d", idx_qp); CMPSPInfo::Entry sp; assert(_my_sps->getSP(propertyForSale, sp)); uint32_t marginRequirementContract = sp.margin_requirement; int64_t marginRequirement = static_cast<int64_t>(marginRequirementContract); uint32_t collateralCurrency = sp.collateral_currency; uint32_t notionalSize = sp.notional_size; PrintToLog("\n---------------------------------------------------\n"); PrintToLog("Inside x_trade function:\n"); PrintToLog("marginRequirement : %d\n", marginRequirement); PrintToLog("marginRequirementContract : %d\n", marginRequirementContract); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("notional size : %d\n",notionalSize); /********************************************************/ /** Preconditions */ assert(pold->getProperty() == pnew->getProperty()); PrintToLog("________________________________________________________\n"); PrintToLog("Inside x_trade:\n"); PrintToLog("Checking effective prices and trading actions:\n"); PrintToLog("Effective price pold: %d\n", FormatContractShortMP(pold->getEffectivePrice()) ); PrintToLog("Effective price pnew: %d\n", FormatContractShortMP(pnew->getEffectivePrice()) ); PrintToLog("Amount for sale pold: %d\n", pold->getAmountForSale() ); PrintToLog("Amount for sale pnew: %d\n", pnew->getAmountForSale() ); PrintToLog("Trading action pold: %d\n", pold->getTradingAction() ); PrintToLog("Trading action pnew: %d\n", pnew->getTradingAction() ); PrintToLog("Trade Status: %s\n", tradeStatus); /********************************************************/ uint32_t property_traded = pold->getProperty(); int64_t poldPositiveBalanceB = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t pnewPositiveBalanceB = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t poldNegativeBalanceB = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE); int64_t pnewNegativeBalanceB = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE); PrintToLog("poldPositiveBalanceB: %d, poldNegativeBalanceB: %d\n", poldPositiveBalanceB, poldNegativeBalanceB); PrintToLog("pnewPositiveBalanceB: %d, pnewNegativeBalanceB: %d\n", pnewPositiveBalanceB, pnewNegativeBalanceB); int64_t possitive_sell = (pold->getTradingAction() == SELL) ? poldPositiveBalanceB : pnewPositiveBalanceB; int64_t negative_sell = (pold->getTradingAction() == SELL) ? poldNegativeBalanceB : pnewNegativeBalanceB; int64_t possitive_buy = (pold->getTradingAction() == SELL) ? pnewPositiveBalanceB : poldPositiveBalanceB; int64_t negative_buy = (pold->getTradingAction() == SELL) ? pnewNegativeBalanceB : poldNegativeBalanceB; int64_t seller_amount = (pold->getTradingAction() == SELL) ? pold->getAmountForSale() : pnew->getAmountForSale(); int64_t buyer_amount = (pold->getTradingAction() == SELL) ? pnew->getAmountForSale() : pold->getAmountForSale(); std::string seller_address = (pold->getTradingAction() == SELL) ? pold->getAddr() : pnew->getAddr(); std::string buyer_address = (pold->getTradingAction() == SELL) ? pnew->getAddr() : pold->getAddr(); /********************************************************/ int64_t nCouldBuy = buyer_amount < seller_amount ? buyer_amount : seller_amount; PrintToLog("This is the nCouldBuy %d\n", nCouldBuy); PrintToLog("possitive_sell: %d, negative_sell: %d\n", possitive_sell, negative_sell); PrintToLog("possitive_buy: %d, negative_buy: %d\n", possitive_buy, negative_buy); if (nCouldBuy == 0) { // if (msc_debug_metadex1) PrintToLog("The buyer has not enough contracts for sale!\n"); ++offerIt; continue; } /********************************************************/ int64_t difference_s = 0, difference_b = 0; if ( possitive_sell != 0 ) { difference_s = possitive_sell - nCouldBuy; if (difference_s >= 0) assert(update_tally_map(seller_address, property_traded, -nCouldBuy, POSSITIVE_BALANCE)); else { assert(update_tally_map(seller_address, property_traded, -possitive_sell, POSSITIVE_BALANCE)); assert(update_tally_map(seller_address, property_traded, -difference_s, NEGATIVE_BALANCE)); } } else if ( negative_sell != 0 || negative_sell == 0 || possitive_sell == 0 ) assert(update_tally_map(seller_address, property_traded, nCouldBuy, NEGATIVE_BALANCE)); if ( negative_buy != 0 ) { difference_b = negative_buy - nCouldBuy; if (difference_b >= 0) assert(update_tally_map(buyer_address, property_traded, -nCouldBuy, NEGATIVE_BALANCE)); else { assert(update_tally_map(buyer_address, property_traded, -negative_buy, NEGATIVE_BALANCE)); assert(update_tally_map(buyer_address, property_traded, -difference_b, POSSITIVE_BALANCE)); } } else if ( possitive_buy != 0 || possitive_buy == 0 || negative_buy == 0 ) assert(update_tally_map(buyer_address, property_traded, nCouldBuy, POSSITIVE_BALANCE)); /********************************************************/ int64_t poldPositiveBalanceL = getMPbalance(pold->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t pnewPositiveBalanceL = getMPbalance(pnew->getAddr(), property_traded, POSSITIVE_BALANCE); int64_t poldNegativeBalanceL = getMPbalance(pold->getAddr(), property_traded, NEGATIVE_BALANCE); int64_t pnewNegativeBalanceL = getMPbalance(pnew->getAddr(), property_traded, NEGATIVE_BALANCE); std::string Status_s = "Empty"; std::string Status_b = "Empty"; NewReturn = TRADED; CMPContractDex contract_replacement = *pold; int64_t creplNegativeBalance = getMPbalance(contract_replacement.getAddr(), property_traded, NEGATIVE_BALANCE); int64_t creplPositiveBalance = getMPbalance(contract_replacement.getAddr(), property_traded, POSSITIVE_BALANCE); PrintToLog("poldPositiveBalance: %d, poldNegativeBalance: %d\n", poldPositiveBalanceL, poldNegativeBalanceL); PrintToLog("pnewPositiveBalance: %d, pnewNegativeBalance: %d\n", pnewPositiveBalanceL, pnewNegativeBalanceL); PrintToLog("creplPositiveBalance: %d, creplNegativeBalance: %d\n", creplPositiveBalance, creplNegativeBalance); int64_t remaining = seller_amount >= buyer_amount ? seller_amount - buyer_amount : buyer_amount - seller_amount; if ( (seller_amount > buyer_amount && pold->getTradingAction() == SELL) || (seller_amount < buyer_amount && pold->getTradingAction() == BUY)) { contract_replacement.setAmountForsale(remaining, "moreinseller"); pnew->setAmountForsale(0, "no_remaining"); NewReturn = TRADED_MOREINSELLER; } else if ( (seller_amount < buyer_amount && pold->getTradingAction() == SELL) || (seller_amount > buyer_amount && pold->getTradingAction() == BUY)) { contract_replacement.setAmountForsale(0, "no_remaining"); pnew->setAmountForsale(remaining, "moreinbuyer"); NewReturn = TRADED_MOREINBUYER; } else if (seller_amount == buyer_amount) { pnew->setAmountForsale(0, "no_remaining"); contract_replacement.setAmountForsale(0, "no_remaining"); NewReturn = TRADED; } /********************************************************/ int64_t countClosedSeller = 0, countClosedBuyer = 0; if ( possitive_sell > 0 && negative_sell == 0 ) { if ( pold->getTradingAction() == SELL ) { Status_s = possitive_sell > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedSeller = creplPositiveBalance == 0 ? possitive_sell : abs( possitive_sell - creplPositiveBalance ); } else { Status_s = possitive_sell > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted": "LongPosIncreased") ); countClosedSeller = pnewPositiveBalanceL == 0 ? possitive_sell : abs( possitive_sell - pnewPositiveBalanceL ); } } else if ( negative_sell > 0 && possitive_sell == 0 ) { if ( pold->getTradingAction() == SELL ) { Status_s = negative_sell > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedSeller = creplNegativeBalance == 0 ? negative_sell : abs( negative_sell - creplNegativeBalance ); } else { Status_s = negative_sell > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedSeller = pnewNegativeBalanceL == 0 ? negative_sell : abs( negative_sell - pnewNegativeBalanceL ); } } else if ( negative_sell == 0 && possitive_sell == 0 ) { if ( pold->getTradingAction() == SELL ) Status_s = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition"; else Status_s = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition"; countClosedSeller = 0; } /********************************************************/ if ( possitive_buy > 0 && negative_buy == 0 ) { if ( pold->getTradingAction() == BUY ) { Status_b = possitive_buy > creplPositiveBalance && creplPositiveBalance != 0 ? "LongPosNettedPartly" : ( creplPositiveBalance == 0 && creplNegativeBalance == 0 ? "LongPosNetted" : ( creplPositiveBalance == 0 && creplNegativeBalance > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedBuyer = creplPositiveBalance == 0 ? possitive_buy : abs( possitive_buy - creplPositiveBalance ); } else { Status_b = possitive_buy > pnewPositiveBalanceL && pnewPositiveBalanceL != 0 ? "LongPosNettedPartly" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL == 0 ? "LongPosNetted" : ( pnewPositiveBalanceL == 0 && pnewNegativeBalanceL > 0 ? "OpenShortPosByLongPosNetted" : "LongPosIncreased") ); countClosedBuyer = pnewPositiveBalanceL == 0 ? possitive_buy : abs( possitive_buy - pnewPositiveBalanceL ); } } else if ( negative_buy > 0 && possitive_buy == 0 ) { if ( pold->getTradingAction() == BUY ) { Status_b = negative_buy > creplNegativeBalance && creplNegativeBalance != 0 ? "ShortPosNettedPartly" : ( creplNegativeBalance == 0 && creplPositiveBalance == 0 ? "ShortPosNetted" : ( creplNegativeBalance == 0 && creplPositiveBalance > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased" ) ); countClosedBuyer = creplNegativeBalance == 0 ? negative_buy : abs( negative_buy - creplNegativeBalance ); } else { Status_b = negative_buy > pnewNegativeBalanceL && pnewNegativeBalanceL != 0 ? "ShortPosNettedPartly" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL == 0 ? "ShortPosNetted" : ( pnewNegativeBalanceL == 0 && pnewPositiveBalanceL > 0 ? "OpenLongPosByShortPosNetted" : "ShortPosIncreased") ); countClosedBuyer = pnewNegativeBalanceL == 0 ? negative_buy : abs( negative_buy - pnewNegativeBalanceL ); } } else if ( negative_buy == 0 && possitive_buy == 0 ) { if ( pold->getTradingAction() == BUY ) Status_b = creplPositiveBalance > 0 ? "OpenLongPosition" : "OpenShortPosition"; else Status_b = pnewPositiveBalanceL > 0 ? "OpenLongPosition" : "OpenShortPosition"; countClosedBuyer = 0; } /********************************************************/ int64_t lives_maker = 0, lives_taker = 0; if( creplPositiveBalance > 0 && creplNegativeBalance == 0 ) lives_maker = creplPositiveBalance; else if( creplNegativeBalance > 0 && creplPositiveBalance == 0 ) lives_maker = creplNegativeBalance; if( pnewPositiveBalanceL && pnewNegativeBalanceL == 0 ) lives_taker = pnewPositiveBalanceL; else if( pnewNegativeBalanceL > 0 && pnewPositiveBalanceL == 0 ) lives_taker = pnewNegativeBalanceL; if ( countClosedSeller < 0 ) countClosedSeller = 0; if ( countClosedBuyer < 0 ) countClosedBuyer = 0; /********************************************************/ std::string Status_maker = "", Status_taker = ""; if (pold->getAddr() == seller_address) { Status_maker = Status_s; Status_taker = Status_b; } else { Status_maker = Status_b; Status_taker = Status_s; } PrintToLog("Status_maker = %d, Status_taker = %d\n", Status_maker, Status_taker); std::string Status_s0 = "EmptyStr", Status_s1 = "EmptyStr", Status_s2 = "EmptyStr", Status_s3 = "EmptyStr"; std::string Status_b0 = "EmptyStr", Status_b1 = "EmptyStr", Status_b2 = "EmptyStr", Status_b3 = "EmptyStr"; int64_t lives_maker0 = 0, lives_maker1 = 0, lives_maker2 = 0, lives_maker3 = 0; int64_t lives_taker0 = 0, lives_taker1 = 0, lives_taker2 = 0, lives_taker3 = 0; int64_t nCouldBuy0 = 0, nCouldBuy1 = 0, nCouldBuy2 = 0, nCouldBuy3 = 0; lives_maker0 = lives_maker; lives_taker0 = lives_taker; nCouldBuy0 = nCouldBuy; /********************************************************/ if ( pold->getTradingAction() == SELL ) { // If maker Sell and Open Short by Long Netted: status_sj -> makers if ( Status_maker == "OpenShortPosByLongPosNetted" ) { if ( Status_taker == "OpenLongPosByShortPosNetted" ) { if ( possitive_sell > negative_buy ) { Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; Status_b1 = "ShortPosNetted"; lives_taker1 = 0; nCouldBuy1 = negative_buy; Status_s2 = "LongPosNetted"; lives_maker2 = 0; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker1; nCouldBuy2 = lives_maker1; Status_s3 = "OpenShortPosition"; lives_maker3 = nCouldBuy - possitive_sell; Status_b3 = "LongPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( possitive_sell < negative_buy ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = negative_buy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; Status_b3 = "OpenLongPosition"; lives_taker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( possitive_sell == negative_buy ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNetted"; lives_taker1 = 0; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker2; nCouldBuy2 = lives_maker2; } } else if ( Status_taker == "ShortPosNettedPartly" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNettedPartly"; lives_taker2 = lives_taker1 - lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "ShortPosNetted" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "OpenLongPosition" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "OpenLongPosition"; lives_taker1 = possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "LongPosIncreased" ) { Status_s1 = "LongPosNetted"; lives_maker1 = 0; Status_b1 = "LongPosIncreased"; lives_taker1 = possitive_buy + possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } } // Checked } else { // If maker Buy and Open Long by Short Netted: status_bj -> makers if ( Status_maker == "OpenLongPosByShortPosNetted" ) { if ( Status_taker == "OpenShortPosByLongPosNetted" ) { if ( negative_buy < possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker1; Status_s2 = "LongPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_taker1; Status_b3 = "LongPosIncreased"; lives_maker3 = lives_maker2 + nCouldBuy - possitive_sell; Status_s3 = "OpenShortPosition"; lives_taker3 = nCouldBuy - possitive_sell; nCouldBuy3 = lives_taker3; } else if ( negative_buy > possitive_sell ) { Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; Status_s1 = "LongPosNetted"; lives_taker1 = 0; nCouldBuy1 = lives_maker1; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker1; nCouldBuy2 = lives_maker1; Status_b3 = "OpenLongPosition"; lives_maker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( negative_buy == possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNetted"; lives_taker1 = 0; nCouldBuy1 = possitive_sell; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker2; nCouldBuy2 = lives_maker2; } } else if ( Status_taker == "LongPosNettedPartly" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNettedPartly"; lives_taker2 = lives_taker1 - lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "LongPosNetted" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNetted"; lives_taker2 = 0; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "OpenShortPosition" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "OpenShortPosition"; lives_taker1 = negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } else if ( Status_taker == "ShortPosIncreased" ) { Status_b1 = "ShortPosNetted"; lives_maker1 = 0; Status_s1 = "ShortPosIncreased"; lives_taker1 = negative_sell + negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_maker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_taker2 = lives_taker1 + lives_maker2; nCouldBuy2 = lives_maker2; } } // Checked } /********************************************************/ if ( pold->getTradingAction() == BUY ) { // If taker Sell and Open Short by Long Netted: status_sj -> taker if ( Status_taker == "OpenShortPosByLongPosNetted" ) { if ( Status_maker == "OpenLongPosByShortPosNetted" ) { if ( possitive_sell > negative_buy ) { Status_s1 = "LongPosNettedPartly"; lives_taker1 = possitive_sell - negative_buy; Status_b1 = "ShortPosNetted"; lives_maker1 = 0; nCouldBuy1 = negative_buy; Status_s2 = "LongPosNetted"; lives_taker2 = 0; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker1; nCouldBuy2 = lives_taker1; Status_s3 = "OpenShortPosition"; lives_taker3 = nCouldBuy - possitive_sell; Status_b3 = "LongPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( possitive_sell < negative_buy ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell ; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = lives_maker1; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; Status_b3 = "OpenLongPosition"; lives_maker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_taker3 = lives_taker2 + lives_maker3; nCouldBuy3 = lives_maker3; } else if ( possitive_sell == negative_buy ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNetted"; lives_maker1 = 0; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "OpenLongPosition"; lives_maker2 = lives_taker2; nCouldBuy2 = lives_taker2; } } else if ( Status_maker == "ShortPosNettedPartly" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNettedPartly"; lives_maker2 = lives_maker1 - lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "ShortPosNetted" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "ShortPosNettedPartly"; lives_maker1 = negative_buy - possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "ShortPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "OpenLongPosition" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "OpenLongPosition"; lives_maker1 = possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "LongPosIncreased" ) { Status_s1 = "LongPosNetted"; lives_taker1 = 0; Status_b1 = "LongPosIncreased"; lives_maker1 = possitive_buy + possitive_sell; nCouldBuy1 = possitive_sell; Status_s2 = "OpenShortPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_b2 = "LongPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } } // Checked } else { // If taker Buy and Open Long by Short Netted: status_bj -> taker if ( Status_taker == "OpenLongPosByShortPosNetted" ) { if ( Status_maker == "OpenShortPosByLongPosNetted" ) { if ( negative_buy < possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = lives_maker1; Status_s2 = "LongPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_maker1; Status_b3 = "LongPosIncreased"; lives_taker3 = lives_taker2 + nCouldBuy - possitive_sell; Status_s3 = "OpenShortPosition"; lives_maker3 = nCouldBuy - possitive_sell; nCouldBuy3 = lives_maker3; } else if ( negative_buy > possitive_sell ) { Status_b1 = "ShortPosNettedPartly"; lives_taker1 = negative_buy - possitive_sell; Status_s1 = "LongPosNetted"; lives_maker1 = 0; nCouldBuy1 = lives_taker1; Status_b2 = "ShortPosNetted"; lives_taker2 = 0; Status_s2 = "OpenShortPosition"; lives_maker2 = negative_buy - possitive_sell; nCouldBuy2 = negative_buy - possitive_sell; Status_b3 = "OpenLongPosition"; lives_taker3 = nCouldBuy - negative_buy; Status_s3 = "ShortPosIncreased"; lives_maker3 = lives_maker2 + lives_taker3; nCouldBuy3 = lives_taker3; } else if ( negative_buy == possitive_sell ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNetted"; lives_maker1 = 0; nCouldBuy1 = possitive_sell; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - possitive_sell; Status_s2 = "OpenShortPosition"; lives_maker2 = lives_taker2; nCouldBuy2 = lives_taker2; } } else if ( Status_maker == "LongPosNettedPartly" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNettedPartly"; lives_maker2 = lives_maker1 - lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "LongPosNetted" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "LongPosNettedPartly"; lives_maker1 = possitive_sell - negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "LongPosNetted"; lives_maker2 = 0; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "OpenShortPosition" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "OpenShortPosition"; lives_maker1 = negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } else if ( Status_maker == "ShortPosIncreased" ) { Status_b1 = "ShortPosNetted"; lives_taker1 = 0; Status_s1 = "ShortPosIncreased"; lives_maker1 = negative_sell + negative_buy; nCouldBuy1 = negative_buy; Status_b2 = "OpenLongPosition"; lives_taker2 = nCouldBuy - negative_buy; Status_s2 = "ShortPosIncreased"; lives_maker2 = lives_maker1 + lives_taker2; nCouldBuy2 = lives_taker2; } } // Checked } /********************************************************************/ std::string Status_maker0="EmptyStr", Status_maker1="EmptyStr", Status_maker2="EmptyStr", Status_maker3="EmptyStr"; std::string Status_taker0="EmptyStr", Status_taker1="EmptyStr", Status_taker2="EmptyStr", Status_taker3="EmptyStr"; std::vector<std::string> v_status; std::vector<int64_t> v_livesc; std::vector<int64_t> v_ncouldbuy; v_ncouldbuy.push_back(nCouldBuy0); v_ncouldbuy.push_back(nCouldBuy1); v_ncouldbuy.push_back(nCouldBuy2); v_ncouldbuy.push_back(nCouldBuy3); v_livesc.push_back(lives_maker0); v_livesc.push_back(lives_taker0); v_livesc.push_back(lives_maker1); v_livesc.push_back(lives_taker1); v_livesc.push_back(lives_maker2); v_livesc.push_back(lives_taker2); v_livesc.push_back(lives_maker3); v_livesc.push_back(lives_taker3); if ( pold->getAddr() == seller_address ) { v_status.push_back(Status_s); v_status.push_back(Status_b); v_status.push_back(Status_s1); v_status.push_back(Status_b1); v_status.push_back(Status_s2); v_status.push_back(Status_b2); v_status.push_back(Status_s3); v_status.push_back(Status_b3); } else { v_status.push_back(Status_b); v_status.push_back(Status_s); v_status.push_back(Status_b1); v_status.push_back(Status_s1); v_status.push_back(Status_b2); v_status.push_back(Status_s2); v_status.push_back(Status_b3); v_status.push_back(Status_s3); } Status_maker0 = Status_maker; Status_taker0 = Status_taker; if ( pold->getAddr() == seller_address ) { Status_maker1 = Status_s1; Status_taker1 = Status_b1; Status_maker2 = Status_s2; Status_taker2 = Status_b2; Status_maker3 = Status_s3; Status_taker3 = Status_b3; } else { Status_maker1 = Status_b1; Status_taker1 = Status_s1; Status_maker2 = Status_b2; Status_taker2 = Status_s2; Status_maker3 = Status_b3; Status_taker3 = Status_s3; } /********************************************************/ t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), pold->getAddr(), pnew->getAddr(), pold->getEffectivePrice(), contract_replacement.getAmountForSale(), pnew->getAmountForSale(), pold->getBlock(), pnew->getBlock(), property_traded, tradeStatus, lives_maker0, lives_maker1, lives_maker2, lives_maker3, lives_taker0, lives_taker1, lives_taker2, lives_taker3, Status_maker0, Status_taker0, Status_maker1, Status_taker1, Status_maker2, Status_taker2, Status_maker3, Status_taker3, nCouldBuy0, nCouldBuy1, nCouldBuy2, nCouldBuy3); /********************************************************/ int index = static_cast<unsigned int>(property_traded); marketP[index] = pold->getEffectivePrice(); uint64_t marketPriceNow = marketP[index]; PrintToLog("\nmarketPrice Now : %d, marketP[index] = %d\n", marketPriceNow, marketP[index]); t_tradelistdb->recordForUPNL(pnew->getHash(),pnew->getAddr(),property_traded,pold->getEffectivePrice()); // if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString()); pofferSet->erase(offerIt++); if (0 < remaining) pofferSet->insert(contract_replacement); } } static const std::string getTradeReturnType(MatchReturnType ret) { switch (ret) { case NOTHING: return "NOTHING"; case TRADED: return "TRADED"; case TRADED_MOREINSELLER: return "TRADED_MOREINSELLER"; case TRADED_MOREINBUYER: return "TRADED_MOREINBUYER"; case ADDED: return "ADDED"; case CANCELLED: return "CANCELLED"; default: return "* unknown *"; } } // Used by rangeInt64, xToInt64 static bool rangeInt64(const int128_t& value) { return (std::numeric_limits<int64_t>::min() <= value && value <= std::numeric_limits<int64_t>::max()); } // Used by xToString static bool rangeInt64(const rational_t& value) { return (rangeInt64(value.numerator()) && rangeInt64(value.denominator())); } // Used by CMPMetaDEx::displayUnitPrice static int64_t xToRoundUpInt64(const rational_t& value) { // for integer rounding up: ceil(num / denom) => 1 + (num - 1) / denom int128_t result = int128_t(1) + (value.numerator() - int128_t(1)) / value.denominator(); assert(rangeInt64(result)); return result.convert_to<int64_t>(); } std::string xToString(const dec_float& value) { return value.str(DISPLAY_PRECISION_LEN, std::ios_base::fixed); } std::string xToString(const int128_t& value) { return strprintf("%s", boost::lexical_cast<std::string>(value)); } std::string xToString(const rational_t& value) { if (rangeInt64(value)) { int64_t num = value.numerator().convert_to<int64_t>(); int64_t denom = value.denominator().convert_to<int64_t>(); dec_float x = dec_float(num) / dec_float(denom); return xToString(x); } else return strprintf("%s / %s", xToString(value.numerator()), xToString(value.denominator())); } /********************************************************************/ /** New things for Contracts */ std::string xToString(const uint64_t &price) { return strprintf("%s", boost::lexical_cast<std::string>(price)); } std::string xToString(const int64_t &price) { return strprintf("%s", boost::lexical_cast<std::string>(price)); } std::string xToString(const uint32_t &value) { return strprintf("%s", boost::lexical_cast<std::string>(value)); } ui128 multiply_int64_t(int64_t &m, int64_t &n) { ui128 product; multiply(product, m, n); return product; } ui128 multiply_uint64_t(uint64_t &m, uint64_t &n) { ui128 product; multiply(product, m, n); return product; } /*The metadex of tokens*/ // find the best match on the market // NOTE: sometimes I refer to the older order as seller & the newer order as buyer, in this trade // INPUT: property, desprop, desprice = of the new order being inserted; the new object being processed // RETURN: MatchReturnType x_Trade(CMPMetaDEx* const pnew) { const uint32_t propertyForSale = pnew->getProperty(); const uint32_t propertyDesired = pnew->getDesProperty(); MatchReturnType NewReturn = NOTHING; bool bBuyerSatisfied = false; // if (msc_debug_metadex1) PrintToLog("%s(%s: prop=%d, desprop=%d, desprice= %s);newo: %s\n", // __FUNCTION__, pnew->getAddr(), propertyForSale, propertyDesired, xToString(pnew->inversePrice()), pnew->ToString()); md_PricesMap* const ppriceMap = get_Prices(propertyDesired); // nothing for the desired property exists in the market, sorry! if (!ppriceMap) { PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } // within the desired property map (given one property) iterate over the items looking at prices for (md_PricesMap::iterator priceIt = ppriceMap->begin(); priceIt != ppriceMap->end(); ++priceIt) { // check all prices const rational_t sellersPrice = priceIt->first; // if (msc_debug_metadex2) PrintToLog("comparing prices: desprice %s needs to be GREATER THAN OR EQUAL TO %s\n", // xToString(pnew->inversePrice()), xToString(sellersPrice)); // Is the desired price check satisfied? The buyer's inverse price must be larger than that of the seller. if (pnew->inversePrice() < sellersPrice) { continue; } md_Set* const pofferSet = &(priceIt->second); // at good (single) price level and property iterate over offers looking at all parameters to find the match md_Set::iterator offerIt = pofferSet->begin(); while (offerIt != pofferSet->end()) { // specific price, check all properties const CMPMetaDEx* const pold = &(*offerIt); assert(pold->unitPrice() == sellersPrice); // if (msc_debug_metadex1) PrintToLog("Looking at existing: %s (its prop= %d, its des prop= %d) = %s\n", // xToString(sellersPrice), pold->getProperty(), pold->getDesProperty(), pold->ToString()); // does the desired property match? if (pold->getDesProperty() != propertyForSale) { ++offerIt; continue; } // if (msc_debug_metadex1) PrintToLog("MATCH FOUND, Trade: %s = %s\n", xToString(sellersPrice), pold->ToString()); // match found, execute trade now! const int64_t seller_amountForSale = pold->getAmountRemaining(); const int64_t buyer_amountOffered = pnew->getAmountRemaining(); // if (msc_debug_metadex1) PrintToLog("$$ trading using price: %s; seller: forsale=%d, desired=%d, remaining=%d, buyer amount offered=%d\n", // xToString(sellersPrice), pold->getAmountForSale(), pold->getAmountDesired(), pold->getAmountRemaining(), pnew->getAmountRemaining()); // if (msc_debug_metadex1) PrintToLog("$$ old: %s\n", pold->ToString()); // if (msc_debug_metadex1) PrintToLog("$$ new: %s\n", pnew->ToString()); /////////////////////////// // preconditions assert(0 < pold->getAmountRemaining()); assert(0 < pnew->getAmountRemaining()); assert(pnew->getProperty() != pnew->getDesProperty()); assert(pnew->getProperty() == pold->getDesProperty()); assert(pold->getProperty() == pnew->getDesProperty()); assert(pold->unitPrice() <= pnew->inversePrice()); assert(pnew->unitPrice() <= pold->inversePrice()); /////////////////////////// // First determine how many representable (indivisible) tokens Alice can // purchase from Bob, using Bob's unit price // This implies rounding down, since rounding up is impossible, and would // require more tokens than Alice has arith_uint256 iCouldBuy = (ConvertTo256(pnew->getAmountRemaining()) * ConvertTo256(pold->getAmountForSale())) / ConvertTo256(pold->getAmountDesired()); int64_t nCouldBuy = 0; if (iCouldBuy < ConvertTo256(pold->getAmountRemaining())) { nCouldBuy = ConvertTo64(iCouldBuy); } else { nCouldBuy = pold->getAmountRemaining(); } if (nCouldBuy == 0) { // if (msc_debug_metadex1) PrintToLog( // "-- buyer has not enough tokens for sale to purchase one unit!\n"); ++offerIt; continue; } // If the amount Alice would have to pay to buy Bob's tokens at his price // is fractional, always round UP the amount Alice has to pay // This will always be better for Bob. Rounding in the other direction // will always be impossible, because ot would violate Bob's accepted price arith_uint256 iWouldPay = DivideAndRoundUp((ConvertTo256(nCouldBuy) * ConvertTo256(pold->getAmountDesired())), ConvertTo256(pold->getAmountForSale())); int64_t nWouldPay = ConvertTo64(iWouldPay); // If the resulting adjusted unit price is higher than Alice' price, the // orders shall not execute, and no representable fill is made const rational_t xEffectivePrice(nWouldPay, nCouldBuy); if (xEffectivePrice > pnew->inversePrice()) { // if (msc_debug_metadex1) PrintToLog( // "-- effective price is too expensive: %s\n", xToString(xEffectivePrice)); ++offerIt; continue; } const int64_t buyer_amountGot = nCouldBuy; const int64_t seller_amountGot = nWouldPay; const int64_t buyer_amountLeft = pnew->getAmountRemaining() - seller_amountGot; const int64_t seller_amountLeft = pold->getAmountRemaining() - buyer_amountGot; // if (msc_debug_metadex1) PrintToLog("$$ buyer_got= %d, seller_got= %d, seller_left_for_sale= %d, buyer_still_for_sale= %d\n", // buyer_amountGot, seller_amountGot, seller_amountLeft, buyer_amountLeft); /////////////////////////// // postconditions assert(xEffectivePrice >= pold->unitPrice()); assert(xEffectivePrice <= pnew->inversePrice()); assert(0 <= seller_amountLeft); assert(0 <= buyer_amountLeft); assert(seller_amountForSale == seller_amountLeft + buyer_amountGot); assert(buyer_amountOffered == buyer_amountLeft + seller_amountGot); /////////////////////////// int64_t buyer_amountGotAfterFee = buyer_amountGot; int64_t tradingFee = 0; // strip a 0.05% fee from non-OMNI pairs if fees are activated if (IsFeatureActivated(FEATURE_FEES, pnew->getBlock())) { if (pold->getProperty() > OMNI_PROPERTY_TMSC && pold->getDesProperty() > OMNI_PROPERTY_TMSC) { int64_t feeDivider = 2000; // 0.05% tradingFee = buyer_amountGot / feeDivider; // subtract the fee from the amount the seller will receive buyer_amountGotAfterFee = buyer_amountGot - tradingFee; // add the fee to the fee cache TODO: check the fees file // p_feecache->AddFee(pnew->getDesProperty(), pnew->getBlock(), tradingFee); } else { // if (msc_debug_fees) PrintToLog("Skipping fee reduction for trade match %s:%s as one of the properties is Omni\n", pold->getHash().GetHex(), pnew->getHash().GetHex()); } } // transfer the payment property from buyer to seller assert(update_tally_map(pnew->getAddr(), pnew->getProperty(), -seller_amountGot, BALANCE)); assert(update_tally_map(pold->getAddr(), pold->getDesProperty(), seller_amountGot, BALANCE)); // transfer the market (the one being sold) property from seller to buyer assert(update_tally_map(pold->getAddr(), pold->getProperty(), -buyer_amountGot, METADEX_RESERVE)); assert(update_tally_map(pnew->getAddr(), pnew->getDesProperty(), buyer_amountGotAfterFee, BALANCE)); NewReturn = TRADED; CMPMetaDEx seller_replacement = *pold; // < can be moved into last if block seller_replacement.setAmountRemaining(seller_amountLeft, "seller_replacement"); pnew->setAmountRemaining(buyer_amountLeft, "buyer"); if (0 < buyer_amountLeft) { NewReturn = TRADED_MOREINBUYER; } if (0 == buyer_amountLeft) { bBuyerSatisfied = true; } if (0 < seller_amountLeft) { NewReturn = TRADED_MOREINSELLER; } // if (msc_debug_metadex1) PrintToLog("==== TRADED !!! %u=%s\n", NewReturn, getTradeReturnType(NewReturn)); // record the trade in MPTradeList t_tradelistdb->recordMatchedTrade(pold->getHash(), pnew->getHash(), // < might just pass pold, pnew pold->getAddr(), pnew->getAddr(), pold->getDesProperty(), pnew->getDesProperty(), seller_amountGot, buyer_amountGotAfterFee, pnew->getBlock(), tradingFee); // if (msc_debug_metadex1) PrintToLog("++ erased old: %s\n", offerIt->ToString()); // erase the old seller element pofferSet->erase(offerIt++); // insert the updated one in place of the old if (0 < seller_replacement.getAmountRemaining()) { PrintToLog("++ inserting seller_replacement: %s\n", seller_replacement.ToString()); pofferSet->insert(seller_replacement); } if (bBuyerSatisfied) { assert(buyer_amountLeft == 0); break; } } // specific price, check all properties if (bBuyerSatisfied) break; } // check all prices PrintToLog("%s()=%d:%s\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } /////////////////////////////////////// /** New things for Contracts */ MatchReturnType x_Trade(CMPContractDex* const pnew) { const uint32_t propertyForSale = pnew->getProperty(); uint8_t trdAction = pnew->getTradingAction(); PrintToConsole("Trading action of pnew: %d \n",trdAction); MatchReturnType NewReturn = NOTHING; // if (msc_debug_metadex1) // PrintToLog("%s(%s: prop=%d, desprice= %s);newo: %s\n", __FUNCTION__, pnew->getAddr(), propertyForSale, xToString(pnew->getEffectivePrice()), pnew->ToString()); cd_PricesMap* const ppriceMap = get_PricesCd(propertyForSale); if (!ppriceMap) { PrintToLog("%s()=%d:%s NOT FOUND ON THE MARKET\n", __FUNCTION__, NewReturn, getTradeReturnType(NewReturn)); return NewReturn; } LoopBiDirectional(ppriceMap, trdAction, NewReturn, pnew, propertyForSale); return NewReturn; } ///////////////////////////////////// /** New things for contracts */ int get_LiquidationPrice(int64_t effectivePrice, string address, uint32_t property, uint8_t trading_action) { double percentLiqPrice = 0.95; double liqFactor = 0; int64_t longs = getMPbalance(address, property, POSSITIVE_BALANCE); int64_t shorts = getMPbalance(address, property, NEGATIVE_BALANCE); int64_t oldLiqPrice = getMPbalance (address, property,LIQUIDATION_PRICE); PrintToConsole("longs : %d",longs); PrintToConsole("shorts : %d",shorts); if (longs == 0 && shorts == 0 && oldLiqPrice != 0) { PrintToConsole("oldLiqPrice : %d",oldLiqPrice); assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE)); return -1; } (trading_action == BUY) ? liqFactor = 1 - percentLiqPrice : liqFactor = 1 + percentLiqPrice; double liqPr = static_cast<double> (effectivePrice * liqFactor) ; double aLiqPrice = ( liqPr + static_cast<double>(oldLiqPrice) ) / 2 ; int64_t newLiqPrice = static_cast<int64_t>(aLiqPrice); PrintToConsole ("trading action : %d\n", trading_action); PrintToConsole ("LiqFactor : %d\n", liqFactor); PrintToConsole ("Precio de liquidación antiguo : %d\n", oldLiqPrice); PrintToConsole ("Precio de liquidación actual : %d\n", liqPr); PrintToConsole ("Precio de liquidación Nuevo : %d\n", newLiqPrice); if (oldLiqPrice > 0) { assert(update_tally_map(address, property, -oldLiqPrice, LIQUIDATION_PRICE)); assert(update_tally_map(address, property, newLiqPrice, LIQUIDATION_PRICE)); return 1; } return -1; } //////////////////////////////////////// /** * Used for display of unit prices to 8 decimal places at UI layer. * * Automatically returns unit or inverse price as needed. */ std::string CMPMetaDEx::displayUnitPrice() const { rational_t tmpDisplayPrice; if (getDesProperty() == OMNI_PROPERTY_MSC || getDesProperty() == OMNI_PROPERTY_TMSC) { tmpDisplayPrice = unitPrice(); if (isPropertyDivisible(getProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN; } else { tmpDisplayPrice = inversePrice(); if (isPropertyDivisible(getDesProperty())) tmpDisplayPrice = tmpDisplayPrice * COIN; } // offers with unit prices under 0.00000001 will be excluded from UI layer - TODO: find a better way to identify sub 0.00000001 prices std::string tmpDisplayPriceStr = xToString(tmpDisplayPrice); if (!tmpDisplayPriceStr.empty()) { if (tmpDisplayPriceStr.substr(0,1) == "0") return "0.00000000"; } // we must always round up here - for example if the actual price required is 0.3333333344444 // round: 0.33333333 - price is insufficient and thus won't result in a trade // round: 0.33333334 - price will be sufficient to result in a trade std::string displayValue = FormatDivisibleMP(xToRoundUpInt64(tmpDisplayPrice)); return displayValue; } /** * Used for display of unit prices with 50 decimal places at RPC layer. * * Note: unit price is no longer always shown in OMNI and/or inverted */ std::string CMPMetaDEx::displayFullUnitPrice() const { rational_t tempUnitPrice = unitPrice(); /* Matching types require no action (divisible/divisible or indivisible/indivisible) Non-matching types require adjustment for display purposes divisible/indivisible : *COIN indivisible/divisible : /COIN */ if ( isPropertyDivisible(getProperty()) && !isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice*COIN; if ( !isPropertyDivisible(getProperty()) && isPropertyDivisible(getDesProperty()) ) tempUnitPrice = tempUnitPrice/COIN; std::string unitPriceStr = xToString(tempUnitPrice); return unitPriceStr; } ////////////////////////////////////// /** New things for Contracts */ std::string CMPContractDex::displayFullContractPrice() const { uint64_t priceForsale = getEffectivePrice(); uint64_t amountForsale = getAmountForSale(); int128_t fullprice; if ( isPropertyContract(getProperty()) ) multiply(fullprice, priceForsale, amountForsale); std::string priceForsaleStr = xToString(fullprice); return priceForsaleStr; } ////////////////////////////////////// rational_t CMPMetaDEx::unitPrice() const { rational_t effectivePrice; if (amount_forsale) effectivePrice = rational_t(amount_desired, amount_forsale); return effectivePrice; } rational_t CMPMetaDEx::inversePrice() const { rational_t inversePrice; if (amount_desired) inversePrice = rational_t(amount_forsale, amount_desired); return inversePrice; } int64_t CMPMetaDEx::getAmountToFill() const { // round up to ensure that the amount we present will actually result in buying all available tokens arith_uint256 iAmountNeededToFill = DivideAndRoundUp((ConvertTo256(amount_remaining) * ConvertTo256(amount_desired)), ConvertTo256(amount_forsale)); int64_t nAmountNeededToFill = ConvertTo64(iAmountNeededToFill); return nAmountNeededToFill; } int64_t CMPMetaDEx::getBlockTime() const { CBlockIndex* pblockindex = chainActive[block]; return pblockindex->GetBlockTime(); } void CMPMetaDEx::setAmountRemaining(int64_t amount, const std::string& label) { amount_remaining = amount; PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString()); } /////////////////////////////////////////// void CMPMetaDEx::setAmountForsale(int64_t amount, const std::string& label) { amount_forsale = amount; PrintToLog("update remaining amount still up for sale (%ld %s):%s\n", amount, label, ToString()); } void CMPContractDex::setPrice(int64_t price) { effective_price = price; // PrintToLog("update price still up for sale (%ld):%s\n", price, ToString()); } /////////////////////////////////////////// std::string CMPMetaDEx::ToString() const { return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s", xToString(unitPrice()), addr, block, idx, txid.ToString().substr(0, 10), property, FormatMP(property, amount_forsale), desired_property, FormatMP(desired_property, amount_desired)); } //////////////////////////////////// /** New things for Contract */ std::string CMPContractDex::ToString() const { return strprintf("%s:%34s in %d/%03u, txid: %s , trade #%u %s for #%u %s", xToString(getEffectivePrice()), getAddr(), getBlock(), getIdx(), getHash().ToString().substr(0, 10), getProperty(), FormatMP(getProperty(), getAmountForSale())); } ////////////////////////////////////// void CMPMetaDEx::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const { std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d", addr, block, amount_forsale, property, amount_desired, desired_property, subaction, idx, txid.ToString(), amount_remaining ); // add the line to the hash SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length()); // write the line file << lineOut << std::endl; } //////////////////////////////////// /** New things for Contract */ void CMPContractDex::saveOffer(std::ofstream& file, SHA256_CTX* shaCtx) const { std::string lineOut = strprintf("%s,%d,%d,%d,%d,%d,%d,%d,%s,%d,%d,%d", getAddr(), getBlock(), getAmountForSale(), getProperty(), getAmountDesired(), getDesProperty(), getAction(), getIdx(), getHash().ToString(), getAmountRemaining(), effective_price, trading_action ); // add the line to the hash SHA256_Update(shaCtx, lineOut.c_str(), lineOut.length()); // write the line file << lineOut << std::endl; } //////////////////////////////////// /** New things for Contract */ void saveDataGraphs(std::fstream &file, std::string lineOutSixth1, std::string lineOutSixth2, std::string lineOutSixth3, bool savedata_bool) { std::string lineSixth1 = lineOutSixth1; std::string lineSixth2 = lineOutSixth2; std::string lineSixth3 = lineOutSixth3; if ( savedata_bool ) { file << lineSixth1 << "\n"; file << lineSixth2 << std::endl; } else { file << lineSixth1 << "\n"; file << lineSixth2 << "\n"; file << lineSixth3 << std::endl; } } void saveDataGraphs(std::fstream &file, std::string lineOut) { std::string line = lineOut; file << line << std::endl; } //////////////////////////////////// bool MetaDEx_compare::operator()(const CMPMetaDEx &lhs, const CMPMetaDEx &rhs) const { if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx(); else return lhs.getBlock() < rhs.getBlock(); } /////////////////////////////////////////// /** New things for Contracts */ bool ContractDex_compare::operator()(const CMPContractDex &lhs, const CMPContractDex &rhs) const { if (lhs.getBlock() == rhs.getBlock()) return lhs.getIdx() < rhs.getIdx(); else return lhs.getBlock() < rhs.getBlock(); } /////////////////////////////////////////// bool mastercore::MetaDEx_INSERT(const CMPMetaDEx& objMetaDEx) { // Create an empty price map (to use in case price map for this property does not already exist) md_PricesMap temp_prices; // Attempt to obtain the price map for the property md_PricesMap *p_prices = get_Prices(objMetaDEx.getProperty()); // Create an empty set of metadex objects (to use in case no set currently exists at this price) md_Set temp_indexes; md_Set *p_indexes = NULL; // Prepare for return code std::pair <md_Set::iterator, bool> ret; // Attempt to obtain a set of metadex objects for this price from the price map if (p_prices) p_indexes = get_Indexes(p_prices, objMetaDEx.unitPrice()); // See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier if (!p_indexes) p_indexes = &temp_indexes; // Attempt to insert the metadex object into the set ret = p_indexes->insert(objMetaDEx); if (false == ret.second) return false; // If a prices map did not exist for this property, set p_prices to the temp empty price map if (!p_prices) p_prices = &temp_prices; // Update the prices map with the new set at this price (*p_prices)[objMetaDEx.unitPrice()] = *p_indexes; // Set the metadex map for the property to the updated (or new if it didn't exist) price map metadex[objMetaDEx.getProperty()] = *p_prices; return true; } /////////////////////////////////////////// /** New things for Contracts */ bool mastercore::ContractDex_INSERT(const CMPContractDex &objContractDex) { // Create an empty price map (to use in case price map for this property does not already exist) cd_PricesMap temp_prices; // Attempt to obtain the price map for the property cd_PricesMap *cd_prices = get_PricesCd(objContractDex.getProperty()); // Create an empty set of contractdex objects (to use in case no set currently exists at this price) cd_Set temp_indexes; cd_Set *p_indexes = NULL; // Prepare for return code std::pair <cd_Set::iterator, bool> ret; // Attempt to obtain a set of contractdex objects for this price from the price map if (cd_prices) p_indexes = get_IndexesCd(cd_prices, objContractDex.getEffectivePrice()); // See if the set was populated, if not no set exists at this price level, use the empty set that we created earlier if (!p_indexes) p_indexes = &temp_indexes; // Attempt to insert the contractdex object into the set ret = p_indexes->insert(objContractDex); if (false == ret.second) return false; // If a prices map did not exist for this property, set p_prices to the temp empty price map if (!cd_prices) cd_prices = &temp_prices; // Update the prices map with the new Set at this price (*cd_prices)[objContractDex.getEffectivePrice()] = *p_indexes; // Set the contractdex map for the property to the updated (or new if it didn't exist) price map contractdex[objContractDex.getProperty()] = *cd_prices; // = *cd_prices; return true; } /////////////////////////////////////////// // pretty much directly linked to the ADD TX21 command off the wire int mastercore::MetaDEx_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, uint32_t property_desired, int64_t amount_desired, const uint256& txid, unsigned int idx) { int rc = METADEX_ERROR -1; PrintToConsole("------------------------------------------------------------\n"); PrintToConsole("Inside MetaDEx_ADD\n"); // Create a MetaDEx object from paremeters CMPMetaDEx new_mdex(sender_addr, block, prop, amount, property_desired, amount_desired, txid, idx, CMPTransaction::ADD); // if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_mdex.ToString()); // Ensure this is not a badly priced trade (for example due to zero amounts) if (0 >= new_mdex.unitPrice()) return METADEX_ERROR -66; // Match against existing trades, remainder of the order will be put into the order book // if (msc_debug_metadex3) MetaDEx_debug_print(); x_Trade(&new_mdex); // if (msc_debug_metadex3) MetaDEx_debug_print(); // Insert the remaining order into the MetaDEx maps if (0 < new_mdex.getAmountRemaining()) { //switch to getAmountRemaining() when ready if (!MetaDEx_INSERT(new_mdex)) { PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__); return METADEX_ERROR -70; } else { // move tokens into reserve assert(update_tally_map(sender_addr, prop, -new_mdex.getAmountRemaining(), BALANCE)); assert(update_tally_map(sender_addr, prop, new_mdex.getAmountRemaining(), METADEX_RESERVE)); // if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_mdex.unitPrice()), new_mdex.ToString()); // if (msc_debug_metadex3) MetaDEx_debug_print(); } } rc = 0; return rc; } ///////////////////////////////////////// /** New things for Contract */ int mastercore::ContractDex_ADD(const std::string& sender_addr, uint32_t prop, int64_t amount, int block, const uint256& txid, unsigned int idx, uint64_t effective_price, uint8_t trading_action, int64_t amount_to_reserve) { // int rc = METADEX_ERROR -1; /*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/ CMPContractDex new_cdex(sender_addr, block, prop, amount, 0, 0, txid, idx, CMPTransaction::ADD, effective_price, trading_action); // if (msc_debug_metadex1) PrintToLog("%s(); buyer obj: %s\n", __FUNCTION__, new_cdex.ToString()); // Ensure this is not a badly priced trade (for example due to zero amounts) if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; x_Trade(&new_cdex); // if (msc_debug_metadex3) MetaDEx_debug_print(); // Insert the remaining order into the ContractDex maps if (0 < new_cdex.getAmountForSale()) { //switch to getAmounForSale() when ready if (!ContractDex_INSERT(new_cdex)) { PrintToLog("%s() ERROR: ALREADY EXISTS, line %d, file: %s\n", __FUNCTION__, __LINE__, __FILE__); return METADEX_ERROR -70; // TODO: create new numbers for our errors. } else { PrintToConsole("\nInserted in the orderbook!!\n"); // if (msc_debug_metadex1) PrintToLog("==== INSERTED: %s= %s\n", xToString(new_cdex.getEffectivePrice()), new_cdex.ToString()); // if (msc_debug_metadex3) MetaDEx_debug_print(); } } return 0; } ///////////////////////////////////////// /** New things for Contract */ int mastercore::ContractDex_ADD_MARKET_PRICE(const std::string& sender_addr, uint32_t contractId, int64_t amount, int block, const uint256& txid, unsigned int idx, uint8_t trading_action, int64_t amount_to_reserve) { int rc = METADEX_ERROR -1; PrintToLog("------------------------------------------------------------\n"); PrintToLog("Inside ContractDex_ADD_MARKET_PRICE\n"); /*Remember: Here CMPTransaction::ADD is the subaction coming from CMPMetaDEx*/ if (trading_action == BUY){ uint64_t ask = edgeOrderbook(contractId,BUY); PrintToLog("ask: %d\n",ask); CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, ask, trading_action); // Ensure this is not a badly priced trade (for example due to zero amounts) PrintToLog("effective price of new_cdex /buy/: %d\n",new_cdex.getEffectivePrice()); if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; // Insert the remaining order into the ContractDex maps uint64_t diff; uint64_t oldvalue; uint64_t newvalue; while(true) { oldvalue = new_cdex.getAmountForSale(); x_Trade(&new_cdex); newvalue = new_cdex.getAmountForSale(); if (newvalue == 0) { break; } uint64_t price = edgeOrderbook(contractId,BUY); new_cdex.setPrice(price); PrintToLog("SELL SIDE in while loop/ right side of example/<-------\n"); } } else if (trading_action == SELL){ uint64_t bid = edgeOrderbook(contractId,SELL); PrintToLog("bid: %d\n",bid); CMPContractDex new_cdex(sender_addr, block, contractId, amount, 0, 0, txid, idx, CMPTransaction::ADD, bid, trading_action); // Ensure this is not a badly priced trade (for example due to zero amounts PrintToLog("effective price of new_cdex/sell/: %d\n",new_cdex.getEffectivePrice()); if (0 >= new_cdex.getEffectivePrice()) return METADEX_ERROR -66; // Insert the remaining order into the ContractDex maps uint64_t oldvalue; uint64_t newvalue; uint64_t diff; while(true) { oldvalue = new_cdex.getAmountForSale(); x_Trade(&new_cdex); newvalue = new_cdex.getAmountForSale(); if (newvalue == 0) { break; } uint64_t price = edgeOrderbook(contractId,BUY); new_cdex.setPrice(price); PrintToLog("BUY SIDE in while loop/ right side of example/<-------\n"); } } rc = 0; return rc; } int mastercore::ContractDex_CANCEL_EVERYTHING(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId) { int rc = METADEX_ERROR -40; bool bValid = false; int64_t factorH = factorE; for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { unsigned int prop = my_it->first; // skip property, if it is not in the expected ecosystem if (isMainEcosystemProperty(ecosystem) && !isMainEcosystemProperty(prop)) continue; if (isTestEcosystemProperty(ecosystem) && !isTestEcosystemProperty(prop)) continue; // PrintToLog(" ## property: %u\n", prop); cd_PricesMap &prices = my_it->second; for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; cd_Set &indexes = it->second; // PrintToLog(" # Price Level: %s\n", xToString(price)); for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s= %s\n", xToString(price), it->ToString()); if (it->getAddr() != sender_addr || it->getProperty() != contractId || it->getAmountForSale() == 0) { ++it; continue; } rc = 0; // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); CMPSPInfo::Entry sp; assert(_my_sps->getSP(it->getProperty(), sp)); uint32_t collateralCurrency = sp.collateral_currency; int64_t marginRe = static_cast<int64_t>(sp.margin_requirement); string addr = it->getAddr(); int64_t amountForSale = it->getAmountForSale(); rational_t conv = notionalChange(contractId); int64_t num = conv.numerator().convert_to<int64_t>(); int64_t den = conv.denominator().convert_to<int64_t>(); arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorH))); int64_t redeemed = ConvertTo64(amountMargin); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("margin requirement of contract : %d\n",marginRe); PrintToLog("amountForSale: %d\n",amountForSale); PrintToLog("Address: %d\n",addr); PrintToLog("--------------------------------------------\n"); // move from reserve to balance the collateral assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE)); assert(update_tally_map(addr, collateralCurrency, redeemed, CONTRACTDEX_RESERVE)); // // record the cancellation bValid = true; // p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale indexes.erase(it++); } } } if (bValid == false){ PrintToConsole("You don't have active orders\n"); } return rc; } int mastercore::ContractDex_CANCEL_FOR_BLOCK(const uint256& txid, int block,unsigned int idx, const std::string& sender_addr, unsigned char ecosystem) { int rc = METADEX_ERROR -40; bool bValid = false; for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // PrintToLog(" ## property: %u\n", prop); cd_PricesMap &prices = my_it->second; for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; cd_Set &indexes = it->second; for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { string addr = it->getAddr(); if (addr != sender_addr || it->getBlock()!= block || it->getIdx()!= idx) { ++it; continue; } CMPSPInfo::Entry sp; uint32_t contractId = it->getProperty(); assert(_my_sps->getSP(contractId, sp)); uint32_t collateralCurrency = sp.collateral_currency; uint32_t marginRe = sp.margin_requirement; int64_t balance = getMPbalance(addr,collateralCurrency,BALANCE); int64_t amountForSale = it->getAmountForSale(); rational_t conv = notionalChange(contractId); int64_t num = conv.numerator().convert_to<int64_t>(); int64_t den = conv.denominator().convert_to<int64_t>(); arith_uint256 amountMargin = (ConvertTo256(amountForSale) * ConvertTo256(marginRe) * ConvertTo256(num) / (ConvertTo256(den) * ConvertTo256(factorE))); int64_t redeemed = ConvertTo64(amountMargin); PrintToLog("collateral currency id of contract : %d\n",collateralCurrency); PrintToLog("margin requirement of contract : %d\n",marginRe); PrintToLog("amountForSale: %d\n",amountForSale); PrintToLog("Address: %d\n",addr); std::string sgetback = FormatDivisibleMP(redeemed,false); PrintToLog("amount returned to balance: %d\n",redeemed); PrintToLog("--------------------------------------------\n"); // move from reserve to balance the collateral if (balance > redeemed && balance > 0 && redeemed > 0) { assert(update_tally_map(addr, collateralCurrency, redeemed, BALANCE)); assert(update_tally_map(addr, collateralCurrency, -redeemed, CONTRACTDEX_RESERVE)); } // record the cancellation bValid = true; // p_txlistdb->recordContractDexCancelTX(txid, it->getHash(), bValid, block, it->getProperty(), it->getAmountForSale indexes.erase(it++); rc = 0; } } } if (bValid == false){ PrintToConsole("Incorrect block or idx\n"); } return rc; } int mastercore::ContractDex_CLOSE_POSITION(const uint256& txid, unsigned int block, const std::string& sender_addr, unsigned char ecosystem, uint32_t contractId, uint32_t collateralCurrency) { int64_t shortPosition = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE); int64_t longPosition = getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE); PrintToLog("shortPosition before: %d\n",shortPosition); PrintToLog("longPosition before: %d\n",longPosition); LOCK(cs_tally); // Clearing the position unsigned int idx=0; if (shortPosition > 0 && longPosition == 0){ PrintToLog("Short Position closing...\n"); ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, shortPosition, block, txid, idx,BUY, 0); } else if (longPosition > 0 && shortPosition == 0){ PrintToLog("Long Position closing...\n"); ContractDex_ADD_MARKET_PRICE(sender_addr,contractId, longPosition, block, txid, idx, SELL, 0); } // cleaning liquidation price int64_t liqPrice = getMPbalance(sender_addr,contractId, LIQUIDATION_PRICE); if (liqPrice > 0){ update_tally_map(sender_addr, contractId, -liqPrice, LIQUIDATION_PRICE); } //realized the UPNL int64_t upnl = 0; int64_t ppnl = getMPbalance(sender_addr, contractId, UPNL); int64_t nupnl = getMPbalance(sender_addr, contractId, NUPNL); (ppnl > 0) ? upnl = ppnl : upnl = nupnl ; if (upnl > 0){ update_tally_map(sender_addr, contractId, -upnl, UPNL); update_tally_map(sender_addr, contractId, upnl, REALIZED_PROFIT); PrintToLog("profits: %d\n",upnl); } else if (upnl < 0) { update_tally_map(sender_addr,contractId, upnl, UPNL); update_tally_map(sender_addr, contractId, -upnl, REALIZED_LOSSES); PrintToLog("losses: %d\n",upnl); } int64_t shortPositionAf = getMPbalance(sender_addr,contractId, NEGATIVE_BALANCE); int64_t longPositionAf= getMPbalance(sender_addr,contractId, POSSITIVE_BALANCE); PrintToLog("shortPosition Now: %d\n",shortPositionAf); PrintToLog("longPosition Now: %d\n",longPositionAf); if (shortPositionAf == 0 && longPositionAf == 0){ PrintToLog("POSITION CLOSED!!!\n"); } else { PrintToLog("ERROR: Position partialy Closed\n"); } return 0; } // // /** // * Scans the orderbook and removes every all-pair order // */ // int mastercore::MetaDEx_SHUTDOWN_ALLPAIR() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // md_PricesMap& prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set& indexes = it->second; // for (md_Set::iterator it = indexes.begin(); it != indexes.end();) { // if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // } // return rc; // } // // /////////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_SHUTDOWN_ALLPAIR() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = it->second; // for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // if (it->getDesProperty() > OMNI_PROPERTY_TMSC && it->getProperty() > OMNI_PROPERTY_TMSC) { // no OMNI/TOMNI side to the trade // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // } // return rc; // } // /////////////////////////////////// // // /** // * Scans the orderbook and removes every order // */ // int mastercore::MetaDEx_SHUTDOWN() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // md_PricesMap& prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set& indexes = it->second; // for (md_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // return rc; // } // // ////////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_SHUTDOWN() // { // int rc = 0; // PrintToLog("%s()\n", __FUNCTION__); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = it->second; // for (cd_Set::iterator it = indexes.begin(); it != indexes.end();) { // PrintToLog("%s(): REMOVING %s\n", __FUNCTION__, it->ToString()); // // move from reserve to balance // assert(update_tally_map(it->getAddr(), it->getProperty(), -it->getAmountRemaining(), METADEX_RESERVE)); // assert(update_tally_map(it->getAddr(), it->getProperty(), it->getAmountRemaining(), BALANCE)); // indexes.erase(it++); // } // } // } // return rc; // } // ////////////////////////////////// // // // searches the metadex maps to see if a trade is still open // // allows search to be optimized if propertyIdForSale is specified // bool mastercore::MetaDEx_isOpen(const uint256& txid, uint32_t propertyIdForSale) // { // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue; // md_PricesMap & prices = my_it->second; // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // md_Set & indexes = (it->second); // for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // CMPMetaDEx obj = *it; // if( obj.getHash().GetHex() == txid.GetHex() ) return true; // } // } // } // return false; // } // // ///////////////////////////////////// // /** New things for Contracts */ // bool mastercore::ContractDex_isOpen(const uint256& txid, uint32_t propertyIdForSale) // { // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // if (propertyIdForSale != 0 && propertyIdForSale != my_it->first) continue; // cd_PricesMap &prices = my_it->second; // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // cd_Set &indexes = (it->second); // for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // CMPContractDex obj = *it; // if( obj.getHash().GetHex() == txid.GetHex() ) return true; // } // } // } // return false; // } // //////////////////////////////////// // // /** // * Returns a string describing the status of a trade // * // */ // std::string mastercore::MetaDEx_getStatusText(int tradeStatus) // { // switch (tradeStatus) { // case TRADE_OPEN: return "open"; // case TRADE_OPEN_PART_FILLED: return "open part filled"; // case TRADE_FILLED: return "filled"; // case TRADE_CANCELLED: return "cancelled"; // case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled"; // case TRADE_INVALID: return "trade invalid"; // default: return "unknown"; // } // } // // //////////////////////////////// // /** New things for Contracts */ // std::string mastercore::ContractDex_getStatusText(int tradeStatus) // { // switch (tradeStatus) { // case TRADE_OPEN: return "open"; // case TRADE_OPEN_PART_FILLED: return "open part filled"; // case TRADE_FILLED: return "filled"; // case TRADE_CANCELLED: return "cancelled"; // case TRADE_CANCELLED_PART_FILLED: return "cancelled part filled"; // case TRADE_INVALID: return "trade invalid"; // default: return "unknown"; // } // } // //////////////////////////////// // // /** // * Returns the status of a MetaDEx trade // * // */ // int mastercore::MetaDEx_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold) // { // // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of // // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups. // if (totalSold == -1) { // UniValue tradeArray(UniValue::VARR); // int64_t totalReceived; // t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived); // } // // // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds) // if (!getValidMPTX(txid)) return TRADE_INVALID; // // // Calculate and return the status of the trade via the amount sold and open/closed attributes. // if (MetaDEx_isOpen(txid, propertyIdForSale)) { // if (totalSold == 0) { // return TRADE_OPEN; // } else { // return TRADE_OPEN_PART_FILLED; // } // } else { // if (totalSold == 0) { // return TRADE_CANCELLED; // } else if (totalSold < amountForSale) { // return TRADE_CANCELLED_PART_FILLED; // } else { // return TRADE_FILLED; // } // } // } // // /////////////////////////////// // /** New things for Contracts */ // int mastercore::ContractDex_getStatus(const uint256& txid, uint32_t propertyIdForSale, int64_t amountForSale, int64_t totalSold) // { // // NOTE: If the calling code is already aware of the total amount sold, pass the value in to this function to avoid duplication of // // work. If the calling code doesn't know the amount, leave default (-1) and we will calculate it from levelDB lookups. // if (totalSold == -1) { // UniValue tradeArray(UniValue::VARR); // int64_t totalReceived; // t_tradelistdb->getMatchingTrades(txid, propertyIdForSale, tradeArray, totalSold, totalReceived); // } // // // Return a "trade invalid" status if the trade was invalidated at parsing/interpretation (eg insufficient funds) // if (!getValidMPTX(txid)) return TRADE_INVALID; // // // Calculate and return the status of the trade via the amount sold and open/closed attributes. // if (ContractDex_isOpen(txid, propertyIdForSale)) { // if (totalSold == 0) { // return TRADE_OPEN; // } else { // return TRADE_OPEN_PART_FILLED; // } // } else { // if (totalSold == 0) { // return TRADE_CANCELLED; // } else if (totalSold < amountForSale) { // return TRADE_CANCELLED_PART_FILLED; // } else { // return TRADE_FILLED; // } // } // } // /////////////////////////////// // // void mastercore::MetaDEx_debug_print(bool bShowPriceLevel, bool bDisplay) // { // PrintToLog("<<<\n"); // for (md_PropertiesMap::iterator my_it = metadex.begin(); my_it != metadex.end(); ++my_it) { // uint32_t prop = my_it->first; // // PrintToLog(" ## property: %u\n", prop); // md_PricesMap& prices = my_it->second; // // for (md_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // rational_t price = it->first; // md_Set& indexes = it->second; // // if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price)); // // for (md_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // const CMPMetaDEx& obj = *it; // // if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString()); // else PrintToLog("%s= %s\n", xToString(price), obj.ToString()); // } // } // } // PrintToLog(">>>\n"); // } // // ///////////////////////////////////// // /** New things for Contracts */ // void mastercore::ContractDex_debug_print(bool bShowPriceLevel, bool bDisplay) // { // PrintToLog("<<<\n"); // for (cd_PropertiesMap::iterator my_it = contractdex.begin(); my_it != contractdex.end(); ++my_it) { // uint32_t prop = my_it->first; // // PrintToLog(" ## property: %u\n", prop); // cd_PricesMap &prices = my_it->second; // // for (cd_PricesMap::iterator it = prices.begin(); it != prices.end(); ++it) { // uint64_t price = it->first; // cd_Set &indexes = it->second; // // if (bShowPriceLevel) PrintToLog(" # Price Level: %s\n", xToString(price)); // // for (cd_Set::iterator it = indexes.begin(); it != indexes.end(); ++it) { // const CMPContractDex &obj = *it; // // if (bDisplay) PrintToConsole("%s= %s\n", xToString(price), obj.ToString()); // else PrintToLog("%s= %s\n", xToString(price), obj.ToString()); // } // } // } // PrintToLog(">>>\n"); // } // ///////////////////////////////////// // // /** // * Locates a trade in the MetaDEx maps via txid and returns the trade object // * // */ // const CMPMetaDEx* mastercore::MetaDEx_RetrieveTrade(const uint256& txid) // { // for (md_PropertiesMap::iterator propIter = metadex.begin(); propIter != metadex.end(); ++propIter) { // md_PricesMap & prices = propIter->second; // for (md_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) { // md_Set & indexes = pricesIter->second; // for (md_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) { // if (txid == (*tradesIter).getHash()) return &(*tradesIter); // } // } // } // return (CMPMetaDEx*) NULL; // } // // //////////////////////////////////////// // /** New things for Contracts */ // const CMPContractDex* mastercore::ContractDex_RetrieveTrade(const uint256& txid) // { // for (cd_PropertiesMap::iterator propIter = contractdex.begin(); propIter != contractdex.end(); ++propIter) { // cd_PricesMap &prices = propIter->second; // for (cd_PricesMap::iterator pricesIter = prices.begin(); pricesIter != prices.end(); ++pricesIter) { // cd_Set &indexes = pricesIter->second; // for (cd_Set::iterator tradesIter = indexes.begin(); tradesIter != indexes.end(); ++tradesIter) { // if (txid == (*tradesIter).getHash()) return &(*tradesIter); // } // } // } // return (CMPContractDex*) NULL; // } ////////////////////////////////////////
39.818221
311
0.625448
TradeLayer
0ea35e383669db72128e85e9a2040af441dae97e
11,050
cpp
C++
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/geometry/box.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/geometry/box.h" #include "nau/math/vec3.h" #include "nau/geometry/vertexData.h" #include "nau/material/materialGroup.h" using namespace nau::geometry; using namespace nau::math; using namespace nau::render; using namespace nau::material; Box::Box(void) : Primitive() { float n = 1.0f; std::shared_ptr<std::vector<VertexData::Attr>> vertices = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> tangent = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> textureCoords = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); std::shared_ptr<std::vector<VertexData::Attr>> normals = std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(24)); // FRONT vertices->at (Box::FACE_FRONT + Box::TOP_LEFT).set (-n, n, n); vertices->at (Box::FACE_FRONT + Box::TOP_RIGHT).set ( n, n, n); vertices->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set ( n, -n, n); vertices->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (-n, -n, n); tangent->at (Box::FACE_FRONT + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_FRONT + Box::TOP_LEFT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::TOP_RIGHT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, n, 0.0f); normals->at (Box::FACE_FRONT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, n, 0.0f); //LEFT vertices->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, n, -n); vertices->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, n, n); vertices->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, -n, n); vertices->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, -n, -n); tangent->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, 1.0f, 0.0f); tangent->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 1.0f, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::TOP_LEFT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::TOP_RIGHT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::BOTTOM_RIGHT).set (-n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_LEFT + Box::BOTTOM_LEFT).set (-n, 0.0f, 0.0f, 0.0f); //BACK vertices->at (Box::FACE_BACK + Box::TOP_LEFT).set ( n, n, -n); vertices->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-n, n, -n); vertices->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-n, -n,-n); vertices->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set ( n, -n,-n); tangent->at (Box::FACE_BACK + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_BACK + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_BACK + Box::TOP_LEFT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::TOP_RIGHT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -n, 0.0f); normals->at (Box::FACE_BACK + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -n, 0.0f); //RIGHT vertices->at (Box::FACE_RIGHT + Box::TOP_LEFT).set ( n, n, n); vertices->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set ( n, n, -n); vertices->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set ( n, -n,-n); vertices->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set ( n, -n, n); tangent->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (0.0f, 0.0f, -1.0f, 0.0f); tangent->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, -1.0f, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::TOP_LEFT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::TOP_RIGHT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f, 0.0f); normals->at (Box::FACE_RIGHT + Box::BOTTOM_LEFT).set (n, 0.0f, 0.0f, 0.0f); //TOP vertices->at (Box::FACE_TOP + Box::TOP_LEFT).set (-n, n, -n); vertices->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( n, n, -n); vertices->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set( n, n, n); vertices->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (-n, n, n); tangent->at (Box::FACE_TOP + Box::TOP_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::TOP_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_TOP + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_TOP + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::TOP_LEFT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::TOP_RIGHT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::BOTTOM_RIGHT).set ( 0.0f, n, 0.0f, 0.0f); normals->at (Box::FACE_TOP + Box::BOTTOM_LEFT).set ( 0.0f, n, 0.0f, 0.0f); //BOTTOM vertices->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-n, -n, n); vertices->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( n, -n, n); vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( n, -n, -n); vertices->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-n, -n, -n); tangent->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (-1.0f, 0.0f, 0.0f, 0.0f); tangent->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (-1.0f, 0.0f, 0.0f, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set (0.0f, n, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set (n, n, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set (n, 0.0f, 0.0f); textureCoords->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::TOP_LEFT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::TOP_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::BOTTOM_RIGHT).set ( 0.0f, -n, 0.0f, 0.0f); normals->at (Box::FACE_BOTTOM + Box::BOTTOM_LEFT).set ( 0.0f, -n, 0.0f, 0.0f); std::shared_ptr<VertexData> &vertexData = getVertexData(); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("position")), vertices); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("texCoord0")), textureCoords); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("tangent")), tangent); vertexData->setDataFor (VertexData::GetAttribIndex(std::string("normal")), normals); std::shared_ptr<MaterialGroup> aMaterialGroup = MaterialGroup::Create(this, "__Light Grey"); std::shared_ptr<std::vector<unsigned int>> indices = std::shared_ptr<std::vector<unsigned int>>(new std::vector<unsigned int>(36)); //FRONT indices->at (0) = Box::FACE_FRONT + Box::TOP_LEFT; indices->at (1) = Box::FACE_FRONT + Box::BOTTOM_LEFT; indices->at (2) = Box::FACE_FRONT + Box::TOP_RIGHT; indices->at (3) = Box::FACE_FRONT + Box::BOTTOM_LEFT; indices->at (4) = Box::FACE_FRONT + Box::BOTTOM_RIGHT; indices->at (5) = Box::FACE_FRONT + Box::TOP_RIGHT; //LEFT indices->at (6) = Box::FACE_LEFT + Box::TOP_LEFT; indices->at (7) = Box::FACE_LEFT + Box::BOTTOM_LEFT; indices->at (8) = Box::FACE_LEFT + Box::TOP_RIGHT; indices->at (9) = Box::FACE_LEFT + Box::BOTTOM_LEFT; indices->at (10)= Box::FACE_LEFT + Box::BOTTOM_RIGHT; indices->at (11)= Box::FACE_LEFT + Box::TOP_RIGHT; //BACK indices->at (12)= Box::FACE_BACK + Box::TOP_LEFT; indices->at (13)= Box::FACE_BACK + Box::BOTTOM_LEFT; indices->at (14)= Box::FACE_BACK + Box::TOP_RIGHT; indices->at (15)= Box::FACE_BACK + Box::BOTTOM_LEFT; indices->at (16)= Box::FACE_BACK + Box::BOTTOM_RIGHT; indices->at (17)= Box::FACE_BACK + Box::TOP_RIGHT; //RIGHT indices->at (18)= Box::FACE_RIGHT + Box::TOP_LEFT; indices->at (19)= Box::FACE_RIGHT + Box::BOTTOM_LEFT; indices->at (20)= Box::FACE_RIGHT + Box::TOP_RIGHT; indices->at (21)= Box::FACE_RIGHT + Box::BOTTOM_LEFT; indices->at (22)= Box::FACE_RIGHT + Box::BOTTOM_RIGHT; indices->at (23)= Box::FACE_RIGHT + Box::TOP_RIGHT; //TOP indices->at (24)= Box::FACE_TOP + Box::TOP_LEFT; indices->at (25)= Box::FACE_TOP + Box::BOTTOM_LEFT; indices->at (26)= Box::FACE_TOP + Box::TOP_RIGHT; indices->at (27)= Box::FACE_TOP + Box::BOTTOM_LEFT; indices->at (28)= Box::FACE_TOP + Box::BOTTOM_RIGHT; indices->at (29)= Box::FACE_TOP + Box::TOP_RIGHT; //BOTTOM indices->at (30)= Box::FACE_BOTTOM + Box::TOP_LEFT; indices->at (31)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT; indices->at (32)= Box::FACE_BOTTOM + Box::TOP_RIGHT; indices->at (33)= Box::FACE_BOTTOM + Box::BOTTOM_LEFT; indices->at (34)= Box::FACE_BOTTOM + Box::BOTTOM_RIGHT; indices->at (35)= Box::FACE_BOTTOM + Box::TOP_RIGHT; aMaterialGroup->setIndexList (indices); addMaterialGroup (aMaterialGroup); } Box::~Box(void) { } std::string Box::getClassName() { return "Box"; } void Box::build() { }
45.661157
94
0.648507
Khirion
0ea607cca50a5692e75e755921ca22a0149d13c8
1,129
cpp
C++
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Improvement.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "./INCLUDE/Segment.h" #include "./INCLUDE/LKH.h" /* The Improvement function is used to check whether a done move * has improved the current best tour. * If the tour has been improved, the function computes the penalty gain * and returns 1. Otherwise, the move is undone, and the function returns 0. */ int LKH::LKHAlg::Improvement(GainType * Gain, Node * t1, Node * SUCt1) { GainType NewPenalty; if (!Penalty) { if (*Gain > 0) return 1; RestoreTour(); if (SUC(t1) != SUCt1) Reversed ^= 1; *Gain = PenaltyGain = 0; return 0; } CurrentGain = *Gain; NewPenalty = (this->*Penalty)(); if (NewPenalty <= CurrentPenalty) { if (TSPTW_Makespan) *Gain = (TSPTW_CurrentMakespanCost - TSPTW_MakespanCost()) * Precision; if (NewPenalty < CurrentPenalty || *Gain > 0) { PenaltyGain = CurrentPenalty - NewPenalty; return 1; } } RestoreTour(); if (SUC(t1) != SUCt1) Reversed ^= 1; *Gain = PenaltyGain = 0; return 0; }
27.536585
76
0.568645
BaiChunhui-9803
0ea62fc4b26eb67e890657b54df620d6c40fa9d8
1,513
hpp
C++
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
21
2020-05-02T06:32:23.000Z
2021-07-14T11:22:07.000Z
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
null
null
null
kernels/backend/cuda/image.hpp
wchang22/Nova
3db1e8f8a0dea1dcdd3d3d02332534d5945e17bb
[ "MIT" ]
1
2021-05-24T13:44:56.000Z
2021-05-24T13:44:56.000Z
#ifndef KERNELS_BACKEND_CUDA_IMAGE_HPP #define KERNELS_BACKEND_CUDA_IMAGE_HPP #include "kernels/backend/common/image.hpp" namespace nova { using image2d_read_t = cudaTextureObject_t; using image2d_write_t = cudaSurfaceObject_t; using image2d_array_read_t = cudaTextureObject_t; template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const int2& coords) { return tex2D<W>(image, coords.x, coords.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const float2& coords) { return tex2D<W>(image, coords.x, coords.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_read_t image, const float2& coords, const float2& offset) { return tex2D<W>(image, coords.x + offset.x, coords.y + offset.y); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_array_read_t image, const int2& coords, int index) { return tex2DLayered<W>(image, coords.x, coords.y, index); } template <typename W, AddressMode A = AddressMode::CLAMP> __device__ constexpr W read_image(image2d_array_read_t image, const float2& coords, int index) { return tex2DLayered<W>(image, coords.x, coords.y, index); } template <typename U> __device__ constexpr void write_image(image2d_write_t image, const int2& coords, const U& value) { surf2Dwrite(value, image, coords.x * sizeof(U), coords.y); } } #endif
33.622222
98
0.775942
wchang22
0eaa4e824dee738f47dfa9f67731e15a3043df38
1,855
cpp
C++
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
743
2021-08-02T16:27:27.000Z
2022-03-31T16:34:16.000Z
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
32
2021-08-03T04:47:20.000Z
2022-03-28T23:15:45.000Z
inceptor/templates/public/cpp/process_injection/classic-native-syscalls.cpp
whitefi/inceptor
2234740b76c34b2ab91d05ff675748022c476a81
[ "BSD-4-Clause" ]
138
2021-08-02T16:27:28.000Z
2022-03-31T02:47:20.000Z
#include <Windows.h> #include <stdio.h> #include <stdlib.h> //####USING#### #pragma comment(lib, "ntdll") //####DEFINE#### //####CODE#### int Inject(int pid) { const unsigned char raw[] = ####SHELLCODE####; int length = sizeof(raw); unsigned char* encoded = (unsigned char*)malloc(sizeof(unsigned char) * length * 2); memcpy(encoded, raw, length); //####CALL#### unsigned char* decoded = encoded; unsigned long size = 4096; LARGE_INTEGER sectionSize = { size }; HANDLE sectionHandle = NULL; PVOID localSectionAddress = NULL, remoteSectionAddress = NULL; SIZE_T RegionSize = (SIZE_T)length; LPVOID allocation_start = nullptr; NTSTATUS status; HANDLE targetHandle = OpenProcess(PROCESS_ALL_ACCESS, false, pid); if (targetHandle == 0){ printf("[-] Invalid Target Handle"); exit(1); } status = NtAllocateVirtualMemory(targetHandle, &allocation_start, 0, (PSIZE_T)&RegionSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (status < 0){ printf("[-] Memory allocation failed"); exit(1); } status = NtWriteVirtualMemory(targetHandle, allocation_start, decoded, length, 0); if (status < 0){ printf("[-] Memory writing failed"); exit(1); } HANDLE targetThreadHandle = NULL; NtCreateThreadEx(&targetThreadHandle, GENERIC_EXECUTE, NULL, targetHandle, allocation_start, allocation_start, FALSE, NULL, NULL, NULL, NULL); if (targetThreadHandle == NULL){ printf("[-] Invalid Thread Handle"); exit(1); } return 0; } int main(int argc, char** argv) { //####DELAY#### //####ANTIDEBUG#### //####UNHOOK#### //####ARGS#### int pid = 0; if (argc < 2) { printf("[-] Missing PID... Finding...\n"); //####FIND_PROCESS#### }else{ pid = atoi(argv[1]); } if (pid == 0){ printf("[-] Process not found\n"); exit(1); } Inject(pid); }
21.569767
143
0.633962
whitefi
0eb628c74491a49e649fd4f44d9910783a851d2c
3,188
cpp
C++
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
packages/thirdParty/wxWidgets/wxWidgets-2.9.4/src/common/checkboxcmn.cpp
wivlaro/newton-dynamics
2bafd29aea919f237e56784510db1cb8011d0f40
[ "Zlib" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/common/checkboxcmn.cpp // Purpose: wxCheckBox common code // Author: Julian Smart // Modified by: // Created: 04/01/98 // RCS-ID: $Id$ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_CHECKBOX #include "wx/checkbox.h" extern WXDLLEXPORT_DATA(const char) wxCheckBoxNameStr[] = "check"; // ---------------------------------------------------------------------------- // XTI // ---------------------------------------------------------------------------- wxDEFINE_FLAGS( wxCheckBoxStyle ) wxBEGIN_FLAGS( wxCheckBoxStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxNO_BORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxNO_FULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxEND_FLAGS( wxCheckBoxStyle ) wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxCheckBox, wxControl, "wx/checkbox.h") wxBEGIN_PROPERTIES_TABLE(wxCheckBox) wxEVENT_PROPERTY( Click, wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEvent ) wxPROPERTY( Font, wxFont, SetFont, GetFont, wxEMPTY_PARAMETER_VALUE, \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY( Label,wxString, SetLabel, GetLabel, wxString(), \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY( Value,bool, SetValue, GetValue, wxEMPTY_PARAMETER_VALUE, \ 0 /*flags*/, wxT("Helpstring"), wxT("group")) wxPROPERTY_FLAGS( WindowStyle, wxCheckBoxStyle, long, SetWindowStyleFlag, \ GetWindowStyleFlag, wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \ wxT("Helpstring"), wxT("group")) // style wxEND_PROPERTIES_TABLE() wxEMPTY_HANDLERS_TABLE(wxCheckBox) wxCONSTRUCTOR_6( wxCheckBox, wxWindow*, Parent, wxWindowID, Id, \ wxString, Label, wxPoint, Position, wxSize, Size, long, WindowStyle ) #endif // wxUSE_CHECKBOX
34.652174
86
0.572459
wivlaro
0eb66e44a2618868d454cbc92f49a0c67f9f43d4
4,805
cpp
C++
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/Visual C++ 2008 Feature Pack/StateCollection/StateCollectionView.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "StateCollection.h" #include "StateCollectionDoc.h" #include "StateCollectionView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static const CString strInfo = _T("This sample illustrates how to save/load the current configuration on the fly.\r\n") _T("You can configure two 'environments' - Regular and Debug.\r\n") _T("Just customize the toolbar/menu/docking bars and select 'Project|Save Debug' or 'Project|Save Regular'.\r\n") _T("When you want to switch between configurations select 'Project|Load Debug' or 'Project|Load Regular'.\r\n") _T("When the application is starting up, it loads the default configuration.\r\n\r\n") _T("Note the use of CWinAppEx::LoadState/SaveState."); ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView IMPLEMENT_DYNCREATE(CStateCollectionView, CView) BEGIN_MESSAGE_MAP(CStateCollectionView, CView) ON_WM_LBUTTONDBLCLK() ON_WM_CONTEXTMENU() // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView construction/destruction CStateCollectionView::CStateCollectionView() { // TODO: add construction code here } CStateCollectionView::~CStateCollectionView() { } BOOL CStateCollectionView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView drawing void CStateCollectionView::OnDraw(CDC* pDC) { // CStateCollectionDoc* pDoc = GetDocument(); // ASSERT_VALID(pDoc); const int iOffset = 20; CFont* pFontOld = (CFont*) pDC->SelectStockObject (DEFAULT_GUI_FONT); ASSERT (pFontOld != NULL); CRect rectClient; GetClientRect (&rectClient); CRect rectText = rectClient; rectText.DeflateRect (iOffset, iOffset); pDC->DrawText (strInfo, rectText, DT_CALCRECT | DT_WORDBREAK); rectText.OffsetRect ( (rectClient.Width () - rectText.Width () - 2 * iOffset) / 2, (rectClient.Height () - rectText.Height () - 2 * iOffset) / 2); CRect rectFrame = rectText; rectFrame.InflateRect (iOffset, iOffset); pDC->FillSolidRect (rectFrame, ::GetSysColor (COLOR_INFOBK)); rectFrame.DeflateRect (1, 1); pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW), ::GetSysColor (COLOR_3DLIGHT)); rectFrame.DeflateRect (2, 2); pDC->Draw3dRect (rectFrame, ::GetSysColor (COLOR_3DSHADOW), ::GetSysColor (COLOR_3DLIGHT)); pDC->SetTextColor (::GetSysColor (COLOR_INFOTEXT)); pDC->SetBkMode (TRANSPARENT); pDC->DrawText (strInfo, rectText, DT_WORDBREAK); pDC->SelectObject (pFontOld); } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView printing void CStateCollectionView::OnFilePrintPreview() { AFXPrintPreview (this); } BOOL CStateCollectionView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CStateCollectionView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CStateCollectionView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView diagnostics #ifdef _DEBUG void CStateCollectionView::AssertValid() const { CView::AssertValid(); } void CStateCollectionView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CStateCollectionDoc* CStateCollectionView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CStateCollectionDoc))); return (CStateCollectionDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CStateCollectionView message handlers void CStateCollectionView::OnLButtonDblClk(UINT /*nFlags*/, CPoint /*point*/) { theApp.OnViewDoubleClick (this, IDR_MAINFRAME); } void CStateCollectionView::OnContextMenu(CWnd*, CPoint point) { theApp.ShowPopupMenu (IDR_CONTEXT_MENU, point, this); }
28.772455
114
0.688033
alonmm
0eb8410a4bd9546f67f93f6ca9fcf994bbce4171
1,329
hh
C++
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
6
2016-09-28T18:26:42.000Z
2021-04-10T13:19:05.000Z
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
1
2021-02-09T00:24:04.000Z
2021-02-27T22:08:05.000Z
include/Attributes/CreationDateAttribute.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
5
2017-09-14T09:48:17.000Z
2021-07-19T07:58:34.000Z
/* * Copyright 2021 Aaron Bamberger * Licensed under BSD 2-clause license * See LICENSE file at root of source tree, * or https://opensource.org/licenses/BSD-2-Clause */ #ifndef _CREATION_DATE_ATTRIBUTE_H #define _CREATION_DATE_ATTRIBUTE_H #include "Attributes/StandardAttribute.hh" #include "Util/ValueWithLocation.hh" #include "location.hh" #include <string> #include <cstdint> // TODO: Consider rewriting this to use a standard date/time library, such as boost::date class CreationDateAttribute : public StandardAttribute { public: CreationDateAttribute(ValueWithLocation<std::uint16_t> year, ValueWithLocation<std::uint8_t> month, ValueWithLocation<std::uint8_t> day, ValueWithLocation<std::uint8_t> hour, ValueWithLocation<std::uint8_t> minute, ValueWithLocation<std::uint8_t> second, ValueWithLocation<std::int8_t> utc_offset, yy::location name_location = yy::location()); virtual ~CreationDateAttribute(); private: ValueWithLocation<std::uint16_t> m_year; ValueWithLocation<std::uint8_t> m_month; ValueWithLocation<std::uint8_t> m_day; ValueWithLocation<std::uint8_t> m_hour; ValueWithLocation<std::uint8_t> m_minute; ValueWithLocation<std::uint8_t> m_second; ValueWithLocation<std::int8_t> m_utc_offset; }; #endif // _CREATION_DATE_ATTRIBUTE_H
30.906977
89
0.762227
aaronbamberger
0eb9802deb40156a423cdb6c4308eaaa24d2e0a0
2,848
hpp
C++
src/pathfinder/yapf/yapf_node.hpp
trademarks/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
8
2016-10-21T09:01:43.000Z
2021-05-31T06:32:14.000Z
src/pathfinder/yapf/yapf_node.hpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
null
null
null
src/pathfinder/yapf/yapf_node.hpp
blackberry/OpenTTD
fd7fca73cf61a2960e8df8fa221b179d23ae3ef0
[ "Unlicense" ]
4
2017-05-16T00:15:58.000Z
2020-08-06T01:46:31.000Z
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file yapf_node.hpp Node in the pathfinder's graph. */ #ifndef YAPF_NODE_HPP #define YAPF_NODE_HPP /** Yapf Node Key that evaluates hash from (and compares) tile & exit dir. */ struct CYapfNodeKeyExitDir { TileIndex m_tile; Trackdir m_td; DiagDirection m_exitdir; FORCEINLINE void Set(TileIndex tile, Trackdir td) { m_tile = tile; m_td = td; m_exitdir = (m_td == INVALID_TRACKDIR) ? INVALID_DIAGDIR : TrackdirToExitdir(m_td); } FORCEINLINE int CalcHash() const {return m_exitdir | (m_tile << 2);} FORCEINLINE bool operator == (const CYapfNodeKeyExitDir& other) const {return (m_tile == other.m_tile) && (m_exitdir == other.m_exitdir);} void Dump(DumpTarget &dmp) const { dmp.WriteTile("m_tile", m_tile); dmp.WriteEnumT("m_td", m_td); dmp.WriteEnumT("m_exitdir", m_exitdir); } }; struct CYapfNodeKeyTrackDir : public CYapfNodeKeyExitDir { FORCEINLINE int CalcHash() const {return m_td | (m_tile << 4);} FORCEINLINE bool operator == (const CYapfNodeKeyTrackDir& other) const {return (m_tile == other.m_tile) && (m_td == other.m_td);} }; /** Yapf Node base */ template <class Tkey_, class Tnode> struct CYapfNodeT { typedef Tkey_ Key; typedef Tnode Node; Tkey_ m_key; Node *m_hash_next; Node *m_parent; int m_cost; int m_estimate; FORCEINLINE void Set(Node *parent, TileIndex tile, Trackdir td, bool is_choice) { m_key.Set(tile, td); m_hash_next = NULL; m_parent = parent; m_cost = 0; m_estimate = 0; } FORCEINLINE Node *GetHashNext() {return m_hash_next;} FORCEINLINE void SetHashNext(Node *pNext) {m_hash_next = pNext;} FORCEINLINE TileIndex GetTile() const {return m_key.m_tile;} FORCEINLINE Trackdir GetTrackdir() const {return m_key.m_td;} FORCEINLINE const Tkey_& GetKey() const {return m_key;} FORCEINLINE int GetCost() const {return m_cost;} FORCEINLINE int GetCostEstimate() const {return m_estimate;} FORCEINLINE bool operator < (const Node& other) const {return m_estimate < other.m_estimate;} void Dump(DumpTarget &dmp) const { dmp.WriteStructT("m_key", &m_key); dmp.WriteStructT("m_parent", m_parent); dmp.WriteLine("m_cost = %d", m_cost); dmp.WriteLine("m_estimate = %d", m_estimate); } }; #endif /* YAPF_NODE_HPP */
33.505882
185
0.719803
trademarks
0ebccddc4beac9cf4894a7fa75aef1120720436a
7,956
cpp
C++
Pod/musicFramework/impl/EncodingFunctions.cpp
iKimee/musicXML
5555f5c00e74c8e3f5ddf7e83072bf208602b970
[ "Apache-2.0" ]
3
2018-12-18T06:38:57.000Z
2022-01-25T10:42:19.000Z
Pod/musicFramework/impl/EncodingFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
null
null
null
Pod/musicFramework/impl/EncodingFunctions.cpp
Bone111/MusicXMLParser
674f6b52634abb95008cc04ee02f4df0055851a6
[ "MIT" ]
1
2021-01-29T10:43:31.000Z
2021-01-29T10:43:31.000Z
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "../impl/EncodingFunctions.h" #include "../core/Date.h" #include "../core/elements/Encoder.h" #include "../core/elements/Encoding.h" #include "../core/elements/Encoding.h" #include "../core/elements/EncodingChoice.h" #include "../core/elements/EncodingDate.h" #include "../core/elements/EncodingDescription.h" #include "../core/elements/Identification.h" #include "../core/elements/Software.h" #include "../core/elements/Supports.h" #include "../core/elements/MiscellaneousField.h" #include "../core/elements/Miscellaneous.h" namespace mx { namespace impl { void createEncoding( const api::EncodingData& inEncoding, core::ScoreHeaderGroup& header ) { auto identification = header.getIdentification(); auto encoding = identification->getEncoding(); if( !inEncoding.encoder.empty() ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encoder ); item->getEncoder()->setValue( core::XsString( inEncoding.encoder ) ); encoding->addEncodingChoice( item ); } core::Date tryDate{ inEncoding.encodingDate.year, inEncoding.encodingDate.month, inEncoding.encodingDate.day }; const bool isYearValid = inEncoding.encodingDate.year == tryDate.getYear(); const bool isMonthValid = inEncoding.encodingDate.month == tryDate.getMonth(); const bool isDayValid = inEncoding.encodingDate.day == tryDate.getDay(); if( isYearValid || isMonthValid || isDayValid ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encodingDate ); item->getEncodingDate()->setValue( tryDate ); encoding->addEncodingChoice( item ); } if( !inEncoding.encodingDescription.empty() ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::encodingDescription ); item->getEncodingDescription()->setValue( core::XsString( inEncoding.encodingDescription ) ); encoding->addEncodingChoice( item ); } for( const auto& s : inEncoding.software ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::software ); item->getSoftware()->setValue( core::XsString( s ) ); encoding->addEncodingChoice( item ); } for ( const auto& s : inEncoding.supportedItems ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); auto item = core::makeEncodingChoice(); item->setChoice( core::EncodingChoice::Choice::supports ); auto supports = item->getSupports(); auto attributes = supports->getAttributes(); if ( !s.elementName.empty() ) { attributes->element.setValue( s.elementName ); } if ( !s.attributeName.empty() ) { attributes->hasAttribute = true; attributes->attribute.setValue( s.attributeName ); } if ( !s.specificValue.empty() ) { attributes->hasValue = true; attributes->value.setValue( s.specificValue ); } attributes->type = s.isSupported ? core::YesNo::yes : core::YesNo::no; encoding->addEncodingChoice( item ); } for ( const auto& m : inEncoding.miscelaneousFields ) { header.setHasIdentification( true ); identification->setHasEncoding( true ); identification->setHasMiscellaneous( true ); auto item = core::makeMiscellaneousField(); item->getAttributes()->name.setValue( m.key ); item->setValue( core::XsString{ m.value } ); identification->getMiscellaneous()->addMiscellaneousField( item ); } } api::EncodingData createEncoding( const core::Encoding& inEncoding ) { api::EncodingData outEncoding; bool isDateFound = false; bool isEncoderFound = false; bool isDescriptionFound = false; for( auto ec : inEncoding.getEncodingChoiceSet() ) { switch( ec->getChoice() ) { case core::EncodingChoice::Choice::encodingDate: { if( !isDateFound ) { outEncoding.encodingDate.year = ec->getEncodingDate()->getValue().getYear(); outEncoding.encodingDate.month = ec->getEncodingDate()->getValue().getMonth(); outEncoding.encodingDate.day = ec->getEncodingDate()->getValue().getDay(); isDateFound = true; } break; } case core::EncodingChoice::Choice::encoder: { if( !isEncoderFound ) { outEncoding.encoder = ec->getEncoder()->getValue().getValue(); isEncoderFound = true; } break; } case core::EncodingChoice::Choice::encodingDescription: { if( !isDescriptionFound ) { outEncoding.encodingDescription = ec->getEncodingDescription()->getValue().getValue(); isDescriptionFound = true; } break; } case core::EncodingChoice::Choice::software: { outEncoding.software.emplace_back( ec->getSoftware()->getValue().getValue() ); break; } case core::EncodingChoice::Choice::supports: { auto supportsElement = ec->getSupports(); auto attr = supportsElement->getAttributes(); api::SupportedItem item; item.elementName = attr->element.getValue(); if( attr->hasAttribute ) { item.attributeName = attr->attribute.getValue(); } item.isSupported = ( attr->type == core::YesNo::yes ); if( attr->hasValue ) { item.specificValue = attr->value.getValue(); } outEncoding.supportedItems.push_back( std::move( item ) ); break; } } } return outEncoding; } } }
43.005405
123
0.497612
iKimee
0ebcd089e828e911c1d549990b66e6d9869c5758
584
hh
C++
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
test/DBAL/SchemaTest.hh
decouple/framework
8dcb04e75660c977ed8d53b2e6e3aa7fa5ff9b95
[ "MIT" ]
null
null
null
<?hh // partial namespace Test\DBAL; use Decouple\Test\TestCase; use Decouple\DBAL\DPDO\DPDOMySQLDriver; use Decouple\Common\Contract\DB\Schema; class SchemaTest extends TestCase { public function execute() : void { $driver = new DPDOMySQLDriver(); $connected = $driver->connect(Map { "dbname" => "decouple", "type" => "mysql", "host" => "localhost" }, "decouple", "secret"); $schema = $driver->schema('decouple'); $failed = false; if(!$schema instanceof Schema) { $failed = true; } $this->assertEquals($failed, false); } }
26.545455
42
0.630137
decouple
0ebd0a4fc260475489711501e0fde20ea7be290d
10,353
cxx
C++
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/bblist.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2009 Advanced Micro Devices, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ #include "defs.h" #include "erglob.h" #include "mempool.h" #include "bb.h" #include "cgtarget.h" #include "freq.h" #include "cg.h" /* Since sizeof(BBLIST) is 12, 670*12 = 8040, which is just under 8K. */ #define BBLISTS_PER_BLOCK 670 #define BBLIST_BLOCK_SIZE (BBLISTS_PER_BLOCK * sizeof(BBLIST)) static BBLIST *BBlist_Free_List = NULL; static INT num_bblist_buffers = 0; /* Get a BBLIST item from the free list. If the free list is empty, * allocate a new block and return the first item in the block. */ static BBLIST * bblist_alloc (void) { BBLIST *tmp_list; BBLIST *cur_item; INT i; tmp_list = BBlist_Free_List; if (tmp_list == NULL) { /* TODO: we could use Pu_Alloc instead of malloc here. If we do, we need to make sure to set BBlist_Free_List to NULL whenever we do a Pu_Free. */ tmp_list = (BBLIST *) malloc (BBLIST_BLOCK_SIZE); num_bblist_buffers++; if (tmp_list == NULL) { ErrMsg (EC_No_Mem, "bblist_alloc"); } cur_item = tmp_list; for (i = 0; i < BBLISTS_PER_BLOCK - 1; i++) { BBLIST_next(cur_item) = cur_item + 1; cur_item++; } BBLIST_next(cur_item) = NULL; } BBlist_Free_List = BBLIST_next(tmp_list); BBLIST_prob(tmp_list) = 0.0; BBLIST_next(tmp_list) = NULL; BBLIST_flags(tmp_list) = 0; return tmp_list; } #if USE_DEBUG_VERSION static void bblist_free (BBLIST *lst) { BBLIST *p; FOR_ALL_BBLIST_ITEMS (BBlist_Free_List, p) { if (p == lst) printf ("*** ERROR in bblist_free\n"); } BBLIST_next(lst) = BBlist_Free_List; BBlist_Free_List = lst; } #else #define bblist_free(lst) \ ((BBLIST_next(lst) = BBlist_Free_List), (BBlist_Free_List = lst)) #endif /* Free 'lst', and put back all its elements to the free list. */ void BBlist_Free (BBLIST **lst ) { BBLIST *tmp1, *tmp2; for (tmp1 = *lst; tmp1 != NULL; tmp1 = tmp2) { tmp2 = BBLIST_next(tmp1); bblist_free (tmp1); } *lst = NULL; } /* returns a count of the number of elements in the list. */ INT BBlist_Len (BBLIST *lst) { INT count = 0; BBLIST *p; FOR_ALL_BBLIST_ITEMS (lst, p) count++; return count; } /* Add the bb to the end of the lst. If bb was already in the lst, don't add it twice. */ BBLIST * BBlist_Add_BB (BBLIST **lst, BB *bb) { BBLIST *p, *last; p = *lst; /* check if the lst is empty, If yes put the bb into the list and return. */ if (p == NULL) { p = bblist_alloc (); BBLIST_item(p) = bb; *lst = p; return p; } /* check if the bb is already in the lst. */ last = NULL; for (;p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) return p; last = p; } /* Add the bb to the end of the lst. */ p = bblist_alloc (); BBLIST_item(p) = bb; BBLIST_next(last) = p; return p; } /* Add the bb to the end of the lst with edge probability <prob>. * If bb was already in the lst, just increment edge probability. * Edge probabilities not updated unless FREQ_Frequencies_Computed(). */ BBLIST * BBlist_Add_BB_with_Prob (BBLIST **lst, BB *bb, float prob, BOOL via_feedback, BOOL set_prob #ifdef KEY ,BOOL via_hint #endif ,BOOL incr_prob) { BBLIST *p, *last; p = *lst; /* check if the lst is empty, If yes put the bb into the list and return. */ if (p == NULL) { p = bblist_alloc (); BBLIST_item(p) = bb; if (via_feedback || CG_PU_Has_Feedback) { BBLIST_prob(p) = prob; Set_BBLIST_prob_fb_based(p); } if (set_prob || FREQ_Frequencies_Computed()) { BBLIST_prob(p) = prob; #if defined(KEY) if(via_hint) Set_BBLIST_prob_hint_based(p); #endif Reset_BBLIST_prob_fb_based(p); } *lst = p; return p; } /* check if the bb is already in the lst. */ last = NULL; for (;p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) { if (FREQ_Frequencies_Computed() && incr_prob) { BBLIST_prob(p) += prob; if (BBLIST_prob(p) >= 1.0f) BBLIST_prob(p) = 1.0f; } return p; } last = p; } /* Add the bb to the end of the lst. */ p = bblist_alloc (); BBLIST_item(p) = bb; BBLIST_next(last) = p; if (via_feedback || CG_PU_Has_Feedback) { BBLIST_prob(p) = prob; Set_BBLIST_prob_fb_based(p); } if ( #if defined(KEY) set_prob || #endif FREQ_Frequencies_Computed()) { BBLIST_prob(p) = prob; #if defined(KEY) if(via_hint) Set_BBLIST_prob_hint_based(p); #endif Reset_BBLIST_prob_fb_based(p); } return p; } static const union { INT32 i; float f; } NaN_u = { 0x7fbfffff }; static const float NaN = NaN_u.f; void Link_Pred_Succ (BB *pred, BB *succ) { Verify_BB(pred); Verify_BB(succ); BBLIST *pedge; BBlist_Add_BB (&BB_succs(pred), succ); pedge = BBlist_Add_BB (&BB_preds(succ), pred); /* Poison probability of pred edge since it is unused. */ BBLIST_prob(pedge) = NaN; } void Link_Pred_Succ_with_Prob (BB *pred, BB *succ, float prob, BOOL via_feedback, BOOL set_prob #ifdef KEY , BOOL via_hint #endif , BOOL incr_prob ) { Verify_BB(pred); Verify_BB(succ); BBLIST *pedge; BBlist_Add_BB_with_Prob (&BB_succs(pred), succ, prob, via_feedback, set_prob #ifdef KEY , via_hint #endif , incr_prob ); pedge = BBlist_Add_BB (&BB_preds(succ), pred); /* Poison probability of pred edge since it is unused. */ BBLIST_prob(pedge) = NaN; } /* Delete bb from lst. */ void BBlist_Delete_BB (BBLIST **lst, BB *bb) { BBLIST *p, *last; last = NULL; for (p = *lst; p != NULL; p = BBLIST_next(p)) { if (BBLIST_item(p) == bb) { if (last == NULL) { *lst = BBLIST_next(p); } else { BBLIST_next(last) = BBLIST_next(p); } bblist_free (p); break; } last = p; } } void Unlink_Pred_Succ (BB *pred, BB *succ) { BBlist_Delete_BB (&BB_succs(pred), succ); BBlist_Delete_BB (&BB_preds(succ), pred); } BBLIST * BBlist_Find_BB (BBLIST *lst, BB *bb) /* ----------------------------------------------------------------------- * Returns the BBLIST node in <lst> whose BBLIST_item is <bb>, or NULL * if there is none. * ----------------------------------------------------------------------- */ { BBLIST *p; FOR_ALL_BBLIST_ITEMS(lst, p) if (BBLIST_item(p) == bb) break; return p; } BBLIST * BBlist_Fall_Thru_Succ (BB *bb) /* ----------------------------------------------------------------------- * Returns a pointer to the BBLIST <node> in BB_preds(bb) such that * BBLIST_item(node) is the fall through control flow successor of * <bb>, or NULL if there is none. * ----------------------------------------------------------------------- */ { BB *next = BB_next(bb); BBLIST *node = NULL; if (next && (node = BB_Find_Succ(bb, next))) { /* Make sure it's not a branch target (direct or indirect). */ OP *br_op = BB_branch_op(bb); if (br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount == 0) { /* Indirect jump - no fall-through succ */ node = NULL; } else { TN *dest = OP_opnd(br_op, tfirst); DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount)); DevAssert(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), next)) { /* Remove useless explicit branch to <next> */ BB_Remove_Op(bb, br_op); } else { #if defined(TARG_SL) #ifndef fork_joint if(!OP_fork(br_op)) #endif #endif DevAssert(OP_cond(br_op), ("BB_succs(BB:%d) wrongly contains BB:%d", BB_id(bb), BB_id(next))); } } } } return node; } BBLIST * BBlist_Fall_Thru_Pred (BB *bb) /* ----------------------------------------------------------------------- * Returns a pointer to the BBLIST <node> in BB_preds(bb) such that * BBLIST_item(node) is the fall through control flow predecessor of * <bb>, or NULL if there is none. * ----------------------------------------------------------------------- */ { BB *prev = BB_prev(bb); BBLIST *node = NULL; if (prev && (node = BB_Find_Pred(bb, prev))) { /* Make sure <bb> is not a branch target of <prev> (direct or indirect). */ OP *br_op = BB_branch_op(prev); if (br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount == 0) { /* Indirect jump - no fall-through pred */ node = NULL; } else { TN *dest = OP_opnd(br_op, tfirst); DevAssert(tcount == 1, ("%d branch targets, expected 1", tcount)); DevAssert(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), bb)) { /* Remove useless explicit branch to <bb> */ BB_Remove_Op(prev, br_op); } else { DevAssert(OP_cond(br_op), ("BB_preds(BB:%d) wrongly contains BB:%d", BB_id(bb), BB_id(prev))); } } } } return node; }
25.007246
79
0.60736
sharugupta
b1c013defc09cbb37d164ef1765f8b0d754d5a9f
1,215
cpp
C++
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
math/get_neighbours2D.cpp
hariharanragothaman/Learning-STL
7e5f58083212d04b93159d44e1812069171aa349
[ "MIT" ]
null
null
null
#include "bits/stdc++.h" using namespace std; const std::pair<int, int> moves[] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}}; /* for(auto [dx, dy]: moves) { // Here nr and nc are what comes into the queue - i & j dx += nr; dy += nc; } */ vector<vector<int>> getNeighbours(int r, int c, int R, int C) { vector<vector<int>> neighbours; vector<vector<int>> adj = {{-1, 0}, {0, -1},{1, 0}, {0, 1}}; for(int i=0; i<4; i++) { int nr = adj[i][0] + r; int nc = adj[i][1] + c; if(nr >=0 && nr < R && nc >=0 and nc < C) { neighbours.push_back({nr, nc}); } } return neighbours; } int main() { vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; /* To parse the matrix and get the neighbours of each of the elements */ int R = arr.size(); int C = arr[0].size(); for(int i=0; i<R; i++) { for(int j=0; j<R; j++) { vector<vector<int>> nei = getNeighbours(i, j, R, C); cout << "The neighbours of " << i << " " << j << endl; for(auto c: nei) cout << c[0] << c[1] << endl; cout << "**************************" << endl; } } }
22.5
76
0.438683
hariharanragothaman
b1c0e98ec3849d065085b7114a0535471daa9396
2,072
cpp
C++
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/dataset/config/config-dialog-console/main.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "application-model/application-config-model.h" #include "config-dialog/config-dialog.h" #include <QApplication> #include <QDebug> #include <QIcon> #include "kans.h" #include "textio.h" USING_KANS(TextIO) #include <QThread> USING_KANS(DSM) int main(int argc, char **argv) { QApplication qapp(argc, argv); qapp.setWindowIcon(QIcon(DEFAULT_ICON_FOLDER "/app-icon.png")); Config_Dialog dlg(nullptr); dlg.set_reset_callback([]() { Application_Config_Model::reset( { DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", UNIBUILD_PRI_FOLDER "/build-custom.pro", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri", }, ".reset"); }); dlg.set_proceed_callback([&dlg](QString qs) { qDebug() << qs; Application_Config_Model acm; acm.parse_config_code(qs); { QString result; QString f = acm.insert_to_defines(DEFINES_SRC_FOLDER "/UNIBUILD-custom_defines.h", result); save_file(f, result); } { QString result; QString f = acm.insert_to_choices(CHOICES_PRI_FOLDER "/UNIBUILD-custom_choices.pri", result); save_file(f, result); } { QString result; QString f = acm.insert_to_unibuild(UNIBUILD_PRI_FOLDER "/build-custom.pro", result); save_file(f, result); } { QMap<QString, QString> result; QMap<QString, QString> files {{ { "xpdf", CUSTOM_LIBS_PRI_FOLDER "/_xpdf.pri" }, { "kph", CUSTOM_LIBS_PRI_FOLDER "/_kph.pri" }, { "ss3d", CUSTOM_LIBS_PRI_FOLDER "/_ss3d.pri" } }}; acm.insert_to_custom_libs(files, result); QMapIterator<QString, QString> it(result); while(it.hasNext()) { it.next(); save_file(it.key(), it.value()); } } dlg.register_proceed_completed(qs); }); dlg.show(); return qapp.exec(); }
21.142857
96
0.689189
scignscape
b1c355b9c8abc786c5156b692cc8dbd37374cf30
1,468
cpp
C++
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - The Number of Subpermutations/Time limit exceeded on test 3.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Jul/09/2019 19:04 * solution_verdict: Time limit exceeded on test 3 language: GNU C++14 * run_time: 2000 ms memory_used: 35200 KB * problem: https://codeforces.com/contest/1175/problem/F ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const long mod=1000001011; const int N=1e6,bs=307; int aa[N+2],dp[N+2],lst[N+2]; long pw[N+2],qm[N+2],hs[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n;pw[0]=1; for(int i=1;i<=n;i++)pw[i]=(pw[i-1]*bs)%mod; for(int i=1;i<=n;i++)qm[i]=(qm[i-1]+pw[i])%mod; for(int i=1;i<=n;i++)cin>>aa[i]; dp[n+1]=n+1; for(int i=n;i>=1;i--) { dp[i]=dp[i+1]; if(lst[aa[i]])dp[i]=min(dp[i],lst[aa[i]]); lst[aa[i]]=i; } for(int i=1;i<=n;i++) hs[i]=(hs[i-1]+pw[aa[i]])%mod; int ans=0;dp[0]=1; for(int i=1;i<=n;i++) { int ln=min(n-i+1,aa[i-1]-1); ln=min(ln,dp[i-1]-i); for(int j=i;j<i+ln;j++) if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++; for(int j=dp[i-1];j<dp[i];j++) if(((hs[j]-hs[i-1]+mod)%mod)==qm[j-i+1])ans++; } cout<<ans<<endl; return 0; }
34.952381
111
0.424387
kzvd4729
b1c4430b410f7e361b37593904e11d8dd9dbf90c
4,813
inl
C++
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-06-18T00:48:13.000Z
2021-06-18T00:48:13.000Z
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
6
2021-03-11T21:01:27.000Z
2021-09-06T19:41:46.000Z
src/atta/core/math/matrix.inl
Brenocq/Atta
e29e01067e06b97bc58165bca7351723174c6fc4
[ "MIT" ]
1
2021-09-04T19:54:41.000Z
2021-09-04T19:54:41.000Z
//-------------------------------------------------- // Atta Math // matrix.inl // Date: 2021-04-09 // By Breno Cunha Queiroz //-------------------------------------------------- namespace atta { template <typename T> matrix<T>::matrix(size_t _nrows, size_t _ncols): nrows(_nrows), ncols(_ncols) { rows = std::vector<vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = vector<T>(ncols); } template <typename T> matrix<T>::matrix(size_t _nrows, size_t _ncols, T val): nrows(_nrows), ncols(_ncols) { rows = std::vector<atta::vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = atta::vector<T>(ncols, val); } template <typename T> template <typename U> matrix<T>::matrix(const matrix<U>& m): nrows(m.nrows), ncols(m.ncols) { rows = std::vector<atta::vector<T>>(nrows); for(int i=0;i<nrows;i++) rows[i] = atta::vector<T>(ncols); for(int i=0;i<nrows;i++) for(int j=0;j<ncols;j++) rows[i][j] = m.rows.at(i).at(j); } template <typename T> matrix<T>::~matrix() { } template <typename T> vector<T>& matrix<T>::operator[](size_t i) { return rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator+(const matrix<U>& o) const { matrix<T> res = *this; for(size_t i=0; i<nrows; i++) res.rows[i]+=o.rows[i]; return res; } template <typename T> template <typename U> void matrix<T>::operator+=(const matrix<U>& o) { for(size_t i=0; i<nrows; i++) rows[i]+=o.rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator-(const matrix<U>& o) const { matrix<T> res = *this; for(size_t i=0; i<nrows; i++) res.rows[i]-=o.rows[i]; return res; } template <typename T> template <typename U> void matrix<T>::operator-=(const matrix<U>& o) { for(size_t i=0; i<nrows; i++) rows[i]-=o.rows[i]; } template <typename T> template <typename U> matrix<T> matrix<T>::operator*(const matrix<U>& o) { matrix<T> res = matrix<T>(nrows, o.ncols); size_t i, j, k; for(i=0; i<res.nrows; i++) { for(j=0; j<res.ncols; j++) { res[i][j] = 0; for(k=0; k<ncols; k++) res[i][j] += rows[i][k] * o.rows.at(k).at(j); } } return res; } template <typename T> template <typename U> void matrix<T>::operator*=(const matrix<U>& o) { matrix<T> res = (*this)*o; nrows = res.nrows; ncols = res.ncols; rows = res.rows; } template <typename T> template <typename U> void matrix<T>::operator*=(U v) { (*this) = (*this)*v; } template <typename T> template <typename U> vector<U> matrix<T>::operator*(const vector<U>& v) { vector<U> res(nrows); for(int i=0;i<nrows;i++) { U sum = 0; for(int j=0;j<ncols;j++) sum += rows[i][j]*v.at(j); res[i] = sum; } return res; } template <typename T> template <typename U> matrix<T> matrix<T>::operator*(U v) { matrix<T> res = matrix<T>(nrows, ncols); for(int i=0;i<res.nrows;i++) for(int j=0;j<res.ncols;j++) res.rows[i][j] = rows[i][j]*v; return res; } template <typename T> matrix<T>& matrix<T>::transpose() { std::swap(nrows, ncols); std::vector<vector<T>> cols = std::vector<vector<T>>(nrows); for(int i=0;i<nrows;i++) { cols[i] = vector<T>(ncols); for(int j=0;j<ncols;j++) cols[i][j] = rows[j][i]; } rows = std::move(cols); return *this; } template <typename T> std::string matrix<T>::toString() const { std::string res = "\n["; for(size_t i=0; i<nrows; i++) { res+="["; for(size_t j=0; j<ncols; j++) res += std::to_string(rows.at(i).at(j)) + (j!=ncols-1 ? ", " : "]"); res += i!=nrows-1 ? ",\n" : "]"; } return res; } //------------------------------------------------------------// //-------------------------- Inline --------------------------// //------------------------------------------------------------// template <typename T> inline matrix<T> transpose(const matrix<T>& m) { matrix<T> t = m; t.transpose(); return t; } }
24.18593
84
0.446291
Brenocq
b1c6b8eef546084dcea55ebd8b3d2248adb23535
901
cpp
C++
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
src/lib/file_interpreter.cpp
cuttle-system/cuttle-fileui
f0444501be19352c4734a8c1b2f301c4e17d71ac
[ "MIT" ]
null
null
null
#include <sstream> #include "file_interpreter.hpp" #include "interpreter.hpp" using namespace cuttle; namespace fs = boost::filesystem; void fileui::interpret_file(compile_state_t &state, vm::context_t &context, const fs::path &file_path, std::deque<vm::value_t> &arg_stack) { if (state.cached_files.count(file_path.string())) { std::stringstream input_str (state.cached_files[file_path.string()]); cuttle::vm::interpret(input_str, context, arg_stack); } else { std::ifstream file(file_path.string()); cuttle::vm::interpret(file, context, arg_stack); file.close(); // std::ifstream file1(file_path.string()); // state.cached_files[file_path.string()] = std::string((std::istreambuf_iterator<char>(file1)), // std::istreambuf_iterator<char>()); // file1.close(); } }
40.954545
140
0.63374
cuttle-system
b1cdccc1020badc02ff098d6542f43c889ec72e8
21,461
cpp
C++
src/base/command/RunSimulator.cpp
Randl/GMAT
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
2
2020-01-01T13:14:57.000Z
2020-12-09T07:05:07.000Z
src/base/command/RunSimulator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
1
2018-03-15T08:58:37.000Z
2018-03-20T20:11:26.000Z
src/base/command/RunSimulator.cpp
rdadan/GMAT-R2016a
d6a5b1fed68c33b0c4b1cfbd1e25a71cdfb8f8f5
[ "Apache-2.0" ]
3
2019-10-13T10:26:49.000Z
2020-12-09T07:06:55.000Z
//$Id$ //------------------------------------------------------------------------------ // ClassName //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2009/ / // /** * File description here. */ //------------------------------------------------------------------------------ #include "RunSimulator.hpp" #include "MessageInterface.hpp" //#define DEBUG_INITIALIZATION //#define DEBUG_SIMULATOR_EXECUTION //------------------------------------------------------------------------------ // RunSimulator() //------------------------------------------------------------------------------ /** * Default constructor */ //------------------------------------------------------------------------------ RunSimulator::RunSimulator() : RunSolver ("RunSimulator"), theSimulator (NULL), commandRunning (false), commandComplete (false) { overridePropInit = true; } //------------------------------------------------------------------------------ // ~RunSimulator() //------------------------------------------------------------------------------ /** * Destructor */ //------------------------------------------------------------------------------ RunSimulator::~RunSimulator() { if (theSimulator) delete theSimulator; } //------------------------------------------------------------------------------ // RunSimulator::RunSimulator(const RunSimulator & rs) //------------------------------------------------------------------------------ /** * Copy constructor * * @param rs The command that is copied into the new one */ //------------------------------------------------------------------------------ RunSimulator::RunSimulator(const RunSimulator & rs) : RunSolver (rs), theSimulator (NULL), commandRunning (false), commandComplete (false) { overridePropInit = true; } //------------------------------------------------------------------------------ // RunSimulator & operator=(const RunSimulator & rs) //------------------------------------------------------------------------------ /** * Assignment operator * * @param rs The RunSimulator object that supplies properties this one needs * * @return A reference to this instance */ //------------------------------------------------------------------------------ RunSimulator & RunSimulator::operator=(const RunSimulator & rs) { if (&rs != this) { theSimulator = NULL; commandRunning = false; commandComplete = false; overridePropInit = true; } return *this; } //------------------------------------------------------------------------------ // GmatBase *RunSimulator::Clone() const //------------------------------------------------------------------------------ /** * Cleates a duplicate of a RunSimulator object * * @return a clone of the object */ //------------------------------------------------------------------------------ GmatBase *RunSimulator::Clone() const { return new RunSimulator(*this); } //------------------------------------------------------------------------------ // std::string GetRefObjectName(const Gmat::ObjectType type) const //------------------------------------------------------------------------------ /** * Accesses names for referenced objects. * * @param <type> Type of object requested. * * @return the referenced object's name. */ //------------------------------------------------------------------------------ std::string RunSimulator::GetRefObjectName(const Gmat::ObjectType type) const { switch (type) { case Gmat::SOLVER: #ifdef DEBUG_RUN_SIMULATOR MessageInterface::ShowMessage ("Getting EndFiniteBurn reference burn names\n"); #endif return solverName; default: ; } return RunSolver::GetRefObjectName(type); } //------------------------------------------------------------------------------ // bool SetRefObjectName(const Gmat::ObjectType type, const std::string &name) //------------------------------------------------------------------------------ /** * Sets names for referenced objects. * * @param <type> Type of the object. * @param <name> Name of the object. * * @return true if the name was set, false if not. */ //------------------------------------------------------------------------------ bool RunSimulator::SetRefObjectName(const Gmat::ObjectType type, const std::string &name) { if (type == Gmat::SOLVER) { solverName = name; return true; } return RunSolver::SetRefObjectName(type, name); } //------------------------------------------------------------------------------ // bool RenameRefObject(const Gmat::ObjectType type, // const std::string &oldName, const std::string &newName) //------------------------------------------------------------------------------ /** * Renames referenced objects. * * @param type Type of the object that is renamed. * @param oldName The current name for the object. * @param newName The name the object has when this operation is complete. * * @return true on success. */ //------------------------------------------------------------------------------ bool RunSimulator::RenameRefObject(const Gmat::ObjectType type, const std::string &oldName, const std::string &newName) { // EndFiniteBurn needs to know about Burn and Spacecraft only if (type != Gmat::SOLVER) return RunSolver::RenameRefObject(type, oldName, newName); if (solverName == oldName) { solverName = newName; return true; } return false; } //------------------------------------------------------------------------------ // const std::string GetGeneratingString() //------------------------------------------------------------------------------ /** * Method used to retrieve the string that was parsed to build this GmatCommand. * * This method is used to retrieve the GmatCommand string from the script that * was parsed to build the GmatCommand. It is used to save the script line, so * that the script can be written to a file without inverting the steps taken to * set up the internal object data. As a side benefit, the script line is * available in the GmatCommand structure for debugging purposes. * * @param <mode> Specifies the type of serialization requested. * @param <prefix> Optional prefix appended to the object's name. (Used for * indentation) * @param <useName> Name that replaces the object's name (Not yet used * in commands). * * @return The script line that defines this GmatCommand. */ //------------------------------------------------------------------------------ const std::string& RunSimulator::GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName) { generatingString = prefix + "RunSimulator " + solverName + ";"; return RunSolver::GetGeneratingString(mode, prefix, useName); } //------------------------------------------------------------------------------ // bool Initialize() //------------------------------------------------------------------------------ /** * Prepares the command for execution * * This method prepares the simulator and associated measurement manager and * measurements for the simulation process. Referenced objects are cloned or * set as needed in this method. * * The propagation subsystem is prepared in the base class components of the * command. RunSimulator generaqtes teh PropSetup clones at this level, but * leaves the rest of the initialization process for the PropSetups in the base * class method, which is called from this method. * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool RunSimulator::Initialize() { bool retval = false; // First set the simulator object if (solverName == "") throw CommandException("Cannot initialize RunSimulator command -- the " "simulator name is not specified."); // Clear the old clone if it was set if (theSimulator != NULL) delete theSimulator; GmatBase *simObj = FindObject(solverName); if (simObj == NULL) throw CommandException("Cannot initialize RunSimulator command -- the " "simulator named " + solverName + " cannot be found."); if (!simObj->IsOfType("Simulator")) throw CommandException("Cannot initialize RunSimulator command -- the " "object named " + solverName + " is not a simulator."); theSimulator = (Simulator*)(simObj->Clone()); // Set the streams for the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); StringArray streamList = measman->GetStreamList(); for (UnsignedInt ms = 0; ms < streamList.size(); ++ms) { GmatBase *obj = FindObject(streamList[ms]); if (obj != NULL) { if (obj->IsOfType(Gmat::DATASTREAM)) { Datafile *df = (Datafile*)obj; measman->SetStreamObject(df); } } else throw CommandException("Did not find the object named " + streamList[ms]); } // Next comes the propagator PropSetup *obj = theSimulator->GetPropagator(); #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("Propagator at address %p ", obj); if (obj != NULL) MessageInterface::ShowMessage("is named %s\n", obj->GetName().c_str()); else MessageInterface::ShowMessage("is not yet set\n"); #endif if (obj != NULL) { if (obj->IsOfType(Gmat::PROP_SETUP)) { PropSetup *ps = (PropSetup*)obj->Clone(); // RunSimulator only manages one PropSetup. If that changes, so // does this code if (propagators.size() > 0) { for (std::vector<PropSetup*>::iterator pp = propagators.begin(); pp != propagators.end(); ++pp) { delete (*pp); } propagators.clear(); p.clear(); fm.clear(); } propagators.push_back(ps); p.push_back(ps->GetPropagator()); fm.push_back(ps->GetODEModel()); retval = true; } } else throw CommandException("Cannot initialize RunSimulator command; the " "propagator pointer in the Simulator " + theSimulator->GetName() + " is NULL."); // Now set the participant list MeasurementManager *mm = theSimulator->GetMeasurementManager(); StringArray participants = mm->GetParticipantList(); #ifdef DEBUG_INITIALIZATION MessageInterface::ShowMessage("RunSimulator command found %d " "participants\n", participants.size()); #endif propObjectNames.clear(); propObjectNames.push_back(participants); // Now we can initialize the propagation subsystem by calling up the // inheritance tree. retval = RunSolver::Initialize(); #ifdef DEBUG_INITIALIZATION if (retval == false) MessageInterface::ShowMessage("RunSimulator command failed to " "initialize; RunSolver::Initialize() call failed.\n"); #endif return retval; } //------------------------------------------------------------------------------ // bool Execute() //------------------------------------------------------------------------------ /** * Performs the command side processing for the Simulation * * This method calls the Simulator to determine the state of the Simulation * state machine and responds to that state as needed. Typical command side * responses are to propagate as needed, to clean up memory, or to reset flags * based on the state machine. * * @return true on success, false on failure */ //------------------------------------------------------------------------------ bool RunSimulator::Execute() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("\n\nThe \"%s\" command is running...\n", GetTypeName().c_str()); #endif // Reset the command if called after it has completed execution // todo: Debug this piece; reentrance in a For loop doesn't work yet // if (commandComplete) // TakeAction("Reset"); // Here we should check to see if the command is currently propagating and // finish that first... // Respond to the state in the state machine Solver::SolverState state = theSimulator->GetState(); #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("\nSimulator state is %d\n", state); #endif switch (state) { case Solver::INITIALIZING: PrepareToSimulate(); break; case Solver::PROPAGATING: Propagate(); break; case Solver::CALCULATING: Calculate(); break; case Solver::LOCATING: // The LOCATING state shouldn't trigger until we have event location // implemented, so this case should not fire. LocateEvent(); break; case Solver::SIMULATING: Simulate(); break; case Solver::FINISHED: Finalize(); break; default: throw CommandException("Unknown state " " encountered in the RunSimulator command"); } state = theSimulator->AdvanceState(); return true; } //------------------------------------------------------------------------------ // void RunComplete() //------------------------------------------------------------------------------ /** * Completes processing so that subsequent commands can be run. */ //------------------------------------------------------------------------------ void RunSimulator::RunComplete() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::RunComplete()\n"); #endif commandRunning = false; RunSolver::RunComplete(); } //------------------------------------------------------------------------------ // bool TakeAction(const std::string &action, const std::string &actionData) //------------------------------------------------------------------------------ /** * Performs actions at prompting from higher level structures * * @param action The action that needs to be taken * @param actionData Optional additional data the action needs * * @return true if an action was taken, false if not */ //------------------------------------------------------------------------------ bool RunSimulator::TakeAction(const std::string &action, const std::string &actionData) { if (action == "Reset") { theSimulator->TakeAction("Reset"); commandRunning = false; commandComplete = false; return true; } return RunSolver::TakeAction(action, actionData); } //------------------------------------------------------------------------------ // GmatCommand* GetNext() //------------------------------------------------------------------------------ /** * Retrieves the pointer to the next command that the Sandbox needs to run * * This method returns a pointer to the current RunSimulator command while the * simulation state machine is running. It returns the next pointer after the * simulation has finished execution. * * @return The next comamnd that should Execute() */ //------------------------------------------------------------------------------ GmatCommand* RunSimulator::GetNext() { if (commandRunning) return this; return next; } //------------------------------------------------------------------------------ // Methods triggered by the finite state machine //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // void PrepareToSimulate() //------------------------------------------------------------------------------ /** * Responds to the CALCULATING state of the finite state machine * * Performs the final stages of initialization that need to be performed prior * to running the simulation. This includes the final ODEModel preparation and * the setting for the flags that indicate that a simulation is in process. */ //------------------------------------------------------------------------------ void RunSimulator::PrepareToSimulate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::PrepareToSimulate()\n"); #endif // Prep the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); if (measman->PrepareForProcessing(true) == false) throw CommandException( "Measurement Manager was unable to prepare for processing"); PrepareToPropagate(); commandRunning = true; commandComplete = false; } //------------------------------------------------------------------------------ // void Propagate() //------------------------------------------------------------------------------ /** * Responds to the PROPAGATING state of the finite state machine. * * Propagation from the current epoch to the next simulation epoch is performed * in this method. */ //------------------------------------------------------------------------------ void RunSimulator::Propagate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Propagate()\n"); #endif Real dt = theSimulator->GetTimeStep(); // todo: This is a temporary fix; need to evaluate to find a more elegant // solution here Real maxStep = 600.0; if (dt > maxStep) dt = maxStep; Step(dt); theSimulator->UpdateCurrentEpoch(currEpoch[0]); } //------------------------------------------------------------------------------ // void Calculate() //------------------------------------------------------------------------------ /** * Responds to the CALCULATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Calculate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Calculate()\n"); #endif // We might not need anything here -- it's all Simulator side work } //------------------------------------------------------------------------------ // void LocateEvent() //------------------------------------------------------------------------------ /** * Responds to the LOCATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::LocateEvent() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::LocateEvent()\n"); #endif // We'll figure this out later } //------------------------------------------------------------------------------ // void Simulate() //------------------------------------------------------------------------------ /** * Responds to the SIMULATING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Simulate() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Simulate()\n"); #endif // We might not need anything here -- it's all Simulator side work } //------------------------------------------------------------------------------ // void RunSimulator::Finalize() //------------------------------------------------------------------------------ /** * Responds to the FINALIZING state of the finite state machine */ //------------------------------------------------------------------------------ void RunSimulator::Finalize() { #ifdef DEBUG_SIMULATOR_EXECUTION MessageInterface::ShowMessage("Entered RunSimulator::Finalize()\n"); #endif // Do cleanup here // Finalize the measurement manager MeasurementManager *measman = theSimulator->GetMeasurementManager(); if (measman->ProcessingComplete() == false) MessageInterface::ShowMessage( "Measurement Manager reported a problem completing processing\n"); commandComplete = true; commandRunning = false; }
32.966206
80
0.501281
Randl
b1d36c9eb1587cbe78acaf59ce35de0a417cfdd2
13,625
cpp
C++
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
src/bytearray.cpp
dongzx666/cool
6d13b767491f52ac6c4ee96a3e69d481600e22f7
[ "MIT" ]
null
null
null
#include "bytearray.h" #include "endian.h" #include "log.h" #include "socket.h" #include <cmath> #include <cstddef> #include <cstdint> #include <cstring> #include <endian.h> #include <fstream> #include <iomanip> #include <memory> #include <sstream> #include <stdexcept> #include <string> namespace cool { static cool::Logger::ptr g_logger = LOG_NAME("system"); ByteArray::Node::Node(size_t s) : ptr(new char[s]), next(nullptr), size(s) {} ByteArray::Node::Node() : ptr(nullptr), next(nullptr), size(0) {} ByteArray::Node::~Node() { if (ptr) { delete[] ptr; } } ByteArray::ByteArray(size_t base_size) : m_base_size(base_size), m_pos(0), m_capacity(base_size), m_size(0), m_endian(COOL_BIG_ENDIAN), m_root(new Node(base_size)), m_cur(m_root) {} ByteArray::~ByteArray() { Node *temp = m_root; while (temp) { m_cur = temp; temp = temp->next; delete m_cur; } } bool ByteArray::isLittleEndian() const { return m_endian == COOL_LITTLE_ENDIAN; } void ByteArray::setIsLittleEndian(bool val) { if (val) { m_endian = COOL_LITTLE_ENDIAN; } else { m_endian = COOL_BIG_ENDIAN; } } void ByteArray::write_fint8(int8_t val) { write(&val, sizeof(val)); } void ByteArray::write_fuint8(uint8_t val) { write(&val, sizeof(val)); } void ByteArray::write_fint16(int16_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint16(uint16_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fint32(int32_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint32(uint32_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fint64(int64_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } void ByteArray::write_fuint64(uint64_t val) { if (m_endian != COOL_BYTE_ORDER) { val = byteswap(val); } write(&val, sizeof(val)); } static uint32_t EncodeZigzap32(const int32_t &val) { if (val < 0) { return ((uint32_t)(-val)) * 2 - 1; } else { return val * 2; } } static int32_t DecodeZigzap32(const uint32_t &val) { return (val >> 1) ^ -(val & 1); } static uint64_t EncodeZigzap64(const int64_t &val) { if (val < 0) { return ((uint64_t)(-val)) * 2 - 1; } else { return val * 2; } } static int64_t DecodeZigzap64(const uint64_t &val) { return (val >> 1) ^ -(val & 1); } void ByteArray::write_int32(int32_t val) { write_uint32(EncodeZigzap32(val)); } void ByteArray::write_uint32(uint32_t val) { uint8_t temp[5]; uint8_t i = 0; while (val >= 0x80) { temp[i++] = (val & 0x7f) | 0x80; val >>= 7; } temp[i++] = val; write(temp, i); } void ByteArray::write_int64(int64_t val) { write_uint64(EncodeZigzap64(val)); } void ByteArray::write_uint64(uint64_t val) { uint8_t temp[10]; uint8_t i = 0; while (val >= 0x80) { temp[i++] = (val & 0x7f) | 0x80; val >>= 7; } temp[i++] = val; write(temp, i); } void ByteArray::write_float(float val) { uint32_t temp; memcpy(&temp, &val, sizeof(val)); write_fuint32(temp); } void ByteArray::write_double(double val) { uint64_t temp; memcpy(&temp, &val, sizeof(val)); write_fuint64(temp); } // length: int16, data void ByteArray::write_string_f16(const std::string &val) { write_fint16(val.size()); write(val.c_str(), val.size()); } // length: int32, data void ByteArray::write_string_f32(const std::string &val) { write_fint32(val.size()); write(val.c_str(), val.size()); } // length: int64, data void ByteArray::write_string_f64(const std::string &val) { write_fint64(val.size()); write(val.c_str(), val.size()); } // length: varint, data void ByteArray::write_string_vint(const std::string &val) { write_uint64(val.size()); write(val.c_str(), val.size()); } // data void ByteArray::write_string_withoutlen(const std::string &val) { write(val.c_str(), val.size()); } // read int8_t ByteArray::read_fint8() { int8_t val; read(&val, sizeof(val)); return val; } uint8_t ByteArray::read_fuint8() { uint8_t val; read(&val, sizeof(val)); return val; } #define XX(type) \ type val; \ read(&val, sizeof(val)); \ if (m_endian == COOL_BYTE_ORDER) { \ return val; \ } else { \ return byteswap(val); \ } int16_t ByteArray::read_fint16() { XX(int16_t); } uint16_t ByteArray::read_fuint16() { XX(uint16_t); } int32_t ByteArray::read_fint32() { XX(int32_t); } uint32_t ByteArray::read_fuint32() { XX(uint32_t); } int64_t ByteArray::read_fint64() { XX(int64_t); } uint64_t ByteArray::read_fuint64() { XX(uint64_t); } #undef XX int32_t ByteArray::read_int32() { return DecodeZigzap32(read_uint32()); } uint32_t ByteArray::read_uint32() { uint32_t res = 0; for (int i = 0; i < 32; i += 7) { uint8_t b = read_fuint8(); if (b < 0x80) { res |= ((uint32_t)b) << i; break; } else { res |= (((uint32_t)b & 0x7f) << i); } } return res; } int64_t ByteArray::read_int64() { return DecodeZigzap64(read_uint64()); } uint64_t ByteArray::read_uint64() { uint64_t res = 0; for (int i = 0; i < 64; i += 7) { uint8_t b = read_fuint8(); if (b < 0x80) { res |= ((uint64_t)b) << i; break; } else { res |= (((uint64_t)b & 0x7f) << i); } } return res; } float ByteArray::read_float() { uint32_t temp = read_fuint32(); float res; memcpy(&res, &temp, sizeof(temp)); return res; } double ByteArray::read_double() { uint64_t temp = read_fuint64(); double res; memcpy(&res, &temp, sizeof(temp)); return res; } // length: int16, data std::string ByteArray::read_string_f16() { uint16_t len = read_fuint16(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // length: int32, data std::string ByteArray::read_string_f32() { uint32_t len = read_fuint32(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // length: int64, data std::string ByteArray::read_string_f64() { uint64_t len = read_fuint64(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // data std::string ByteArray::read_string_vint() { uint64_t len = read_fuint64(); std::string buf; buf.resize(len); read(&buf[0], len); return buf; } // inner func void ByteArray::clear() { m_pos = m_size = 0; m_capacity = m_base_size; Node *temp = m_root->next; while (temp) { m_cur = temp; temp = temp->next; delete m_cur; } m_cur = m_root; m_root->next = nullptr; } void ByteArray::write(const void *buf, size_t size) { if (size == 0) { return; } addCapacity(size); size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; while (size > 0) { if (ncap >= size) { memcpy(m_cur->ptr + npos, (const char *)buf + bpos, size); if (m_cur->size == (npos + size)) { m_cur = m_cur->next; } m_pos += size; bpos += size; size = 0; } else { memcpy(m_cur->ptr + npos, (const char *)buf + bpos, ncap); m_pos += ncap; bpos += ncap; size -= ncap; m_cur = m_cur->next; ncap = m_cur->size; npos = 0; } } if (m_pos > m_size) { m_size = m_pos; } } void ByteArray::read(void *buf, size_t size) { if (size > getReadSize()) { throw std::out_of_range("not enough len"); } size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; while (size > 0) { if (ncap >= size) { memcpy((char *)buf + bpos, m_cur->ptr + npos, size); if (m_cur->size == npos + size) { m_cur = m_cur->next; } m_pos += size; bpos += size; size = 0; } else { memcpy((char *)buf + bpos, m_cur->ptr + npos, ncap); m_pos += ncap; bpos += ncap; size -= ncap; m_cur = m_cur->next; ncap = m_cur->size; npos = 0; } } } void ByteArray::read(void *buf, size_t size, size_t pos) const { if (size > getReadSize()) { throw std::out_of_range("not enough len"); } size_t npos = pos % m_base_size; size_t ncap = m_cur->size - npos; size_t bpos = 0; Node *cur = m_cur; while (size > 0) { if (ncap >= size) { memcpy((char *)buf + bpos, cur->ptr + npos, size); if (cur->size == npos + size) { cur = cur->next; } pos += size; bpos += size; size = 0; } else { memcpy((char *)buf + bpos, cur->ptr + npos, ncap); pos += ncap; bpos += ncap; size -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } } } void ByteArray::position(size_t val) { if (val > m_capacity) { throw std::out_of_range("set pos out of range"); } m_pos = val; if (m_pos > m_size) { m_size = m_pos; } m_cur = m_root; while (val > m_cur->size) { val -= m_cur->size; m_cur = m_cur->next; } if (val == m_cur->size) { m_cur = m_cur->next; } } bool ByteArray::writeToFile(const std::string &name) const { std::ofstream ofs; ofs.open(name, std::ios::trunc | std::ios::binary); if (!ofs) { LOG_ERROR(g_logger) << "write to file, name is " << name << " error"; return false; } int64_t read_size = getReadSize(); int64_t pos = m_pos; Node *cur = m_cur; while (read_size > 0) { int diff = pos % m_base_size; int64_t len = (read_size > (int64_t)m_base_size ? m_base_size : read_size) - diff; ofs.write(cur->ptr + diff, len); cur = cur->next; pos += len; read_size -= len; } return true; } bool ByteArray::readFromFile(const std::string &name) { std::ifstream ifs; ifs.open(name, std::ios::binary); if (!ifs) { LOG_ERROR(g_logger) << "read from file, name is " << name << " error"; return false; } std::shared_ptr<char> buf(new char[m_base_size], [](char *ptr) { delete[] ptr; }); while (!ifs.eof()) { ifs.read(buf.get(), m_base_size); write(buf.get(), ifs.gcount()); } return true; } void ByteArray::addCapacity(size_t size) { if (size == 0) { return; } size_t old_cap = getCapacity(); if (old_cap >= size) { LOG_FMT_DEBUG(g_logger, "old_cap(%u) >= size(%u)", old_cap, size); return; } size = size - old_cap; size_t count = (size / m_base_size) + ((size % m_base_size > old_cap) ? 1 : 0); // size_t count = ceil(1.0 * size / m_base_size); Node *temp = m_root; while (temp->next) { temp = temp->next; } Node *first = nullptr; for (size_t i = 0; i < count; ++i) { temp->next = new Node(m_base_size); if (first == nullptr) { first = temp->next; } temp = temp->next; m_capacity += m_base_size; } if (old_cap == 0) { m_cur = first; } } std::string ByteArray::to_string() const { std::string str; str.resize(getReadSize()); if (str.empty()) { return str; } read(&str[0], str.size(), m_pos); return str; } std::string ByteArray::to_hex_string() const { std::string str = to_string(); std::stringstream ss; for (size_t i = 0; i < str.size(); ++i) { if (i > 0 && i % 32 == 0) { ss << std::endl; } ss << std::setw(2) << std::setfill('0') << std::hex << (int)(uint8_t)str[i] << " "; } return ss.str(); } uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers, uint64_t len) const { len = len > getReadSize() ? getReadSize() : len; if (len == 0) { return 0; } uint64_t size = len; size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; struct iovec iov; Node *cur = m_cur; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } uint64_t ByteArray::getReadBuffers(std::vector<iovec> &buffers, uint64_t len, uint64_t pos) const { len = len > getReadSize() ? getReadSize() : len; if (len == 0) { return 0; } uint64_t size = len; size_t npos = pos % m_base_size; size_t count = pos / m_base_size; Node *cur = m_root; while (count > 0) { cur = cur->next; --count; } size_t ncap = cur->size - npos; struct iovec iov; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } uint64_t ByteArray::getWriteBuffers(std::vector<iovec> &buffers, uint64_t len) { if (len == 0) { return 0; } addCapacity(len); uint64_t size = len; size_t npos = m_pos % m_base_size; size_t ncap = m_cur->size - npos; struct iovec iov; Node *cur = m_cur; while (len > 0) { if (ncap >= len) { iov.iov_base = cur->ptr + npos; iov.iov_len = len; len = 0; } else { iov.iov_base = cur->ptr + npos; iov.iov_len = ncap; len -= ncap; cur = cur->next; ncap = cur->size; npos = 0; } buffers.push_back(iov); } return size; } } // namespace cool
22.263072
80
0.584294
dongzx666
b1d378f667928cda69bc2a142c51252e1a566759
966
cpp
C++
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/path/brt/directory_separators.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
// =========================================================================== // This is an open source non-commercial project. // Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: // http://www.viva64.com // =========================================================================== // Copyright 2007 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breath/porting/dependent_code.hpp" #include BREATH_DEPENDENT_CODE( system, directory_separators.cpp ) // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
42
78
0.516563
erez-o
b1d4484f5cd5bbafd7d091be3c8116d6b2e93104
5,263
cpp
C++
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
Raytracer/src/world.cpp
rickyguerin/Animated-Ray-Tracer
cc1afe776c904b2280e5552f5c4654391658382a
[ "MIT" ]
null
null
null
#include "../header/world.h" #include "../header/WorldProgram/sphereProgram.h" #include "../header/WorldProgram/triangleProgram.h" #include "../header/Shape/shape.h" #include "../header/Math/intersection.h" World::World(const glm::vec3& color) { backgroundColor = color; } World::~World() { for (const ShapeProgram* prog : programs) { delete prog; } } void World::addProgram(const std::string& filename) { // Position of dot in name.light size_t lightExt = filename.length() - 6; assert(lightExt > 0); // File is .light if (filename.substr(lightExt).compare(".light") == 0) { lightPrograms.push_back(LightProgram(filename)); return; } // Position of dot in name.sphere size_t sphereExt = filename.length() - 7; assert(sphereExt > 0); // File is .sphere if (filename.substr(sphereExt).compare(".sphere") == 0) { programs.push_back(new SphereProgram(filename)); return; } // Position of dot in name.triangle size_t triangleExt = filename.length() - 9; assert(triangleExt > 0); // File is .triangle if (filename.substr(triangleExt).compare(".triangle") == 0) { programs.push_back(new TriangleProgram(filename)); return; } } void World::loadCurrent(const glm::mat4& cameraMatrix, const float time) { // Load Shapes for (int i = 0; i < programs.size(); i++) { Shape* shape = programs[i]->getShape(time); shape->transformToCameraSpace(cameraMatrix); currentShapes.push_back(shape); } // Load Lights for (int i = 0; i < lightPrograms.size(); i++) { Light light = lightPrograms[i].getLight(time); light.transformToCameraSpace(cameraMatrix); currentLights.push_back(light); } } void World::deleteCurrent() { for (int i = 0; i < programs.size(); i++) { delete currentShapes[i]; } currentShapes.clear(); currentLights.clear(); } glm::vec3 World::trace(const Ray& ray, const float time, const int depth, const bool inside) const { // Determine what Shape is intersected by ray first Intersection closestIntersection = NULL_INTERSECTION; const Shape* intersectedShape = currentShapes[0]; glm::vec3 origin = glm::vec3(0, 0, 0); Intersection currentIntersection; for (int i = 0; i < currentShapes.size(); i++) { currentIntersection = currentShapes[i]->collision(ray); // No intersection occured with this Shape if (currentIntersection.isNull()) { continue; } // If this intersection is closer than the previous closest, update else if (closestIntersection.isNull() || currentIntersection.omega < closestIntersection.omega) { closestIntersection = currentIntersection; intersectedShape = currentShapes[i]; } } // No intersection occurred at all if (closestIntersection.isNull()) { return backgroundColor; } // Intersection occurred, test for shadow else { Intersection closestShadowIntersection = NULL_INTERSECTION; const Shape* shadowIntersectionShape = currentShapes[0]; bool shadow = true; glm::vec3 pixelColor = glm::vec3(0, 0, 0); // Test if any light can reach intersection point for (int i = 0; i < currentLights.size(); i++) { glm::vec3 srd = glm::normalize(currentLights[i].position - closestIntersection.point); glm::vec3 sro = closestIntersection.point + (0.01f * srd); for (int k = 0; k < currentShapes.size(); k++) { currentIntersection = currentShapes[k]->collision(Ray{ sro, srd }); // No intersection occured with this Shape if (currentIntersection.isNull()) { continue; } // If this intersection is closer than the previous closest, update else if (closestShadowIntersection.isNull() || currentIntersection.omega < closestShadowIntersection.omega) { closestShadowIntersection = currentIntersection; shadowIntersectionShape = currentShapes[k]; } } float lightOmega = (currentLights[i].position - closestIntersection.point).length(); // If no shadow ray Intersection, illuminate normally if (closestShadowIntersection.isNull() || closestShadowIntersection.omega > lightOmega) { shadow = false; break; } } // If every light is blocked, return illumination with shadow pixelColor += intersectedShape->illuminate(closestIntersection, currentLights, shadow); if (depth < MAX_DEPTH) { float kReflect = intersectedShape->illumination->kReflect; float kRefract = intersectedShape->illumination->kRefract; float refIndex = intersectedShape->illumination->refIndex; glm::vec3 reflectDir = glm::reflect(ray.direction, closestIntersection.normal); if (kReflect > 0) { pixelColor += kReflect * trace(Ray{closestIntersection.point + (reflectDir * 0.001f), reflectDir}, time, depth + 1, inside); } if (kRefract > 0) { float ni, nt; glm::vec3 refNorm = glm::vec3(closestIntersection.normal); if (inside) { ni = refIndex; nt = 1.0f; refNorm = -refNorm; } else { ni = 1.0f; nt = refIndex; } float test = 1 - ((pow(ni, 2) * (1 - pow(glm::dot(ray.direction, refNorm), 2))) / pow(nt, 2)); glm::vec3 refractDir = glm::refract(ray.direction, refNorm, ni / nt); if (test < 0) { refractDir = glm::vec3(reflectDir); } pixelColor += kRefract * trace(Ray{ closestIntersection.point + (refractDir * 0.001f), refractDir }, time, depth + 1, !inside); } } return pixelColor; } }
30.247126
131
0.694091
rickyguerin
b1d62dbd78a341ebaa4756b65b603bef0b7853a1
666
cc
C++
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
codeforces/1253/e.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://codeforces.com/contest/1253/problem/E #include <bits/stdc++.h> using namespace std; using ii = tuple<int, int>; using vi = vector<int>; using vii = vector<ii>; int main() { int n, m, x, s, l, r; cin >> n >> m; vii a(n); for (int i = 0; i < n; i++) { cin >> x >> s; a[i] = { x - s, x + s }; } vi dp(m + 1); for (int i = 0; i <= m; i++) dp[i] = i; for (int i = 1; i <= m; i++) { for (int j = 0; j < n; j++) { tie(l, r) = a[j]; if (l <= i && i <= r) dp[i] = dp[i - 1]; else if (r < i) { int c = i - r; dp[i] = min(dp[i], dp[max(0, l - c - 1)] + c); } } } cout << dp[m] << '\n'; }
21.483871
54
0.408408
Ashindustry007
b1de7160e7d1447732775e18dd2b58e730305d7c
9,667
cpp
C++
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
gui/src/gui_statusbar.cpp
unnamed-mmo/lxgui
5c4b9d0c164d2d35cfe5c59888b10020184f717d
[ "MIT" ]
null
null
null
#include "lxgui/gui_statusbar.hpp" #include "lxgui/gui_frame.hpp" #include "lxgui/gui_manager.hpp" #include "lxgui/gui_texture.hpp" #include "lxgui/gui_out.hpp" #include "lxgui/gui_alive_checker.hpp" #include "lxgui/gui_uiobject_tpl.hpp" #include <sstream> namespace lxgui { namespace gui { std::array<float,4> select_uvs(const std::array<float,8>& uvs) { std::array<float,4> u; u[0] = uvs[0]; u[1] = uvs[1]; u[2] = uvs[4]; u[3] = uvs[5]; return u; } status_bar::status_bar(manager* pManager) : frame(pManager) { lType_.push_back(CLASS_NAME); } std::string status_bar::serialize(const std::string& sTab) const { std::ostringstream sStr; sStr << frame::serialize(sTab); sStr << sTab << " # Orientation: "; switch (mOrientation_) { case orientation::HORIZONTAL : sStr << "HORIZONTAL"; break; case orientation::VERTICAL : sStr << "VERTICAL"; break; } sStr << "\n"; sStr << sTab << " # Reversed : " << bReversed_ << "\n"; sStr << sTab << " # Value : " << fValue_ << "\n"; sStr << sTab << " # Min value : " << fMinValue_ << "\n"; sStr << sTab << " # Max value : " << fMaxValue_ << "\n"; return sStr.str(); } bool status_bar::can_use_script(const std::string& sScriptName) const { if (frame::can_use_script(sScriptName)) return true; else if (sScriptName == "OnValueChanged") return true; else return false; } void status_bar::copy_from(uiobject* pObj) { frame::copy_from(pObj); status_bar* pStatusBar = down_cast<status_bar>(pObj); if (!pStatusBar) return; this->set_min_value(pStatusBar->get_min_value()); this->set_max_value(pStatusBar->get_max_value()); this->set_value(pStatusBar->get_value()); this->set_bar_draw_layer(pStatusBar->get_bar_draw_layer()); this->set_orientation(pStatusBar->get_orientation()); this->set_reversed(pStatusBar->is_reversed()); texture* pBar = pStatusBar->get_bar_texture(); if (pBar) { std::unique_ptr<texture> pBarTexture = this->create_bar_texture_(); if (this->is_virtual()) pBarTexture->set_virtual(); pBarTexture->set_name(pBar->get_name()); if (!pManager_->add_uiobject(pBarTexture.get())) { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Trying to add \""+pBar->get_name()+"\" to \""+sName_+"\", " "but its name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl; } else { if (!is_virtual()) pBarTexture->create_glue(); pBarTexture->copy_from(pBar); pBarTexture->notify_loaded(); this->set_bar_texture(pBarTexture.get()); this->add_region(std::move(pBarTexture)); } } } void status_bar::set_min_value(float fMin) { if (fMin != fMinValue_) { fMinValue_ = fMin; if (fMinValue_ > fMaxValue_) fMinValue_ = fMaxValue_; fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_max_value(float fMax) { if (fMax != fMaxValue_) { fMaxValue_ = fMax; if (fMaxValue_ < fMinValue_) fMaxValue_ = fMinValue_; fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_min_max_values(float fMin, float fMax) { if (fMin != fMinValue_ || fMax != fMaxValue_) { fMinValue_ = std::min(fMin, fMax); fMaxValue_ = std::max(fMin, fMax); fValue_ = fValue_ > fMaxValue_ ? fMaxValue_ : (fValue_ < fMinValue_ ? fMinValue_ : fValue_); fire_update_bar_texture_(); } } void status_bar::set_value(float fValue) { fValue = fValue > fMaxValue_ ? fMaxValue_ : (fValue < fMinValue_ ? fMinValue_ : fValue); if (fValue != fValue_) { fValue_ = fValue; fire_update_bar_texture_(); } } void status_bar::set_bar_draw_layer(layer_type mBarLayer) { mBarLayer_ = mBarLayer; if (pBarTexture_) pBarTexture_->set_draw_layer(mBarLayer_); } void status_bar::set_bar_draw_layer(const std::string& sBarLayer) { if (sBarLayer == "ARTWORK") mBarLayer_ = layer_type::ARTWORK; else if (sBarLayer == "BACKGROUND") mBarLayer_ = layer_type::BACKGROUND; else if (sBarLayer == "BORDER") mBarLayer_ = layer_type::BORDER; else if (sBarLayer == "HIGHLIGHT") mBarLayer_ = layer_type::HIGHLIGHT; else if (sBarLayer == "OVERLAY") mBarLayer_ = layer_type::OVERLAY; else { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Uknown layer type : \""+sBarLayer+"\". Using \"ARTWORK\"." << std::endl; mBarLayer_ = layer_type::ARTWORK; } if (pBarTexture_) pBarTexture_->set_draw_layer(mBarLayer_); } void status_bar::set_bar_texture(texture* pBarTexture) { pBarTexture_ = pBarTexture; if (!pBarTexture_) return; pBarTexture_->clear_all_points(); if (bReversed_) pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT)); else pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT)); lInitialTextCoords_ = select_uvs(pBarTexture_->get_tex_coord()); fire_update_bar_texture_(); } void status_bar::set_bar_color(const color& mBarColor) { if (!pBarTexture_) { std::unique_ptr<texture> pBarTexture = create_bar_texture_(); pBarTexture->set_name("$parentBarTexture"); if (!pManager_->add_uiobject(pBarTexture.get())) { gui::out << gui::warning << "gui::" << lType_.back() << " : " "Trying to create bar texture for \""+sName_+"\",\n" "but the name was already taken : \""+pBarTexture->get_name()+"\". Skipped." << std::endl; return; } if (!bVirtual_) pBarTexture->create_glue(); pBarTexture->notify_loaded(); set_bar_texture(pBarTexture.get()); add_region(std::move(pBarTexture)); } mBarColor_ = mBarColor; pBarTexture_->set_color(mBarColor_); } void status_bar::set_orientation(orientation mOrient) { if (mOrient != mOrientation_) { mOrientation_ = mOrient; fire_update_bar_texture_(); } } void status_bar::set_reversed(bool bReversed) { if (bReversed == bReversed_) return; bReversed_ = bReversed; if (pBarTexture_) { if (bReversed_) pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::TOPRIGHT, "$parent", anchor_point::TOPRIGHT)); else pBarTexture_->set_point(anchor(pBarTexture_, anchor_point::BOTTOMLEFT, "$parent", anchor_point::BOTTOMLEFT)); pBarTexture_->notify_borders_need_update(); } } float status_bar::get_min_value() const { return fMinValue_; } float status_bar::get_max_value() const { return fMaxValue_; } float status_bar::get_value() const { return fValue_; } layer_type status_bar::get_bar_draw_layer() const { return mBarLayer_; } texture* status_bar::get_bar_texture() const { return pBarTexture_; } const color& status_bar::get_bar_color() const { return mBarColor_; } status_bar::orientation status_bar::get_orientation() const { return mOrientation_; } bool status_bar::is_reversed() const { return bReversed_; } std::unique_ptr<texture> status_bar::create_bar_texture_() { std::unique_ptr<texture> pBarTexture(new texture(pManager_)); pBarTexture->set_special(); pBarTexture->set_parent(this); pBarTexture->set_draw_layer(mBarLayer_); return pBarTexture; } void status_bar::create_glue() { create_glue_<lua_status_bar>(); } void status_bar::update(float fDelta) { if (bUpdateBarTexture_ && pBarTexture_) { float fCoef = (fValue_ - fMinValue_)/(fMaxValue_ - fMinValue_); if (mOrientation_ == orientation::HORIZONTAL) { pBarTexture_->set_rel_width(fCoef); pBarTexture_->set_rel_height(1.0f); } else { pBarTexture_->set_rel_width(1.0f); pBarTexture_->set_rel_height(fCoef); } if (!pBarTexture_->get_texture().empty()) { std::array<float,4> uvs = lInitialTextCoords_; if (mOrientation_ == orientation::HORIZONTAL) { if (bReversed_) uvs[0] = (uvs[0] - uvs[2])*fCoef + uvs[2]; else uvs[2] = (uvs[2] - uvs[0])*fCoef + uvs[0]; } else { if (bReversed_) uvs[3] = (uvs[3] - uvs[1])*fCoef + uvs[1]; else uvs[1] = (uvs[1] - uvs[3])*fCoef + uvs[3]; } pBarTexture_->set_tex_coord(uvs); } bUpdateBarTexture_ = false; } alive_checker mChecker(this); frame::update(fDelta); if (!mChecker.is_alive()) return; } void status_bar::fire_update_bar_texture_() { bUpdateBarTexture_ = true; } } }
27.463068
122
0.589531
unnamed-mmo
b1e12b044d201b5c67c0ceeea3023c68e4072d17
3,837
cc
C++
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-06-30T13:16:14.000Z
2020-06-30T13:16:14.000Z
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
flow/matrix_decomposition.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-03-05T02:44:12.000Z
2020-03-05T02:44:12.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/flow/matrix_decomposition.h" namespace flow { static inline SkVector3 SkVector3Combine(const SkVector3& a, float a_scale, const SkVector3& b, float b_scale) { return { a_scale * a.fX + b_scale * b.fX, // a_scale * a.fY + b_scale * b.fY, // a_scale * a.fZ + b_scale * b.fZ, // }; } static inline SkVector3 SkVector3Cross(const SkVector3& a, const SkVector3& b) { return { (a.fY * b.fZ) - (a.fZ * b.fY), // (a.fZ * b.fX) - (a.fX * b.fZ), // (a.fX * b.fY) - (a.fY * b.fX) // }; } MatrixDecomposition::MatrixDecomposition(const SkMatrix& matrix) : MatrixDecomposition(SkMatrix44{matrix}) {} MatrixDecomposition::MatrixDecomposition(SkMatrix44 matrix) : valid_(false) { if (matrix.get(3, 3) == 0) { return; } for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix.set(j, i, matrix.get(j, i) / matrix.get(3, 3)); } } SkMatrix44 perpective_matrix = matrix; for (int i = 0; i < 3; i++) { perpective_matrix.set(3, i, 0.0); } perpective_matrix.set(3, 3, 1.0); if (perpective_matrix.determinant() == 0.0) { return; } if (matrix.get(3, 0) != 0.0 || matrix.get(3, 1) != 0.0 || matrix.get(3, 2) != 0.0) { const SkVector4 right_hand_side(matrix.get(3, 0), matrix.get(3, 1), matrix.get(3, 2), matrix.get(3, 3)); SkMatrix44 inverted_transposed( SkMatrix44::Uninitialized_Constructor::kUninitialized_Constructor); if (!perpective_matrix.invert(&inverted_transposed)) { return; } inverted_transposed.transpose(); perspective_ = inverted_transposed * right_hand_side; matrix.set(3, 0, 0); matrix.set(3, 1, 0); matrix.set(3, 2, 0); matrix.set(3, 3, 1); } translation_ = {matrix.get(0, 3), matrix.get(1, 3), matrix.get(2, 3)}; matrix.set(0, 3, 0.0); matrix.set(1, 3, 0.0); matrix.set(2, 3, 0.0); SkVector3 row[3]; for (int i = 0; i < 3; i++) { row[i].set(matrix.get(0, i), matrix.get(1, i), matrix.get(2, i)); } scale_.fX = row[0].length(); row[0].normalize(); shear_.fX = row[0].dot(row[1]); row[1] = SkVector3Combine(row[1], 1.0, row[0], -shear_.fX); scale_.fY = row[1].length(); row[1].normalize(); shear_.fX /= scale_.fY; shear_.fY = row[0].dot(row[2]); row[2] = SkVector3Combine(row[2], 1.0, row[0], -shear_.fY); shear_.fZ = row[1].dot(row[2]); row[2] = SkVector3Combine(row[2], 1.0, row[1], -shear_.fZ); scale_.fZ = row[2].length(); row[2].normalize(); shear_.fY /= scale_.fZ; shear_.fZ /= scale_.fZ; if (row[0].dot(SkVector3Cross(row[1], row[2])) < 0) { scale_.fX *= -1; scale_.fY *= -1; scale_.fZ *= -1; for (int i = 0; i < 3; i++) { row[i].fX *= -1; row[i].fY *= -1; row[i].fZ *= -1; } } rotation_.set(0.5 * sqrt(fmax(1.0 + row[0].fX - row[1].fY - row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 - row[0].fX + row[1].fY - row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 - row[0].fX - row[1].fY + row[2].fZ, 0.0)), 0.5 * sqrt(fmax(1.0 + row[0].fX + row[1].fY + row[2].fZ, 0.0))); if (row[2].fY > row[1].fZ) { rotation_.fData[0] = -rotation_.fData[0]; } if (row[0].fZ > row[2].fX) { rotation_.fData[1] = -rotation_.fData[1]; } if (row[1].fX > row[0].fY) { rotation_.fData[2] = -rotation_.fData[2]; } valid_ = true; } MatrixDecomposition::~MatrixDecomposition() = default; bool MatrixDecomposition::IsValid() const { return valid_; } } // namespace flow
27.021127
80
0.551733
alibitek
b1e1b63be32d9ae14afacee97ad9ef162e3ae6b5
8,608
cc
C++
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
9
2018-03-07T19:15:27.000Z
2019-02-22T20:10:23.000Z
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
5
2018-11-13T19:59:46.000Z
2020-04-09T19:31:25.000Z
src/3d/mpi/relax_planes.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
2
2018-07-20T01:06:48.000Z
2019-11-25T12:15:16.000Z
#include <cedar/3d/mpi/plane_mempool.h> #include <cedar/3d/mpi/plane_mpi.h> #include <cedar/3d/mpi/relax_planes.h> namespace cedar { namespace cdr3 { namespace mpi { template<relax_dir rdir> std::shared_ptr<grid_topo> planes<rdir>::slice_topo(const grid_topo & topo3) { auto igrd = std::make_shared<std::vector<len_t>>(NBMG_pIGRD); auto topo2 = std::make_shared<grid_topo>(igrd, 0, 1); topo2->nproc(2) = 1; if (rdir == relax_dir::xy) { MPI_Comm_split(topo3.comm, topo3.coord(2), topo3.coord(1) * topo3.nproc(0) + topo3.coord(0), &topo2->comm); for (auto i : range<std::size_t>(2)) { topo2->nproc(i) = topo3.nproc(i); topo2->coord(i) = topo3.coord(i); topo2->is(i) = topo3.is(i); topo2->nlocal(i) = topo3.nlocal(i); topo2->nglobal(i) = topo3.nglobal(i); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(0); auto & dimy = halo_service.leveldims(1); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else if (rdir == relax_dir::xz) { MPI_Comm_split(topo3.comm, topo3.coord(1), topo3.coord(2) * topo3.nproc(0) + topo3.coord(0), &topo2->comm); for (auto i : range<std::size_t>(2)) { auto i3 = (i == 0) ? 0 : 2; topo2->nproc(i) = topo3.nproc(i3); topo2->coord(i) = topo3.coord(i3); topo2->is(i) = topo3.is(i3); topo2->nlocal(i) = topo3.nlocal(i3); topo2->nglobal(i) = topo3.nglobal(i3); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(0); auto & dimy = halo_service.leveldims(2); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else if (rdir == relax_dir::yz) { MPI_Comm_split(topo3.comm, topo3.coord(0), topo3.coord(2) * topo3.nproc(1) + topo3.coord(1), &topo2->comm); for (auto i : range<std::size_t>(2)) { auto i3 = i + 1; topo2->nproc(i) = topo3.nproc(i3); topo2->coord(i) = topo3.coord(i3); topo2->is(i) = topo3.is(i3); topo2->nlocal(i) = topo3.nlocal(i3); topo2->nglobal(i) = topo3.nglobal(i3); } auto & halo_service = this->services->template get<halo_exchange>(); auto & dimx = halo_service.leveldims(1); auto & dimy = halo_service.leveldims(2); topo2->dimxfine.resize(topo2->nproc(0)); topo2->dimyfine.resize(topo2->nproc(1)); for (auto i : range<len_t>(topo2->nproc(0))) { topo2->dimxfine[i] = dimx(i, topo3.level()); } for (auto j : range<len_t>(topo2->nproc(1))) { topo2->dimyfine[j] = dimy(j, topo3.level()); } } else { log::error << "invalid relax_dir for planes" << std::endl; } return topo2; } template std::shared_ptr<grid_topo> planes<relax_dir::xy>::slice_topo(const grid_topo & topo3); template std::shared_ptr<grid_topo> planes<relax_dir::yz>::slice_topo(const grid_topo & topo3); template std::shared_ptr<grid_topo> planes<relax_dir::xz>::slice_topo(const grid_topo & topo3); template<relax_dir rdir> template<class sten3, class sten2> void planes<rdir>::setup_impl(const stencil_op<sten3> & so, std::vector<slv2_ptr<sten2>> & planes, std::array<plane_ult<sten2>, 2> & threads, std::array<plane_team, 2> & teams) { #ifdef PLANE_AGG this->aggregate = this->params->plane_agg; teams[0].threads = threads[0].get_threads(); teams[1].threads = threads[1].get_threads(); #else this->aggregate = false; #endif int nplanes = so.shape(2); auto rng = so.range(2); if (rdir == relax_dir::xz) { rng = so.range(1); nplanes = so.shape(1); } else if (rdir == relax_dir::yz) { rng = so.range(0); nplanes = so.shape(0); } auto kgs = so.grid().is(2); auto topo2 = slice_topo(so.grid()); auto conf2 = this->params->plane_config; auto log_planes = conf2->template get<bool>("log-planes", false); cdr2::mpi::kman_ptr master_kmans[2]; { auto tmp = log_begin(log_planes, kgs + 1 - 1, relax_dir_name<rdir>::value, topo2->comm); master_kmans[0] = master_kman(*conf2, (nplanes / 2) + (nplanes % 2), aggregate, teams[0]); log_end(log_planes, tmp); tmp = log_begin(log_planes, kgs + 2 - 1, relax_dir_name<rdir>::value, topo2->comm); master_kmans[1] = master_kman(*conf2, nplanes / 2, aggregate, teams[1]); log_end(log_planes, tmp); } for (auto ipl : rng) { int i = ipl-1; cdr2::mpi::kman_ptr kman2; auto so2_ptr = std::make_unique<cdr2::mpi::stencil_op<sten2>>(topo2); auto & so2 = *so2_ptr; plane_util<rdir>::copy_coeff(so, so2, ipl); timer_pause(); auto tmp = log_begin(log_planes, kgs + ipl - 1, relax_dir_name<rdir>::value, topo2->comm); if (i < 2) kman2 = master_kmans[i]; else { kman2 = worker_kman(*conf2, (i % 2 == 0) ? (nplanes / 2) + (nplanes % 2) : nplanes / 2, aggregate, teams[i % 2], i / 2); } planes.emplace_back(std::make_unique<cdr2::mpi::solver<sten2>>(so2, conf2, kman2)); log_end(log_planes, tmp); planes.back()->give_op(std::move(so2_ptr)); timer_play(); // setup fine-grid solution and right hand side with contiguous memory across planes { service_manager<cdr2::mpi::stypes> & sman = kman2->services(); auto & mpool = sman.get<services::mempool>(); std::size_t nbytes = topo2->nlocal(0) * topo2->nlocal(1) * sizeof(real_t); real_t *xaddr = (real_t*) mpool.addr(services::mempool::sol, nbytes); real_t *baddr = (real_t*) mpool.addr(services::mempool::rhs, nbytes); planes.back()->levels.template get<sten2>(0).x = cdr2::mpi::grid_func(xaddr, topo2); planes.back()->levels.template get<sten2>(0).b = cdr2::mpi::grid_func(baddr, topo2); } #ifdef PLANE_AGG if (aggregate) threads[i % 2].add_plane(planes.back().get()); #endif } // setup services for solve with ults #ifdef PLANE_AGG if (aggregate) { for (auto ipl : rng) { int i = ipl - 1; setup_agg_solve(*planes[i]); planes[i]->apply_heirs([](cdr2::mpi::solver<cdr2::nine_pt> & child) { setup_agg_solve(child); }); } } #endif } template void planes<relax_dir::xy>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::yz>::setup_impl<xxvii_pt, cdr2::nine_pt>(const stencil_op<xxvii_pt> & so, std::vector<slv2_ptr<cdr2::nine_pt>> & planes, std::array<plane_ult<cdr2::nine_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xy>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::xz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); template void planes<relax_dir::yz>::setup_impl<seven_pt, cdr2::five_pt>(const stencil_op<seven_pt> & so, std::vector<slv2_ptr<cdr2::five_pt>> & planes, std::array<plane_ult<cdr2::five_pt>, 2> & threads, std::array<plane_team, 2> & teams); }}}
42.196078
152
0.599907
cedar-framework
b1e5565e834926da666656b23cae4639dc61b21e
984
cpp
C++
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Core/application/parsing/preprocessing/SymbolTable.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "SymbolTable.hpp" #include "foundation/ArgumentException.hpp" namespace aapp = axis::application::parsing::preprocessing; aapp::SymbolTable::SymbolTable(void) { // no op } aapp::SymbolTable::~SymbolTable(void) { // erases symbol table and call destructors of every every contained element _table.clear(); } void aapp::SymbolTable::AddSymbol( Symbol& symbol ) { if (IsDefined(symbol.Name)) { throw axis::foundation::ArgumentException(); } _table[symbol.Name] = &symbol; } void aapp::SymbolTable::ClearTable( void ) { _table.clear(); } bool aapp::SymbolTable::IsDefined( const axis::String& name ) const { symbol_table::const_iterator it = _table.find(name); return (it != _table.end()); } const axis::String& aapp::SymbolTable::GetValue( const axis::String& name ) const { symbol_table::const_iterator it = _table.find(name); if (it == _table.end()) { // element not found throw axis::foundation::ArgumentException(); } return (it->second)->Value; }
21.391304
81
0.716463
renato-yuzup
b1e6fe39ea7a5e5a8fd4d0adef72a983b9f20547
11,788
cpp
C++
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
libatlaspack/src/textureatlaspacker.cpp
bzeller/atlaspack
abc80eff35b25af367c7b9e91272f5ff82e09272
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2017 Benjamin Zeller * * 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 <AtlasPack/TextureAtlasPacker> #include <AtlasPack/textureatlas_p.h> #include <AtlasPack/JobQueue> #include <boost/filesystem.hpp> #include <iostream> #include <fstream> #include <sstream> namespace fs = boost::filesystem; namespace AtlasPack { /** * \internal * Represents a Node in the packing tree algorithm, * can contain either child nodes or a image. The rect * variable is always set. */ struct Node { Node (Rect _rect = Rect()) : rect(_rect){} std::shared_ptr<Node> left; std::shared_ptr<Node> right; Rect rect; Image img; }; class TextureAtlasPackerPrivate { public: Node *insertImage (const Image &img, Node *node); bool collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter, std::basic_ostream<char> *descStr, Node *node, JobQueue<bool> *painterQueue, std::vector<std::future<bool> > &painterResults, std::string *err = nullptr); Node m_root; }; /** * @brief TextureAtlasPrivate::insertImage * \returns the Node the Image was inserted into, nullptr if not enough space is available */ Node *TextureAtlasPackerPrivate::insertImage(const Image &img, Node *node) { //if we have children, we are not a leaf if (node->left || node->right) { //first inside left: Node *newNode = insertImage(img, node->left.get()); if (newNode) return newNode; //no space in left, insert right return insertImage(img, node->right.get()); } else { //this path is entered if we found a leaf node //first check if the space is already filled if (node->img.isValid()) return nullptr; Pos nodePos = node->rect.topLeft; Size nodeSize = node->rect.size; //check if there is enough room if (nodeSize.height < img.height() || nodeSize.width < img.width()) { //node too small return nullptr; } //check if we found a perfect fit if (nodeSize.height == img.height() && nodeSize.width == img.width()) { //perfect fit, store the image node->img = img; return node; } //At this poing the node is splitted up //we will split in a way that we always end up with the biggest possible //empty rectangle size_t remainWidth = nodeSize.width - img.width(); size_t remainHeight = nodeSize.height - img.height(); if (remainWidth > remainHeight) { node->left = std::make_shared<Node>(Rect(nodePos, Size(img.width(), nodeSize.height))); node->right = std::make_shared<Node>(Rect(Pos(nodePos.x+img.width(), nodePos.y), Size(nodeSize.width - img.width(), nodeSize.height))); } else { node->left = std::make_shared<Node>(Rect(nodePos, Size(nodeSize.width, img.height()))); node->right = std::make_shared<Node>(Rect(Pos(nodePos.x, nodePos.y + img.height()), Size(nodeSize.width, nodeSize.height - img.height()))); } //now insert into leftmost Node return insertImage(img, node->left.get()); } } /** * @internal * @brief TextureAtlasPackerPrivate::collectNodes * Iterates over the full tree, filling the \a atlas and painting the images using the \a painter as well as writing * the image rectangle and filenmame into the output stream given by \a descStr. * If a error occurs and \a err is set, a error message is put there. */ bool TextureAtlasPackerPrivate::collectNodes(TextureAtlasPrivate *atlas, std::shared_ptr<PaintDevice> painter, std::basic_ostream<char> *descStr, Node *node, JobQueue<bool> *painterQueue, std::vector<std::future<bool>> &painterResults, std::string *err) { bool collected = false; if(node->img.isValid()) { collected = true; // we found a Image node, lets fill the information into the given structures Texture t(node->rect.topLeft, node->img); atlas->m_textures[node->img.path()] = t; // Renders the node into the atlas image, called from a async thread auto fun = [](std::shared_ptr<PaintDevice> painter, Node *node){ // paint the texture into the cache image if(!painter->paintImageFromFile(node->rect.topLeft, node->img.path())) { std::cout<<"Failed to paint image "<<node->img.path(); return false; } return true; }; // push the future results into a vector, so we can check if we had errors after all tasks are done painterResults.push_back(painterQueue->addTask(std::bind(fun, painter, node))); // the description file is written as a CSV file // @NOTE possible room for improvement, make the description file structure modular, // to make it easy to use another format (*descStr) << node->img.path() <<"," << t.pos.x<<"," << t.pos.y<<"," << t.image.width()<<"," << t.image.height()<<"\n"; } if (collected && (node->left || node->right )) { //this should never happen, if it does at least print a warning about it if(collected) std::cerr<<"Node has leafs AND image?"<<std::endl; } //recursively iterate through the child nodes, start with the left node again if(node->left) { if (!collectNodes(atlas, painter, descStr, node->left.get(), painterQueue, painterResults, err)) return false; } if(node->right){ if (!collectNodes(atlas, painter, descStr, node->right.get(), painterQueue, painterResults, err)) return false; } return true; } /** * @class TextureAtlasPacker::TextureAtlasPacker * Implements a packing algorithm to pack images into a bigger texture, called * a \a AtlasPack::TextureAtlas. This can speed up image loading in applications that make use * of a lot of small image files. * * This implementation makes use of the lightmap packing algorithm that can be found at http://blackpawn.com/texts/lightmaps/default.html */ TextureAtlasPacker::TextureAtlasPacker(Size atlasSize) : p(new TextureAtlasPackerPrivate()) { p->m_root.rect = Rect(Pos(0,0), atlasSize); } TextureAtlasPacker::~TextureAtlasPacker() { if (p) delete p; } /*! * \brief TextureAtlasPacker::size * Returns the current geometrical size of the texture atlas. */ Size TextureAtlasPacker::size() const { return p->m_root.rect.size; } /*! * \brief TextureAtlasPacker::insertImage * Tried to insert the \sa AtlasPack::Image given by \a img into the atlas. * The internal algorithm will split the atlas rectangle into smaller portions * until the image fits. * Returns \a true on success, or \a false in case the atlas does not have enough remaining space. */ bool TextureAtlasPacker::insertImage(const Image &img) { return p->insertImage(img, &p->m_root) != nullptr; } /** * \brief TextureAtlasPacker::compile * Compiles the current in memory state of the TextureAtlas into a description and * image file and stores them on disk. Expects \a basePath to point at a user writeable directory, * the last part of \a basePath will be used to form the texture atlas description file and image file names. * * \note This can take a lot of time for a big list of images, however the implementation does run with multiple * threads to speed the process up. */ TextureAtlas TextureAtlasPacker::compile(const std::string &basePath, Backend *backend, std::string *error) const { try { //the basepath is used to create the filenames for the 2 output files fs::path descFileName(basePath + ".atlas"); fs::path textureFile(basePath + ".png"); JobQueue<bool> jobs; //check if the output directory exists if (!fs::exists(descFileName.parent_path()) || !fs::is_directory(descFileName.parent_path())) { if (error) *error = "Basepath is not a directory or does not exist"; return TextureAtlas(); } //create atlas description text file std::ofstream descFile(descFileName.string(), std::ios::trunc | std::ios::out); if(!descFile.is_open()) { if (error) { std::stringstream s; s << "Could not create atlas index file "<<descFileName.string()<<" "<<strerror(errno); *error = s.str(); } return TextureAtlas(); } //get new painter instance from the backend auto painter = backend->createPaintDevice(p->m_root.rect.size); std::unique_ptr<TextureAtlasPrivate> priv = std::make_unique<TextureAtlasPrivate>(); std::vector<std::future<bool> > paintResults; //recursively collect all nodes, write them to the desc file and give paint tasks to the //JobQueue to run asynchronously if(!p->collectNodes(priv.get(), painter, &descFile, &p->m_root, &jobs, paintResults, error)) return TextureAtlas(); //wait until all painters are done jobs.waitForAllRunningTasks(); //check if we have errors in some of the painters, no need //to print which one here, because the painters will print a error message on their //own if required for (std::future<bool> &res : paintResults) { if (!res.get()) { std::cout<<"Some images failed to paint"; return TextureAtlas(); } } //finally save the result to a file if(!painter->exportToFile(textureFile.string())) { if (error) *error = "Failed to export Texture to file"; return TextureAtlas(); } descFile.close(); return TextureAtlas(priv.release()); } catch (const fs::filesystem_error& ex) { std::cerr << "Filesystem error while compiling the texture atlas: "<<ex.what() << std::endl; } catch (const std::exception &ex) { std::cerr << "Catched an exception when compiling the texture atlas."<<ex.what()<< std::endl; } catch (...) { std::cerr << "Catched an unknown exception when compiling the texture atlas." << std::endl; } return TextureAtlas(); } }
36.495356
141
0.625382
bzeller
b1e72c610db4b5556b161f6eedb7b96a501e00c3
2,387
hpp
C++
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
src/base/factory/AtmosphereFactory.hpp
supalogix/GMAT
eea9987ef0978b3e6702e70b587a098b2cbce14e
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // AtmosphereFactory //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2017 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Wendy Shoan // Created: 2004/08/12 // /** * This class is the factory class for Atmospheres. */ //------------------------------------------------------------------------------ #ifndef AtmosphereFactory_hpp #define AtmosphereFactory_hpp #include "gmatdefs.hpp" #include "Factory.hpp" #include "AtmosphereModel.hpp" class GMAT_API AtmosphereFactory : public Factory { public: GmatBase* CreateObject(const std::string &ofType, const std::string &withName = ""); AtmosphereModel* CreateAtmosphereModel(const std::string &ofType, const std::string &withName = ""); // method to return list of types of objects that this factory can create virtual StringArray GetListOfCreatableObjects( const std::string &qualifier = "Earth"); // default constructor AtmosphereFactory(); // constructor AtmosphereFactory(StringArray createList); // copy constructor AtmosphereFactory(const AtmosphereFactory& fact); // assignment operator AtmosphereFactory& operator= (const AtmosphereFactory& fact); // destructor ~AtmosphereFactory(); protected: // protected data private: }; #endif // AtmosphereFactory_hpp
31.407895
80
0.617093
supalogix
b1e762019e0a0c1218fa988e80a15a94a950c77d
26,612
hh
C++
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
8
2015-07-02T08:23:30.000Z
2020-11-17T19:00:38.000Z
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
gazebo/rendering/Camera.hh
thomas-moulard/gazebo-deb
456da84cfb7b0bdac53241f6c4e86ffe1becfa7d
[ "ECL-2.0", "Apache-2.0" ]
10
2015-04-22T18:33:15.000Z
2021-11-16T10:17:45.000Z
/* * Copyright 2012 Open Source Robotics Foundation * * 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. * */ /* Desc: A persepective OGRE Camera * Author: Nate Koenig * Date: 15 July 2003 */ #ifndef _RENDERING_CAMERA_HH_ #define _RENDERING_CAMERA_HH_ #include <boost/enable_shared_from_this.hpp> #include <string> #include <utility> #include <list> #include <vector> #include <deque> #include "common/Event.hh" #include "common/Time.hh" #include "math/Angle.hh" #include "math/Pose.hh" #include "math/Plane.hh" #include "math/Vector2i.hh" #include "msgs/MessageTypes.hh" #include "rendering/RenderTypes.hh" #include "sdf/sdf.hh" // Forward Declarations namespace Ogre { class Texture; class RenderTarget; class Camera; class Viewport; class SceneNode; class AnimationState; class CompositorInstance; } namespace gazebo { /// \ingroup gazebo_rendering /// \brief Rendering namespace namespace rendering { class MouseEvent; class ViewController; class Scene; class GaussianNoiseCompositorListener; /// \addtogroup gazebo_rendering Rendering /// \brief A set of rendering related class, functions, and definitions /// \{ /// \class Camera Camera.hh rendering/rendering.hh /// \brief Basic camera sensor /// /// This is the base class for all cameras. class Camera : public boost::enable_shared_from_this<Camera> { /// \brief Constructor /// \param[in] _namePrefix Unique prefix name for the camera. /// \param[in] _scene Scene that will contain the camera /// \param[in] _autoRender Almost everyone should leave this as true. public: Camera(const std::string &_namePrefix, ScenePtr _scene, bool _autoRender = true); /// \brief Destructor public: virtual ~Camera(); /// \brief Load the camera with a set of parmeters /// \param[in] _sdf The SDF camera info public: virtual void Load(sdf::ElementPtr _sdf); /// \brief Load the camera with default parmeters public: virtual void Load(); /// \brief Initialize the camera public: virtual void Init(); /// \brief Set the render Hz rate /// \param[in] _hz The Hz rate public: void SetRenderRate(double _hz); /// \brief Get the render Hz rate /// \return The Hz rate public: double GetRenderRate() const; /// \brief Render the camera /// /// Called after the pre-render signal. This function will generate /// camera images public: void Render(); /// \brief Post render /// /// Called afer the render signal. public: virtual void PostRender(); /// \internal /// \brief Update the camera information. This does not render images. /// /// This function gets called automatically. There is no need for the /// average user to call this function. public: virtual void Update(); /// \brief Finalize the camera. /// /// This function is called before the camera is destructed public: virtual void Fini(); /// Deprecated. /// \sa GetInitialized public: inline bool IsInitialized() const GAZEBO_DEPRECATED(1.5); /// \brief Return true if the camera has been initialized /// \return True if initialized was successful public: bool GetInitialized() const; /// \internal /// \brief Set the ID of the window this camera is rendering into. /// \param[in] _windowId The window id of the camera. public: void SetWindowId(unsigned int _windowId); /// \brief Get the ID of the window this camera is rendering into. /// \return The ID of the window. public: unsigned int GetWindowId() const; /// \brief Set the scene this camera is viewing /// \param[in] _scene Pointer to the scene public: void SetScene(ScenePtr _scene); /// \brief Get the global pose of the camera /// \return Pose of the camera in the world coordinate frame public: math::Pose GetWorldPose(); /// \brief Get the camera position in the world /// \return The world position of the camera public: math::Vector3 GetWorldPosition() const; /// \brief Get the camera's orientation in the world /// \return The camera's orientation as a math::Quaternion public: math::Quaternion GetWorldRotation() const; /// \brief Set the global pose of the camera /// \param[in] _pose The new math::Pose of the camera public: virtual void SetWorldPose(const math::Pose &_pose); /// \brief Set the world position /// \param[in] _pos The new position of the camera public: void SetWorldPosition(const math::Vector3 &_pos); /// \brief Set the world orientation /// \param[in] _quat The new orientation of the camera public: void SetWorldRotation(const math::Quaternion &_quat); /// \brief Translate the camera /// \param[in] _direction The translation vector public: void Translate(const math::Vector3 &_direction); /// \brief Rotate the camera around the yaw axis /// \param[in] _angle Rotation amount public: void RotateYaw(math::Angle _angle); /// \brief Rotate the camera around the pitch axis /// \param[in] _angle Pitch amount public: void RotatePitch(math::Angle _angle); /// \brief Set the clip distances /// \param[in] _near Near clip distance in meters /// \param[in] _far Far clip distance in meters public: void SetClipDist(float _near, float _far); /// \brief Set the camera FOV (horizontal) /// \param[in] _radians Horizontal field of view public: void SetHFOV(math::Angle _angle); /// \brief Get the camera FOV (horizontal) /// \return The horizontal field of view public: math::Angle GetHFOV() const; /// \brief Get the camera FOV (vertical) /// \return The vertical field of view public: math::Angle GetVFOV() const; /// \brief Set the image size /// \param[in] _w Image width /// \param[in] _h Image height public: void SetImageSize(unsigned int _w, unsigned int _h); /// \brief Set the image height /// \param[in] _w Image width public: void SetImageWidth(unsigned int _w); /// \brief Set the image height /// \param[in] _h Image height public: void SetImageHeight(unsigned int _h); /// \brief Get the width of the image /// \return Image width public: virtual unsigned int GetImageWidth() const; /// \brief Get the width of the off-screen render texture /// \return Render texture width public: unsigned int GetTextureWidth() const; /// \brief Get the height of the image /// \return Image height public: virtual unsigned int GetImageHeight() const; /// \brief Get the depth of the image /// \return Depth of the image public: unsigned int GetImageDepth() const; /// \brief Get the string representation of the image format. /// \return String representation of the image format. public: std::string GetImageFormat() const; /// \brief Get the height of the off-screen render texture /// \return Render texture height public: unsigned int GetTextureHeight() const; /// \brief Get the image size in bytes /// \return Size in bytes public: size_t GetImageByteSize() const; /// \brief Calculate image byte size base on a few parameters. /// \param[in] _width Width of an image /// \param[in] _height Height of an image /// \param[in] _format Image format /// \return Size of an image based on the parameters public: static size_t GetImageByteSize(unsigned int _width, unsigned int _height, const std::string &_format); /// \brief Get the Z-buffer value at the given image coordinate. /// \param[in] _x Image coordinate; (0, 0) specifies the top-left corner. /// \param[in] _y Image coordinate; (0, 0) specifies the top-left corner. /// \returns Image z value; note that this is abitrarily scaled and /// is @e not the same as the depth value. public: double GetZValue(int _x, int _y); /// \brief Get the near clip distance /// \return Near clip distance public: double GetNearClip(); /// \brief Get the far clip distance /// \return Far clip distance public: double GetFarClip(); /// \brief Enable or disable saving /// \param[in] _enable Set to True to enable saving of frames public: void EnableSaveFrame(bool _enable); /// \brief Set the save frame pathname /// \param[in] _pathname Directory in which to store saved image frames public: void SetSaveFramePathname(const std::string &_pathname); /// \brief Save the last frame to disk /// \param[in] _filename File in which to save a single frame /// \return True if saving was successful public: bool SaveFrame(const std::string &_filename); /// \brief Get a pointer to the ogre camera /// \return Pointer to the OGRE camera public: Ogre::Camera *GetOgreCamera() const; /// \brief Get a pointer to the Ogre::Viewport /// \return Pointer to the Ogre::Viewport public: Ogre::Viewport *GetViewport() const; /// \brief Get the viewport width in pixels /// \return The viewport width public: unsigned int GetViewportWidth() const; /// \brief Get the viewport height in pixels /// \return The viewport height public: unsigned int GetViewportHeight() const; /// \brief Get the viewport up vector /// \return The viewport up vector public: math::Vector3 GetUp(); /// \brief Get the viewport right vector /// \return The viewport right vector public: math::Vector3 GetRight(); /// \brief Get the average FPS /// \return The average frames per second public: virtual float GetAvgFPS() {return 0;} /// \brief Get the triangle count /// \return The current triangle count public: virtual unsigned int GetTriangleCount() {return 0;} /// \brief Set the aspect ratio /// \param[in] _ratio The aspect ratio (width / height) in pixels public: void SetAspectRatio(float _ratio); /// \brief Get the apect ratio /// \return The aspect ratio (width / height) in pixels public: float GetAspectRatio() const; /// \brief Set the camera's scene node /// \param[in] _node The scene nodes to attach the camera to public: void SetSceneNode(Ogre::SceneNode *_node); /// \brief Get the camera's scene node /// \return The scene node the camera is attached to public: Ogre::SceneNode *GetSceneNode() const; /// \brief Get the camera's pitch scene node /// \return The pitch node the camera is attached to public: Ogre::SceneNode *GetPitchNode() const; /// \brief Get a pointer to the image data /// /// Get the raw image data from a camera's buffer. /// \param[in] _i Index of the camera's texture (0 = RGB, 1 = depth). /// \return Pointer to the raw data, null if data is not available. public: virtual const unsigned char *GetImageData(unsigned int i = 0); /// \brief Get the camera's name /// \return The name of the camera public: std::string GetName() const; /// \brief Set the camera's name /// \param[in] _name New name for the camera public: void SetName(const std::string &_name); /// \brief Toggle whether to view the world in wireframe public: void ToggleShowWireframe(); /// \brief Set whether to view the world in wireframe /// \param[in] _s Set to True to render objects as wireframe public: void ShowWireframe(bool _s); /// \brief Get a world space ray as cast from the camera /// through the viewport /// \param[in] _screenx X coordinate in the camera's viewport, in pixels. /// \param[in] _screeny Y coordinate in the camera's viewport, in pixels. /// \param[out] _origin Origin in the world coordinate frame of the /// resulting ray /// \param[out] _dir Direction of the resulting ray public: void GetCameraToViewportRay(int _screenx, int _screeny, math::Vector3 &_origin, math::Vector3 &_dir); /// \brief Set whether to capture data /// \param[in] _value Set to true to capture data into a memory buffer. public: void SetCaptureData(bool _value); /// \brief Capture data once and save to disk public: void SetCaptureDataOnce(); /// \brief Set the render target /// \param[in] _textureName Name of the new render texture public: void CreateRenderTexture(const std::string &_textureName); /// \brief Get the scene this camera is in /// \return Pointer to scene containing this camera public: ScenePtr GetScene() const; /// \brief Get point on a plane /// \param[in] _x X cooridnate in camera's viewport, in pixels /// \param[in] _y Y cooridnate in camera's viewport, in pixels /// \param[in] _plane Plane on which to find the intersecting point /// \param[out] _result Point on the plane /// \return True if a valid point was found public: bool GetWorldPointOnPlane(int _x, int _y, const math::Plane &_plane, math::Vector3 &_result); /// \brief Set the camera's render target /// \param[in] _target Pointer to the render target public: virtual void SetRenderTarget(Ogre::RenderTarget *_target); /// \brief Attach the camera to a scene node /// \param[in] _visualName Name of the visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual public: void AttachToVisual(const std::string &_visualName, bool _inheritOrientation, double _minDist = 0.0, double _maxDist = 0.0); /// \brief Set the camera to track a scene node /// \param[in] _visualName Name of the visual to track public: void TrackVisual(const std::string &_visualName); /// \brief Get the render texture /// \return Pointer to the render texture public: Ogre::Texture *GetRenderTexture() const; /// \brief Get the camera's direction vector /// \return Direction the camera is facing public: math::Vector3 GetDirection() const; /// \brief Connect to the new image signal /// \param[in] _subscriber Callback that is called when a new image is /// generated /// \return A pointer to the connection. This must be kept in scope. public: template<typename T> event::ConnectionPtr ConnectNewImageFrame(T _subscriber) {return newImageFrame.Connect(_subscriber);} /// \brief Disconnect from an image frame /// \param[in] _c The connection to disconnect public: void DisconnectNewImageFrame(event::ConnectionPtr &_c) {newImageFrame.Disconnect(_c);} /// \brief Save a frame using an image buffer /// \param[in] _image The raw image buffer /// \param[in] _width Width of the image /// \param[in] _height Height of the image /// \param[in] _depth Depth of the image data /// \param[in] _format Format the image data is in /// \param[in] _filename Name of the file in which to write the frame /// \return True if saving was successful public: static bool SaveFrame(const unsigned char *_image, unsigned int _width, unsigned int _height, int _depth, const std::string &_format, const std::string &_filename); /// \brief Get the last time the camera was rendered /// \return Time the camera was last rendered public: common::Time GetLastRenderWallTime(); /// \brief Return true if the visual is within the camera's view /// frustum /// \param[in] _visual The visual to check for visibility /// \return True if the _visual is in the camera's frustum public: bool IsVisible(VisualPtr _visual); /// \brief Return true if the visual is within the camera's view /// frustum /// \param[in] _visualName Name of the visual to check for visibility /// \return True if the _visual is in the camera's frustum public: bool IsVisible(const std::string &_visualName); /// \brief Return true if the camera is moving due to an animation. public: bool IsAnimating() const; /// \brief Move the camera to a position (this is an animated motion). /// \sa Camera::MoveToPositions /// \param[in] _pose End position of the camera /// \param[in] _time Duration of the camera's movement public: virtual bool MoveToPosition(const math::Pose &_pose, double _time); /// \brief Move the camera to a series of poses (this is an /// animated motion). /// \sa Camera::MoveToPosition /// \param[in] _pts Vector of poses to move to /// \param[in] _time Duration of the entire move /// \param[in] _onComplete Callback that is called when the move is /// complete public: bool MoveToPositions(const std::vector<math::Pose> &_pts, double _time, boost::function<void()> _onComplete = NULL); /// \brief Get the path to saved screenshots. /// \return Path to saved screenshots. public: std::string GetScreenshotPath() const; /// \brief Implementation of the render call protected: virtual void RenderImpl(); /// \brief Implementation of the Camera::TrackVisual call /// \param[in] _visualName Name of the visual to track /// \return True if able to track the visual protected: bool TrackVisualImpl(const std::string &_visualName); /// \brief Set the camera to track a scene node /// \param[in] _visual The visual to track /// \return True if able to track the visual protected: virtual bool TrackVisualImpl(VisualPtr _visual); /// \brief Attach the camera to a scene node /// \param[in] _visualName Name of the visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual /// \return True on success protected: virtual bool AttachToVisualImpl(const std::string &_name, bool _inheritOrientation, double _minDist = 0, double _maxDist = 0); /// \brief Attach the camera to a visual /// \param[in] _visual The visual to attach the camera to /// \param[in] _inheritOrientation True means camera acquires the visual's /// orientation /// \param[in] _minDist Minimum distance the camera is allowed to get to /// the visual /// \param[in] _maxDist Maximum distance the camera is allowd to get from /// the visual /// \return True on success protected: virtual bool AttachToVisualImpl(VisualPtr _visual, bool _inheritOrientation, double _minDist = 0, double _maxDist = 0); /// \brief Get the next frame filename based on SDF parameters /// \return The frame's filename protected: std::string GetFrameFilename(); /// \brief Internal function used to indicate that an animation has /// completed. protected: virtual void AnimationComplete(); /// \brief if user requests bayer image, post process rgb from ogre /// to generate bayer formats /// \param[in] _dst Destination buffer for the image data /// \param[in] _src Source image buffer /// \param[in] _format Format of the source buffer /// \param[in] _width Image width /// \param[in] _height Image height private: void ConvertRGBToBAYER(unsigned char *_dst, unsigned char *_src, std::string _format, int _width, int _height); /// \brief Set the clip distance based on stored SDF values private: void SetClipDist(); /// \brief Get the OGRE image pixel format in /// \param[in] _format The Gazebo image format /// \return Integer representation of the Ogre image format private: static int GetOgrePixelFormat(const std::string &_format); /// \brief Create the ogre camera. private: void CreateCamera(); /// \brief Name of the camera. protected: std::string name; /// \brief Camera's SDF values. protected: sdf::ElementPtr sdf; /// \brief ID of the window that the camera is attached to. protected: unsigned int windowId; /// \brief Width of the render texture. protected: unsigned int textureWidth; /// \brief Height of the render texture. protected: unsigned int textureHeight; /// \brief The OGRE camera protected: Ogre::Camera *camera; /// \brief Viewport the ogre camera uses. protected: Ogre::Viewport *viewport; /// \brief Scene node that controls camera position. protected: Ogre::SceneNode *sceneNode; /// \brief Scene nod that controls camera pitch. protected: Ogre::SceneNode *pitchNode; // \brief Buffer for a single image frame. protected: unsigned char *saveFrameBuffer; /// \brief Buffer for a bayer image frame. protected: unsigned char *bayerFrameBuffer; /// \brief Number of saved frames. protected: unsigned int saveCount; /// \brief Path to saved screenshots. protected: std::string screenshotPath; /// \brief Format for saving images. protected: int imageFormat; /// \brief Save image width. protected: int imageWidth; /// \brief Save image height. protected: int imageHeight; /// \brief Target that renders frames. protected: Ogre::RenderTarget *renderTarget; /// \brief Texture that receives results from rendering. protected: Ogre::Texture *renderTexture; /// \brief True to capture frames into an image buffer. protected: bool captureData; /// \brief True to capture a frame once and save to disk. protected: bool captureDataOnce; /// \brief True if new data is available. protected: bool newData; /// \brief Time the last frame was rendered. protected: common::Time lastRenderWallTime; /// \brief Pointer to the scene. protected: ScenePtr scene; /// \brief Event triggered when a new frame is generated. protected: event::EventT<void(const unsigned char *, unsigned int, unsigned int, unsigned int, const std::string &)> newImageFrame; /// \brief The camera's event connections. protected: std::vector<event::ConnectionPtr> connections; /// \brief List of requests. protected: std::list<msgs::Request> requests; /// \brief True if initialized. protected: bool initialized; /// \brief Animation state, used to animate the camera. protected: Ogre::AnimationState *animState; /// \brief Previous time the camera animation was updated. protected: common::Time prevAnimTime; /// \brief User callback for when an animation completes. protected: boost::function<void()> onAnimationComplete; /// \brief Pointer to image SDF element. private: sdf::ElementPtr imageElem; /// \brief Visual that the camera is tracking. private: VisualPtr trackedVisual; /// \brief Counter used to create unique camera names. private: static unsigned int cameraCounter; /// \brief Deferred shading geometry buffer. private: Ogre::CompositorInstance *dsGBufferInstance; /// \brief Deferred shading merge compositor. private: Ogre::CompositorInstance *dsMergeInstance; /// \brief Deferred lighting geometry buffer. private: Ogre::CompositorInstance *dlGBufferInstance; /// \brief Deferred lighting merge compositor. private: Ogre::CompositorInstance *dlMergeInstance; /// \brief Screen space ambient occlusion compositor. private: Ogre::CompositorInstance *ssaoInstance; /// \brief Gaussian noise compositor private: Ogre::CompositorInstance *gaussianNoiseInstance; /// \brief Gaussian noise compositor listener private: boost::shared_ptr<GaussianNoiseCompositorListener> gaussianNoiseCompositorListener; /// \brief Queue of move positions. private: std::deque<std::pair<math::Pose, double> > moveToPositionQueue; /// \brief Render period. private: common::Time renderPeriod; /// \brief Which noise type we support private: enum NoiseModelType { NONE, GAUSSIAN }; /// \brief If true, apply the noise model specified by other /// noise parameters private: bool noiseActive; /// \brief Which type of noise we're applying private: enum NoiseModelType noiseType; /// \brief If noiseType==GAUSSIAN, noiseMean is the mean of the /// distibution from which we sample private: double noiseMean; /// \brief If noiseType==GAUSSIAN, noiseStdDev is the standard /// devation of the distibution from which we sample private: double noiseStdDev; }; /// \} } } #endif
37.534556
80
0.645498
thomas-moulard