text
stringlengths
5
1.04M
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/storage/minfs/lazy_reader.h" namespace minfs { zx_status_t LazyReader::Read(ByteRange range, ReaderInterface* reader) { if (range.Length() == 0) return ZX_OK; // Find the first block that isn't loaded. const range::Range block_range = BytesToBlocks(range, reader->BlockSize()); // TODO(fxbug.dev/50842): Make RleBitmap work with uint64_t. size_t block = static_cast<size_t>(block_range.Start()); if (mapped_.GetOne(block)) { mapped_.Find(false, block + 1, block_range.End(), 1, &block); } // Loop through all unloaded block ranges and enqueue reads for them. while (block < block_range.End()) { size_t end; mapped_.Find(true, block + 1, block_range.End(), 1, &end); zx_status_t status = EnumerateBlocks(BlockRange(block, end), [&](BlockRange range) { return reader->Enqueue(range); }); if (status != ZX_OK) return status; mapped_.Find(false, end + 1, block_range.End(), 1, &block); } // Issue and wait for the reads to complete. zx_status_t status = reader->RunRequests(); if (status != ZX_OK) return status; // Mark the whole range as loaded. mapped_.Set(block_range.Start(), block_range.End()); return ZX_OK; } void LazyReader::SetLoaded(BlockRange range, bool set) { if (set) { mapped_.Set(range.Start(), range.End()); } else { mapped_.Clear(range.Start(), range.End()); } } zx::status<uint64_t> MappedFileReader::Enqueue(BlockRange range) { zx::status<DeviceBlockRange> status = mapper_.Map(range); if (status.is_error()) return status.take_error(); const DeviceBlockRange device_range = status.value(); if (device_range.IsMapped()) { builder_.Add( storage::Operation{ .type = storage::OperationType::kRead, .vmo_offset = range.Start(), .dev_offset = device_range.block(), .length = device_range.count(), }, &buffer_); } else { // This probably isn't necessary because the blocks should already be clean, but it's safe. buffer_.Zero(range.Start(), device_range.count()); } return zx::ok(device_range.count()); } } // namespace minfs
#include <pybind11/pybind11.h> #include <osmium/geom/mercator_projection.hpp> #include <osmium/geom/coordinates.hpp> #include <osmium/geom/haversine.hpp> #include <osmium/geom/factory.hpp> #include <osmium/geom/wkb.hpp> #include <osmium/geom/wkt.hpp> #include <osmium/geom/geojson.hpp> namespace py = pybind11; namespace og = osmium::geom; struct WKBFactory : osmium::geom::WKBFactory<> { public: WKBFactory() : og::WKBFactory<>(og::wkb_type::wkb, og::out_type::hex) {} }; using WKTFactory = og::WKTFactory<>; using GeoJSONFactory = og::GeoJSONFactory<>; PYBIND11_MODULE(geom, m) { py::enum_<og::use_nodes>(m, "use_nodes") .value("UNIQUE", og::use_nodes::unique) .value("ALL", og::use_nodes::all) .export_values() ; py::enum_<og::direction>(m, "direction") .value("BACKWARD", og::direction::backward) .value("FORWARD", og::direction::forward) .export_values() ; py::class_<osmium::geom::Coordinates>(m, "Coordinates", "Class representing coordinates") .def(py::init<>()) .def(py::init<double, double>()) .def(py::init<osmium::Location const &>()) .def_readonly("x", &osmium::geom::Coordinates::x, "(read-only) X coordinate.") .def_readonly("y", &osmium::geom::Coordinates::y, "(read-only) Y coordinate.") .def("valid", &osmium::geom::Coordinates::valid, "True if coordinates are valid") ; m.def("haversine_distance", (double (*)(const osmium::WayNodeList&)) &og::haversine::distance, py::arg("list"), "Compute the distance using the Haversine algorithm which takes the " "curvature of earth into account. If a :py:class:`WayNodeList` is given " "as a parameter the total length of the way in meters is computed."); m.def("lonlat_to_mercator", &og::lonlat_to_mercator, py::arg("coordinate"), "Convert coordinates from WGS84 to Mercator projection."); m.def("mercator_to_lonlat", &og::mercator_to_lonlat, py::arg("coordinate"), "Convert coordinates from WGS84 to Mercator projection."); py::class_<WKBFactory>(m, "WKBFactory", "Factory that creates WKB from osmium geometries.") .def(py::init<>()) .def_property_readonly("epsg", &WKBFactory::epsg, "(read-only) EPSG number of the output geometry.") .def_property_readonly("proj_string", &WKBFactory::proj_string, "(read-only) projection string of the output geometry.") .def("create_point", (std::string (WKBFactory::*)(const osmium::Location&) const) &WKBFactory::create_point, py::arg("location"), "Create a point geometry from a :py:class:`osmium.osm.Location`.") .def("create_point", (std::string (WKBFactory::*)(const osmium::Node&)) &WKBFactory::create_point, py::arg("node"), "Create a point geometry from a :py:class:`osmium.osm.Node`.") .def("create_point", (std::string (WKBFactory::*)(const osmium::NodeRef&)) &WKBFactory::create_point, py::arg("ref"), "Create a point geometry from a :py:class:`osmium.osm.NodeRef`.") .def("create_linestring", (std::string (WKBFactory::*)(const osmium::WayNodeList&, og::use_nodes, og::direction)) &WKBFactory::create_linestring, py::arg("list"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.WayNodeList`.") .def("create_linestring", (std::string (WKBFactory::*)(const osmium::Way&, og::use_nodes, og::direction)) &WKBFactory::create_linestring, py::arg("way"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.Way`.") .def("create_multipolygon", &WKBFactory::create_multipolygon, py::arg("area"), "Create a MultiPolygon geometry from a :py:class:`osmium.osm.Area`.") ; py::class_<WKTFactory>(m, "WKTFactory", "Factory that creates WKT from osmium geometries.") .def(py::init<>()) .def_property_readonly("epsg", &WKTFactory::epsg, "(read-only) EPSG number of the output geometry.") .def_property_readonly("proj_string", &WKTFactory::proj_string, "(read-only) projection string of the output geometry.") .def("create_point", (std::string (WKTFactory::*)(const osmium::Location&) const) &WKTFactory::create_point, py::arg("location"), "Create a point geometry from a :py:class:`osmium.osm.Location`.") .def("create_point", (std::string (WKTFactory::*)(const osmium::Node&)) &WKTFactory::create_point, py::arg("node"), "Create a point geometry from a :py:class:`osmium.osm.Node`.") .def("create_point", (std::string (WKTFactory::*)(const osmium::NodeRef&)) &WKTFactory::create_point, py::arg("ref"), "Create a point geometry from a :py:class:`osmium.osm.NodeRef`.") .def("create_linestring", (std::string (WKTFactory::*)(const osmium::WayNodeList&, og::use_nodes, og::direction)) &WKTFactory::create_linestring, py::arg("list"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.WayNodeList`.") .def("create_linestring", (std::string (WKTFactory::*)(const osmium::Way&, og::use_nodes, og::direction)) &WKTFactory::create_linestring, py::arg("way"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.Way`.") .def("create_multipolygon", &WKTFactory::create_multipolygon, py::arg("area"), "Create a MultiPolygon geometry from a :py:class:`osmium.osm.Area`.") ; py::class_<GeoJSONFactory>(m, "GeoJSONFactory", "Factory that creates GeoJSON geometries from osmium geometries.") .def(py::init<>()) .def_property_readonly("epsg", &GeoJSONFactory::epsg, "(read-only) EPSG number of the output geometry.") .def_property_readonly("proj_string", &GeoJSONFactory::proj_string, "(read-only) projection string of the output geometry.") .def("create_point", (std::string (GeoJSONFactory::*)(const osmium::Location&) const) &GeoJSONFactory::create_point, py::arg("location"), "Create a point geometry from a :py:class:`osmium.osm.Location`.") .def("create_point", (std::string (GeoJSONFactory::*)(const osmium::Node&)) &GeoJSONFactory::create_point, py::arg("node"), "Create a point geometry from a :py:class:`osmium.osm.Node`.") .def("create_point", (std::string (GeoJSONFactory::*)(const osmium::NodeRef&)) &GeoJSONFactory::create_point, py::arg("ref"), "Create a point geometry from a :py:class:`osmium.osm.NodeRef`.") .def("create_linestring", (std::string (GeoJSONFactory::*)(const osmium::WayNodeList&, og::use_nodes, og::direction)) &GeoJSONFactory::create_linestring, py::arg("list"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.WayNodeList`.") .def("create_linestring", (std::string (GeoJSONFactory::*)(const osmium::Way&, og::use_nodes, og::direction)) &GeoJSONFactory::create_linestring, py::arg("way"), py::arg("use_nodes")=og::use_nodes::unique, py::arg("direction")=og::direction::forward, "Create a LineString geometry from a :py:class:`osmium.osm.Way`.") .def("create_multipolygon", &GeoJSONFactory::create_multipolygon, py::arg("area"), "Create a MultiPolygon geometry from a :py:class:`osmium.osm.Area`.") ; }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" #include "UnicodeStorage.hpp" #include "CharRow.hpp" // Routine Description: // - assignment operator. will store extended glyph data in a separate storage location // Arguments: // - chars - the glyph data to store void CharRowCellReference::operator=(const std::wstring_view chars) { THROW_HR_IF(E_INVALIDARG, chars.empty()); if (chars.size() == 1) { _cellData().Char() = chars.front(); _cellData().DbcsAttr().SetGlyphStored(false); } else { auto& storage = _parent.GetUnicodeStorage(); const auto key = _parent.GetStorageKey(_index); storage.StoreGlyph(key, { chars.cbegin(), chars.cend() }); _cellData().DbcsAttr().SetGlyphStored(true); } } // Routine Description: // - implicit conversion to vector<wchar_t> operator. // Return Value: // - std::vector<wchar_t> of the glyph data in the referenced cell CharRowCellReference::operator std::wstring_view() const { return _glyphData(); } // Routine Description: // - The CharRowCell this object "references" // Return Value: // - ref to the CharRowCell CharRowCell& CharRowCellReference::_cellData() { return _parent._data.at(_index); } // Routine Description: // - The CharRowCell this object "references" // Return Value: // - ref to the CharRowCell const CharRowCell& CharRowCellReference::_cellData() const { return _parent._data.at(_index); } // Routine Description: // - the glyph data of the referenced cell // Return Value: // - the glyph data std::wstring_view CharRowCellReference::_glyphData() const { if (_cellData().DbcsAttr().IsGlyphStored()) { const auto& text = _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index)); return { text.data(), text.size() }; } else { return { &_cellData().Char(), 1 }; } } // Routine Description: // - gets read-only iterator to the beginning of the glyph data // Return Value: // - iterator of the glyph data CharRowCellReference::const_iterator CharRowCellReference::begin() const { if (_cellData().DbcsAttr().IsGlyphStored()) { return _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index)).data(); } else { return &_cellData().Char(); } } // Routine Description: // - get read-only iterator to the end of the glyph data // Return Value: // - end iterator of the glyph data #pragma warning(push) #pragma warning(disable : 26481) // TODO GH 2672: eliminate using pointers raw as begin/end markers in this class CharRowCellReference::const_iterator CharRowCellReference::end() const { if (_cellData().DbcsAttr().IsGlyphStored()) { const auto& chars = _parent.GetUnicodeStorage().GetText(_parent.GetStorageKey(_index)); return chars.data() + chars.size(); } else { return &_cellData().Char() + 1; } } #pragma warning(pop) bool operator==(const CharRowCellReference& ref, const std::vector<wchar_t>& glyph) { const auto& dbcsAttr = ref._cellData().DbcsAttr(); if (glyph.size() == 1 && dbcsAttr.IsGlyphStored()) { return false; } else if (glyph.size() > 1 && !dbcsAttr.IsGlyphStored()) { return false; } else if (glyph.size() == 1 && !dbcsAttr.IsGlyphStored()) { return ref._cellData().Char() == glyph.front(); } else { const auto& chars = ref._parent.GetUnicodeStorage().GetText(ref._parent.GetStorageKey(ref._index)); return chars == glyph; } } bool operator==(const std::vector<wchar_t>& glyph, const CharRowCellReference& ref) { return ref == glyph; }
/**************************************************************************** * * Copyright (c) 2021 PX4 Development Team. 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. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "SensorMagSim.hpp" #include <drivers/drv_sensor.h> #include <lib/world_magnetic_model/geo_mag_declination.h> using namespace matrix; SensorMagSim::SensorMagSim() : ModuleParams(nullptr), ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::hp_default) { _px4_mag.set_device_type(DRV_MAG_DEVTYPE_MAGSIM); } SensorMagSim::~SensorMagSim() { perf_free(_loop_perf); } bool SensorMagSim::init() { ScheduleOnInterval(20_ms); // 50 Hz return true; } float SensorMagSim::generate_wgn() { // generate white Gaussian noise sample with std=1 // algorithm 1: // float temp=((float)(rand()+1))/(((float)RAND_MAX+1.0f)); // return sqrtf(-2.0f*logf(temp))*cosf(2.0f*M_PI_F*rand()/RAND_MAX); // algorithm 2: from BlockRandGauss.hpp static float V1, V2, S; static bool phase = true; float X; if (phase) { do { float U1 = (float)rand() / (float)RAND_MAX; float U2 = (float)rand() / (float)RAND_MAX; V1 = 2.0f * U1 - 1.0f; V2 = 2.0f * U2 - 1.0f; S = V1 * V1 + V2 * V2; } while (S >= 1.0f || fabsf(S) < 1e-8f); X = V1 * float(sqrtf(-2.0f * float(logf(S)) / S)); } else { X = V2 * float(sqrtf(-2.0f * float(logf(S)) / S)); } phase = !phase; return X; } void SensorMagSim::Run() { if (should_exit()) { ScheduleClear(); exit_and_cleanup(); return; } perf_begin(_loop_perf); // Check if parameters have changed if (_parameter_update_sub.updated()) { // clear update parameter_update_s param_update; _parameter_update_sub.copy(&param_update); updateParams(); } if (_vehicle_global_position_sub.updated()) { vehicle_global_position_s gpos; if (_vehicle_global_position_sub.copy(&gpos)) { if (gpos.eph < 1000) { // magnetic field data returned by the geo library using the current GPS position const float mag_declination_gps = get_mag_declination_radians(gpos.lat, gpos.lon); const float mag_inclination_gps = get_mag_inclination_radians(gpos.lat, gpos.lon); const float mag_strength_gps = get_mag_strength_gauss(gpos.lat, gpos.lon); _mag_earth_pred = Dcmf(Eulerf(0, -mag_inclination_gps, mag_declination_gps)) * Vector3f(mag_strength_gps, 0, 0); _mag_earth_available = true; } } } if (_mag_earth_available) { vehicle_attitude_s attitude; if (_vehicle_attitude_sub.update(&attitude)) { Vector3f expected_field = Dcmf{Quatf{attitude.q}} .transpose() * _mag_earth_pred; expected_field += noiseGauss3f(0.02f, 0.02f, 0.03f); _px4_mag.update(attitude.timestamp, expected_field(0) + _sim_mag_offset_x.get(), expected_field(1) + _sim_mag_offset_y.get(), expected_field(2) + _sim_mag_offset_z.get()); } } perf_end(_loop_perf); } int SensorMagSim::task_spawn(int argc, char *argv[]) { SensorMagSim *instance = new SensorMagSim(); if (instance) { _object.store(instance); _task_id = task_id_is_work_queue; if (instance->init()) { return PX4_OK; } } else { PX4_ERR("alloc failed"); } delete instance; _object.store(nullptr); _task_id = -1; return PX4_ERROR; } int SensorMagSim::custom_command(int argc, char *argv[]) { return print_usage("unknown command"); } int SensorMagSim::print_usage(const char *reason) { if (reason) { PX4_WARN("%s\n", reason); } PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description )DESCR_STR"); PRINT_MODULE_USAGE_NAME("sensor_mag_sim", "system"); PRINT_MODULE_USAGE_COMMAND("start"); PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); return 0; } extern "C" __EXPORT int sensor_mag_sim_main(int argc, char *argv[]) { return SensorMagSim::main(argc, argv); }
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "utils/NebulaKeyUtils.h" #include <gtest/gtest.h> #include <rocksdb/db.h> #include <limits> #include "fs/TempDir.h" #include "storage/test/TestUtils.h" #include "storage/mutate/UpdateVertexProcessor.h" #include "dataman/RowSetReader.h" #include "dataman/RowReader.h" namespace nebula { namespace storage { void mockData(kvstore::KVStore* kv) { LOG(INFO) << "Prepare data..."; std::vector<kvstore::KV> data; for (int32_t partId = 0; partId < 3; partId++) { for (int32_t vertexId = partId * 10; vertexId < (partId + 1) * 10; vertexId++) { // NOTE: the range of tagId is [3001, 3008], excluding 3009(for insert test). for (int32_t tagId = 3001; tagId < 3010 - 1; tagId++) { // Write multi versions, we should get/update the latest version for (int32_t version = 0; version < 3; version++) { auto key = NebulaKeyUtils::vertexKey(partId, vertexId, tagId, std::numeric_limits<int32_t>::max() - version); RowWriter writer; for (int64_t numInt = 0; numInt < 3; numInt++) { writer << partId + tagId + version + numInt; } for (auto numString = 3; numString < 6; numString++) { writer << folly::stringPrintf("tag_string_col_%d_%d", numString, version); } auto val = writer.encode(); data.emplace_back(std::move(key), std::move(val)); } } } folly::Baton<true, std::atomic> baton; kv->asyncMultiPut(0, partId, std::move(data), [&](kvstore::ResultCode code) { CHECK_EQ(code, kvstore::ResultCode::SUCCEEDED); baton.post(); }); baton.wait(); } } TEST(UpdateVertexTest, Set_Filter_Yield_Test) { fs::TempDir rootPath("/tmp/UpdateVertexTest.XXXXXX"); std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path()); LOG(INFO) << "Prepare meta..."; auto schemaMan = TestUtils::mockSchemaMan(); auto indexMan = TestUtils::mockIndexMan(); mockData(kv.get()); LOG(INFO) << "Build UpdateVertexRequest..."; GraphSpaceID spaceId = 0; PartitionID partId = 0; VertexID vertexId = 1; cpp2::UpdateVertexRequest req; req.set_space_id(spaceId); req.set_vertex_id(vertexId); req.set_part_id(partId); LOG(INFO) << "Build filter..."; // left int: $^.3001.tag_3001_col_2 >= 3001 auto* tag1 = new std::string("3001"); auto* prop1 = new std::string("tag_3001_col_2"); auto* srcExp1 = new SourcePropertyExpression(tag1, prop1); auto* priExp1 = new PrimaryExpression(3001L); auto* left = new RelationalExpression(srcExp1, RelationalExpression::Operator::GE, priExp1); // right string: $^.3001.tag_3001_col_3 == tag_string_col_3_2; auto* tag2 = new std::string("3001"); auto* prop2 = new std::string("tag_3001_col_3"); auto* srcExp2 = new SourcePropertyExpression(tag2, prop2); std::string col3("tag_string_col_3_2"); auto* priExp2 = new PrimaryExpression(col3); auto* right = new RelationalExpression(srcExp2, RelationalExpression::Operator::EQ, priExp2); // left AND right is ture auto logExp = std::make_unique<LogicalExpression>(left, LogicalExpression::AND, right); req.set_filter(Expression::encode(logExp.get())); LOG(INFO) << "Build update items..."; std::vector<cpp2::UpdateItem> items; // int: 3001.tag_3001_col_0 = 1 cpp2::UpdateItem item1; item1.set_name("3001"); item1.set_prop("tag_3001_col_0"); PrimaryExpression val1(1L); item1.set_value(Expression::encode(&val1)); items.emplace_back(item1); // string: 3001.tag_3001_col_4 = tag_string_col_4_2_new cpp2::UpdateItem item2; item2.set_name("3001"); item2.set_prop("tag_3001_col_4"); std::string col4new("tag_string_col_4_2_new"); PrimaryExpression val2(col4new); item2.set_value(Expression::encode(&val2)); items.emplace_back(item2); req.set_update_items(std::move(items)); LOG(INFO) << "Build yield..."; // Return tag props: 3001.tag_3001_col_0, 3001.tag_3001_col_2, 3001.tag_3001_col_4 decltype(req.return_columns) tmpColumns; for (int i = 0; i < 3; i++) { SourcePropertyExpression sourcePropExp( new std::string(folly::to<std::string>(3001)), new std::string(folly::stringPrintf("tag_%d_col_%d", 3001, i * 2))); tmpColumns.emplace_back(Expression::encode(&sourcePropExp)); } req.set_return_columns(std::move(tmpColumns)); req.set_insertable(false); LOG(INFO) << "Test UpdateVertexRequest..."; auto* processor = UpdateVertexProcessor::instance(kv.get(), schemaMan.get(), indexMan.get(), nullptr); auto f = processor->getFuture(); processor->process(req); auto resp = std::move(f).get(); LOG(INFO) << "Check the results..."; EXPECT_EQ(0, resp.result.failed_codes.size()); EXPECT_FALSE(resp.get_upsert()); ASSERT_TRUE(resp.__isset.schema); auto provider = std::make_shared<ResultSchemaProvider>(resp.schema); auto reader = RowReader::getRowReader(resp.data, provider); EXPECT_EQ(3, reader->numFields()); for (int i = 0; i < 3; i++) { auto res = RowReader::getPropByIndex(reader.get(), i); if (ok(res)) { switch (i) { case 0: { auto&& v0 = value(std::move(res)); EXPECT_EQ(1L, boost::get<int64_t>(v0)); break; } case 1: { auto&& v1 = value(std::move(res)); EXPECT_EQ(0 + 3001 + 2 + 2, boost::get<int64_t>(v1)); break; } case 2: { auto&& v2 = value(std::move(res)); EXPECT_STREQ("tag_string_col_4_2_new", boost::get<std::string>(v2).c_str()); break; } default: break; } } } // get tag3001 from kvstore directly std::vector<std::string> keys; std::vector<std::string> values; auto lastVersion = std::numeric_limits<int32_t>::max() - 2; auto vertexKey = NebulaKeyUtils::vertexKey(partId, vertexId, 3001, lastVersion); keys.emplace_back(vertexKey); auto ret = kv->multiGet(spaceId, partId, std::move(keys), &values); EXPECT_EQ(kvstore::ResultCode::SUCCEEDED, ret.first); EXPECT_EQ(1, values.size()); auto tagSchema = schemaMan->getTagSchema(spaceId, 3001); auto tagReader = RowReader::getRowReader(values[0], tagSchema); for (int i = 0; i < 1; i++) { auto res = RowReader::getPropByName(tagReader.get(), folly::stringPrintf("tag_%d_col_%d", 3001, i*2)); CHECK(ok(res)); switch (i) { case 0: { auto&& v0 = value(std::move(res)); EXPECT_EQ(1L, boost::get<int64_t>(v0)); break; } case 1: { auto&& v1 = value(std::move(res)); EXPECT_EQ(0 + 3001 + 2 + 2, boost::get<int64_t>(v1)); break; } case 2: { auto&& v2 = value(std::move(res)); EXPECT_STREQ("tag_string_col_4_2_new", boost::get<std::string>(v2).c_str()); break; } default: break; } } } TEST(UpdateVertexTest, Insertable_Test) { fs::TempDir rootPath("/tmp/UpdateVertexTest.XXXXXX"); std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path()); LOG(INFO) << "Prepare meta..."; auto schemaMan = TestUtils::mockSchemaMan(); auto indexMan = TestUtils::mockIndexMan(); mockData(kv.get()); LOG(INFO) << "Build UpdateVertexRequest..."; GraphSpaceID spaceId = 0; PartitionID partId = 0; VertexID vertexId = 1; cpp2::UpdateVertexRequest req; req.set_space_id(spaceId); req.set_vertex_id(vertexId); req.set_part_id(partId); req.set_filter(""); LOG(INFO) << "Build update items..."; std::vector<cpp2::UpdateItem> items; // int: 3009.tag_3009_col_0 = 1 cpp2::UpdateItem item1; item1.set_name("3009"); item1.set_prop("tag_3009_col_0"); PrimaryExpression val1(1L); item1.set_value(Expression::encode(&val1)); items.emplace_back(item1); // string: 3009.tag_3009_col_4 = tag_string_col_4_2_new cpp2::UpdateItem item2; item2.set_name("3009"); item2.set_prop("tag_3009_col_4"); std::string col4new("tag_string_col_4_2_new"); PrimaryExpression val2(col4new); item2.set_value(Expression::encode(&val2)); items.emplace_back(item2); req.set_update_items(std::move(items)); LOG(INFO) << "Build yield..."; // Return tag props: tag_3009_col_0, tag_3009_col_2, tag_3009_col_4 decltype(req.return_columns) tmpColumns; for (int i = 0; i < 3; i++) { SourcePropertyExpression sourcePropExp( new std::string(folly::to<std::string>(3009)), new std::string(folly::stringPrintf("tag_%d_col_%d", 3009, i * 2))); tmpColumns.emplace_back(Expression::encode(&sourcePropExp)); } req.set_return_columns(std::move(tmpColumns)); LOG(INFO) << "Make it insertable..."; // insert tag: 3009.tag_3009_col_4 req.set_insertable(true); LOG(INFO) << "Test UpdateVertexRequest..."; auto* processor = UpdateVertexProcessor::instance(kv.get(), schemaMan.get(), indexMan.get(), nullptr); auto f = processor->getFuture(); processor->process(req); auto resp = std::move(f).get(); LOG(INFO) << "Check the results..."; EXPECT_EQ(0, resp.result.failed_codes.size()); EXPECT_TRUE(resp.get_upsert()); ASSERT_TRUE(resp.__isset.schema); auto provider = std::make_shared<ResultSchemaProvider>(resp.schema); auto reader = RowReader::getRowReader(resp.data, provider); EXPECT_EQ(3, reader->numFields()); // 3009.tag_3009_col_0 auto res = RowReader::getPropByIndex(reader.get(), 0); if (ok(res)) { auto&& v = value(std::move(res)); EXPECT_EQ(1L, boost::get<int64_t>(v)); } // 3009.tag_3009_col_2 res = RowReader::getPropByIndex(reader.get(), 1); if (ok(res)) { auto&& v = value(std::move(res)); EXPECT_EQ(0, boost::get<int64_t>(v)); } // 3009.tag_3009_col_4 res = RowReader::getPropByIndex(reader.get(), 7); if (ok(res)) { auto&& v = value(std::move(res)); EXPECT_STREQ("tag_string_col_4_2_new", boost::get<std::string>(v).c_str()); } // get tag3009 from kvstore directly auto prefix = NebulaKeyUtils::vertexPrefix(partId, vertexId, 3009); std::unique_ptr<kvstore::KVIterator> iter; auto ret = kv->prefix(spaceId, partId, prefix, &iter); EXPECT_EQ(kvstore::ResultCode::SUCCEEDED, ret); EXPECT_TRUE(iter && iter->valid()); reader = RowReader::getTagPropReader(schemaMan.get(), iter->val(), spaceId, 3009); res = RowReader::getPropByName(reader.get(), item2.get_prop()); EXPECT_TRUE(ok(res)); auto&& v = value(std::move(res)); EXPECT_STREQ("tag_string_col_4_2_new", boost::get<std::string>(v).c_str()); } TEST(UpdateVertexTest, Invalid_Set_Test) { fs::TempDir rootPath("/tmp/UpdateVertexTest.XXXXXX"); std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path()); LOG(INFO) << "Prepare meta..."; auto schemaMan = TestUtils::mockSchemaMan(); auto indexMan = TestUtils::mockIndexMan(); mockData(kv.get()); LOG(INFO) << "Build UpdateVertexRequest..."; GraphSpaceID spaceId = 0; PartitionID partId = 0; VertexID vertexId = 1; cpp2::UpdateVertexRequest req; req.set_space_id(spaceId); req.set_vertex_id(vertexId); req.set_part_id(partId); req.set_filter(""); LOG(INFO) << "Build invalid update items..."; std::vector<cpp2::UpdateItem> items; // 3001.tag_3001_col_0 = e101.col_0 cpp2::UpdateItem item; item.set_name("3001"); item.set_prop("tag_3001_col_0"); auto* alias = new std::string("e101"); auto* edgeProp = new std::string("col_0"); AliasPropertyExpression edgeExp(new std::string(""), alias, edgeProp); item.set_value(Expression::encode(&edgeExp)); items.emplace_back(item); req.set_update_items(std::move(items)); req.set_insertable(false); LOG(INFO) << "Test UpdateVertexRequest..."; auto* processor = UpdateVertexProcessor::instance(kv.get(), schemaMan.get(), indexMan.get(), nullptr); auto f = processor->getFuture(); processor->process(req); auto resp = std::move(f).get(); LOG(INFO) << "Check the results..."; EXPECT_EQ(1, resp.result.failed_codes.size()); EXPECT_TRUE(nebula::storage::cpp2::ErrorCode::E_INVALID_UPDATER == resp.result.failed_codes[0].code); EXPECT_FALSE(nebula::storage::cpp2::ErrorCode::E_INVALID_FILTER == resp.result.failed_codes[0].code); } TEST(UpdateVertexTest, Invalid_Filter_Test) { fs::TempDir rootPath("/tmp/UpdateVertexTest.XXXXXX"); std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path()); LOG(INFO) << "Prepare meta..."; auto schemaMan = TestUtils::mockSchemaMan(); auto indexMan = TestUtils::mockIndexMan(); mockData(kv.get()); LOG(INFO) << "Build UpdateVertexRequest..."; GraphSpaceID spaceId = 0; PartitionID partId = 0; VertexID vertexId = 1; cpp2::UpdateVertexRequest req; req.set_space_id(spaceId); req.set_vertex_id(vertexId); req.set_part_id(partId); req.set_filter(""); LOG(INFO) << "Build invalid filter..."; auto* prop = new std::string("tag_3001_col_0"); auto inputExp = std::make_unique<InputPropertyExpression>(prop); req.set_filter(Expression::encode(inputExp.get())); LOG(INFO) << "Build update items..."; std::vector<cpp2::UpdateItem> items; // int: 3001.tag_3001_col_0 = 1L cpp2::UpdateItem item; item.set_name("3001"); item.set_prop("tag_3001_col_0"); PrimaryExpression val(1L); item.set_value(Expression::encode(&val)); items.emplace_back(item); req.set_update_items(std::move(items)); req.set_insertable(false); LOG(INFO) << "Test UpdateVertexRequest..."; auto* processor = UpdateVertexProcessor::instance(kv.get(), schemaMan.get(), indexMan.get(), nullptr); auto f = processor->getFuture(); processor->process(req); auto resp = std::move(f).get(); LOG(INFO) << "Check the results..."; EXPECT_EQ(1, resp.result.failed_codes.size()); EXPECT_TRUE(nebula::storage::cpp2::ErrorCode::E_INVALID_FILTER == resp.result.failed_codes[0].code); EXPECT_FALSE(nebula::storage::cpp2::ErrorCode::E_INVALID_UPDATER == resp.result.failed_codes[0].code); } TEST(UpdateVertexTest, CorruptDataTest) { fs::TempDir rootPath("/tmp/UpdateVertexTest.XXXXXX"); std::unique_ptr<kvstore::KVStore> kv = TestUtils::initKV(rootPath.path()); LOG(INFO) << "Prepare meta..."; auto schemaMan = TestUtils::mockSchemaMan(); auto indexMan = TestUtils::mockIndexMan(); LOG(INFO) << "Write a vertex with empty value!"; // partId, srcId, tagId, version auto key = NebulaKeyUtils::vertexKey(0, 10, 3001, 0); std::vector<kvstore::KV> data; data.emplace_back(std::make_pair(key, "")); folly::Baton<> baton; kv->asyncMultiPut(0, 0, std::move(data), [&](kvstore::ResultCode code) { CHECK_EQ(code, kvstore::ResultCode::SUCCEEDED); baton.post(); }); baton.wait(); LOG(INFO) << "Build UpdateVertexRequest..."; GraphSpaceID spaceId = 0; PartitionID partId = 0; VertexID vertexId = 10; cpp2::UpdateVertexRequest req; req.set_space_id(spaceId); req.set_vertex_id(vertexId); req.set_part_id(partId); req.set_filter(""); LOG(INFO) << "Build update items..."; std::vector<cpp2::UpdateItem> items; // int: 3001.tag_3001_col_0 = 1L cpp2::UpdateItem item; item.set_name("3001"); item.set_prop("tag_3001_col_0"); PrimaryExpression val(1L); item.set_value(Expression::encode(&val)); items.emplace_back(item); req.set_update_items(std::move(items)); req.set_insertable(false); LOG(INFO) << "Test UpdateVertexRequest..."; auto* processor = UpdateVertexProcessor::instance(kv.get(), schemaMan.get(), indexMan.get(), nullptr); auto f = processor->getFuture(); processor->process(req); auto resp = std::move(f).get(); LOG(INFO) << "Check the results..."; EXPECT_EQ(1, resp.result.failed_codes.size()); EXPECT_TRUE(cpp2::ErrorCode::E_TAG_NOT_FOUND == resp.result.failed_codes[0].code); EXPECT_EQ(0, resp.result.failed_codes[0].part_id); } } // namespace storage } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, true); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); }
// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** Venture Line Super Rider driver ***************************************************************************/ #include "emu.h" #include "includes/suprridr.h" #include "screen.h" /************************************* * * Tilemap callbacks * *************************************/ TILE_GET_INFO_MEMBER(suprridr_state::get_tile_info) { uint8_t code = m_bgram[tile_index]; SET_TILE_INFO_MEMBER(0, code, 0, 0); } TILE_GET_INFO_MEMBER(suprridr_state::get_tile_info2) { uint8_t code = m_fgram[tile_index]; SET_TILE_INFO_MEMBER(1, code, 0, 0); } /************************************* * * Video startup * *************************************/ void suprridr_state::video_start() { m_fg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(suprridr_state::get_tile_info2),this), TILEMAP_SCAN_ROWS, 8,8, 32,32); m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(suprridr_state::get_tile_info),this), TILEMAP_SCAN_ROWS, 8,8, 32,32); m_bg_tilemap_noscroll = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(suprridr_state::get_tile_info),this), TILEMAP_SCAN_ROWS, 8,8, 32,32); m_fg_tilemap->set_transparent_pen(0); save_item(NAME(m_flipx)); save_item(NAME(m_flipy)); } /************************************* * * Color PROM decoding * *************************************/ PALETTE_INIT_MEMBER(suprridr_state, suprridr) { const uint8_t *color_prom = memregion("proms")->base(); int i; for (i = 0; i < 96; i++) { int bit0,bit1,bit2,r,g,b; /* red component */ bit0 = (*color_prom >> 0) & 0x01; bit1 = (*color_prom >> 1) & 0x01; bit2 = (*color_prom >> 2) & 0x01; r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; /* green component */ bit0 = (*color_prom >> 3) & 0x01; bit1 = (*color_prom >> 4) & 0x01; bit2 = (*color_prom >> 5) & 0x01; g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; /* blue component */ bit0 = (*color_prom >> 6) & 0x01; bit1 = (*color_prom >> 7) & 0x01; b = 0x4f * bit0 + 0xa8 * bit1; palette.set_pen_color(i,rgb_t(r,g,b)); color_prom++; } } /************************************* * * Screen flip/scroll registers * *************************************/ WRITE8_MEMBER(suprridr_state::flipx_w) { m_flipx = data & 1; machine().tilemap().set_flip_all((m_flipx ? TILEMAP_FLIPX : 0) | (m_flipy ? TILEMAP_FLIPY : 0)); } WRITE8_MEMBER(suprridr_state::flipy_w) { m_flipy = data & 1; machine().tilemap().set_flip_all((m_flipx ? TILEMAP_FLIPX : 0) | (m_flipy ? TILEMAP_FLIPY : 0)); } WRITE8_MEMBER(suprridr_state::fgdisable_w) { m_fg_tilemap->enable(~data & 1); } WRITE8_MEMBER(suprridr_state::fgscrolly_w) { m_fg_tilemap->set_scrolly(0, data); } WRITE8_MEMBER(suprridr_state::bgscrolly_w) { m_bg_tilemap->set_scrolly(0, data); } int suprridr_state::is_screen_flipped() { return m_flipx; /* or is it flipy? */ } /************************************* * * Video RAM writes * *************************************/ WRITE8_MEMBER(suprridr_state::bgram_w) { m_bgram[offset] = data; m_bg_tilemap->mark_tile_dirty(offset); m_bg_tilemap_noscroll->mark_tile_dirty(offset); } WRITE8_MEMBER(suprridr_state::fgram_w) { m_fgram[offset] = data; m_fg_tilemap->mark_tile_dirty(offset); } /************************************* * * Video refresh * *************************************/ uint32_t suprridr_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { rectangle subclip; const rectangle &visarea = screen.visible_area(); /* render left 4 columns with no scroll */ subclip = visarea;; subclip.max_x = subclip.min_x + (m_flipx ? 1*8 : 4*8) - 1; subclip &= cliprect; m_bg_tilemap_noscroll->draw(screen, bitmap, subclip, 0, 0); /* render right 1 column with no scroll */ subclip = visarea;; subclip.min_x = subclip.max_x - (m_flipx ? 4*8 : 1*8) + 1; subclip &= cliprect; m_bg_tilemap_noscroll->draw(screen, bitmap, subclip, 0, 0); /* render the middle columns normally */ subclip = visarea;; subclip.min_x += m_flipx ? 1*8 : 4*8; subclip.max_x -= m_flipx ? 4*8 : 1*8; subclip &= cliprect; m_bg_tilemap->draw(screen, bitmap, subclip, 0, 0); /* render the top layer */ m_fg_tilemap->draw(screen, bitmap, cliprect, 0, 0); /* draw the sprites */ for (int i = 0; i < 48; i++) { int code = (m_spriteram[i*4+1] & 0x3f) | ((m_spriteram[i*4+2] >> 1) & 0x40); int color = m_spriteram[i*4+2] & 0x7f; int fx = m_spriteram[i*4+1] & 0x40; int fy = m_spriteram[i*4+1] & 0x80; int x = m_spriteram[i*4+3]; int y = 240 - m_spriteram[i*4+0]; if (m_flipx) { fx = !fx; x = 240 - x; } if (m_flipy) { fy = !fy; y = 240 - y; } m_gfxdecode->gfx(2)->transpen(bitmap,cliprect, code, color, fx, fy, x, y, 0); } return 0; }
/*========================================================================= Program: Visualization Toolkit Module: vtkSurfaceLICPainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSurfaceLICPainter.h" #include "vtkInformation.h" #include "vtkScalarsToColors.h" #include "vtkScalarsToColorsPainter.h" #include "vtkPainterCommunicator.h" #include "vtkSurfaceLICComposite.h" #include "vtkBase64Utilities.h" #include "vtkBoundingBox.h" #include "vtkCellData.h" #include "vtkColorMaterialHelper.h" #include "vtkCompositeDataIterator.h" #include "vtkCompositeDataSet.h" #include "vtkFrameBufferObject2.h" #include "vtkRenderbuffer.h" #include "vtkPixelBufferObject.h" #include "vtkPixelExtent.h" #include "vtkGarbageCollector.h" #include "vtkGenericDataObjectReader.h" #include "vtkImageData.h" #include "vtkLightingHelper.h" #include "vtkLineIntegralConvolution2D.h" #include "vtkMatrix4x4.h" #include "vtkMath.h" #include "vtkMinimalStandardRandomSequence.h" #include "vtkNoise200x200.h" #include "vtkObjectFactory.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLExtensionManager.h" #include "vtkOpenGLModelViewProjectionMonitor.h" #include "vtkOpenGLLightMonitor.h" #include "vtkBackgroundColorMonitor.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkCamera.h" #include "vtkShader2Collection.h" #include "vtkShader2.h" #include "vtkShaderProgram2.h" #include "vtkSmartPointer.h" #include "vtkTextureObject.h" #include "vtkUniformVariables.h" #include "vtkWeakPointer.h" #include "vtkUnsignedCharArray.h" #include "vtkFloatArray.h" #include "vtkgl.h" #include "vtkOpenGLError.h" #include <cassert> #include <cstring> #include <algorithm> #include <limits> #include <vector> #include <deque> #include <cstdlib> using std::vector; using std::deque; using std::string; typedef vtkLineIntegralConvolution2D vtkLIC2D; // use parallel timer for benchmarks and scaling // if not defined vtkTimerLOG is used. // #define vtkSurfaceLICPainterTIME #if !defined(vtkSurfaceLICPainterTIME) #include "vtkTimerLog.h" #endif // write intermediate results to disk for debugging #define vtkSurfaceLICPainterDEBUG 0 #if vtkSurfaceLICPainterDEBUG >= 2 #include "vtkTextureIO.h" #include <sstream> using std::ostringstream; //---------------------------------------------------------------------------- static string mpifn(vtkPainterCommunicator *comm, const char *fn) { ostringstream oss; oss << comm->GetRank() << "_" << fn; return oss.str(); } #endif // Enable stream min/max computations. Streaming is accomplished // via PBO+glReadPixels to read just the regions we are updating. // Without streaming PBO+glGetTexImage is used to uplaod the entire // screen sized texture, of which (in parallel) we are updating only // a small part of. #define STREAMING_MIN_MAX // store depths in a texture. if not a renderbuffer object is used. // NOTE: this must be on because of a slight diffference in how // texture filtering is implemented by os mesa. #define USE_DEPTH_TEXTURE extern const char* vtkSurfaceLICPainter_GeomFs; extern const char* vtkSurfaceLICPainter_GeomVs; extern const char* vtkSurfaceLICPainter_SC; extern const char* vtkSurfaceLICPainter_CE; extern const char* vtkSurfaceLICPainter_DCpy; namespace vtkSurfaceLICPainterUtil { inline double vtkClamp(double val, const double& min, const double& max) { val = (val < min)? min : val; val = (val > max)? max : val; return val; } // Description // find min/max of unmasked fragments across all regions // download the entire screen then search each region void FindMinMax( vtkTextureObject *tex, deque<vtkPixelExtent> &blockExts, float &min, float &max) { // download entire screen vtkPixelBufferObject *pbo = tex->Download(); float *pHSLColors = static_cast<float*>(pbo->MapPackedBuffer()); // search regions int size0 = tex->GetWidth(); size_t nBlocks = blockExts.size(); for (size_t e=0; e<nBlocks; ++e) { const vtkPixelExtent &blockExt = blockExts[e]; for (int j=blockExt[2]; j<=blockExt[3]; ++j) { for (int i=blockExt[0]; i<=blockExt[1]; ++i) { size_t id = 4*(size0*j+i); if (pHSLColors[id+3] != 0.0f) { float L = pHSLColors[id+2]; min = min > L ? L : min; max = max < L ? L : max; } } } } pbo->UnmapPackedBuffer(); pbo->Delete(); #if vtkSurfaceLICPainterDEBUG >= 1 cerr << "min=" << min << " max=" << max << endl; #endif } // Description // find min/max of unmasked fragments across all regions // download each search each region individually void StreamingFindMinMax( vtkFrameBufferObject2 *fbo, deque<vtkPixelExtent> &blockExts, float &min, float &max) { size_t nBlocks = blockExts.size(); // initiate download fbo->ActivateReadBuffer(1U); vtkStaticCheckFrameBufferStatusMacro(vtkgl::FRAMEBUFFER_EXT); vector<vtkPixelBufferObject*> pbos(nBlocks, NULL); for (size_t e=0; e<nBlocks; ++e) { pbos[e] = fbo->Download( blockExts[e].GetData(), VTK_FLOAT, 4, GL_FLOAT, GL_RGBA); } fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 1U); fbo->DeactivateDrawBuffers(); fbo->DeactivateReadBuffer(); // map search and release each region for (size_t e=0; e<nBlocks; ++e) { vtkPixelBufferObject *&pbo = pbos[e]; float *pColors = (float*)pbo->MapPackedBuffer(); size_t n = blockExts[e].Size(); for (size_t i = 0; i<n; ++i) { if (pColors[4*i+3] != 0.0f) { float L = pColors[4*i+2]; min = min > L ? L : min; max = max < L ? L : max; } } pbo->UnmapPackedBuffer(); pbo->Delete(); pbo = NULL; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << "min=" << min << " max=" << max << endl; #endif } /** integer log base 2 */ int ilog2(unsigned int n) { if (n == 0) { return -1; } unsigned int r = 0; while ((n >>= 1)) { r += 1; } return r; } /** An interface to a random number generator. We can't use c stdlib since we're not gauranteed to get consistent. sequences across platform or library version and that would prevent consistent output during regression tests. */ class RandomNumberGeneratorInterface { public: RandomNumberGeneratorInterface() { this->RNG = vtkMinimalStandardRandomSequence::New(); } ~RandomNumberGeneratorInterface() { this->RNG->Delete(); } /** Seed the random number generator */ void SetSeed(int seedVal) { #if 0 srand(seedVal); #else this->RNG->SetSeed(seedVal); #endif } /** Get a random number in the range of 0 to 1. */ double GetRandomNumber() { #if 0 double val = static_cast<double>(rand())/RAND_MAX; #else double val = this->RNG->GetValue(); this->RNG->Next(); #endif return val; } private: void operator=(const RandomNumberGeneratorInterface &); // not implemented RandomNumberGeneratorInterface(const RandomNumberGeneratorInterface &); // not implemented private: vtkMinimalStandardRandomSequence *RNG; }; /** 2D Noise Generator. Generate arrays for use as noise texture in the LIC algorithm. Can generate noise with uniform or Gaussian distributions, with a desired number of noise levels, and a desired frequency (f < 1 is impulse noise). */ class RandomNoise2D { public: RandomNoise2D(){} // Description: // Generate a patch of random gray scale values along with an // alpha channel (in vtk array format). The data should be // deleted by later calling DeleteValues. Grain size and sideLen // may be modified to match the noise generator requirements, // returned arrays will be sized accordingly. // // type - UNIFORM=0, GAUSSIAN=1, PERLIN=2 // sideLen - side length of square patch in pixels (in/out) // grainSize - grain size of noise values in pixels (in/out) // nLevels - number of noise intesity levels // minNoiseVal - set the min for noise pixels (position distribution) // maxNoiseVal - set the max for noise pixels (position distribution) // impulseProb - probability of impulse noise,1 touches every pixel // impulseBgNoiseVal - set the background color for impulse noise // seed - seed for random number generator enum { UNIFORM = 0, GAUSSIAN = 1, PERLIN = 2 }; float *Generate( int type, int &sideLen, int &grainLize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed); // Description // Delete the passed in array of values. void DeleteValues(unsigned char *vals){ free(vals); } private: // Description: // Generate noise with a uniform distribution. float *GenerateUniform( int sideLen, int grainLize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed); // Description: // Generate noise with a Gaussian distribution. float *GenerateGaussian( int sideLen, int grainLize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed); // Description: // Generate Perlin noise with a Gaussian distribution. float *GeneratePerlin( int sideLen, int grainLize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed); // Description: // A way of controling the probability (from 0.0 to 1.0) that you // generate values. returns 1 if you should generate a value. // for example this is used to control the frequency of impulse // noise. int ShouldGenerateValue(double prob); // Description: // Get a valid the length of the side of the patch and grains size in pixels // given a desired patch side length and a grain size. This ensures that all // grains are the same size. void GetValidDimensionAndGrainSize(int type, int &dim, int &grainSize); private: RandomNumberGeneratorInterface ValueGen; RandomNumberGeneratorInterface ProbGen; }; //----------------------------------------------------------------------------- void RandomNoise2D::GetValidDimensionAndGrainSize(int type, int &sideLen, int &grainSize) { // perlin noise both side len and grain size need to be powers of 2 if (type == PERLIN) { sideLen = 1 << ilog2(sideLen); grainSize = 1 << ilog2(grainSize); } // grains can't be larger than the patch if (sideLen < grainSize) { sideLen = grainSize; } // generate noise with agiven grainSize size on the patch if (sideLen % grainSize) { // grainSize is not an even divsior of sideLen, adjust sideLen to // next larger even divisor sideLen = grainSize * (sideLen/grainSize + 1); } } //----------------------------------------------------------------------------- int RandomNoise2D::ShouldGenerateValue(double prob) { if (this->ProbGen.GetRandomNumber() > (1.0 - prob)) { return 1; } return 0; } //----------------------------------------------------------------------------- float *RandomNoise2D::Generate( int type, int &sideLen, int &grainSize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed) { this->GetValidDimensionAndGrainSize(type, sideLen, grainSize); switch (type) { case GAUSSIAN: return this->GenerateGaussian( sideLen, grainSize, minNoiseVal, maxNoiseVal, nLevels, impulseProb, impulseBgNoiseVal, seed); case UNIFORM: return this->GenerateUniform( sideLen, grainSize, minNoiseVal, maxNoiseVal, nLevels, impulseProb, impulseBgNoiseVal, seed); case PERLIN: return this->GeneratePerlin( sideLen, grainSize, minNoiseVal, maxNoiseVal, nLevels, impulseProb, impulseBgNoiseVal, seed); } return NULL; } //----------------------------------------------------------------------------- float *RandomNoise2D::GenerateUniform( int sideLen, int grainSize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed) { // generate a patch of single pixel random values // with a uniform distribution and fixed number of levels nLevels = nLevels < 1 ? 1 : nLevels; int maxLevel = nLevels-1; float delta = 1.0f/maxLevel; minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; float noiseRange = maxNoiseVal - minNoiseVal; impulseProb = impulseProb < 0.0 ? 0.0 : impulseProb; impulseProb = impulseProb > 1.0 ? 1.0 : impulseProb; impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; this->ValueGen.SetSeed(seed); this->ProbGen.SetSeed(seed); const int sdim = sideLen/grainSize; const int sdim2 = sdim*sdim; float *rvals=(float*)malloc(sdim2*sizeof(float)); for (int i=0; i<sdim2; ++i) { rvals[i] = impulseBgNoiseVal; } for (int j=0; j<sdim; ++j) { for (int i=0; i<sdim; ++i) { int idx=j*sdim+i; if ((impulseProb == 1.0) || this->ShouldGenerateValue(impulseProb)) { int l = static_cast<int>(this->ValueGen.GetRandomNumber()*nLevels); l = l > maxLevel ? maxLevel : l; // needed for 1.0 rvals[idx] = nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; } } } // map single pixel random values onto a patch of values of // the requested grain size const int ncomp = 2; const int dim2 = sideLen*sideLen; const int ntup = ncomp*dim2; float *noise = (float*)malloc(ntup*sizeof(float)); for (int j=0; j<sideLen; ++j) { for (int i=0; i<sideLen; ++i) { int idx=ncomp*(j*sideLen+i); int ii = i/grainSize; int jj = j/grainSize; int iidx = jj*sdim+ii; noise[idx] = rvals[iidx]; noise[idx+1] = 1.0f; // alpha } } free(rvals); return noise; } //----------------------------------------------------------------------------- float *RandomNoise2D::GenerateGaussian( int sideLen, int grainSize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed) { // the distribution becomes Gaussian as N goes to infinity const int N = 2048; // generate a patch of single pixel random values // with a gaussian distribution impulseProb = impulseProb < 0.0 ? 0.0 : impulseProb; impulseProb = impulseProb > 1.0 ? 1.0 : impulseProb; impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; this->ValueGen.SetSeed(seed); this->ProbGen.SetSeed(seed); const int sdim = sideLen/grainSize; const int sdim2 = sdim*sdim; float *rvals = (float*)malloc(sdim2*sizeof(float)); for (int i=0; i<sdim2; ++i) { rvals[i] = 0.0f; } for (int j=0; j<sdim; ++j) { for (int i=0; i<sdim; ++i) { int idx = j*sdim+i; if ((impulseProb == 1.0) || this->ShouldGenerateValue(impulseProb)) { double val = 0.0; for (int q=0; q<N; ++q) { val += this->ValueGen.GetRandomNumber(); } rvals[idx] = static_cast<float>(val); } } } // normalize noise field from eps to nLevels onto 0 to 1 // and restrict to the requested number of levels // min/max float minVal = static_cast<float>(N+1); float maxVal = 0.0f; for (int i=0; i<sdim2; ++i) { // for impulseProb < 1 background is 0 but pixels that are touched // have a much larger value, after normalization the gaussian // distribution is compressed and localized near 1. We can fix this // by ignoring zero values. minVal = impulseProb == 1.0 ? (rvals[i] < minVal ? rvals[i] : minVal) : (rvals[i] < minVal && rvals[i] > 0.0f ? rvals[i] : minVal); maxVal = rvals[i]>maxVal ? rvals[i] : maxVal; } float maxMinDiff = maxVal-minVal; // because we ignore zero when impulseProb<1 we have to be careful // here so that we can support one noise level. minVal = maxMinDiff == 0.0f ? 0.0f : minVal; maxMinDiff = maxMinDiff == 0.0f ? (maxVal == 0.0f ? 1.0f : maxVal) : maxMinDiff; nLevels = nLevels < 1 ? 1 : nLevels; int maxLevel = nLevels-1; float delta = 1.0f/maxLevel; minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; float noiseRange = maxNoiseVal - minNoiseVal; for (int i=0; i<sdim2; ++i) { // normalize float val = rvals[i] < minVal ? rvals[i] : (rvals[i] - minVal)/maxMinDiff; // restrict int l = static_cast<int>(val*nLevels); l = l > maxLevel ? maxLevel : l; rvals[i] = rvals[i] < minVal ? impulseBgNoiseVal : nLevels == 1 ? maxNoiseVal : minNoiseVal + (l*delta) * noiseRange; } // map single pixel random values onto a patch of values of // the requested grain size const int ncomp = 2; const int dim2 = sideLen*sideLen; const int ntup = ncomp*dim2; float *noise = (float*)malloc(ntup*sizeof(float)); for (int j=0; j<sideLen; ++j) { for (int i=0; i<sideLen; ++i) { int idx = ncomp*(j*sideLen+i); int ii = i/grainSize; int jj = j/grainSize; int iidx = jj*sdim+ii; noise[idx] = rvals[iidx]; noise[idx+1] = 1.0; // alpha } } free(rvals); return noise; } //----------------------------------------------------------------------------- float *RandomNoise2D::GeneratePerlin( int sideLen, int grainSize, float minNoiseVal, float maxNoiseVal, int nLevels, double impulseProb, float impulseBgNoiseVal, int seed) { // note: requires power of 2 sideLen, and sideLen > grainSize const int ncomp = 2; const int dim2 = sideLen*sideLen; const int ntup = ncomp*dim2; float *noise = static_cast<float*>(malloc(ntup*sizeof(float))); for (int i=0; i<ntup; i+=2) { noise[i ] = 0.0f; noise[i+1] = 1.0f; // alpha channel } impulseProb = impulseProb < 0.0 ? 0.0 : impulseProb; impulseProb = impulseProb > 1.0 ? 1.0 : impulseProb; impulseBgNoiseVal = impulseBgNoiseVal < 0.0f ? 0.0f : impulseBgNoiseVal; impulseBgNoiseVal = impulseBgNoiseVal > 1.0f ? 1.0f : impulseBgNoiseVal; minNoiseVal = minNoiseVal < 0.0f ? 0.0f : minNoiseVal; maxNoiseVal = maxNoiseVal > 1.0f ? 1.0f : maxNoiseVal; //int nIter = ilog2(static_cast<unsigned int>(sideLen-1<nLevels ? sideLen-1 : nLevels)); int nIter = ilog2(static_cast<unsigned int>(grainSize)); for (int w=0; w<nIter; ++w) { // reduce range with grain size float levelNoiseMin = 0.0f; float levelNoiseMax = 0.1f + 0.9f/static_cast<float>(1<<(nIter-1-w)); //float levelNoiseMax = 1.0f - levelNoiseMin; // generate a level of noise int levelGrainSize = 1<<w; float *levelNoise = GenerateGaussian( sideLen, levelGrainSize, levelNoiseMin, levelNoiseMax, nLevels, impulseProb, impulseBgNoiseVal, seed); /*// smooth int nsp = w; for (int k=0; k<nsp; ++k) { for (int j=0; j<sideLen; ++j) { for (int i=0; i<sideLen; ++i) { float K[9] = { 0.0191724, 0.100120, 0.0191724, 0.1001200, 0.522831, 0.1001200, 0.0191724, 0.100120, 0.0191724 }; float val=0.0; for (int q=0; q<3; ++q) { for (int p=0; p<3; ++p) { int ii = i+p-1; ii = ii < 0 ? i : ii; ii = ii >= sideLen ? i : ii; int jj = j+q-1; jj = jj < 0 ? j : jj; jj = jj >= sideLen ? j : jj; int idx = 2*(sideLen*jj+ii); val += levelNoise[idx]*K[q*3+p]; } } levelNoise[2*(sideLen*j+i)] = val; } } }*/ // accumulate for (int i=0; i<ntup; i+=2) { noise[i] += levelNoise[i]; } free(levelNoise); } // normalize float minVal = static_cast<float>(nIter+1); float maxVal = 0.0f; for (int i=0; i<ntup; i+=2) { float val = noise[i]; minVal = val<minVal ? val : minVal; maxVal = val>maxVal ? val : maxVal; } float maxMinDiff = maxVal - minVal; if ( maxMinDiff <= 0.0f ) { maxMinDiff = 1.0f; minVal = 0.0f; } for (int i=0; i<ntup; i+=2) { noise[i] = (noise[i] - minVal) / maxMinDiff; } return noise; } /** Load a predefiined texture that has been "pickled" in a string. This texture is 200x200 pixles, has a Gaussian distribution, and intensities ranging between 0 and 206. This is the texture that is used when GenerateNoiseTexture is disabled. */ vtkImageData *vtkGetNoiseResource() { std::string base64string; for (unsigned int cc=0; cc < file_noise200x200_vtk_nb_sections; cc++) { base64string += reinterpret_cast<const char*>(file_noise200x200_vtk_sections[cc]); } unsigned char* binaryInput = new unsigned char[file_noise200x200_vtk_decoded_length + 10]; unsigned long binarylength = vtkBase64Utilities::Decode( reinterpret_cast<const unsigned char*>(base64string.c_str()), static_cast<unsigned long>(base64string.length()), binaryInput); assert("check valid_length" && (binarylength == file_noise200x200_vtk_decoded_length)); vtkGenericDataObjectReader* reader = vtkGenericDataObjectReader::New(); reader->ReadFromInputStringOn(); reader->SetBinaryInputString( reinterpret_cast<char*>(binaryInput), static_cast<int>(binarylength)); reader->Update(); vtkImageData* data = vtkImageData::New(); data->ShallowCopy(reader->GetOutput()); delete [] binaryInput; reader->Delete(); return data; } }; using namespace vtkSurfaceLICPainterUtil; /** Internal data */ class vtkSurfaceLICPainter::vtkInternals { public: vtkSmartPointer<vtkOpenGLLightMonitor> LightMonitor[vtkLightingHelper::VTK_MAX_LIGHTS]; vtkSmartPointer<vtkOpenGLModelViewProjectionMonitor> ViewMonitor; vtkSmartPointer<vtkBackgroundColorMonitor> BGMonitor; vtkWeakPointer<vtkOpenGLRenderWindow> Context; bool GLSupport; int Viewsize[2]; long long LastInputDataSetMTime; long long LastPropertyMTime; long long LastLUTMTime; deque<vtkPixelExtent> BlockExts; vtkPixelExtent DataSetExt; bool ContextNeedsUpdate; bool OutputDataNeedsUpdate; bool CommunicatorNeedsUpdate; bool GeometryNeedsUpdate; bool GatherNeedsUpdate; bool LICNeedsUpdate; bool ColorNeedsUpdate; vtkPainterCommunicator *Communicator; #ifdef USE_DEPTH_TEXTURE vtkSmartPointer<vtkTextureObject> DepthImage; #else vtkSmartPointer<vtkRenderbuffer> DepthImage; #endif vtkSmartPointer<vtkTextureObject> GeometryImage; vtkSmartPointer<vtkTextureObject> VectorImage; vtkSmartPointer<vtkTextureObject> CompositeVectorImage; vtkSmartPointer<vtkTextureObject> MaskVectorImage; vtkSmartPointer<vtkTextureObject> CompositeMaskVectorImage; vtkSmartPointer<vtkTextureObject> NoiseImage; vtkSmartPointer<vtkTextureObject> LICImage; vtkSmartPointer<vtkTextureObject> RGBColorImage; vtkSmartPointer<vtkTextureObject> HSLColorImage; vtkSmartPointer<vtkImageData> Noise; vtkSmartPointer<vtkFrameBufferObject2> FBO; vtkSmartPointer<vtkShaderProgram2> RenderGeometryPass; vtkSmartPointer<vtkShaderProgram2> ColorPass; vtkSmartPointer<vtkShaderProgram2> ColorEnhancePass; vtkSmartPointer<vtkShaderProgram2> CopyPass; vtkSmartPointer<vtkLightingHelper> LightingHelper; vtkSmartPointer<vtkColorMaterialHelper> ColorMaterialHelper; vtkSmartPointer<vtkSurfaceLICComposite> Compositor; vtkSmartPointer<vtkLineIntegralConvolution2D> LICer; int FieldAssociation; int FieldAttributeType; std::string FieldName; bool FieldNameSet; bool HasVectors; // Description: // Constructor vtkInternals() { const int nLights = vtkLightingHelper::VTK_MAX_LIGHTS; for (int i=0; i<nLights; ++i) { this->LightMonitor[i] = vtkSmartPointer<vtkOpenGLLightMonitor>::New(); this->LightMonitor[i]->SetLightId(i); } this->ViewMonitor = vtkSmartPointer<vtkOpenGLModelViewProjectionMonitor>::New(); this->BGMonitor = vtkSmartPointer<vtkBackgroundColorMonitor>::New(); this->Viewsize[0] = this->Viewsize[1] = 0; this->LastInputDataSetMTime = 0; this->LastPropertyMTime = 0; this->LastLUTMTime = 0; this->GLSupport = false; this->ContextNeedsUpdate = true; this->OutputDataNeedsUpdate = true; this->CommunicatorNeedsUpdate = true; this->GeometryNeedsUpdate = true; this->LICNeedsUpdate = true; this->GatherNeedsUpdate = true; this->ColorNeedsUpdate = true; this->Communicator = new vtkPainterCommunicator; this->HasVectors = false; this->FieldNameSet = false; this->FieldAttributeType = 0; this->FieldAssociation = 0; this->LightingHelper = vtkSmartPointer<vtkLightingHelper>::New(); this->ColorMaterialHelper = vtkSmartPointer<vtkColorMaterialHelper>::New(); } // Description: // Destructor ~vtkInternals() { this->ClearGraphicsResources(); const int nLights = vtkLightingHelper::VTK_MAX_LIGHTS; for (int i=0; i<nLights; ++i) { this->LightMonitor[i] = NULL; } this->ViewMonitor = NULL; this->BGMonitor = NULL; this->LightingHelper = NULL; this->ColorMaterialHelper = NULL; if (this->Communicator) { delete this->Communicator; } } // Description: // Check for OpenGL support static bool IsSupported(vtkOpenGLRenderWindow *context) { if (context == NULL) { vtkGenericWarningMacro("OpenGL render window required"); return false; } bool lic2d = vtkLineIntegralConvolution2D::IsSupported(context); bool floatFormats = vtkTextureObject::IsSupported(context, true, true, false); bool renderbuffer = true; #if !defined(USE_DEPTH_TEXTURE) renderbuffer = vtkRenderbuffer::IsSupported(context); #endif bool support = lic2d && floatFormats && renderbuffer; if (!support) { vtkOpenGLExtensionManager *manager = context->GetExtensionManager(); vtkGenericWarningMacro( << "SurfaceLIC is not supported" << endl << context->GetClassName() << endl << manager->GetDriverGLVendor() << endl << manager->GetDriverGLVersion() << endl << manager->GetDriverGLRenderer() << endl << "LIC support = " << lic2d << endl << "floating point texture formats = " << floatFormats << endl << "render buffers = " << renderbuffer); return false; } return true; } // Description: // Free textures and shader programs we're holding a reference to. void ClearGraphicsResources() { this->ClearTextures(); this->RenderGeometryPass = NULL; this->ColorPass = NULL; this->ColorEnhancePass = NULL; this->CopyPass = NULL; this->Compositor = NULL; this->LICer = NULL; this->FBO = NULL; this->LightingHelper->Initialize(0, VTK_SHADER_TYPE_VERTEX); this->ColorMaterialHelper->Initialize(0); } // Description: // Free textures we're holding a reference to. void ClearTextures() { this->DepthImage = NULL; this->GeometryImage = NULL; this->VectorImage = NULL; this->MaskVectorImage = NULL; this->CompositeVectorImage = NULL; this->CompositeMaskVectorImage = NULL; this->NoiseImage = NULL; this->LICImage = NULL; this->RGBColorImage = NULL; this->HSLColorImage = NULL; } // Description: // Allocate textures. void AllocateTextures( vtkRenderWindow *context, int *viewsize) { this->AllocateDepthTexture(context, viewsize, this->DepthImage); this->AllocateTexture(context, viewsize, this->GeometryImage, vtkTextureObject::Nearest); this->AllocateTexture(context, viewsize, this->VectorImage, vtkTextureObject::Linear); this->AllocateTexture(context, viewsize, this->MaskVectorImage, vtkTextureObject::Linear); this->AllocateTexture(context, viewsize, this->CompositeVectorImage, vtkTextureObject::Linear); this->AllocateTexture(context, viewsize, this->CompositeMaskVectorImage, vtkTextureObject::Linear); this->AllocateTexture(context, viewsize, this->LICImage, vtkTextureObject::Nearest); this->AllocateTexture(context, viewsize, this->RGBColorImage, vtkTextureObject::Nearest); this->AllocateTexture(context, viewsize, this->HSLColorImage, vtkTextureObject::Nearest); } // Description: // Allocate a size texture, store in the given smart pointer. void AllocateTexture( vtkRenderWindow *context, int *viewsize, vtkSmartPointer<vtkTextureObject> &tex, int filter = vtkTextureObject::Nearest) { if ( !tex ) { vtkTextureObject * newTex = vtkTextureObject::New(); newTex->SetContext(context); newTex->SetBaseLevel(0); newTex->SetMaxLevel(0); newTex->SetWrapS(vtkTextureObject::ClampToEdge); newTex->SetWrapT(vtkTextureObject::ClampToEdge); newTex->SetMinificationFilter(filter); newTex->SetMagnificationFilter(filter); newTex->SetBorderColor(0.0f, 0.0f, 0.0f, 0.0f); newTex->Create2D(viewsize[0], viewsize[1], 4, VTK_FLOAT, false); newTex->SetAutoParameters(0); tex = newTex; newTex->Delete(); } } // Description: // Allocate a size texture, store in the given smart pointer. #ifdef USE_DEPTH_TEXTURE void AllocateDepthTexture( vtkRenderWindow *context, int *viewsize, vtkSmartPointer<vtkTextureObject> &tex) { if ( !tex ) { vtkTextureObject * newTex = vtkTextureObject::New(); newTex->SetContext(context); newTex->AllocateDepth(viewsize[0], viewsize[1], vtkTextureObject::Float32); newTex->SetAutoParameters(0); tex = newTex; newTex->Delete(); } } #else void AllocateDepthTexture( vtkRenderWindow *context, int *viewsize, vtkSmartPointer<vtkRenderbuffer> &buf) { if ( !buf ) { vtkRenderbuffer * newBuf = vtkRenderbuffer::New(); newBuf->SetContext(context); newBuf->CreateDepthAttachment(viewsize[0], viewsize[1]); buf = newBuf; newBuf->Delete(); } } #endif // Description: // After LIC has been computed reset/clean internal state void Updated() { this->ContextNeedsUpdate = false; this->OutputDataNeedsUpdate = false; this->CommunicatorNeedsUpdate = false; this->GeometryNeedsUpdate = false; this->GatherNeedsUpdate = false; this->LICNeedsUpdate = false; this->ColorNeedsUpdate = false; } // Description: // Force all stages to re-execute. Necessary if the // context or communicator changes. void UpdateAll() { this->ContextNeedsUpdate = true; this->OutputDataNeedsUpdate= true; this->CommunicatorNeedsUpdate= true; this->GeometryNeedsUpdate= true; this->GatherNeedsUpdate= true; this->LICNeedsUpdate= true; this->ColorNeedsUpdate= true; } // Description: // Convert viewport to texture coordinates void ViewportQuadTextureCoords(GLfloat *tcoords) { tcoords[0] = tcoords[2] = 0.0f; tcoords[1] = tcoords[3] = 1.0f; } // Description: // Convert a viewport to a bounding box and it's texture coordinates for a // screen size texture. void ViewportQuadPoints(const vtkPixelExtent &viewportExt, GLfloat *quadpts) { viewportExt.GetData(quadpts); } // Description: // Convert a viewport to a bounding box and it's texture coordinates for a // screen size texture. void ViewportQuadTextureCoords( const vtkPixelExtent &viewExt, const vtkPixelExtent &viewportExt, GLfloat *tcoords) { GLfloat viewsize[2]; viewExt.Size(viewsize); // cell to node vtkPixelExtent next(viewportExt); next.CellToNode(); next.GetData(tcoords); tcoords[0] = tcoords[0]/viewsize[0]; tcoords[1] = tcoords[1]/viewsize[0]; tcoords[2] = tcoords[2]/viewsize[1]; tcoords[3] = tcoords[3]/viewsize[1]; } // Description: // Convert the entire view to a bounding box and it's texture coordinates for // a screen size texture. void ViewQuadPoints(GLfloat *quadpts) { quadpts[0] = quadpts[2] = 0.0f; quadpts[1] = quadpts[3] = 1.0f; } // Description: // Convert the entire view to a bounding box and it's texture coordinates for // a screen size texture. void ViewQuadTextureCoords(GLfloat *tcoords) { tcoords[0] = tcoords[2] = 0.0f; tcoords[1] = tcoords[3] = 1.0f; } // Description: // Render a quad (to trigger a shader to run) void RenderQuad( const vtkPixelExtent &viewExt, const vtkPixelExtent &viewportExt, int nTexUnits) { // cell to node vtkPixelExtent next(viewportExt); next.CellToNode(); GLfloat quadPts[4]; next.GetData(quadPts); GLfloat quadTCoords[4]; this->ViewportQuadTextureCoords(viewExt, viewportExt, quadTCoords); int ids[8] = {0,2, 1,2, 1,3, 0,3}; glBegin(GL_QUADS); for (int q=0; q<4; ++q) { int qq = 2*q; for (int i=0; i<nTexUnits; ++i) { GLenum texUnit = vtkgl::TEXTURE0+i; vtkgl::MultiTexCoord2f(texUnit, quadTCoords[ids[qq]], quadTCoords[ids[qq+1]]); } glVertex2f(quadPts[ids[qq]], quadPts[ids[qq+1]]); } glEnd(); } // Description: // Test to see if some lighting parameters had changed since the // last render internal. bool LightingChanged() { bool anyChanged = false; const int nLights = vtkLightingHelper::VTK_MAX_LIGHTS; for (int i=0; i<nLights; ++i) // must look at all { if ( this->LightMonitor[i]->StateChanged() ) { anyChanged = true; } } return anyChanged; } // Description: // Test to see if some model view related parameters had changed since // the last render internal. bool ViewChanged() { return this->ViewMonitor->StateChanged(); } // Description: // Test to see if background colors or mode has changed since the // last render internal. bool BackgroundChanged(vtkRenderer *ren) { return this->BGMonitor->StateChanged(ren); } // Description: // Compute the index into the 4x4 OpenGL ordered matrix. inline int idx(int row, int col) { return 4*col+row; } // Description: // given a axes aligned bounding box in // normalized device coordinates test for // view frustum visibility. // if all points are outside one of the // view frustum planes then this box // is not visible. we might have false // positive where more than one clip // plane intersects the box. bool VisibilityTest(double ndcBBox[24]) { // check all points in the direction d // at the same time. for (int d=0; d<3; ++d) { if (((ndcBBox[ d] < -1.0) && (ndcBBox[3 + d] < -1.0) && (ndcBBox[6 + d] < -1.0) && (ndcBBox[9 + d] < -1.0) && (ndcBBox[12 + d] < -1.0) && (ndcBBox[15 + d] < -1.0) && (ndcBBox[18 + d] < -1.0) && (ndcBBox[21 + d] < -1.0)) ||((ndcBBox[ d] > 1.0) && (ndcBBox[3 + d] > 1.0) && (ndcBBox[6 + d] > 1.0) && (ndcBBox[9 + d] > 1.0) && (ndcBBox[12 + d] > 1.0) && (ndcBBox[15 + d] > 1.0) && (ndcBBox[18 + d] > 1.0) && (ndcBBox[21 + d] > 1.0)) ) { return false; } } return true; } // Description: // Given world space bounds, // compute bounding boxes in clip and normalized device // coordinates and perform view frustum visiblity test. // return true if the bounds are visible. If so the passed // in extent object is initialized with the corresponding //screen space extents. bool ProjectBounds( double PMV[16], int viewsize[2], double bounds[6], vtkPixelExtent &screenExt) { // this is how to get the 8 corners of a bounding // box from the VTK bounds int bbIds[24] = { 0,2,4, 1,2,4, 1,3,4, 0,3,4, 0,2,5, 1,2,5, 1,3,5, 0,3,5 }; // normalized device coordinate bounding box double ndcBBox[24]; for (int q = 0; q<8; ++q) { int qq = 3*q; // bounding box corner double wx = bounds[bbIds[qq ]]; double wy = bounds[bbIds[qq+1]]; double wz = bounds[bbIds[qq+2]]; // to clip coordinates ndcBBox[qq ] = wx * PMV[idx(0,0)] + wy * PMV[idx(0,1)] + wz * PMV[idx(0,2)] + PMV[idx(0,3)]; ndcBBox[qq+1] = wx * PMV[idx(1,0)] + wy * PMV[idx(1,1)] + wz * PMV[idx(1,2)] + PMV[idx(1,3)]; ndcBBox[qq+2] = wx * PMV[idx(2,0)] + wy * PMV[idx(2,1)] + wz * PMV[idx(2,2)] + PMV[idx(2,3)]; double ndcw = wx * PMV[idx(3,0)] + wy * PMV[idx(3,1)] + wz * PMV[idx(3,2)] + PMV[idx(3,3)]; // TODO // if the point is past the near clipping plane // we need to do something more robust. this ensures // the correct result but its inefficient if (ndcw < 0.0) { screenExt = vtkPixelExtent(viewsize[0], viewsize[1]); //cerr << "W<0!!!!!!!!!!!!!" << endl; return true; } // to normalized device coordinates ndcw = (ndcw == 0.0 ? 1.0 : 1.0/ndcw); ndcBBox[qq ] *= ndcw; ndcBBox[qq+1] *= ndcw; ndcBBox[qq+2] *= ndcw; } // compute screen extent only if the object // is inside the view frustum. if (VisibilityTest(ndcBBox)) { // these bounds are visible. compute screen // space exents double vx = viewsize[0] - 1.0; double vy = viewsize[1] - 1.0; double vx2 = viewsize[0] * 0.5; double vy2 = viewsize[1] * 0.5; vtkBoundingBox box; for (int q=0; q<8; ++q) { int qq = 3*q; double sx = (ndcBBox[qq ] + 1.0) * vx2; double sy = (ndcBBox[qq+1] + 1.0) * vy2; box.AddPoint( vtkClamp(sx, 0.0, vx), vtkClamp(sy, 0.0, vy), 0.0); } // to screen extent const double *s0 = box.GetMinPoint(); const double *s1 = box.GetMaxPoint(); screenExt[0] = static_cast<int>(s0[0]); screenExt[1] = static_cast<int>(s1[0]); screenExt[2] = static_cast<int>(s0[1]); screenExt[3] = static_cast<int>(s1[1]); return true; } // these bounds aren't visible return false; } // Description: // Compute screen space extents for each block in the input // dataset and for the entire dataset. Only visible blocks // are used in the computations. int ProjectBounds( vtkDataObject *dobj, int viewsize[2], vtkPixelExtent &dataExt, deque<vtkPixelExtent> &blockExts) { // get the modelview projection matrix GLdouble P[16]; GLdouble MV[16]; GLdouble PMV[16]; glGetDoublev(GL_PROJECTION_MATRIX, P); glGetDoublev(GL_MODELVIEW_MATRIX, MV); for ( int c = 0; c < 4; c ++ ) { for ( int r = 0; r < 4; r ++ ) { PMV[c*4+r] = P[idx(r,0)] * MV[idx(0,c)] + P[idx(r,1)] * MV[idx(1,c)] + P[idx(r,2)] * MV[idx(2,c)] + P[idx(r,3)] * MV[idx(3,c)]; } } // dataset case vtkDataSet* ds = dynamic_cast<vtkDataSet*>(dobj); if (ds && ds->GetNumberOfCells()) { double bounds[6]; ds->GetBounds(bounds); if ( vtkBoundingBox::IsValid(bounds) && this->ProjectBounds(PMV, viewsize, bounds, dataExt) ) { // the dataset is visible // add its extent blockExts.push_back(dataExt); return 1; } //cerr << "ds " << ds << " not visible " << endl; return 0; } // composite dataset case vtkCompositeDataSet* cd = dynamic_cast<vtkCompositeDataSet*>(dobj); if (cd) { // process each block's bounds vtkBoundingBox bbox; vtkCompositeDataIterator* iter = cd->NewIterator(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { ds = dynamic_cast<vtkDataSet*>(iter->GetCurrentDataObject()); if (ds && ds->GetNumberOfCells()) { double bounds[6]; ds->GetBounds(bounds); vtkPixelExtent screenExt; if ( vtkBoundingBox::IsValid(bounds) && this->ProjectBounds(PMV, viewsize, bounds, screenExt) ) { // this block is visible // save it's screen extent // and accumulate its bounds blockExts.push_back(screenExt); bbox.AddBounds(bounds); } //else { cerr << "leaf " << ds << " not visible " << endl << endl;} } } iter->Delete(); // process accumulated dataset bounds double bounds[6]; bbox.GetBounds(bounds); if ( vtkBoundingBox::IsValid(bounds) && this->ProjectBounds(PMV, viewsize, bounds, dataExt) ) { return 1; } return 0; } //cerr << "ds " << ds << " no cells " << endl; return 0; } // Description: // Shrink an extent to tightly bound non-zero values void GetPixelBounds(float *rgba, int ni, vtkPixelExtent &ext) { vtkPixelExtent text; for (int j=ext[2]; j<=ext[3]; ++j) { for (int i=ext[0]; i<=ext[1]; ++i) { if (rgba[4*(j*ni+i)+3] > 0.0f) { text[0] = text[0] > i ? i : text[0]; text[1] = text[1] < i ? i : text[1]; text[2] = text[2] > j ? j : text[2]; text[3] = text[3] < j ? j : text[3]; } } } ext = text; } // Description: // Shrink a set of extents to tightly bound non-zero values // cull extent if it's empty void GetPixelBounds(float *rgba, int ni, deque<vtkPixelExtent> &blockExts) { vector<vtkPixelExtent> tmpExts(blockExts.begin(),blockExts.end()); blockExts.clear(); size_t nBlocks = tmpExts.size(); for (size_t b=0; b<nBlocks; ++b) { vtkPixelExtent &tmpExt = tmpExts[b]; GetPixelBounds(rgba, ni, tmpExt); if (!tmpExt.Empty()) { blockExts.push_back(tmpExt); } } } }; //---------------------------------------------------------------------------- vtkObjectFactoryNewMacro(vtkSurfaceLICPainter); //---------------------------------------------------------------------------- vtkSurfaceLICPainter::vtkSurfaceLICPainter() { this->Internals = new vtkInternals(); this->Output = 0; this->Enable = 1; this->AlwaysUpdate = 0; this->StepSize = 1; this->NumberOfSteps = 20; this->NormalizeVectors = 1; this->EnhancedLIC = 1; this->EnhanceContrast = 0; this->LowLICContrastEnhancementFactor = 0.0; this->HighLICContrastEnhancementFactor = 0.0; this->LowColorContrastEnhancementFactor = 0.0; this->HighColorContrastEnhancementFactor = 0.0; this->AntiAlias = 0; this->ColorMode = COLOR_MODE_BLEND; this->LICIntensity = 0.8; this->MapModeBias = 0.0; this->GenerateNoiseTexture = 0; this->NoiseType = NOISE_TYPE_GAUSSIAN; this->NoiseTextureSize = 200; this->MinNoiseValue = 0.0; this->MaxNoiseValue = 0.8; this->NoiseGrainSize = 1; this->NumberOfNoiseLevels = 256; this->ImpulseNoiseProbability = 1.0; this->ImpulseNoiseBackgroundValue = 0.0; this->NoiseGeneratorSeed = 1; this->MaskOnSurface = 0; this->MaskThreshold = 0.0; this->MaskIntensity = 0.0; this->MaskColor[0] = 0.5; this->MaskColor[1] = 0.5; this->MaskColor[2] = 0.5; this->CompositeStrategy = COMPOSITE_AUTO; this->SetInputArrayToProcess( vtkDataObject::FIELD_ASSOCIATION_POINTS_THEN_CELLS, vtkDataSetAttributes::VECTORS); } //---------------------------------------------------------------------------- vtkSurfaceLICPainter::~vtkSurfaceLICPainter() { #if vtkSurfaceLICPainterDEBUG >= 1 cerr << "=====vtkSurfaceLICPainter::~vtkSurfaceLICPainter" << endl; #endif this->ReleaseGraphicsResources(this->Internals->Context); delete this->Internals; if (this->Output) { this->Output->Delete(); this->Output = 0; } } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetInputArrayToProcess( int fieldAssociation, const char* name) { if ( !this->Internals->FieldNameSet || (this->Internals->FieldAssociation != fieldAssociation) || (this->Internals->FieldName != name) ) { this->Internals->FieldAssociation = fieldAssociation; this->Internals->FieldName = name; this->Internals->FieldNameSet = true; this->Internals->HasVectors = false; this->Internals->UpdateAll(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetInputArrayToProcess( int fieldAssociation, int fieldAttributeType) { if ( (this->Internals->FieldAssociation != fieldAssociation) || (this->Internals->FieldAttributeType != fieldAttributeType) || this->Internals->FieldNameSet ) { this->Internals->FieldAssociation = fieldAssociation; this->Internals->FieldAttributeType = fieldAttributeType; this->Internals->FieldNameSet = false; this->Internals->HasVectors = false; this->Internals->UpdateAll(); this->Modified(); } } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::ReleaseGraphicsResources(vtkWindow* win) { this->Internals->ClearGraphicsResources(); this->Internals->Context = NULL; if (this->Output) { this->Output->Delete(); this->Output = NULL; } this->Superclass::ReleaseGraphicsResources(win); } //---------------------------------------------------------------------------- #define vtkSetMonitoredParameterMacro(_name, _type, _code) \ void vtkSurfaceLICPainter::Set##_name (_type val) \ { \ if (val == this->_name) \ { \ return; \ } \ _code \ this->_name = val; \ this->Modified(); \ } // output dataset vtkSetMonitoredParameterMacro( Enable, int, this->Internals->OutputDataNeedsUpdate = true;) // lic vtkSetMonitoredParameterMacro( GenerateNoiseTexture, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NoiseType, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NoiseTextureSize, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NoiseGrainSize, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( MinNoiseValue, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( MaxNoiseValue, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NumberOfNoiseLevels, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( ImpulseNoiseProbability, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( ImpulseNoiseBackgroundValue, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NoiseGeneratorSeed, int, this->Internals->Noise = NULL; this->Internals->NoiseImage = NULL; this->Internals->LICNeedsUpdate = true;) // compositor vtkSetMonitoredParameterMacro( CompositeStrategy, int, this->Internals->GatherNeedsUpdate = true;) // lic/compositor vtkSetMonitoredParameterMacro( NumberOfSteps, int, this->Internals->GatherNeedsUpdate = true; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( StepSize, double, this->Internals->GatherNeedsUpdate = true; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( NormalizeVectors, int, val = val < 0 ? 0 : val; val = val > 1 ? 1 : val; this->Internals->GatherNeedsUpdate = true; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( MaskThreshold, double, this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( EnhancedLIC, int, this->Internals->GatherNeedsUpdate = true; this->Internals->LICNeedsUpdate = true;) // lic vtkSetMonitoredParameterMacro( LowLICContrastEnhancementFactor, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( HighLICContrastEnhancementFactor, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->LICNeedsUpdate = true;) vtkSetMonitoredParameterMacro( AntiAlias, int, val = val < 0 ? 0 : val; this->Internals->GatherNeedsUpdate = true; this->Internals->LICNeedsUpdate = true;) // geometry vtkSetMonitoredParameterMacro( MaskOnSurface, int, val = val < 0 ? 0 : val; val = val > 1 ? 1 : val; this->Internals->GeometryNeedsUpdate = true;) // colors vtkSetMonitoredParameterMacro( ColorMode, int, this->Internals->ColorNeedsUpdate = true;) vtkSetMonitoredParameterMacro( LICIntensity, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->ColorNeedsUpdate = true;) vtkSetMonitoredParameterMacro( MaskIntensity, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->ColorNeedsUpdate = true;) vtkSetMonitoredParameterMacro( MapModeBias, double, val = val <-1.0 ? -1.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->ColorNeedsUpdate = true;) vtkSetMonitoredParameterMacro( LowColorContrastEnhancementFactor, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->ColorNeedsUpdate = true;) vtkSetMonitoredParameterMacro( HighColorContrastEnhancementFactor, double, val = val < 0.0 ? 0.0 : val; val = val > 1.0 ? 1.0 : val; this->Internals->ColorNeedsUpdate = true;) //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetMaskColor(double *val) { double rgb[3]; for (int q=0; q<3; ++q) { rgb[q] = val[q]; rgb[q] = rgb[q] < 0.0 ? 0.0 : rgb[q]; rgb[q] = rgb[q] > 1.0 ? 1.0 : rgb[q]; } if ( (rgb[0] == this->MaskColor[0]) && (rgb[1] == this->MaskColor[1]) && (rgb[2] == this->MaskColor[2]) ) { return; } for (int q=0; q<3; ++q) { this->MaskColor[q] = rgb[q]; } this->Internals->ColorNeedsUpdate = true; this->Modified(); } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetEnhanceContrast(int val) { val = val < ENHANCE_CONTRAST_OFF ? ENHANCE_CONTRAST_OFF : val; val = val > ENHANCE_CONTRAST_BOTH ? ENHANCE_CONTRAST_BOTH : val; if (val == this->EnhanceContrast) { return; } switch ( this->EnhanceContrast ) { case ENHANCE_CONTRAST_OFF: switch ( val ) { case ENHANCE_CONTRAST_LIC: case ENHANCE_CONTRAST_BOTH: this->Internals->LICNeedsUpdate = true; break; case ENHANCE_CONTRAST_COLOR: this->Internals->ColorNeedsUpdate = true; break; } break; case ENHANCE_CONTRAST_LIC: switch ( val ) { case ENHANCE_CONTRAST_OFF: case ENHANCE_CONTRAST_COLOR: this->Internals->LICNeedsUpdate = true; break; case ENHANCE_CONTRAST_BOTH: this->Internals->ColorNeedsUpdate = true; break; } break; case ENHANCE_CONTRAST_COLOR: switch ( val ) { case ENHANCE_CONTRAST_LIC: case ENHANCE_CONTRAST_BOTH: this->Internals->LICNeedsUpdate = true; break; case ENHANCE_CONTRAST_OFF: this->Internals->ColorNeedsUpdate = true; break; } break; case ENHANCE_CONTRAST_BOTH: switch ( val ) { case ENHANCE_CONTRAST_OFF: this->Internals->LICNeedsUpdate = true; break; case ENHANCE_CONTRAST_COLOR: this->Internals->LICNeedsUpdate = true; case ENHANCE_CONTRAST_LIC: this->Internals->ColorNeedsUpdate = true; break; } break; } this->EnhanceContrast = val; this->Modified(); } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetNoiseDataSet(vtkImageData *data) { if (data == this->Internals->Noise) { return; } this->Internals->Noise = data; this->Internals->NoiseImage = NULL; this->Modified(); } //---------------------------------------------------------------------------- vtkImageData *vtkSurfaceLICPainter::GetNoiseDataSet() { if (this->Internals->Noise == NULL) { vtkImageData *noise = NULL; if ( this->GenerateNoiseTexture ) { // report potential issues if ( this->NoiseGrainSize >= this->NoiseTextureSize ) { vtkErrorMacro( "NoiseGrainSize must be smaller than NoiseTextureSize"); } if ( this->MinNoiseValue >= this->MaxNoiseValue ) { vtkErrorMacro( "MinNoiseValue must be smaller than MaxNoiseValue"); } if ( (this->ImpulseNoiseProbability == 1.0) && (this->NumberOfNoiseLevels < 2) ) { vtkErrorMacro( "NumberOfNoiseLevels must be greater than 1 " "when not generating impulse noise"); } // generate a custom noise texture based on the // current settings. int noiseTextureSize = this->NoiseTextureSize; int noiseGrainSize = this->NoiseGrainSize; RandomNoise2D noiseGen; float *noiseValues = noiseGen.Generate( this->NoiseType, noiseTextureSize, noiseGrainSize, static_cast<float>(this->MinNoiseValue), static_cast<float>(this->MaxNoiseValue), this->NumberOfNoiseLevels, this->ImpulseNoiseProbability, static_cast<float>(this->ImpulseNoiseBackgroundValue), this->NoiseGeneratorSeed); if ( noiseValues == NULL ) { vtkErrorMacro("Failed to generate noise."); } vtkFloatArray *noiseArray = vtkFloatArray::New(); noiseArray->SetNumberOfComponents(2); noiseArray->SetName("noise"); vtkIdType arraySize = 2*noiseTextureSize*noiseTextureSize; noiseArray->SetArray(noiseValues, arraySize, 0); noise = vtkImageData::New(); noise->SetSpacing(1.0, 1.0, 1.0); noise->SetOrigin(0.0, 0.0, 0.0); noise->SetDimensions(noiseTextureSize, noiseTextureSize, 1); noise->GetPointData()->SetScalars(noiseArray); noiseArray->Delete(); } else { // load a predefined noise texture. noise = vtkGetNoiseResource(); } this->Internals->Noise = noise; this->Internals->NoiseImage = NULL; noise->Delete(); noise = NULL; } return this->Internals->Noise; } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::UpdateNoiseImage(vtkRenderWindow *renWin) { vtkImageData *noiseDataSet = this->GetNoiseDataSet(); int ext[6]; noiseDataSet->GetExtent(ext); unsigned int dataWidth = ext[1]-ext[0]+1; unsigned int dataHeight = ext[3]-ext[2]+1; vtkDataArray *noiseArray = noiseDataSet->GetPointData()->GetScalars(); int dataType = noiseArray->GetDataType(); void *data = noiseArray->GetVoidPointer(0); int dataComps = noiseArray->GetNumberOfComponents(); unsigned int dataSize = noiseArray->GetNumberOfTuples()*dataComps; vtkPixelBufferObject *pbo = vtkPixelBufferObject::New(); pbo->SetContext(renWin); pbo->Upload1D(dataType, data, dataSize, 1, 0); vtkTextureObject *tex = vtkTextureObject::New(); tex->SetContext(renWin); tex->SetBaseLevel(0); tex->SetMaxLevel(0); tex->SetWrapS(vtkTextureObject::Repeat); tex->SetWrapT(vtkTextureObject::Repeat); tex->SetMinificationFilter(vtkTextureObject::Nearest); tex->SetMagnificationFilter(vtkTextureObject::Nearest); tex->Create2D(dataWidth, dataHeight, dataComps, pbo, false); tex->SetAutoParameters(0); pbo->Delete(); this->Internals->NoiseImage = tex; tex->Delete(); } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::IsSupported(vtkRenderWindow *renWin) { vtkOpenGLRenderWindow *context = vtkOpenGLRenderWindow::SafeDownCast(renWin); return vtkInternals::IsSupported(context); } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::CanRenderSurfaceLIC(vtkActor *actor, int typeFlags) { // check the render context for GL fetaure support // note this also handles non-opengl render window if ( this->Internals->ContextNeedsUpdate && !vtkSurfaceLICPainter::IsSupported(this->Internals->Context) ) { vtkErrorMacro("SurfaceLIC is not supported"); return false; } bool canRender = false; // check for common situations where surface lic // isn't computed. GLint polyMode[2]; glGetIntegerv(GL_POLYGON_MODE, polyMode); int rep = actor->GetProperty()->GetRepresentation(); if ( this->Enable && this->Internals->HasVectors && (rep == VTK_SURFACE) && (typeFlags & (vtkPainter::POLYS|vtkPainter::STRIPS)) && (polyMode[0] == GL_FILL) // should I be checking backface mode too? && glIsEnabled(GL_LIGHTING) ) { canRender = true; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " CanRender " << canRender << endl; #endif return canRender; } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::InitializeResources() { bool initialized = true; // noise image if (!this->Internals->NoiseImage) { initialized = false; this->UpdateNoiseImage(this->Internals->Context); } // compositer for parallel operation if (!this->Internals->Compositor) { this->Internals->UpdateAll(); vtkSurfaceLICComposite *compositor = vtkSurfaceLICComposite::New(); compositor->SetContext(this->Internals->Context); this->Internals->Compositor = compositor; compositor->Delete(); } // image LIC if (!this->Internals->LICer) { initialized = false; vtkLineIntegralConvolution2D *LICer = vtkLineIntegralConvolution2D::New(); LICer->SetContext(this->Internals->Context); this->Internals->LICer = LICer; LICer->Delete(); } // frame buffers if (!this->Internals->FBO) { initialized = false; vtkFrameBufferObject2 * fbo = vtkFrameBufferObject2::New(); fbo->SetContext(this->Internals->Context); this->Internals->FBO = fbo; fbo->Delete(); } // load shader codes if (!this->Internals->RenderGeometryPass) { initialized = false; vtkShaderProgram2 * prog = vtkShaderProgram2::New(); prog->SetContext(this->Internals->Context); vtkShader2 *s = vtkShader2::New(); s->SetSourceCode(vtkSurfaceLICPainter_GeomVs); s->SetType(VTK_SHADER_TYPE_VERTEX); s->SetContext(this->Internals->Context); vtkShader2 *s2 = vtkShader2::New(); s2->SetSourceCode(vtkSurfaceLICPainter_GeomFs); s2->SetType(VTK_SHADER_TYPE_FRAGMENT); s2->SetContext(this->Internals->Context); prog->GetShaders()->AddItem(s); prog->GetShaders()->AddItem(s2); s->Delete(); s2->Delete(); this->Internals->LightingHelper->Initialize(prog, VTK_SHADER_TYPE_VERTEX); this->Internals->ColorMaterialHelper->Initialize(prog); prog->Build(); if (prog->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("geometry shader failed to build."); } this->Internals->RenderGeometryPass = prog; prog->Delete(); } if (!this->Internals->ColorPass) { initialized = false; vtkShaderProgram2 *prog = vtkShaderProgram2::New(); prog->SetContext(this->Internals->Context); vtkShader2 *s = vtkShader2::New(); s->SetSourceCode(vtkSurfaceLICPainter_SC); s->SetType(VTK_SHADER_TYPE_FRAGMENT); s->SetContext(this->Internals->Context); prog->GetShaders()->AddItem(s); s->Delete(); prog->Build(); if (prog->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("scalar color shader failed to build."); } this->Internals->ColorPass = prog; prog->Delete(); } if (!this->Internals->ColorEnhancePass) { initialized = false; vtkShaderProgram2 *prog = vtkShaderProgram2::New(); prog->SetContext(this->Internals->Context); vtkShader2 *s = vtkShader2::New(); s->SetSourceCode(vtkSurfaceLICPainter_CE); s->SetType(VTK_SHADER_TYPE_FRAGMENT); s->SetContext(this->Internals->Context); prog->GetShaders()->AddItem(s); s->Delete(); prog->Build(); if (prog->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("color contrast enhance shader failed to build."); } this->Internals->ColorEnhancePass = prog; prog->Delete(); } if (!this->Internals->CopyPass) { initialized = false; vtkShaderProgram2 *prog = vtkShaderProgram2::New(); prog->SetContext(this->Internals->Context); vtkShader2 *s = vtkShader2::New(); s->SetSourceCode(vtkSurfaceLICPainter_DCpy); s->SetType(VTK_SHADER_TYPE_FRAGMENT); s->SetContext(this->Internals->Context); prog->GetShaders()->AddItem(s); s->Delete(); prog->Build(); if (prog->GetLastBuildStatus() != VTK_SHADER_PROGRAM2_LINK_SUCCEEDED) { vtkErrorMacro("color contrast enhance shader failed to build."); } this->Internals->CopyPass = prog; prog->Delete(); } // if any of the above were not already initialized // then execute all stages if (!initialized) { this->Internals->UpdateAll(); } } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToColorLIC() { if ( this->Internals->ColorNeedsUpdate || this->Internals->LICNeedsUpdate || this->Internals->GatherNeedsUpdate || this->Internals->GeometryNeedsUpdate || this->Internals->CommunicatorNeedsUpdate || this->Internals->OutputDataNeedsUpdate || this->Internals->ContextNeedsUpdate || this->AlwaysUpdate ) { this->Internals->ColorNeedsUpdate = true; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToColorLIC " << this->Internals->ColorNeedsUpdate << endl; #endif return this->Internals->ColorNeedsUpdate; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToComputeLIC() { if ( this->Internals->LICNeedsUpdate || this->Internals->GatherNeedsUpdate || this->Internals->GeometryNeedsUpdate || this->Internals->CommunicatorNeedsUpdate || this->Internals->OutputDataNeedsUpdate || this->Internals->ContextNeedsUpdate || this->AlwaysUpdate ) { this->Internals->LICNeedsUpdate = true; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToComputeLIC " << this->Internals->LICNeedsUpdate << endl; #endif return this->Internals->LICNeedsUpdate; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToGatherVectors() { if ( this->Internals->GatherNeedsUpdate || this->Internals->GeometryNeedsUpdate || this->Internals->OutputDataNeedsUpdate || this->Internals->CommunicatorNeedsUpdate || this->Internals->ContextNeedsUpdate || this->AlwaysUpdate ) { this->Internals->GatherNeedsUpdate = true; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToGatherVectors " << this->Internals->GatherNeedsUpdate << endl; #endif return this->Internals->GatherNeedsUpdate; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToRenderGeometry( vtkRenderer *renderer, vtkActor *actor) { // view changed or // user modifiable parameters if ( this->Internals->GeometryNeedsUpdate || this->Internals->CommunicatorNeedsUpdate || this->Internals->OutputDataNeedsUpdate || this->Internals->ContextNeedsUpdate || this->AlwaysUpdate ) { this->Internals->GeometryNeedsUpdate = true; } // lights changed if ( this->Internals->LightingChanged() ) { this->Internals->GeometryNeedsUpdate = true; } // props changed long long propMTime = actor->GetProperty()->GetMTime(); if ( this->Internals->LastPropertyMTime != propMTime ) { this->Internals->LastPropertyMTime = propMTime; this->Internals->GeometryNeedsUpdate = true; } // background colors changed if (this->Internals->BackgroundChanged(renderer)) { this->Internals->GeometryNeedsUpdate = true; this->Internals->ColorNeedsUpdate = true; } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToUpdateGeometry " << this->Internals->GeometryNeedsUpdate << endl; #endif return this->Internals->GeometryNeedsUpdate; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToUpdateCommunicator() { // no comm or externally modfied paramters if ( this->Internals->CommunicatorNeedsUpdate || this->Internals->ContextNeedsUpdate || this->Internals->OutputDataNeedsUpdate || !this->Internals->Communicator || this->AlwaysUpdate ) { this->Internals->CommunicatorNeedsUpdate = true; this->Internals->UpdateAll(); } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToUpdateCommunicator " << this->Internals->CommunicatorNeedsUpdate << endl; #endif return this->Internals->CommunicatorNeedsUpdate; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::NeedToUpdateOutputData() { vtkDataObject *input = this->GetInput(); // input dataset changed long long inputMTime = input->GetMTime(); if ( (this->Internals->LastInputDataSetMTime < inputMTime) || !this->Output || this->AlwaysUpdate) { this->Internals->LastInputDataSetMTime = inputMTime; this->Internals->UpdateAll(); } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToUpdateOutputData " << this->Internals->OutputDataNeedsUpdate << endl; #endif return this->Internals->OutputDataNeedsUpdate; } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::ValidateContext(vtkRenderer *renderer) { bool modified = false; vtkOpenGLRenderWindow *context = vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow()); // context changed if (this->Internals->Context != context) { modified = true; if (this->Internals->Context) { this->ReleaseGraphicsResources(this->Internals->Context); } this->Internals->Context = context; } // viewport size changed int viewsize[2]; renderer->GetTiledSize(&viewsize[0], &viewsize[1]); if ( this->Internals->Viewsize[0] != viewsize[0] || this->Internals->Viewsize[1] != viewsize[1] ) { modified = true; // udpate view size this->Internals->Viewsize[0] = viewsize[0]; this->Internals->Viewsize[1] = viewsize[1]; // resize textures this->Internals->ClearTextures(); this->Internals->AllocateTextures(context, viewsize); } // view changed if (this->Internals->ViewChanged()) { modified = true; } // if anything changed execute all stages if (modified) { this->Internals->UpdateAll(); } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToUpdatContext " << modified << endl; #endif } //---------------------------------------------------------------------------- vtkPainterCommunicator *vtkSurfaceLICPainter::CreateCommunicator(int) { return new vtkPainterCommunicator; } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::CreateCommunicator() { // compute screen space pixel extent of local blocks and // union of local blocks. only blocks that pass view frustum // visibility test are used in the computation. vtkDataObject *input = this->GetInput(); this->Internals->DataSetExt.Clear(); this->Internals->BlockExts.clear(); int includeRank = this->Internals->ProjectBounds( input, this->Internals->Viewsize, this->Internals->DataSetExt, this->Internals->BlockExts); if (this->Internals->Communicator) { delete this->Internals->Communicator; this->Internals->Communicator = NULL; } this->Internals->Communicator = this->CreateCommunicator(includeRank); #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " is rendering " << includeRank << endl; #endif } //----------------------------------------------------------------------------- void vtkSurfaceLICPainter::ProcessInformation(vtkInformation* info) { #if vtkSurfaceLICPainterDEBUG >= 1 bool LUTNeedsUpdate = false; #endif // detect when the LUT has been modified if (info->Has(vtkScalarsToColorsPainter::LOOKUP_TABLE())) { vtkObjectBase *lutObj = info->Get(vtkScalarsToColorsPainter::LOOKUP_TABLE()); vtkScalarsToColors *lut = vtkScalarsToColors::SafeDownCast(lutObj); long long lutMTime; if (lut && ((lutMTime = lut->GetMTime()) > this->Internals->LastLUTMTime)) { this->Internals->LastLUTMTime = lutMTime; this->Internals->UpdateAll(); #if vtkSurfaceLICPainterDEBUG >= 1 LUTNeedsUpdate = true; #endif } } #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " NeedToUpdateLUT " << LUTNeedsUpdate << endl; #endif } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::SetUpdateAll() { this->Internals->UpdateAll(); } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::RenderInternal( vtkRenderer *renderer, vtkActor *actor, unsigned long typeflags, bool forceCompileOnly) { #if vtkSurfaceLICPainterDEBUG >= 1 cerr << this->Internals->Communicator->GetWorldRank() << " ===== " << this->GetClassName() << "::RenderInternal" << endl; #endif #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::RenderInternal"); #else vtkSmartPointer<vtkTimerLog> timer = vtkSmartPointer<vtkTimerLog>::New(); timer->StartTimer(); #endif vtkOpenGLClearErrorMacro(); this->ValidateContext(renderer); if (this->NeedToUpdateOutputData()) { // if the input data has changed we need to // reload vector attributes and recompute // all, but only if the output is valid. this->PrepareOutput(); } if (this->NeedToUpdateCommunicator()) { #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::CreateCommunicator"); #endif // create a communicator that contains only ranks // that have visible data. In parallel this is a // collective operation accross all ranks. In // serial this is a no-op. this->CreateCommunicator(); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::CreateCommunicator"); #endif } vtkPainterCommunicator *comm = this->Internals->Communicator; if (comm->GetIsNull()) { // other rank's may have some visible data but we // have none and should not participate further #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::RenderInternal"); #endif return; } if (!this->CanRenderSurfaceLIC(actor, typeflags)) { // we've determined that there's no work for us, or that the // requisite opengl extensions are not available. pass control on // to delegate renderer and return. this->Superclass::RenderInternal(renderer, actor, typeflags, forceCompileOnly); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::RenderInternal"); #endif return; } // allocate rendering resources, initialize or update // textures and shaders. this->InitializeResources(); // Save context and matrix state to be able to restore. glPushAttrib(GL_ALL_ATTRIB_BITS); glMatrixMode(GL_PROJECTION); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); vtkPixelExtent viewExt( this->Internals->Viewsize[0], this->Internals->Viewsize[1]); // save the active fbo and its draw buffer int prevDrawBuf = 0; glGetIntegerv(GL_DRAW_BUFFER, &prevDrawBuf); int prevFbo = 0; glGetIntegerv(vtkgl::DRAW_FRAMEBUFFER_BINDING_EXT, &prevFbo); // ------------------------------------------- render geometry, project vectors onto screen, etc if (this->NeedToRenderGeometry(renderer, actor)) { #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::RenderGeometry"); #endif // setup our fbo vtkFrameBufferObject2 *fbo = this->Internals->FBO; fbo->SaveCurrentBindings(); fbo->Bind(vtkgl::FRAMEBUFFER_EXT); fbo->AddDepthAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, this->Internals->DepthImage); fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U, this->Internals->GeometryImage); fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 1U, this->Internals->VectorImage); fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 2U, this->Internals->MaskVectorImage); fbo->ActivateDrawBuffers(3); vtkCheckFrameBufferStatusMacro(vtkgl::FRAMEBUFFER_EXT); // clear internal color and depth buffers // the LIC'er requires *all* fragments in the vector // texture to be initialized to 0 glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT); // setup projection shader vtkShaderProgram2 *geometryPass = this->Internals->RenderGeometryPass; vtkUniformVariables *uniforms = geometryPass->GetUniformVariables(); uniforms->SetUniformft("uMaskOnSurface", this->MaskOnSurface); this->Internals->LightingHelper->EncodeLightState(); this->Internals->ColorMaterialHelper->SetUniformVariables(); // render geometry through delegate chain. not looping over blocks // here since composite dataset painter is in the chain. geometryPass->Use(); typeflags &= (vtkPainter::POLYS|vtkPainter::STRIPS); this->Superclass::RenderInternal(renderer, actor, typeflags, forceCompileOnly); geometryPass->Restore(); fbo->RemoveRenDepthAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 1U); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 2U); fbo->DeactivateDrawBuffers(); fbo->UnBind(vtkgl::FRAMEBUFFER_EXT); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::RenderGeometry"); #endif #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slicp_geometry_image.vtm"), this->Internals->GeometryImage, this->Internals->BlockExts); vtkTextureIO::Write( mpifn(comm,"slicp_vector_image.vtm"), this->Internals->VectorImage, this->Internals->BlockExts); vtkTextureIO::Write( mpifn(comm,"slicp_mask_vector_image.vtm"), this->Internals->MaskVectorImage, this->Internals->BlockExts); #if defined(USE_DEPTH_TEXTURE) vtkTextureIO::Write( mpifn(comm,"slicp_depth_image.vtm"), this->Internals->DepthImage, this->Internals->BlockExts); #endif #endif } // --------------------------------------------- compoiste vectors for parallel LIC if (this->NeedToGatherVectors()) { #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::GatherVectors"); #endif // get tight screen space bounds to reduce communication/computation vtkPixelBufferObject *vecPBO = this->Internals->VectorImage->Download(); void *pVecPBO = vecPBO->MapPackedBuffer(); this->Internals->GetPixelBounds( (float*)pVecPBO, this->Internals->Viewsize[0], this->Internals->BlockExts); // initialize compositor this->Internals->Compositor->Initialize( viewExt, this->Internals->BlockExts, this->CompositeStrategy, this->StepSize, this->NumberOfSteps, this->NormalizeVectors, this->EnhancedLIC, this->AntiAlias); if (comm->GetMPIInitialized()) { // parallel run // need to use the communicator provided by the rendering engine this->Internals->Compositor->SetCommunicator(comm); // build compositing program and set up the screen space decomp // with guard pixels int iErr = 0; iErr = this->Internals->Compositor->BuildProgram((float*)pVecPBO); if (iErr) { vtkErrorMacro("Failed to construct program, reason " << iErr); } // composite vectors vtkTextureObject *compositeVectors = this->Internals->CompositeVectorImage; iErr = this->Internals->Compositor->Gather( pVecPBO, VTK_FLOAT, 4, compositeVectors); if (iErr) { vtkErrorMacro("Failed to composite vectors, reason " << iErr); } // composite mask vectors vtkTextureObject *compositeMaskVectors = this->Internals->CompositeMaskVectorImage; vtkPixelBufferObject *maskVecPBO = this->Internals->MaskVectorImage->Download(); void *pMaskVecPBO = maskVecPBO->MapPackedBuffer(); iErr = this->Internals->Compositor->Gather( pMaskVecPBO, VTK_FLOAT, 4, compositeMaskVectors); if (iErr) { vtkErrorMacro("Failed to composite mask vectors, reason " << iErr); } maskVecPBO->UnmapPackedBuffer(); maskVecPBO->Delete(); // restore the default communicator this->Internals->Compositor->RestoreDefaultCommunicator(); #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slicp_new_vector_image.vtm"), this->Internals->CompositeVectorImage, this->Internals->Compositor->GetDisjointGuardExtents()); vtkTextureIO::Write( mpifn(comm,"slicp_new_mask_vector_image.vtm"), this->Internals->CompositeMaskVectorImage, this->Internals->Compositor->GetDisjointGuardExtents()); #endif } else { // serial run // make the decomposition disjoint and add guard pixels this->Internals->Compositor->InitializeCompositeExtents((float*)pVecPBO); // use the lic decomp from here on out, in serial we have this // flexibility because we don't need to worry about ordered compositing // or IceT's scissor boxes this->Internals->BlockExts = this->Internals->Compositor->GetCompositeExtents(); // pass through without compositing this->Internals->CompositeVectorImage = this->Internals->VectorImage; this->Internals->CompositeMaskVectorImage = this->Internals->MaskVectorImage; } vecPBO->UnmapPackedBuffer(); vecPBO->Delete(); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::GatherVectors"); #endif } // ------------------------------------------- LIC on screen if ( this->NeedToComputeLIC() ) { #if vtkSurfaceLICPainterDEBUG >= 2 ostringstream oss; if ( this->GenerateNoiseTexture ) { const char *noiseType[3]={"unif","gauss","perl"}; oss << "slicp_noise_" << noiseType[this->NoiseType] << "_size_" << this->NoiseTextureSize << "_grain_" << this->NoiseGrainSize << "_minval_" << this->MinNoiseValue << "_maxval_" << this->MaxNoiseValue << "_nlevels_" << this->NumberOfNoiseLevels << "_impulseprob_" << this->ImpulseNoiseProbability << "_impulseprob_" << this->ImpulseNoiseBackgroundValue << ".vtk"; } else { oss << "slicp_noise_default.vtk"; } vtkTextureIO::Write( mpifn(comm, oss.str().c_str()), this->Internals->NoiseImage); #endif #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::ComputeLIC"); #endif // TODO -- this means that the steps size is a function // of aspect ratio which is pretty insane... // convert from window units to texture units // this isn't correct since there's no way to account // for anisotropy in the trasnform to texture space double tcScale[2] = { 1.0/this->Internals->Viewsize[0], 1.0/this->Internals->Viewsize[1]}; double stepSize = this->StepSize*sqrt(tcScale[0]*tcScale[0]+tcScale[1]*tcScale[1]); stepSize = stepSize <= 0.0 ? 1.0e-10 : stepSize; // configure image lic vtkLineIntegralConvolution2D *LICer = this->Internals->LICer; LICer->SetStepSize(stepSize); LICer->SetNumberOfSteps(this->NumberOfSteps); LICer->SetEnhancedLIC(this->EnhancedLIC); switch (this->EnhanceContrast) { case ENHANCE_CONTRAST_LIC: case ENHANCE_CONTRAST_BOTH: LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_ON); break; default: LICer->SetEnhanceContrast(vtkLIC2D::ENHANCE_CONTRAST_OFF); } LICer->SetLowContrastEnhancementFactor(this->LowLICContrastEnhancementFactor); LICer->SetHighContrastEnhancementFactor(this->HighLICContrastEnhancementFactor); LICer->SetAntiAlias(this->AntiAlias); LICer->SetComponentIds(0, 1); LICer->SetNormalizeVectors(this->NormalizeVectors); LICer->SetMaskThreshold(this->MaskThreshold); LICer->SetCommunicator(comm); // loop over composited extents const deque<vtkPixelExtent> &compositeExts = this->Internals->Compositor->GetCompositeExtents(); const deque<vtkPixelExtent> &disjointGuardExts = this->Internals->Compositor->GetDisjointGuardExtents(); this->Internals->LICImage.TakeReference( LICer->Execute( viewExt, // screen extent disjointGuardExts, // disjoint extent of valid vectors compositeExts, // disjoint extent where lic is needed this->Internals->CompositeVectorImage, this->Internals->CompositeMaskVectorImage, this->Internals->NoiseImage)); if (!this->Internals->LICImage) { vtkErrorMacro("Failed to compute image LIC"); return; } #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::ComputeLIC"); #endif #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slicp_lic.vtm"), this->Internals->LICImage, compositeExts); #endif // ------------------------------------------- move from LIC decomp back to geometry decomp if ( comm->GetMPIInitialized() && (this->Internals->Compositor->GetStrategy()!=COMPOSITE_INPLACE ) ) { #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::ScatterLIC"); #endif // parallel run // need to use the communicator provided by the rendering engine this->Internals->Compositor->SetCommunicator(comm); vtkPixelBufferObject *licPBO = this->Internals->LICImage->Download(); void *pLicPBO = licPBO->MapPackedBuffer(); vtkTextureObject *newLicImage = NULL; int iErr = this->Internals->Compositor->Scatter(pLicPBO, VTK_FLOAT, 4, newLicImage); if (iErr) { vtkErrorMacro("Failed to scatter lic"); } licPBO->UnmapPackedBuffer(); licPBO->Delete(); this->Internals->LICImage = NULL; this->Internals->LICImage = newLicImage; newLicImage->Delete(); // restore the default communicator this->Internals->Compositor->RestoreDefaultCommunicator(); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::ScatterLIC"); #endif #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slicp_new_lic.vtm"), this->Internals->LICImage, this->Internals->BlockExts); #endif } } // ------------------------------------------- combine scalar colors + LIC if ( this->NeedToColorLIC() ) { #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::ColorLIC"); #endif vtkFrameBufferObject2 *fbo = this->Internals->FBO; fbo->SaveCurrentBindings(); fbo->Bind(vtkgl::FRAMEBUFFER_EXT); fbo->InitializeViewport(this->Internals->Viewsize[0], this->Internals->Viewsize[1]); fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U, this->Internals->RGBColorImage); fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 1U, this->Internals->HSLColorImage); fbo->ActivateDrawBuffers(2U); vtkCheckFrameBufferStatusMacro(vtkgl::FRAMEBUFFER_EXT); #if 0 glDisable(GL_SCISSOR_TEST); glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); #else // clear the parts of the screen which we will modify glEnable(GL_SCISSOR_TEST); glClearColor(0.0, 0.0, 0.0, 0.0); size_t nBlocks = this->Internals->BlockExts.size(); for (size_t e=0; e<nBlocks; ++e) { vtkPixelExtent ext = this->Internals->BlockExts[e]; ext.Grow(2); // halo for linear filtering ext &= viewExt; unsigned int extSize[2]; ext.Size(extSize); glScissor(ext[0], ext[2], extSize[0], extSize[1]); glClear(GL_COLOR_BUFFER_BIT); } glDisable(GL_SCISSOR_TEST); #endif this->Internals->VectorImage->Activate(vtkgl::TEXTURE0); this->Internals->GeometryImage->Activate(vtkgl::TEXTURE1); this->Internals->LICImage->Activate(vtkgl::TEXTURE2); vtkShaderProgram2 *colorPass = this->Internals->ColorPass; vtkUniformVariables *uniforms = colorPass->GetUniformVariables(); uniforms->SetUniformit("texVectors", 0); uniforms->SetUniformit("texGeomColors", 1); uniforms->SetUniformit("texLIC", 2); uniforms->SetUniformit("uScalarColorMode", this->ColorMode); uniforms->SetUniformft("uLICIntensity", this->LICIntensity); uniforms->SetUniformft("uMapBias", this->MapModeBias); uniforms->SetUniformft("uMaskIntensity", this->MaskIntensity); uniforms->SetUniformft("uMaskColor", 3, this->MaskColor); colorPass->Use(); for (size_t e=0; e<nBlocks; ++e) { this->Internals->RenderQuad(viewExt, this->Internals->BlockExts[e], 1); } colorPass->Restore(); this->Internals->VectorImage->Deactivate(vtkgl::TEXTURE0); this->Internals->GeometryImage->Deactivate(vtkgl::TEXTURE1); this->Internals->LICImage->Deactivate(vtkgl::TEXTURE2); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::ColorLIC"); #endif // --------------------------------------------- color contrast enhance if ( ( this->EnhanceContrast == ENHANCE_CONTRAST_COLOR ) || ( this->EnhanceContrast == ENHANCE_CONTRAST_BOTH ) ) { #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slic_color_rgb_in.vtm"), this->Internals->RGBColorImage, this->Internals->BlockExts); vtkTextureIO::Write( mpifn(comm,"slic_color_hsl_in.vtm"), this->Internals->HSLColorImage, this->Internals->BlockExts); #endif #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::ContrastEnhance"); #endif // find min/max lighness value for color contrast enhancement. float LMin = VTK_FLOAT_MAX; float LMax = -VTK_FLOAT_MAX; float LMaxMinDiff = VTK_FLOAT_MAX; #ifdef STREAMING_MIN_MAX StreamingFindMinMax(fbo, this->Internals->BlockExts, LMin, LMax); #else FindMinMax( this->Internals->HSLColorImage, this->Internals->BlockExts, LMin, LMax); #endif if ( this->Internals->BlockExts.size() && ((LMax <= LMin) || (LMin < 0.0f) || (LMax > 1.0f)) ) { vtkErrorMacro( << comm->GetRank() << ": Invalid range " << LMin << ", " << LMax << " for color contrast enhancement"); LMin = 0.0; LMax = 1.0; LMaxMinDiff = 1.0; } // global collective reduction for parallel operation this->GetGlobalMinMax(comm, LMin, LMax); // set M and m as a fraction of the range. LMaxMinDiff = LMax-LMin; LMin += LMaxMinDiff*this->LowColorContrastEnhancementFactor; LMax -= LMaxMinDiff*this->HighColorContrastEnhancementFactor; LMaxMinDiff = LMax-LMin; // normalize shader fbo->AddColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U, this->Internals->RGBColorImage); fbo->ActivateDrawBuffer(0U); vtkCheckFrameBufferStatusMacro(vtkgl::DRAW_FRAMEBUFFER_EXT); this->Internals->GeometryImage->Activate(vtkgl::TEXTURE0); this->Internals->HSLColorImage->Activate(vtkgl::TEXTURE1); this->Internals->LICImage->Activate(vtkgl::TEXTURE2); vtkShaderProgram2 *colorEnhancePass = this->Internals->ColorEnhancePass; uniforms = colorEnhancePass->GetUniformVariables(); uniforms->SetUniformit("texGeomColors", 0); uniforms->SetUniformit("texHSLColors", 1); uniforms->SetUniformit("texLIC", 2); uniforms->SetUniformft("uLMin", LMin); uniforms->SetUniformft("uLMaxMinDiff", LMaxMinDiff); colorEnhancePass->Use(); for (size_t e=0; e<nBlocks; ++e) { this->Internals->RenderQuad(viewExt, this->Internals->BlockExts[e], 1); } colorEnhancePass->Restore(); this->Internals->GeometryImage->Deactivate(vtkgl::TEXTURE0); this->Internals->HSLColorImage->Deactivate(vtkgl::TEXTURE1); this->Internals->LICImage->Deactivate(vtkgl::TEXTURE2); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U); fbo->DeactivateDrawBuffers(); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::ContrastEnhance"); #endif } else { fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 0U); fbo->RemoveTexColorAttachment(vtkgl::DRAW_FRAMEBUFFER_EXT, 1U); fbo->DeactivateDrawBuffers(); } fbo->UnBind(vtkgl::FRAMEBUFFER_EXT); #if vtkSurfaceLICPainterDEBUG >= 2 vtkTextureIO::Write( mpifn(comm,"slicp_new_rgb.vtm"), this->Internals->RGBColorImage, this->Internals->BlockExts); #endif } // ----------------------------------------------- depth test and copy to screen #ifdef vtkSurfaceLICPainterTIME this->StartTimerEvent("vtkSurfaceLICPainter::DepthCopy"); #endif vtkgl::BindFramebufferEXT(vtkgl::FRAMEBUFFER_EXT, prevFbo); glDrawBuffer(prevDrawBuf); vtkFrameBufferObject2::InitializeViewport( this->Internals->Viewsize[0], this->Internals->Viewsize[1]); glEnable(GL_DEPTH_TEST); this->Internals->DepthImage->Activate(vtkgl::TEXTURE0); this->Internals->RGBColorImage->Activate(vtkgl::TEXTURE1); vtkShaderProgram2 *copyPass = this->Internals->CopyPass; vtkUniformVariables *uniforms = copyPass->GetUniformVariables(); uniforms->SetUniformit("texDepth", 0); uniforms->SetUniformit("texRGBColors", 1); copyPass->Use(); size_t nBlocks = this->Internals->BlockExts.size(); for (size_t e=0; e<nBlocks; ++e) { this->Internals->RenderQuad(viewExt, this->Internals->BlockExts[e], 1); } copyPass->Restore(); this->Internals->DepthImage->Deactivate(vtkgl::TEXTURE0); this->Internals->RGBColorImage->Deactivate(vtkgl::TEXTURE1); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::DepthCopy"); #endif // this->Internals->Updated(); // Essential to restore the context to what it was before we started messing // with it. glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); // clear opengl error flags and be absolutely certain that nothing failed. vtkOpenGLCheckErrorMacro("failed during surface lic painter"); #ifdef vtkSurfaceLICPainterTIME this->EndTimerEvent("vtkSurfaceLICPainter::RenderInternal"); #else timer->StopTimer(); #endif } //----------------------------------------------------------------------------- void vtkSurfaceLICPainter::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->Output, "Output PolyData"); } //---------------------------------------------------------------------------- vtkDataObject* vtkSurfaceLICPainter::GetOutput() { #if vtkSurfaceLICPainterDEBUG >= 1 cerr << "=====vtkSurfaceLICPainter::GetOutput" << endl; #endif if (this->Enable && this->Output) { return this->Output; } return this->GetInput(); } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::PrepareOutput() { vtkDataObject* input = this->GetInput(); if ((input == NULL) || !this->Enable) { if (this->Output) { this->Output->Delete(); this->Output = NULL; this->Internals->HasVectors = false; } return false; } if (this->Internals->OutputDataNeedsUpdate) { if (this->Output) { this->Output->Delete(); this->Output = NULL; } this->Output = input->NewInstance(); this->Output->ShallowCopy(input); this->Internals->HasVectors = false; } if (!this->Internals->HasVectors) { this->Internals->HasVectors = this->VectorsToTCoords(this->Output); } return this->Internals->HasVectors; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::VectorsToTCoords(vtkDataObject *dataObj) { bool hasVectors = false; vtkCompositeDataSet *cd = vtkCompositeDataSet::SafeDownCast(dataObj); if (cd) { vtkCompositeDataIterator* iter = cd->NewIterator(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { vtkDataSet* ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); if (ds && ds->GetNumberOfCells()) { this->ClearTCoords(ds); hasVectors |= this->VectorsToTCoords(ds); } } iter->Delete(); return hasVectors; } vtkDataSet* ds = vtkDataSet::SafeDownCast(dataObj); if (ds && ds->GetNumberOfCells()) { this->ClearTCoords(ds); hasVectors |= this->VectorsToTCoords(ds); } if ( hasVectors ) { // force downstream updates (display lists, etc) this->Output->Modified(); } return hasVectors; } //---------------------------------------------------------------------------- bool vtkSurfaceLICPainter::VectorsToTCoords(vtkDataSet *data) { // don't use SafeDownCast here for rendering performance vtkDataArray *vectors = NULL; bool hasCellVectors = false; if (this->Internals->FieldNameSet) { vectors = vtkDataArray::SafeDownCast( this->GetInputArrayToProcess( this->Internals->FieldAssociation, this->Internals->FieldName.c_str(), data, &hasCellVectors)); } else { vectors = vtkDataArray::SafeDownCast( this->GetInputArrayToProcess( this->Internals->FieldAssociation, this->Internals->FieldAttributeType, data, &hasCellVectors)); } if ( vectors == NULL ) { return false; } vtkDataSetAttributes *atts = NULL; if ( hasCellVectors ) { atts = data->GetCellData(); } else { atts = data->GetPointData(); } int id = -1; int nArrays = atts->GetNumberOfArrays(); for (int i=0; i<nArrays; ++i) { if ( atts->GetArray(i) == vectors ) { id = i; break; } } atts->SetActiveAttribute(id, vtkDataSetAttributes::TCOORDS); return true; } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::ClearTCoords(vtkDataSet *data) { data->GetCellData()->SetActiveAttribute(-1, vtkDataSetAttributes::TCOORDS); data->GetPointData()->SetActiveAttribute(-1, vtkDataSetAttributes::TCOORDS); } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::GetBounds(vtkDataObject* dobj, double bounds[6]) { #if vtkSurfaceLICPainterDEBUG >= 1 cerr << "=====vtkSurfaceLICPainter::GetBounds" << endl; #endif // don't use SafeDownCast here for rendering performance vtkMath::UninitializeBounds(bounds); vtkDataSet* ds = vtkDataSet::SafeDownCast(dobj); if (ds) { ds->GetBounds(bounds); return; } vtkCompositeDataSet* cd = vtkCompositeDataSet::SafeDownCast(dobj); if (cd) { vtkBoundingBox bbox; vtkCompositeDataIterator* iter = cd->NewIterator(); for (iter->InitTraversal(); !iter->IsDoneWithTraversal(); iter->GoToNextItem()) { ds = vtkDataSet::SafeDownCast(iter->GetCurrentDataObject()); if (ds && ds->GetNumberOfCells()) { ds->GetBounds(bounds); bbox.AddBounds(bounds); } } iter->Delete(); bbox.GetBounds(bounds); return; } vtkErrorMacro("unsupported dataset " << dobj->GetClassName()); } //---------------------------------------------------------------------------- void vtkSurfaceLICPainter::PrintSelf(ostream & os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "NumberOfSteps=" << this->NumberOfSteps << endl << indent << "StepSize=" << this->StepSize << endl << indent << "NormalizeVectors=" << this->NormalizeVectors << endl << indent << "EnhancedLIC=" << this->EnhancedLIC << endl << indent << "EnhanceContrast=" << this->EnhanceContrast << endl << indent << "LowLICContrastEnhancementFactor=" << this->LowLICContrastEnhancementFactor << endl << indent << "HighLICContrastEnhancementFactor=" << this->HighLICContrastEnhancementFactor << endl << indent << "LowColorContrastEnhancementFactor=" << this->LowColorContrastEnhancementFactor << endl << indent << "HighColorContrastEnhancementFactor=" << this->HighColorContrastEnhancementFactor << endl << indent << "AntiAlias=" << this->AntiAlias << endl << indent << "MaskOnSurface=" << this->MaskOnSurface << endl << indent << "MaskThreshold=" << this->MaskThreshold << endl << indent << "MaskIntensity=" << this->MaskIntensity << endl << indent << "MaskColor=" << this->MaskColor[0] << ", " << this->MaskColor[1] << ", " << this->MaskColor[2] << endl << indent << "ColorMode=" << this->ColorMode << endl << indent << "LICIntensity=" << this->LICIntensity << endl << indent << "MapModeBias=" << this->MapModeBias << endl << indent << "GenerateNoiseTexture=" << this->GenerateNoiseTexture << endl << indent << "NoiseType=" << this->NoiseType << endl << indent << "NoiseTextureSize=" << this->NoiseTextureSize << endl << indent << "NoiseGrainSize=" << this->NoiseGrainSize << endl << indent << "MinNoiseValue=" << this->MinNoiseValue << endl << indent << "MaxNoiseValue=" << this->MaxNoiseValue << endl << indent << "NumberOfNoiseLevels=" << this->NumberOfNoiseLevels << endl << indent << "ImpulseNoiseProbablity=" << this->ImpulseNoiseProbability << endl << indent << "ImpulseNoiseBackgroundValue=" << this->ImpulseNoiseBackgroundValue << endl << indent << "NoiseGeneratorSeed=" << this->NoiseGeneratorSeed << endl << indent << "AlwaysUpdate=" << this->AlwaysUpdate << endl << indent << "Enable=" << this->Enable << endl << indent << "CompositeStrategy=" << this->CompositeStrategy << endl; }
// Copyright (c) 2019-2023 The PIVXL developers // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2011-2013 The PPCoin developers // Copyright (c) 2013-2014 The NovaCoin Developers // Copyright (c) 2014-2018 The BlackCoin Developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "zpiv/accumulators.h" #include "zpiv/accumulatormap.h" #include "addrman.h" #include "alert.h" #include "blocksignature.h" #include "chainparams.h" #include "checkpoints.h" #include "checkqueue.h" #include "consensus/merkle.h" #include "init.h" #include "kernel.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeman.h" #include "merkleblock.h" #include "messagesigner.h" #include "net.h" #include "obfuscation.h" #include "pow.h" #include "spork.h" #include "sporkdb.h" #include "swifttx.h" #include "txdb.h" #include "txmempool.h" #include "guiinterface.h" #include "util.h" #include "utilmoneystr.h" #include "validationinterface.h" #include "zpivchain.h" #include "zpiv/zerocoin.h" #include "libzerocoin/Denominations.h" #include "invalid.h" #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/thread.hpp> #include <boost/foreach.hpp> #include <atomic> #include <queue> #if defined(NDEBUG) #error "PIVXL cannot be compiled without assertions." #endif /** * Global state */ CCriticalSection cs_main; BlockMap mapBlockIndex; std::map<uint256, uint256> mapProofOfStake; std::map<unsigned int, unsigned int> mapHashedBlocks; CChain chainActive; CBlockIndex* pindexBestHeader = NULL; int64_t nTimeBestReceived = 0; CWaitableCriticalSection csBestBlock; CConditionVariable cvBlockChange; int nScriptCheckThreads = 0; bool fImporting = false; bool fReindex = false; bool fTxIndex = true; bool fIsBareMultisigStd = true; bool fCheckBlockIndex = false; bool fVerifyingBlocks = false; unsigned int nCoinCacheSize = 5000; bool fAlerts = DEFAULT_ALERTS; bool fClearSpendCache = false; /* If the tip is older than this (in seconds), the node is considered to be in initial block download. */ int64_t nMaxTipAge = DEFAULT_MAX_TIP_AGE; int64_t nReserveBalance = 0; /** Fees smaller than this (in upiv) are considered zero fee (for relaying and mining) * We are ~100 times smaller then bitcoin now (2015-06-23), set minRelayTxFee only 10 times higher * so it's still 10 times lower comparing to bitcoin. */ CFeeRate minRelayTxFee = CFeeRate(10000); CTxMemPool mempool(::minRelayTxFee); struct COrphanTx { CTransaction tx; NodeId fromPeer; }; std::map<uint256, COrphanTx> mapOrphanTransactions; std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev; std::map<uint256, int64_t> mapRejectedBlocks; std::map<uint256, int64_t> mapZerocoinspends; //txid, time received /***/ CLightWorker lightWorker; void EraseOrphansFor(NodeId peer); static void CheckBlockIndex(); /** Constant stuff for coinbase transactions we create: */ CScript COINBASE_FLAGS; const std::string strMessageMagic = "DarkNet Signed Message:\n"; // Internal stuff namespace { struct CBlockIndexWorkComparator { bool operator()(CBlockIndex* pa, CBlockIndex* pb) const { // First sort by most total work, ... if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; // ... then by earliest time received, ... if (pa->nSequenceId < pb->nSequenceId) return false; if (pa->nSequenceId > pb->nSequenceId) return true; // Use pointer address as tie breaker (should only happen with blocks // loaded from disk, as those all have id 0). if (pa < pb) return false; if (pa > pb) return true; // Identical blocks. return false; } }; CBlockIndex* pindexBestInvalid; /** * The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and * as good as our current tip or better. Entries may be failed, though. */ std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates; /** Number of nodes with fSyncStarted. */ int nSyncStarted = 0; /** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */ std::multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked; CCriticalSection cs_LastBlockFile; std::vector<CBlockFileInfo> vinfoBlockFile; int nLastBlockFile = 0; /** * Every received block is assigned a unique and increasing identifier, so we * know which one to give priority in case of a fork. */ CCriticalSection cs_nBlockSequenceId; /** Blocks loaded from disk are assigned id 0, so start the counter at 1. */ uint32_t nBlockSequenceId = 1; /** * Sources of received blocks, to be able to send them reject messages or ban * them, if processing happens afterwards. Protected by cs_main. */ std::map<uint256, NodeId> mapBlockSource; /** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */ struct QueuedBlock { uint256 hash; CBlockIndex* pindex; //! Optional. int64_t nTime; //! Time of "getdata" request in microseconds. int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested. bool fValidatedHeaders; //! Whether this block has validated headers at the time of request. }; std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight; /** Number of blocks in flight with validated headers. */ int nQueuedValidatedHeaders = 0; /** Number of preferable block download peers. */ int nPreferredDownload = 0; /** Dirty block index entries. */ std::set<CBlockIndex*> setDirtyBlockIndex; /** Dirty block file entries. */ std::set<int> setDirtyFileInfo; } // anon namespace ////////////////////////////////////////////////////////////////////////////// // // Registration of network node signals. // namespace { struct CBlockReject { unsigned char chRejectCode; std::string strRejectReason; uint256 hashBlock; }; class CNodeBlocks { public: CNodeBlocks(): maxSize(0), maxAvg(0) { maxSize = GetArg("-blockspamfiltermaxsize", DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE); maxAvg = GetArg("-blockspamfiltermaxavg", DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG); } bool onBlockReceived(int nHeight) { if(nHeight > 0 && maxSize && maxAvg) { addPoint(nHeight); return true; } return false; } bool updateState(CValidationState& state, bool ret) { // No Blocks size_t size = points.size(); if(size == 0) return ret; // Compute the number of the received blocks size_t nBlocks = 0; for(auto point : points) { nBlocks += point.second; } // Compute the average value per height double nAvgValue = (double)nBlocks / size; // Ban the node if try to spam bool banNode = (nAvgValue >= 1.5 * maxAvg && size >= maxAvg) || (nAvgValue >= maxAvg && nBlocks >= maxSize) || (nBlocks >= maxSize * 3); if(banNode) { // Clear the points and ban the node points.clear(); return state.DoS(100, error("block-spam ban node for sending spam")); } return ret; } private: void addPoint(int height) { // Remove the last element in the list if(points.size() == maxSize) { points.erase(points.begin()); } // Add the point to the list int occurrence = 0; auto mi = points.find(height); if (mi != points.end()) occurrence = (*mi).second; occurrence++; points[height] = occurrence; } private: std::map<int,int> points; size_t maxSize; size_t maxAvg; }; /** * Maintain validation-specific state about nodes, protected by cs_main, instead * by CNode's own locks. This simplifies asynchronous operation, where * processing of incoming data is done after the ProcessMessage call returns, * and we're no longer holding the node's locks. */ struct CNodeState { //! The peer's address CService address; //! Whether we have a fully established connection. bool fCurrentlyConnected; //! Accumulated misbehaviour score for this peer. int nMisbehavior; //! Whether this peer should be disconnected and banned (unless whitelisted). bool fShouldBan; //! String name of this peer (debugging/logging purposes). std::string name; //! List of asynchronously-determined block rejections to notify this peer about. std::vector<CBlockReject> rejects; //! The best known block we know this peer has announced. CBlockIndex* pindexBestKnownBlock; //! The hash of the last unknown block this peer has announced. uint256 hashLastUnknownBlock; //! The last full block we both have. CBlockIndex* pindexLastCommonBlock; //! Whether we've started headers synchronization with this peer. bool fSyncStarted; //! Since when we're stalling block download progress (in microseconds), or 0. int64_t nStallingSince; std::list<QueuedBlock> vBlocksInFlight; int nBlocksInFlight; //! Whether we consider this a preferred download peer. bool fPreferredDownload; CNodeBlocks nodeBlocks; CNodeState() { fCurrentlyConnected = false; nMisbehavior = 0; fShouldBan = false; pindexBestKnownBlock = NULL; hashLastUnknownBlock = uint256(0); pindexLastCommonBlock = NULL; fSyncStarted = false; nStallingSince = 0; nBlocksInFlight = 0; fPreferredDownload = false; } }; /** Map maintaining per-node state. Requires cs_main. */ std::map<NodeId, CNodeState> mapNodeState; // Requires cs_main. CNodeState* State(NodeId pnode) { std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); if (it == mapNodeState.end()) return NULL; return &it->second; } int GetHeight() { while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } return chainActive.Height(); } } void UpdatePreferredDownload(CNode* node, CNodeState* state) { nPreferredDownload -= state->fPreferredDownload; // Whether this node should be marked as a preferred download node. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; nPreferredDownload += state->fPreferredDownload; } void InitializeNode(NodeId nodeid, const CNode* pnode) { LOCK(cs_main); CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second; state.name = pnode->addrName; state.address = pnode->addr; } void FinalizeNode(NodeId nodeid) { LOCK(cs_main); CNodeState* state = State(nodeid); if (state->fSyncStarted) nSyncStarted--; if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { AddressCurrentlyConnected(state->address); } for (const QueuedBlock& entry : state->vBlocksInFlight) mapBlocksInFlight.erase(entry.hash); EraseOrphansFor(nodeid); nPreferredDownload -= state->fPreferredDownload; mapNodeState.erase(nodeid); } // Requires cs_main. void MarkBlockAsReceived(const uint256& hash) { std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end()) { CNodeState* state = State(itInFlight->second.first); nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders; state->vBlocksInFlight.erase(itInFlight->second.second); state->nBlocksInFlight--; state->nStallingSince = 0; mapBlocksInFlight.erase(itInFlight); } } // Requires cs_main. void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex = NULL) { CNodeState* state = State(nodeid); assert(state != NULL); // Make sure it's not listed somewhere already. MarkBlockAsReceived(hash); QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL}; nQueuedValidatedHeaders += newentry.fValidatedHeaders; std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry); state->nBlocksInFlight++; mapBlocksInFlight[hash] = std::make_pair(nodeid, it); } /** Check whether the last unknown block a peer advertised is not yet known. */ void ProcessBlockAvailability(NodeId nodeid) { CNodeState* state = State(nodeid); assert(state != NULL); if (state->hashLastUnknownBlock != 0) { BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock); if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) { if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = itOld->second; state->hashLastUnknownBlock = uint256(0); } } } /** Update tracking information about which blocks a peer is assumed to have. */ void UpdateBlockAvailability(NodeId nodeid, const uint256& hash) { CNodeState* state = State(nodeid); assert(state != NULL); ProcessBlockAvailability(nodeid); BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end() && it->second->nChainWork > 0) { // An actually better block was announced. if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork) state->pindexBestKnownBlock = it->second; } else { // An unknown block was announced; just assume that the latest one is the best one. state->hashLastUnknownBlock = hash; } } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-NULL. */ CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; } /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has * at most count entries. */ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller) { if (count == 0) return; vBlocks.reserve(vBlocks.size() + count); CNodeState* state = State(nodeid); assert(state != NULL); // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) { // This peer has nothing interesting. return; } if (state->pindexLastCommonBlock == NULL) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor // of their current tip anymore. Go back enough to fix that. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; std::vector<CBlockIndex*> vToFetch; CBlockIndex* pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; } // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the mean time, update // pindexLastCommonBlock as long as all ancestors are already downloaded. for (CBlockIndex* pindex : vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; } if (pindex->nStatus & BLOCK_HAVE_DATA) { if (pindex->nChainTx) state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { // The block is not already downloaded, and not yet in flight. if (pindex->nHeight > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != nodeid) { // We aren't able to fetch anything, but we would be if the download window was one larger. nodeStaller = waitingfor; } return; } vBlocks.push_back(pindex); if (vBlocks.size() == count) { return; } } else if (waitingfor == -1) { // This is the first already-in-flight block. waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } } } } } // anon namespace bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats) { LOCK(cs_main); CNodeState* state = State(nodeid); if (state == NULL) return false; stats.nMisbehavior = state->nMisbehavior; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; for (const QueuedBlock& queue : state->vBlocksInFlight) { if (queue.pindex) stats.vHeightInFlight.push_back(queue.pindex->nHeight); } return true; } void RegisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.GetHeight.connect(&GetHeight); nodeSignals.ProcessMessages.connect(&ProcessMessages); nodeSignals.SendMessages.connect(&SendMessages); nodeSignals.InitializeNode.connect(&InitializeNode); nodeSignals.FinalizeNode.connect(&FinalizeNode); } void UnregisterNodeSignals(CNodeSignals& nodeSignals) { nodeSignals.GetHeight.disconnect(&GetHeight); nodeSignals.ProcessMessages.disconnect(&ProcessMessages); nodeSignals.SendMessages.disconnect(&SendMessages); nodeSignals.InitializeNode.disconnect(&InitializeNode); nodeSignals.FinalizeNode.disconnect(&FinalizeNode); } CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator) { // Find the first block the caller has in the main chain for (const uint256& hash : locator.vHave) { BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (chain.Contains(pindex)) return pindex; } } return chain.Genesis(); } CCoinsViewCache* pcoinsTip = NULL; CBlockTreeDB* pblocktree = NULL; CZerocoinDB* zerocoinDB = NULL; CSporkDB* pSporkDB = NULL; ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CTransaction& tx, NodeId peer) { uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz > 5000) { LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString()); return false; } mapOrphanTransactions[hash].tx = tx; mapOrphanTransactions[hash].fromPeer = peer; for (const CTxIn& txin : tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(), mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size()); return true; } void static EraseOrphanTx(uint256 hash) { std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash); if (it == mapOrphanTransactions.end()) return; for (const CTxIn& txin : it->second.tx.vin) { std::map<uint256, std::set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash); if (itPrev == mapOrphanTransactionsByPrev.end()) continue; itPrev->second.erase(hash); if (itPrev->second.empty()) mapOrphanTransactionsByPrev.erase(itPrev); } mapOrphanTransactions.erase(it); } void EraseOrphansFor(NodeId peer) { int nErased = 0; std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); while (iter != mapOrphanTransactions.end()) { std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid if (maybeErase->second.fromPeer == peer) { EraseOrphanTx(maybeErase->second.tx.GetHash()); ++nErased; } } if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } bool IsStandardTx(const CTransaction& tx, std::string& reason) { AssertLockHeld(cs_main); if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) { reason = "version"; return false; } // Treat non-final transactions as non-standard to prevent a specific type // of double-spend attack, as well as DoS attacks. (if the transaction // can't be mined, the attacker isn't expending resources broadcasting it) // Basically we don't want to propagate transactions that can't be included in // the next block. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height() // is set to the value of nHeight in the block. However, when IsFinalTx() // is called within CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a transaction can // be part of the *next* block, we need to call IsFinalTx() with one more // than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, chainActive.Height() + 1)) { reason = "non-final"; return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); unsigned int nMaxSize = tx.ContainsZerocoins() ? MAX_ZEROCOIN_TX_SIZE : MAX_STANDARD_TX_SIZE; if (sz >= nMaxSize) { reason = "tx-size"; return false; } for (const CTxIn& txin : tx.vin) { if (txin.IsZerocoinSpend() || txin.IsZerocoinPublicSpend()) continue; // Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed // keys. (remember the 520 byte limit on redeemScript size) That works // out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 // bytes of scriptSig, which we round off to 1650 bytes for some minor // future-proofing. That's also enough to spend a 20-of-20 // CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not // considered standard) if (txin.scriptSig.size() > 1650) { reason = "scriptsig-size"; return false; } if (!txin.scriptSig.IsPushOnly()) { reason = "scriptsig-not-pushonly"; return false; } } unsigned int nDataOut = 0; txnouttype whichType; for (const CTxOut& txout : tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) { reason = "scriptpubkey"; return false; } if (whichType == TX_NULL_DATA) nDataOut++; else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) { reason = "bare-multisig"; return false; } else if (txout.IsDust(::minRelayTxFee)) { reason = "dust"; return false; } } // only one OP_RETURN txout is permitted if (nDataOut > 1) { reason = "multi-op-return"; return false; } return true; } bool IsFinalTx(const CTransaction& tx, int nBlockHeight, int64_t nBlockTime) { AssertLockHeld(cs_main); // Time based nLockTime implemented in 0.1.6 if (tx.nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = chainActive.Height(); if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; for (const CTxIn& txin : tx.vin) if (!txin.IsFinal()) return false; return true; } /** * Check transaction inputs to mitigate two * potential denial-of-service attacks: * * 1. scriptSigs with extra data stuffed into them, * not consumed by scriptPubKey (or P2SH script) * 2. P2SH scripts with a crazy number of expensive * CHECKSIG/CHECKMULTISIG operations */ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) { if (tx.IsCoinBase() || tx.HasZerocoinSpendInputs()) return true; // coinbase has no inputs and zerocoinspend has a special input //todo should there be a check for a 'standard' zerocoinspend here? for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]); std::vector<std::vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig // IsStandard() will have already returned false // and this method isn't called. std::vector<std::vector<unsigned char> > stack; if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker())) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); std::vector<std::vector<unsigned char> > vSolutions2; txnouttype whichType2; if (Solver(subscript, whichType2, vSolutions2)) { int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } else { // Any other Script with less than 15 sigops OK: unsigned int sigops = subscript.GetSigOpCount(true); // ... extra data left on the stack after execution is OK, too: return (sigops <= MAX_P2SH_SIGOPS); } } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; for (const CTxIn& txin : tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } for (const CTxOut& txout : tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs) { if (tx.IsCoinBase() || tx.HasZerocoinSpendInputs()) // a tx containing a zc spend can have only zc inputs return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxOut& prevout = inputs.GetOutputFor(tx.vin[i]); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } int GetInputAge(CTxIn& vin) { CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewMemPool viewMempool(pcoinsTip, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view const CCoins* coins = view.AccessCoins(vin.prevout.hash); if (coins) { if (coins->nHeight < 0) return 0; return (chainActive.Tip()->nHeight + 1) - coins->nHeight; } else return -1; } } int GetIXConfirmations(uint256 nTXHash) { int sigs = 0; std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash); if (i != mapTxLocks.end()) { sigs = (*i).second.CountSignatures(); } if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) { return nSwiftTXDepth; } return 0; } bool MoneyRange(CAmount nValueOut) { return nValueOut >= 0 && nValueOut <= Params().MaxMoneyOut(); } bool CheckZerocoinMint(const uint256& txHash, const CTxOut& txout, CValidationState& state, bool fCheckOnly) { libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if(!TxOutToPublicCoin(txout, pubCoin, state)) return state.DoS(100, error("CheckZerocoinMint(): TxOutToPublicCoin() failed")); if (!pubCoin.validate()) return state.DoS(100, error("CheckZerocoinMint() : PubCoin does not validate")); return true; } bool ContextualCheckZerocoinMint(const CTransaction& tx, const libzerocoin::PublicCoin& coin, const CBlockIndex* pindex) { if (pindex->nHeight >= Params().Zerocoin_Block_Public_Spend_Enabled()) { // Zerocoin MINTs have been disabled return error("%s: Mints disabled at height %d - unable to add pubcoin %s", __func__, pindex->nHeight, coin.getValue().GetHex().substr(0, 10)); } if (pindex->nHeight >= Params().Zerocoin_Block_V2_Start() && Params().NetworkID() != CBaseChainParams::TESTNET) { //See if this coin has already been added to the blockchain uint256 txid; int nHeight; if (zerocoinDB->ReadCoinMint(coin.getValue(), txid) && IsTransactionInChain(txid, nHeight)) return error("%s: pubcoin %s was already accumulated in tx %s", __func__, coin.getValue().GetHex().substr(0, 10), txid.GetHex()); } return true; } bool isBlockBetweenFakeSerialAttackRange(int nHeight) { if (Params().NetworkID() != CBaseChainParams::MAIN) return false; return nHeight <= Params().Zerocoin_Block_EndFakeSerial(); } bool CheckPublicCoinSpendEnforced(int blockHeight, bool isPublicSpend) { if (blockHeight >= Params().Zerocoin_Block_Public_Spend_Enabled()) { // reject old coin spend if (!isPublicSpend) { return error("%s: failed to add block with older zc spend version", __func__); } } else { if (isPublicSpend) { return error("%s: failed to add block, public spend enforcement not activated", __func__); } } return true; } int CurrentPublicCoinSpendVersion() { return sporkManager.IsSporkActive(SPORK_18_ZEROCOIN_PUBLICSPEND_V4) ? 4 : 3; } bool CheckPublicCoinSpendVersion(int version) { return version == CurrentPublicCoinSpendVersion(); } bool ContextualCheckZerocoinSpend(const CTransaction& tx, const libzerocoin::CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) { if(!ContextualCheckZerocoinSpendNoSerialCheck(tx, spend, pindex, hashBlock)){ return false; } //Reject serial's that are already in the blockchain int nHeightTx = 0; if (IsSerialInBlockchain(spend->getCoinSerialNumber(), nHeightTx)) return error("%s : zPIV spend with serial %s is already in block %d\n", __func__, spend->getCoinSerialNumber().GetHex(), nHeightTx); return true; } bool ContextualCheckZerocoinSpendNoSerialCheck(const CTransaction& tx, const libzerocoin::CoinSpend* spend, CBlockIndex* pindex, const uint256& hashBlock) { //Check to see if the zPIV is properly signed if (pindex->nHeight >= Params().Zerocoin_Block_V2_Start()) { try { if (!spend->HasValidSignature()) return error("%s: V2 zPIV spend does not have a valid signature\n", __func__); } catch (const libzerocoin::InvalidSerialException& e) { // Check if we are in the range of the attack if(!isBlockBetweenFakeSerialAttackRange(pindex->nHeight)) return error("%s: Invalid serial detected, txid %s, in block %d\n", __func__, tx.GetHash().GetHex(), pindex->nHeight); else LogPrintf("%s: Invalid serial detected within range in block %d\n", __func__, pindex->nHeight); } libzerocoin::SpendType expectedType = libzerocoin::SpendType::SPEND; if (tx.IsCoinStake()) expectedType = libzerocoin::SpendType::STAKE; if (spend->getSpendType() != expectedType) { return error("%s: trying to spend zPIV without the correct spend type. txid=%s\n", __func__, tx.GetHash().GetHex()); } } bool fUseV1Params = spend->getCoinVersion() < libzerocoin::PrivateCoin::PUBKEY_VERSION; //Reject serial's that are not in the acceptable value range if (!spend->HasValidSerial(Params().Zerocoin_Params(fUseV1Params))) { // Up until this block our chain was not checking serials correctly.. if (!isBlockBetweenFakeSerialAttackRange(pindex->nHeight)) return error("%s : zPIV spend with serial %s from tx %s is not in valid range\n", __func__, spend->getCoinSerialNumber().GetHex(), tx.GetHash().GetHex()); else LogPrintf("%s:: HasValidSerial :: Invalid serial detected within range in block %d\n", __func__, pindex->nHeight); } return true; } bool CheckZerocoinSpend(const CTransaction& tx, bool fVerifySignature, CValidationState& state, bool fFakeSerialAttack) { //max needed non-mint outputs should be 2 - one for redemption address and a possible 2nd for change if (tx.vout.size() > 2) { int outs = 0; for (const CTxOut& out : tx.vout) { if (out.IsZerocoinMint()) continue; outs++; } if (outs > 2 && !tx.IsCoinStake()) return state.DoS(100, error("CheckZerocoinSpend(): over two non-mint outputs in a zerocoinspend transaction")); } //compute the txout hash that is used for the zerocoinspend signatures CMutableTransaction txTemp; for (const CTxOut& out : tx.vout) { txTemp.vout.push_back(out); } uint256 hashTxOut = txTemp.GetHash(); bool fValidated = false; std::set<CBigNum> serials; CAmount nTotalRedeemed = 0; for (const CTxIn& txin : tx.vin) { //only check txin that is a zcspend bool isPublicSpend = txin.IsZerocoinPublicSpend(); if (!txin.IsZerocoinSpend() && !isPublicSpend) continue; libzerocoin::CoinSpend newSpend; CTxOut prevOut; if (isPublicSpend) { if(!GetOutput(txin.prevout.hash, txin.prevout.n, state, prevOut)){ return state.DoS(100, error("CheckZerocoinSpend(): public zerocoin spend prev output not found, prevTx %s, index %d", txin.prevout.hash.GetHex(), txin.prevout.n)); } libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZPIVModule::parseCoinSpend(txin, tx, prevOut, publicSpend)){ return state.DoS(100, error("CheckZerocoinSpend(): public zerocoin spend parse failed")); } newSpend = publicSpend; } else { newSpend = TxInToZerocoinSpend(txin); } //check that the denomination is valid if (newSpend.getDenomination() == libzerocoin::ZQ_ERROR) return state.DoS(100, error("Zerocoinspend does not have the correct denomination")); //check that denomination is what it claims to be in nSequence if (newSpend.getDenomination() != txin.nSequence) return state.DoS(100, error("Zerocoinspend nSequence denomination does not match CoinSpend")); //make sure the txout has not changed if (newSpend.getTxOutHash() != hashTxOut) return state.DoS(100, error("Zerocoinspend does not use the same txout that was used in the SoK")); if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend ret(params); if (!ZPIVModule::validateInput(txin, prevOut, tx, ret)){ return state.DoS(100, error("CheckZerocoinSpend(): public zerocoin spend did not verify")); } } else // Skip signature verification during initial block download if (fVerifySignature) { //see if we have record of the accumulator used in the spend tx CBigNum bnAccumulatorValue = 0; if (!zerocoinDB->ReadAccumulatorValue(newSpend.getAccumulatorChecksum(), bnAccumulatorValue)) { uint32_t nChecksum = newSpend.getAccumulatorChecksum(); return state.DoS(100, error("%s: Zerocoinspend could not find accumulator associated with checksum %s", __func__, HexStr(BEGIN(nChecksum), END(nChecksum)))); } libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), newSpend.getDenomination(), bnAccumulatorValue); //Check that the coin has been accumulated if(!newSpend.Verify(accumulator, !fFakeSerialAttack)) return state.DoS(100, error("CheckZerocoinSpend(): zerocoin spend did not verify")); } if (serials.count(newSpend.getCoinSerialNumber())) return state.DoS(100, error("Zerocoinspend serial is used twice in the same tx")); serials.insert(newSpend.getCoinSerialNumber()); //make sure that there is no over redemption of coins nTotalRedeemed += libzerocoin::ZerocoinDenominationToAmount(newSpend.getDenomination()); fValidated = true; } if (!tx.IsCoinStake() && nTotalRedeemed < tx.GetValueOut()) { LogPrintf("redeemed = %s , spend = %s \n", FormatMoney(nTotalRedeemed), FormatMoney(tx.GetValueOut())); return state.DoS(100, error("Transaction spend more than was redeemed in zerocoins")); } return fValidated; } bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fRejectBadUTXO, CValidationState& state, bool fFakeSerialAttack, bool fColdStakingActive) { // Basic checks that don't depend on any context if (tx.vin.empty()) return state.DoS(10, error("CheckTransaction() : vin empty"), REJECT_INVALID, "bad-txns-vin-empty"); if (tx.vout.empty()) return state.DoS(10, error("CheckTransaction() : vout empty"), REJECT_INVALID, "bad-txns-vout-empty"); // Size limits unsigned int nMaxSize = MAX_ZEROCOIN_TX_SIZE; if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > nMaxSize) return state.DoS(100, error("CheckTransaction() : size limits failed"), REJECT_INVALID, "bad-txns-oversize"); const CAmount minColdStakingAmount = Params().GetMinColdStakingAmount(); // Check for negative or overflow output values CAmount nValueOut = 0; for (const CTxOut& txout : tx.vout) { if (txout.IsEmpty() && !tx.IsCoinBase() && !tx.IsCoinStake()) return state.DoS(100, error("CheckTransaction(): txout empty for user transaction")); if (txout.nValue < 0) return state.DoS(100, error("CheckTransaction() : txout.nValue negative"), REJECT_INVALID, "bad-txns-vout-negative"); if (txout.nValue > Params().MaxMoneyOut()) return state.DoS(100, error("CheckTransaction() : txout.nValue too high"), REJECT_INVALID, "bad-txns-vout-toolarge"); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return state.DoS(100, error("CheckTransaction() : txout total out of range"), REJECT_INVALID, "bad-txns-txouttotal-toolarge"); if (fZerocoinActive && txout.IsZerocoinMint()) { if(!CheckZerocoinMint(tx.GetHash(), txout, state, true)) return state.DoS(100, error("CheckTransaction() : invalid zerocoin mint")); } // check cold staking enforcement (for delegations) and value out if (txout.scriptPubKey.IsPayToColdStaking()) { if (!fColdStakingActive) return state.DoS(10, error("%s: cold staking not active", __func__), REJECT_INVALID, "bad-txns-cold-stake"); if (txout.nValue < minColdStakingAmount) return state.DoS(100, error("%s: dust amount (%d) not allowed for cold staking. Min amount: %d", __func__, txout.nValue, minColdStakingAmount), REJECT_INVALID, "bad-txns-cold-stake"); } } std::set<COutPoint> vInOutPoints; std::set<CBigNum> vZerocoinSpendSerials; int nZCSpendCount = 0; for (const CTxIn& txin : tx.vin) { // Check for duplicate inputs if (vInOutPoints.count(txin.prevout)) return state.DoS(100, error("CheckTransaction() : duplicate inputs"), REJECT_INVALID, "bad-txns-inputs-duplicate"); //duplicate zcspend serials are checked in CheckZerocoinSpend() if (!txin.IsZerocoinSpend()) { vInOutPoints.insert(txin.prevout); } else if (!txin.IsZerocoinPublicSpend()) { nZCSpendCount++; } } if (fZerocoinActive) { if (nZCSpendCount > Params().Zerocoin_MaxSpendsPerTransaction()) return state.DoS(100, error("CheckTransaction() : there are more zerocoin spends than are allowed in one transaction")); //require that a zerocoinspend only has inputs that are zerocoins if (tx.HasZerocoinSpendInputs()) { for (const CTxIn& in : tx.vin) { if (!in.IsZerocoinSpend() && !in.IsZerocoinPublicSpend()) return state.DoS(100, error("CheckTransaction() : zerocoinspend contains inputs that are not zerocoins")); } // Do not require signature verification if this is initial sync and a block over 24 hours old bool fVerifySignature = !IsInitialBlockDownload() && (GetTime() - chainActive.Tip()->GetBlockTime() < (60*60*24)); if (!CheckZerocoinSpend(tx, fVerifySignature, state, fFakeSerialAttack)) return state.DoS(100, error("CheckTransaction() : invalid zerocoin spend")); } } if (tx.IsCoinBase()) { if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 150) return state.DoS(100, error("CheckTransaction() : coinbase script size=%d", tx.vin[0].scriptSig.size()), REJECT_INVALID, "bad-cb-length"); } else if (fZerocoinActive && tx.HasZerocoinSpendInputs()) { if (tx.vin.size() < 1) return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has less than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend"); if (tx.HasZerocoinPublicSpendInputs()) { // tx has public zerocoin spend inputs if(static_cast<int>(tx.vin.size()) > Params().Zerocoin_MaxPublicSpendsPerTransaction()) return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has more than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend"); } else { // tx has regular zerocoin spend inputs if(static_cast<int>(tx.vin.size()) > Params().Zerocoin_MaxSpendsPerTransaction()) return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has more than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend"); } } else { for (const CTxIn& txin : tx.vin) if (txin.prevout.IsNull() && (fZerocoinActive && !txin.IsZerocoinSpend())) return state.DoS(10, error("CheckTransaction() : prevout is null"), REJECT_INVALID, "bad-txns-prevout-null"); } return true; } bool CheckFinalTx(const CTransaction& tx, int flags) { AssertLockHeld(cs_main); // By convention a negative value for flags indicates that the // current network-enforced consensus rules should be used. In // a future soft-fork scenario that would mean checking which // rules would be enforced for the next block and setting the // appropriate flags. At the present time no soft-forks are // scheduled, so no flags are set. flags = std::max(flags, 0); // CheckFinalTx() uses chainActive.Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call // IsFinalTx() with one more than chainActive.Height(). const int nBlockHeight = chainActive.Height() + 1; // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. // When the next block is created its previous block will be the current // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); } CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree) { { LOCK(mempool.cs); uint256 hash = tx.GetHash(); double dPriorityDelta = 0; CAmount nFeeDelta = 0; mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta); if (dPriorityDelta > 0 || nFeeDelta > 0) return 0; } CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes); if (fAllowFree) { // There is a free transaction area in blocks created by most miners, // * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000 // to be considered to fall into this category. We don't want to encourage sending // multiple transactions instead of one big transaction to avoid fees. if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000)) nMinFee = 0; } if (!MoneyRange(nMinFee)) nMinFee = Params().MaxMoneyOut(); return nMinFee; } bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees) { AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; //Temporarily disable zerocoin for maintenance if (sporkManager.IsSporkActive(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && tx.ContainsZerocoins()) return state.DoS(10, error("%s : Zerocoin transactions are temporarily disabled for maintenance", __func__), REJECT_INVALID, "bad-tx"); // Check transaction int chainHeight = chainActive.Height(); bool fColdStakingActive = sporkManager.IsSporkActive(SPORK_17_COLDSTAKING_ENFORCEMENT); if (!CheckTransaction(tx, chainHeight >= Params().Zerocoin_StartHeight(), true, state, isBlockBetweenFakeSerialAttackRange(chainHeight), fColdStakingActive)) return state.DoS(100, error("%s : CheckTransaction failed", __func__), REJECT_INVALID, "bad-tx"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, error("%s : coinbase as individual tx", __func__), REJECT_INVALID, "coinbase"); //Coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return state.DoS(100, error("%s : coinstake as individual tx (id=%s): %s", __func__, tx.GetHash().GetHex(), tx.ToString()), REJECT_INVALID, "coinstake"); // Only accept nLockTime-using transactions that can be mined in the next // block; we don't want our mempool filled up with transactions that can't // be mined yet. if (!CheckFinalTx(tx, STANDARD_LOCKTIME_VERIFY_FLAGS)) return state.DoS(0, false, REJECT_NONSTANDARD, "non-final"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) std::string reason; if (Params().RequireStandard() && !IsStandardTx(tx, reason)) return state.DoS(0, error("%s : nonstandard transaction: %s", __func__, reason), REJECT_NONSTANDARD, reason); // is it already in the memory pool? uint256 hash = tx.GetHash(); if (pool.exists(hash)) { return error("%s tx already in mempool", __func__); } // ----------- swiftTX transaction scanning ----------- for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { return state.DoS(0, error("%s : conflicts with existing transaction lock: %s", __func__, reason), REJECT_INVALID, "tx-lock-conflict"); } } } bool hasZcSpendInputs = tx.HasZerocoinSpendInputs(); // Check for conflicts with in-memory transactions if (!hasZcSpendInputs) { LOCK(pool.cs); // protect pool.mapNextTx for (const auto &in : tx.vin) { COutPoint outpoint = in.prevout; if (pool.mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; } } } { CCoinsView dummy; CCoinsViewCache view(&dummy); CAmount nValueIn = 0; if (hasZcSpendInputs) { nValueIn = tx.GetZerocoinSpent(); //Check that txid is not already in the chain int nHeightTx = 0; if (IsTransactionInChain(tx.GetHash(), nHeightTx)) return state.Invalid(error("%s : zPIV spend tx %s already in block %d", __func__, tx.GetHash().GetHex(), nHeightTx), REJECT_DUPLICATE, "bad-txns-inputs-spent"); //Check for double spending of serial #'s for (const CTxIn& txIn : tx.vin) { // Only allow for zc spends inputs bool isPublicSpend = txIn.IsZerocoinPublicSpend(); bool isPrivZerocoinSpend = txIn.IsZerocoinSpend(); if (!isPrivZerocoinSpend && !isPublicSpend) { return state.Invalid(error("%s: failed for tx %s, every input must be a zcspend or zcpublicspend", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } // Check enforcement if (!CheckPublicCoinSpendEnforced(chainActive.Height(), isPublicSpend)){ return state.Invalid(error("%s: CheckPublicCoinSpendEnforced failed for tx %s", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZPIVModule::ParseZerocoinPublicSpend(txIn, tx, state, publicSpend)){ return false; } if (!ContextualCheckZerocoinSpend(tx, &publicSpend, chainActive.Tip(), 0)) return state.Invalid(error("%s: ContextualCheckZerocoinSpend failed for tx %s", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); // Check that the version matches the one enforced with SPORK_18 if (!CheckPublicCoinSpendVersion(publicSpend.getVersion())) { return state.Invalid(error("%s : Public Zerocoin spend version %d not accepted. must be version %d.", __func__, publicSpend.getVersion(), CurrentPublicCoinSpendVersion()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } } else { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn); if (!ContextualCheckZerocoinSpend(tx, &spend, chainActive.Tip(), 0)) return state.Invalid(error("%s: ContextualCheckZerocoinSpend failed for tx %s", __func__, tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } } } else { LOCK(pool.cs); CCoinsViewMemPool viewMemPool(pcoinsTip, pool); view.SetBackend(viewMemPool); // do we already have it? if (view.HaveCoins(hash)) return false; // do all inputs exist? // Note that this does not check for the presence of actual outputs (see the next check for that), // only helps filling in pfMissingInputs (to determine missing vs spent). for (const CTxIn& txin : tx.vin) { if (!view.HaveCoins(txin.prevout.hash)) { if (pfMissingInputs) *pfMissingInputs = true; return false; } //Check for invalid/fraudulent inputs if (!ValidOutPoint(txin.prevout, chainActive.Height())) { return state.Invalid(error("%s : tried to spend invalid input %s in tx %s", __func__, txin.prevout.ToString(), tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs"); } } // Check that zPIV mints (if included) are not already known for (auto& out : tx.vout) { if (!out.IsZerocoinMint()) continue; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.Invalid(error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); if (!ContextualCheckZerocoinMint(tx, coin, chainActive.Tip())) return state.Invalid(error("%s: zerocoin mint failed contextual check", __func__)); } // are the actual inputs available? if (!view.HaveInputs(tx)) return state.Invalid(error("%s : inputs already spent", __func__), REJECT_DUPLICATE, "bad-txns-inputs-spent"); // Bring the best block into scope view.GetBestBlock(); nValueIn = view.GetValueIn(tx); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool view.SetBackend(dummy); } // Check for non-standard pay-to-script-hash in inputs if (Params().RequireStandard() && !AreInputsStandard(tx, view)) return error("%s : nonstandard transaction input", __func__); // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. if (!hasZcSpendInputs) { unsigned int nSigOps = GetLegacySigOpCount(tx); unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT; nSigOps += GetP2SHSigOpCount(tx, view); if(nSigOps > nMaxSigOps) return state.DoS(0, error("%s : too many sigops %s, %d > %d", __func__, hash.ToString(), nSigOps, nMaxSigOps), REJECT_NONSTANDARD, "bad-txns-too-many-sigops"); } CAmount nValueOut = tx.GetValueOut(); CAmount nFees = nValueIn - nValueOut; double dPriority = 0; if (!hasZcSpendInputs) view.GetPriority(tx, chainActive.Height()); CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height()); unsigned int nSize = entry.GetTxSize(); // Don't accept it if it can't get into a block // but prioritise dstx and don't check fees for it if (mapObfuscationBroadcastTxes.count(hash)) { mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN); } else if (!ignoreFees) { CAmount txMinFee = GetMinRelayFee(tx, nSize, true); if (fLimitFree && nFees < txMinFee && !hasZcSpendInputs) return state.DoS(0, error("%s : not enough fees %s, %d < %d", __func__, hash.ToString(), nFees, txMinFee), REJECT_INSUFFICIENTFEE, "insufficient fee"); // Require that free transactions have sufficient priority to be mined in the next block. if (tx.HasZerocoinMintOutputs()) { if(nFees < Params().Zerocoin_MintFee() * tx.GetZerocoinMintCount()) return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee for zerocoinmint"); } else if (!hasZcSpendInputs && GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority"); } // Continuously rate-limit free (really, very-low-fee) transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !hasZcSpendInputs) { static CCriticalSection csFreeLimiter; static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); LOCK(csFreeLimiter); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000) return state.DoS(0, error("%s : free transaction rejected by rate limiter", __func__), REJECT_INSUFFICIENTFEE, "rate limited free transaction"); LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize); dFreeCount += nSize; } } if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) return error("%s : insane fees %s, %d > %d", __func__, hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000); // As zero fee transactions are not going to be accepted in the near future (4.0) and the code will be fully refactored soon. // This is just a quick inline towards that goal, the mempool by default will not accept them. Blocking // any subsequent network relay. if ((Params().NetworkID() != CBaseChainParams::REGTEST) && nFees == 0 && !hasZcSpendInputs) { return error("%s : zero fees not accepted %s, %d > %d", __func__, hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000); } bool fCLTVIsActivated = chainActive.Tip()->nHeight >= Params().BIP65ActivationHeight(); // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. int flags = STANDARD_SCRIPT_VERIFY_FLAGS; if (fCLTVIsActivated) flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; if (!CheckInputs(tx, state, view, true, flags, true)) { return error("%s : ConnectInputs failed %s", __func__, hash.ToString()); } // Check again against just the consensus-critical mandatory script // verification flags, in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For // instance the STRICTENC flag was incorrectly allowing certain // CHECKSIG NOT scripts to pass, even though they were invalid. // // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks, however allowing such transactions into the mempool // can be exploited as a DoS attack. flags = MANDATORY_SCRIPT_VERIFY_FLAGS; if (fCLTVIsActivated) flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; if (!CheckInputs(tx, state, view, true, flags, true)) { return error("%s : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", __func__, hash.ToString()); } // Store transaction in memory pool.addUnchecked(hash, entry); } SyncWithWallets(tx, nullptr); //Track zerocoinspends and ensure that they are given priority to make it into the blockchain if (hasZcSpendInputs) mapZerocoinspends[tx.GetHash()] = GetAdjustedTime(); return true; } bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool isDSTX) { AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; if (!CheckTransaction(tx, chainActive.Height() >= Params().Zerocoin_StartHeight(), true, state)) return error("AcceptableInputs: : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return state.DoS(100, error("AcceptableInputs: : coinbase as individual tx"), REJECT_INVALID, "coinbase"); // Rather not work on nonstandard transactions (unless -testnet/-regtest) std::string reason; // for any real tx this will be checked on AcceptToMemoryPool anyway // if (Params().RequireStandard() && !IsStandardTx(tx, reason)) // return state.DoS(0, // error("AcceptableInputs : nonstandard transaction: %s", reason), // REJECT_NONSTANDARD, reason); // is it already in the memory pool? uint256 hash = tx.GetHash(); if (pool.exists(hash)) return false; // ----------- swiftTX transaction scanning ----------- for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { return state.DoS(0, error("AcceptableInputs : conflicts with existing transaction lock: %s", reason), REJECT_INVALID, "tx-lock-conflict"); } } } // Check for conflicts with in-memory transactions if (!tx.HasZerocoinSpendInputs()) { LOCK(pool.cs); // protect pool.mapNextTx for (const auto &in : tx.vin) { COutPoint outpoint = in.prevout; if (pool.mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; } } } { CCoinsView dummy; CCoinsViewCache view(&dummy); CAmount nValueIn = 0; { LOCK(pool.cs); CCoinsViewMemPool viewMemPool(pcoinsTip, pool); view.SetBackend(viewMemPool); // do we already have it? if (view.HaveCoins(hash)) return false; // do all inputs exist? // Note that this does not check for the presence of actual outputs (see the next check for that), // only helps filling in pfMissingInputs (to determine missing vs spent). for (const CTxIn& txin : tx.vin) { if (!view.HaveCoins(txin.prevout.hash)) { if (pfMissingInputs) *pfMissingInputs = true; return false; } // check for invalid/fraudulent inputs if (!ValidOutPoint(txin.prevout, chainActive.Height())) { return state.Invalid(error("%s : tried to spend invalid input %s in tx %s", __func__, txin.prevout.ToString(), tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs"); } } // are the actual inputs available? if (!view.HaveInputs(tx)) return state.Invalid(error("AcceptableInputs : inputs already spent"), REJECT_DUPLICATE, "bad-txns-inputs-spent"); // Bring the best block into scope view.GetBestBlock(); nValueIn = view.GetValueIn(tx); // we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool view.SetBackend(dummy); } // Check for non-standard pay-to-script-hash in inputs // for any real tx this will be checked on AcceptToMemoryPool anyway // if (Params().RequireStandard() && !AreInputsStandard(tx, view)) // return error("AcceptableInputs: : nonstandard transaction input"); // Check that the transaction doesn't have an excessive number of // sigops, making it impossible to mine. Since the coinbase transaction // itself can contain sigops MAX_TX_SIGOPS is less than // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than // merely non-standard transaction. unsigned int nSigOps = GetLegacySigOpCount(tx); unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT; nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > nMaxSigOps) return state.DoS(0, error("AcceptableInputs : too many sigops %s, %d > %d", hash.ToString(), nSigOps, nMaxSigOps), REJECT_NONSTANDARD, "bad-txns-too-many-sigops"); CAmount nValueOut = tx.GetValueOut(); CAmount nFees = nValueIn - nValueOut; double dPriority = view.GetPriority(tx, chainActive.Height()); CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height()); unsigned int nSize = entry.GetTxSize(); // Don't accept it if it can't get into a block // but prioritise dstx and don't check fees for it if (isDSTX) { mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN); } else { // same as !ignoreFees for AcceptToMemoryPool CAmount txMinFee = GetMinRelayFee(tx, nSize, true); if (fLimitFree && nFees < txMinFee && !tx.HasZerocoinSpendInputs()) return state.DoS(0, error("AcceptableInputs : not enough fees %s, %d < %d", hash.ToString(), nFees, txMinFee), REJECT_INSUFFICIENTFEE, "insufficient fee"); // Require that free transactions have sufficient priority to be mined in the next block. if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) { return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority"); } // Continuously rate-limit free (really, very-low-fee) transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !tx.HasZerocoinSpendInputs()) { static CCriticalSection csFreeLimiter; static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); LOCK(csFreeLimiter); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000) return state.DoS(0, error("AcceptableInputs : free transaction rejected by rate limiter"), REJECT_INSUFFICIENTFEE, "rate limited free transaction"); LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize); dFreeCount += nSize; } } if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000) return error("AcceptableInputs: : insane fees %s, %d > %d", hash.ToString(), nFees, ::minRelayTxFee.GetFee(nSize) * 10000); bool fCLTVIsActivated = chainActive.Tip()->nHeight >= Params().BIP65ActivationHeight(); // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. int flags = STANDARD_SCRIPT_VERIFY_FLAGS; if (fCLTVIsActivated) flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; if (!CheckInputs(tx, state, view, false, flags, true)) { return error("AcceptableInputs: : ConnectInputs failed %s", hash.ToString()); } // Check again against just the consensus-critical mandatory script // verification flags, in case of bugs in the standard flags that cause // transactions to pass as valid when they're actually invalid. For // instance the STRICTENC flag was incorrectly allowing certain // CHECKSIG NOT scripts to pass, even though they were invalid. // // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks, however allowing such transactions into the mempool // can be exploited as a DoS attack. // for any real tx this will be checked on AcceptToMemoryPool anyway // if (!CheckInputs(tx, state, view, false, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) // { // return error("AcceptableInputs: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString()); // } // Store transaction in memory // pool.addUnchecked(hash, entry); } // SyncWithWallets(tx, NULL); return true; } bool GetOutput(const uint256& hash, unsigned int index, CValidationState& state, CTxOut& out) { CTransaction txPrev; uint256 hashBlock; if (!GetTransaction(hash, txPrev, hashBlock, true)) { return state.DoS(100, error("Output not found")); } if (index > txPrev.vout.size()) { return state.DoS(100, error("Output not found, invalid index %d for %s",index, hash.GetHex())); } out = txPrev.vout[index]; return true; } /** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */ bool GetTransaction(const uint256& hash, CTransaction& txOut, uint256& hashBlock, bool fAllowSlow, CBlockIndex* blockIndex) { CBlockIndex* pindexSlow = blockIndex; LOCK(cs_main); if (!blockIndex) { if (mempool.lookup(hash, txOut)) { return true; } if (fTxIndex) { CDiskTxPos postx; if (pblocktree->ReadTxIndex(hash, postx)) { CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION); if (file.IsNull()) return error("%s: OpenBlockFile failed", __func__); CBlockHeader header; try { file >> header; fseek(file.Get(), postx.nTxOffset, SEEK_CUR); file >> txOut; } catch (const std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } hashBlock = header.GetHash(); if (txOut.GetHash() != hash) return error("%s : txid mismatch", __func__); return true; } // transaction not found in the index, nothing more can be done return false; } if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it int nHeight = -1; { CCoinsViewCache& view = *pcoinsTip; const CCoins* coins = view.AccessCoins(hash); if (coins) nHeight = coins->nHeight; } if (nHeight > 0) pindexSlow = chainActive[nHeight]; } } if (pindexSlow) { CBlock block; if (ReadBlockFromDisk(block, pindexSlow)) { for (const CTransaction& tx : block.vtx) { if (tx.GetHash() == hash) { txOut = tx; hashBlock = pindexSlow->GetBlockHash(); return true; } } } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos) { // Open history file to append CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("WriteBlockToDisk : OpenBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(block); fileout << FLATDATA(Params().MessageStart()) << nSize; // Write block long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("WriteBlockToDisk : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << block; return true; } bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos) { block.SetNull(); // Open history file to read CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("ReadBlockFromDisk : OpenBlockFile failed"); // Read block try { filein >> block; } catch (const std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } // Check the header if (block.IsProofOfWork()) { if (!CheckProofOfWork(block.GetHash(), block.nBits)) return error("ReadBlockFromDisk : Errors in block header"); } return true; } bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex) { if (!ReadBlockFromDisk(block, pindex->GetBlockPos())) return false; if (block.GetHash() != pindex->GetBlockHash()) { LogPrintf("%s : block=%s index=%s\n", __func__, block.GetHash().GetHex(), pindex->GetBlockHash().GetHex()); return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index"); } return true; } double ConvertBitsToDouble(unsigned int nBits) { int nShift = (nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } int64_t GetBlockValue(int nHeight) { if (Params().NetworkID() == CBaseChainParams::TESTNET) { if (nHeight < 200 && nHeight > 0) return 250000 * COIN; } if (Params().NetworkID() == CBaseChainParams::REGTEST) { if (nHeight == 0) return 250 * COIN; } int64_t nSubsidy = 0; if (nHeight <= Params().LAST_POW_BLOCK() && nHeight >= 0) { nSubsidy = 15536 * COIN; } else { nSubsidy = 4 * COIN; } return nSubsidy; } CAmount GetSeeSaw(const CAmount& blockValue, int nMasternodeCount, int nHeight) { //if a mn count is inserted into the function we are looking for a specific result for a masternode count if (nMasternodeCount < 1){ if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) nMasternodeCount = mnodeman.stable_size(); else nMasternodeCount = mnodeman.size(); } int64_t nMoneySupply = chainActive.Tip()->nMoneySupply; int64_t mNodeCoins = nMasternodeCount * Params().MasternodeCollateral(); // Use this log to compare the masternode count for different clients //LogPrintf("Adjusting seesaw at height %d with %d masternodes (without drift: %d) at %ld\n", nHeight, nMasternodeCount, nMasternodeCount - Params().MasternodeCountDrift(), GetTime()); if (fDebug) LogPrintf("GetMasternodePayment(): moneysupply=%s, nodecoins=%s \n", FormatMoney(nMoneySupply).c_str(), FormatMoney(mNodeCoins).c_str()); CAmount ret = 0; if (mNodeCoins == 0) { ret = 0; } else if (nHeight <= 325000) { if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > 0) { ret = blockValue * .85; } else if (mNodeCoins <= (nMoneySupply * .1) && mNodeCoins > (nMoneySupply * .05)) { ret = blockValue * .8; } else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .1)) { ret = blockValue * .75; } else if (mNodeCoins <= (nMoneySupply * .2) && mNodeCoins > (nMoneySupply * .15)) { ret = blockValue * .7; } else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .2)) { ret = blockValue * .65; } else if (mNodeCoins <= (nMoneySupply * .3) && mNodeCoins > (nMoneySupply * .25)) { ret = blockValue * .6; } else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .3)) { ret = blockValue * .55; } else if (mNodeCoins <= (nMoneySupply * .4) && mNodeCoins > (nMoneySupply * .35)) { ret = blockValue * .5; } else if (mNodeCoins <= (nMoneySupply * .45) && mNodeCoins > (nMoneySupply * .4)) { ret = blockValue * .45; } else if (mNodeCoins <= (nMoneySupply * .5) && mNodeCoins > (nMoneySupply * .45)) { ret = blockValue * .4; } else if (mNodeCoins <= (nMoneySupply * .55) && mNodeCoins > (nMoneySupply * .5)) { ret = blockValue * .35; } else if (mNodeCoins <= (nMoneySupply * .6) && mNodeCoins > (nMoneySupply * .55)) { ret = blockValue * .3; } else if (mNodeCoins <= (nMoneySupply * .65) && mNodeCoins > (nMoneySupply * .6)) { ret = blockValue * .25; } else if (mNodeCoins <= (nMoneySupply * .7) && mNodeCoins > (nMoneySupply * .65)) { ret = blockValue * .2; } else if (mNodeCoins <= (nMoneySupply * .75) && mNodeCoins > (nMoneySupply * .7)) { ret = blockValue * .15; } else { ret = blockValue * .1; } } else if (nHeight > 325000) { if (mNodeCoins <= (nMoneySupply * .01) && mNodeCoins > 0) { ret = blockValue * .90; } else if (mNodeCoins <= (nMoneySupply * .02) && mNodeCoins > (nMoneySupply * .01)) { ret = blockValue * .88; } else if (mNodeCoins <= (nMoneySupply * .03) && mNodeCoins > (nMoneySupply * .02)) { ret = blockValue * .87; } else if (mNodeCoins <= (nMoneySupply * .04) && mNodeCoins > (nMoneySupply * .03)) { ret = blockValue * .86; } else if (mNodeCoins <= (nMoneySupply * .05) && mNodeCoins > (nMoneySupply * .04)) { ret = blockValue * .85; } else if (mNodeCoins <= (nMoneySupply * .06) && mNodeCoins > (nMoneySupply * .05)) { ret = blockValue * .84; } else if (mNodeCoins <= (nMoneySupply * .07) && mNodeCoins > (nMoneySupply * .06)) { ret = blockValue * .83; } else if (mNodeCoins <= (nMoneySupply * .08) && mNodeCoins > (nMoneySupply * .07)) { ret = blockValue * .82; } else if (mNodeCoins <= (nMoneySupply * .09) && mNodeCoins > (nMoneySupply * .08)) { ret = blockValue * .81; } else if (mNodeCoins <= (nMoneySupply * .10) && mNodeCoins > (nMoneySupply * .09)) { ret = blockValue * .80; } else if (mNodeCoins <= (nMoneySupply * .11) && mNodeCoins > (nMoneySupply * .10)) { ret = blockValue * .79; } else if (mNodeCoins <= (nMoneySupply * .12) && mNodeCoins > (nMoneySupply * .11)) { ret = blockValue * .78; } else if (mNodeCoins <= (nMoneySupply * .13) && mNodeCoins > (nMoneySupply * .12)) { ret = blockValue * .77; } else if (mNodeCoins <= (nMoneySupply * .14) && mNodeCoins > (nMoneySupply * .13)) { ret = blockValue * .76; } else if (mNodeCoins <= (nMoneySupply * .15) && mNodeCoins > (nMoneySupply * .14)) { ret = blockValue * .75; } else if (mNodeCoins <= (nMoneySupply * .16) && mNodeCoins > (nMoneySupply * .15)) { ret = blockValue * .74; } else if (mNodeCoins <= (nMoneySupply * .17) && mNodeCoins > (nMoneySupply * .16)) { ret = blockValue * .73; } else if (mNodeCoins <= (nMoneySupply * .18) && mNodeCoins > (nMoneySupply * .17)) { ret = blockValue * .72; } else if (mNodeCoins <= (nMoneySupply * .19) && mNodeCoins > (nMoneySupply * .18)) { ret = blockValue * .71; } else if (mNodeCoins <= (nMoneySupply * .20) && mNodeCoins > (nMoneySupply * .19)) { ret = blockValue * .70; } else if (mNodeCoins <= (nMoneySupply * .21) && mNodeCoins > (nMoneySupply * .20)) { ret = blockValue * .69; } else if (mNodeCoins <= (nMoneySupply * .22) && mNodeCoins > (nMoneySupply * .21)) { ret = blockValue * .68; } else if (mNodeCoins <= (nMoneySupply * .23) && mNodeCoins > (nMoneySupply * .22)) { ret = blockValue * .67; } else if (mNodeCoins <= (nMoneySupply * .24) && mNodeCoins > (nMoneySupply * .23)) { ret = blockValue * .66; } else if (mNodeCoins <= (nMoneySupply * .25) && mNodeCoins > (nMoneySupply * .24)) { ret = blockValue * .65; } else if (mNodeCoins <= (nMoneySupply * .26) && mNodeCoins > (nMoneySupply * .25)) { ret = blockValue * .64; } else if (mNodeCoins <= (nMoneySupply * .27) && mNodeCoins > (nMoneySupply * .26)) { ret = blockValue * .63; } else if (mNodeCoins <= (nMoneySupply * .28) && mNodeCoins > (nMoneySupply * .27)) { ret = blockValue * .62; } else if (mNodeCoins <= (nMoneySupply * .29) && mNodeCoins > (nMoneySupply * .28)) { ret = blockValue * .61; } else if (mNodeCoins <= (nMoneySupply * .30) && mNodeCoins > (nMoneySupply * .29)) { ret = blockValue * .60; } else if (mNodeCoins <= (nMoneySupply * .31) && mNodeCoins > (nMoneySupply * .30)) { ret = blockValue * .59; } else if (mNodeCoins <= (nMoneySupply * .32) && mNodeCoins > (nMoneySupply * .31)) { ret = blockValue * .58; } else if (mNodeCoins <= (nMoneySupply * .33) && mNodeCoins > (nMoneySupply * .32)) { ret = blockValue * .57; } else if (mNodeCoins <= (nMoneySupply * .34) && mNodeCoins > (nMoneySupply * .33)) { ret = blockValue * .56; } else if (mNodeCoins <= (nMoneySupply * .35) && mNodeCoins > (nMoneySupply * .34)) { ret = blockValue * .55; } else if (mNodeCoins <= (nMoneySupply * .363) && mNodeCoins > (nMoneySupply * .35)) { ret = blockValue * .54; } else if (mNodeCoins <= (nMoneySupply * .376) && mNodeCoins > (nMoneySupply * .363)) { ret = blockValue * .53; } else if (mNodeCoins <= (nMoneySupply * .389) && mNodeCoins > (nMoneySupply * .376)) { ret = blockValue * .52; } else if (mNodeCoins <= (nMoneySupply * .402) && mNodeCoins > (nMoneySupply * .389)) { ret = blockValue * .51; } else if (mNodeCoins <= (nMoneySupply * .415) && mNodeCoins > (nMoneySupply * .402)) { ret = blockValue * .50; } else if (mNodeCoins <= (nMoneySupply * .428) && mNodeCoins > (nMoneySupply * .415)) { ret = blockValue * .49; } else if (mNodeCoins <= (nMoneySupply * .441) && mNodeCoins > (nMoneySupply * .428)) { ret = blockValue * .48; } else if (mNodeCoins <= (nMoneySupply * .454) && mNodeCoins > (nMoneySupply * .441)) { ret = blockValue * .47; } else if (mNodeCoins <= (nMoneySupply * .467) && mNodeCoins > (nMoneySupply * .454)) { ret = blockValue * .46; } else if (mNodeCoins <= (nMoneySupply * .48) && mNodeCoins > (nMoneySupply * .467)) { ret = blockValue * .45; } else if (mNodeCoins <= (nMoneySupply * .493) && mNodeCoins > (nMoneySupply * .48)) { ret = blockValue * .44; } else if (mNodeCoins <= (nMoneySupply * .506) && mNodeCoins > (nMoneySupply * .493)) { ret = blockValue * .43; } else if (mNodeCoins <= (nMoneySupply * .519) && mNodeCoins > (nMoneySupply * .506)) { ret = blockValue * .42; } else if (mNodeCoins <= (nMoneySupply * .532) && mNodeCoins > (nMoneySupply * .519)) { ret = blockValue * .41; } else if (mNodeCoins <= (nMoneySupply * .545) && mNodeCoins > (nMoneySupply * .532)) { ret = blockValue * .40; } else if (mNodeCoins <= (nMoneySupply * .558) && mNodeCoins > (nMoneySupply * .545)) { ret = blockValue * .39; } else if (mNodeCoins <= (nMoneySupply * .571) && mNodeCoins > (nMoneySupply * .558)) { ret = blockValue * .38; } else if (mNodeCoins <= (nMoneySupply * .584) && mNodeCoins > (nMoneySupply * .571)) { ret = blockValue * .37; } else if (mNodeCoins <= (nMoneySupply * .597) && mNodeCoins > (nMoneySupply * .584)) { ret = blockValue * .36; } else if (mNodeCoins <= (nMoneySupply * .61) && mNodeCoins > (nMoneySupply * .597)) { ret = blockValue * .35; } else if (mNodeCoins <= (nMoneySupply * .623) && mNodeCoins > (nMoneySupply * .61)) { ret = blockValue * .34; } else if (mNodeCoins <= (nMoneySupply * .636) && mNodeCoins > (nMoneySupply * .623)) { ret = blockValue * .33; } else if (mNodeCoins <= (nMoneySupply * .649) && mNodeCoins > (nMoneySupply * .636)) { ret = blockValue * .32; } else if (mNodeCoins <= (nMoneySupply * .662) && mNodeCoins > (nMoneySupply * .649)) { ret = blockValue * .31; } else if (mNodeCoins <= (nMoneySupply * .675) && mNodeCoins > (nMoneySupply * .662)) { ret = blockValue * .30; } else if (mNodeCoins <= (nMoneySupply * .688) && mNodeCoins > (nMoneySupply * .675)) { ret = blockValue * .29; } else if (mNodeCoins <= (nMoneySupply * .701) && mNodeCoins > (nMoneySupply * .688)) { ret = blockValue * .28; } else if (mNodeCoins <= (nMoneySupply * .714) && mNodeCoins > (nMoneySupply * .701)) { ret = blockValue * .27; } else if (mNodeCoins <= (nMoneySupply * .727) && mNodeCoins > (nMoneySupply * .714)) { ret = blockValue * .26; } else if (mNodeCoins <= (nMoneySupply * .74) && mNodeCoins > (nMoneySupply * .727)) { ret = blockValue * .25; } else if (mNodeCoins <= (nMoneySupply * .753) && mNodeCoins > (nMoneySupply * .74)) { ret = blockValue * .24; } else if (mNodeCoins <= (nMoneySupply * .766) && mNodeCoins > (nMoneySupply * .753)) { ret = blockValue * .23; } else if (mNodeCoins <= (nMoneySupply * .779) && mNodeCoins > (nMoneySupply * .766)) { ret = blockValue * .22; } else if (mNodeCoins <= (nMoneySupply * .792) && mNodeCoins > (nMoneySupply * .779)) { ret = blockValue * .21; } else if (mNodeCoins <= (nMoneySupply * .805) && mNodeCoins > (nMoneySupply * .792)) { ret = blockValue * .20; } else if (mNodeCoins <= (nMoneySupply * .818) && mNodeCoins > (nMoneySupply * .805)) { ret = blockValue * .19; } else if (mNodeCoins <= (nMoneySupply * .831) && mNodeCoins > (nMoneySupply * .818)) { ret = blockValue * .18; } else if (mNodeCoins <= (nMoneySupply * .844) && mNodeCoins > (nMoneySupply * .831)) { ret = blockValue * .17; } else if (mNodeCoins <= (nMoneySupply * .857) && mNodeCoins > (nMoneySupply * .844)) { ret = blockValue * .16; } else if (mNodeCoins <= (nMoneySupply * .87) && mNodeCoins > (nMoneySupply * .857)) { ret = blockValue * .15; } else if (mNodeCoins <= (nMoneySupply * .883) && mNodeCoins > (nMoneySupply * .87)) { ret = blockValue * .14; } else if (mNodeCoins <= (nMoneySupply * .896) && mNodeCoins > (nMoneySupply * .883)) { ret = blockValue * .13; } else if (mNodeCoins <= (nMoneySupply * .909) && mNodeCoins > (nMoneySupply * .896)) { ret = blockValue * .12; } else if (mNodeCoins <= (nMoneySupply * .922) && mNodeCoins > (nMoneySupply * .909)) { ret = blockValue * .11; } else if (mNodeCoins <= (nMoneySupply * .935) && mNodeCoins > (nMoneySupply * .922)) { ret = blockValue * .10; } else if (mNodeCoins <= (nMoneySupply * .945) && mNodeCoins > (nMoneySupply * .935)) { ret = blockValue * .09; } else if (mNodeCoins <= (nMoneySupply * .961) && mNodeCoins > (nMoneySupply * .945)) { ret = blockValue * .08; } else if (mNodeCoins <= (nMoneySupply * .974) && mNodeCoins > (nMoneySupply * .961)) { ret = blockValue * .07; } else if (mNodeCoins <= (nMoneySupply * .987) && mNodeCoins > (nMoneySupply * .974)) { ret = blockValue * .06; } else if (mNodeCoins <= (nMoneySupply * .99) && mNodeCoins > (nMoneySupply * .987)) { ret = blockValue * .05; } else { ret = blockValue * .01; } } return ret; } int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount, bool isZPIVStake) { int64_t ret = 0; if (nHeight > Params().LAST_POW_BLOCK()) { ret = blockValue * 0.70; // 70% to masternodes } return ret; } bool IsInitialBlockDownload() { LOCK(cs_main); if (fImporting || fReindex || fVerifyingBlocks || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate()) return true; static bool lockIBDState = false; if (lockIBDState) return false; bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 || pindexBestHeader->GetBlockTime() < GetTime() - nMaxTipAge); if (!state) lockIBDState = true; return state; } bool fLargeWorkForkFound = false; bool fLargeWorkInvalidChainFound = false; CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL; void CheckForkWarningConditions() { AssertLockHeld(cs_main); // Before we get past initial download, we cannot reliably alert about forks // (we assume we don't get stuck on a fork before the last checkpoint) if (IsInitialBlockDownload()) return; // If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it) // of our head, drop it if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72) pindexBestForkTip = NULL; if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) { if (!fLargeWorkForkFound && pindexBestForkBase) { if (pindexBestForkBase->phashBlock) { std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") + pindexBestForkBase->phashBlock->ToString() + std::string("'"); CAlert::Notify(warning, true); } } if (pindexBestForkTip && pindexBestForkBase) { if (pindexBestForkBase->phashBlock) { LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n", pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(), pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString()); fLargeWorkForkFound = true; } } else { LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n"); fLargeWorkInvalidChainFound = true; } } else { fLargeWorkForkFound = false; fLargeWorkInvalidChainFound = false; } } void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) { AssertLockHeld(cs_main); // If we are on a fork that is sufficiently large, set a warning flag CBlockIndex* pfork = pindexNewForkTip; CBlockIndex* plonger = chainActive.Tip(); while (pfork && pfork != plonger) { while (plonger && plonger->nHeight > pfork->nHeight) plonger = plonger->pprev; if (pfork == plonger) break; pfork = pfork->pprev; } // We define a condition which we should warn the user about as a fork of at least 7 blocks // who's tip is within 72 blocks (+/- 3 hours if no one mines it) of ours // or a chain that is entirely longer than ours and invalid (note that this should be detected by both) // We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network // hash rate operating on the fork. // We define it this way because it allows us to only store the highest fork tip (+ base) which meets // the 7-block condition and from this always have the most-likely-to-cause-warning fork if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) && pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && chainActive.Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; } CheckForkWarningConditions(); } // Requires cs_main. void Misbehaving(NodeId pnode, int howmuch) { if (howmuch == 0) return; CNodeState* state = State(pnode); if (state == NULL) return; state->nMisbehavior += howmuch; int banscore = GetArg("-banscore", 100); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior); state->fShouldBan = true; } else LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork) pindexBestInvalid = pindexNew; LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n", pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexNew->GetBlockTime())); LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime())); CheckForkWarningConditions(); } void static InvalidBlockFound(CBlockIndex* pindex, const CValidationState& state) { int nDoS = 0; if (state.IsInvalid(nDoS)) { std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash()); if (it != mapBlockSource.end() && State(it->second)) { CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()}; State(it->second)->rejects.push_back(reject); if (nDoS > 0) Misbehaving(it->second, nDoS); } } if (!state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); InvalidChainFound(pindex); } } void UpdateCoins(const CTransaction& tx, CValidationState& state, CCoinsViewCache& inputs, CTxUndo& txundo, int nHeight) { // mark inputs spent if (!tx.IsCoinBase() && !tx.HasZerocoinSpendInputs()) { txundo.vprevout.reserve(tx.vin.size()); for (const CTxIn& txin : tx.vin) { txundo.vprevout.push_back(CTxInUndo()); bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back()); assert(ret); } } // add outputs inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight); } bool CScriptCheck::operator()() { const CScript& scriptSig = ptxTo->vin[nIn].scriptSig; if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) { return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error)); } return true; } std::map<COutPoint, COutPoint> mapInvalidOutPoints; std::map<CBigNum, CAmount> mapInvalidSerials; void AddInvalidSpendsToMap(const CBlock& block) { for (const CTransaction& tx : block.vtx) { if (!tx.ContainsZerocoins()) continue; //Check all zerocoinspends for bad serials for (const CTxIn& in : tx.vin) { bool isPublicSpend = in.IsZerocoinPublicSpend(); if (in.IsZerocoinSpend() || isPublicSpend) { libzerocoin::CoinSpend* spend; if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); CValidationState state; if (!ZPIVModule::ParseZerocoinPublicSpend(in, tx, state, publicSpend)){ throw std::runtime_error("Failed to parse public spend"); } spend = &publicSpend; } else { libzerocoin::CoinSpend spendObj = TxInToZerocoinSpend(in); spend = &spendObj; } //If serial is not valid, mark all outputs as bad if (!spend->HasValidSerial(Params().Zerocoin_Params(false))) { mapInvalidSerials[spend->getCoinSerialNumber()] = spend->getDenomination() * COIN; // Derive the actual valid serial from the invalid serial if possible CBigNum bnActualSerial = spend->CalculateValidSerial(Params().Zerocoin_Params(false)); uint256 txHash; if (zerocoinDB->ReadCoinSpend(bnActualSerial, txHash)) { mapInvalidSerials[bnActualSerial] = spend->getDenomination() * COIN; CTransaction txPrev; uint256 hashBlock; if (!GetTransaction(txHash, txPrev, hashBlock, true)) continue; //Record all txouts from txPrev as invalid for (unsigned int i = 0; i < txPrev.vout.size(); i++) { //map to an empty outpoint to represent that this is the first in the chain of bad outs mapInvalidOutPoints[COutPoint(txPrev.GetHash(), i)] = COutPoint(); } } //Record all txouts from this invalid zerocoin spend tx as invalid for (unsigned int i = 0; i < tx.vout.size(); i++) { //map to an empty outpoint to represent that this is the first in the chain of bad outs mapInvalidOutPoints[COutPoint(tx.GetHash(), i)] = COutPoint(); } } } } } } bool ValidOutPoint(const COutPoint& out, int nHeight) { bool isInvalid = nHeight >= Params().Block_Enforce_Invalid() && invalid_out::ContainsOutPoint(out); return !isInvalid; } CAmount GetInvalidUTXOValue() { CAmount nValue = 0; for (auto out : invalid_out::setInvalidOutPoints) { bool fSpent = false; CCoinsViewCache cache(pcoinsTip); const CCoins *coins = cache.AccessCoins(out.hash); if(!coins || !coins->IsAvailable(out.n)) fSpent = true; if (!fSpent) nValue += coins->vout[out.n].nValue; } return nValue; } bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck>* pvChecks) { if (!tx.IsCoinBase() && !tx.HasZerocoinSpendInputs()) { if (pvChecks) pvChecks->reserve(tx.vin.size()); // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!inputs.HaveInputs(tx)) return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString())); // While checking, GetBestBlock() refers to the parent block. // This is also true for mempool checks. CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second; int nSpendHeight = pindexPrev->nHeight + 1; CAmount nValueIn = 0; CAmount nFees = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint& prevout = tx.vin[i].prevout; const CCoins* coins = inputs.AccessCoins(prevout.hash); assert(coins); // If prev is coinbase, check that it's matured if (coins->IsCoinBase() || coins->IsCoinStake()) { if (nSpendHeight - coins->nHeight < Params().COINBASE_MATURITY()) return state.Invalid( error("CheckInputs() : tried to spend coinbase at depth %d, coinstake=%d", nSpendHeight - coins->nHeight, coins->IsCoinStake()), REJECT_INVALID, "bad-txns-premature-spend-of-coinbase"); } // Check for negative or overflow input values nValueIn += coins->vout[prevout.n].nValue; if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return state.DoS(100, error("CheckInputs() : txin values out of range"), REJECT_INVALID, "bad-txns-inputvalues-outofrange"); } if (!tx.IsCoinStake()) { if (nValueIn < tx.GetValueOut()) return state.DoS(100, error("CheckInputs() : %s value in (%s) < value out (%s)", tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())), REJECT_INVALID, "bad-txns-in-belowout"); // Tally transaction fees CAmount nTxFee = nValueIn - tx.GetValueOut(); if (nTxFee < 0) return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()), REJECT_INVALID, "bad-txns-fee-negative"); nFees += nTxFee; if (!MoneyRange(nFees)) return state.DoS(100, error("CheckInputs() : nFees out of range"), REJECT_INVALID, "bad-txns-fee-outofrange"); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. // Skip ECDSA signature verification when connecting blocks // before the last block chain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (fScriptChecks) { for (unsigned int i = 0; i < tx.vin.size(); i++) { const COutPoint& prevout = tx.vin[i].prevout; const CCoins* coins = inputs.AccessCoins(prevout.hash); assert(coins); // Verify signature CScriptCheck check(*coins, tx, i, flags, cacheStore); if (pvChecks) { pvChecks->push_back(CScriptCheck()); check.swap(pvChecks->back()); } else if (!check()) { if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) { // Check whether the failure was caused by a // non-mandatory script verification check, such as // non-standard DER encodings or non-null dummy // arguments; if so, don't trigger DoS protection to // avoid splitting the network between upgraded and // non-upgraded nodes. CScriptCheck check(*coins, tx, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore); if (check()) return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError()))); } // Failures of other flags indicate a transaction that is // invalid in new blocks, e.g. a invalid P2SH. We DoS ban // such nodes as they are not following the protocol. That // said during an upgrade careful thought should be taken // as to the correct behavior - we may want to continue // peering with non-upgraded nodes even after a soft-fork // super-majority vote has passed. return state.DoS(100, false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError()))); } } } } return true; } bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean) { if (pindex->GetBlockHash() != view.GetBestBlock()) LogPrintf("%s : pindex=%s view=%s\n", __func__, pindex->GetBlockHash().GetHex(), view.GetBestBlock().GetHex()); assert(pindex->GetBlockHash() == view.GetBestBlock()); if (pfClean) *pfClean = false; bool fClean = true; CBlockUndo blockUndo; CDiskBlockPos pos = pindex->GetUndoPos(); if (pos.IsNull()) return error("DisconnectBlock() : no undo data available"); if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash())) return error("DisconnectBlock() : failure reading undo data"); if (blockUndo.vtxundo.size() + 1 != block.vtx.size()) return error("DisconnectBlock() : block and undo data inconsistent"); // undo transactions in reverse order for (int i = block.vtx.size() - 1; i >= 0; i--) { const CTransaction& tx = block.vtx[i]; /** UNDO ZEROCOIN DATABASING * note we only undo zerocoin databasing in the following statement, value to and from PIVXL * addresses should still be handled by the typical bitcoin based undo code * */ if (tx.ContainsZerocoins()) { if (tx.HasZerocoinSpendInputs()) { //erase all zerocoinspends in this transaction for (const CTxIn &txin : tx.vin) { bool isPublicSpend = txin.IsZerocoinPublicSpend(); if (txin.scriptSig.IsZerocoinSpend() || isPublicSpend) { CBigNum serial; if (isPublicSpend) { libzerocoin::ZerocoinParams *params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); CValidationState state; if (!ZPIVModule::ParseZerocoinPublicSpend(txin, tx, state, publicSpend)) { return error("Failed to parse public spend"); } serial = publicSpend.getCoinSerialNumber(); } else { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txin); serial = spend.getCoinSerialNumber(); } if (!zerocoinDB->EraseCoinSpend(serial)) return error("failed to erase spent zerocoin in block"); //if this was our spend, then mark it unspent now if (pwalletMain) { if (pwalletMain->IsMyZerocoinSpend(serial)) { if (!pwalletMain->SetMintUnspent(serial)) LogPrintf("%s: failed to automatically reset mint", __func__); } } } } } if (tx.HasZerocoinMintOutputs()) { //erase all zerocoinmints in this transaction for (const CTxOut &txout : tx.vout) { if (txout.scriptPubKey.empty() || !txout.IsZerocoinMint()) continue; libzerocoin::PublicCoin pubCoin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(txout, pubCoin, state)) return error("DisconnectBlock(): TxOutToPublicCoin() failed"); if (!zerocoinDB->EraseCoinMint(pubCoin.getValue())) return error("DisconnectBlock(): Failed to erase coin mint"); } } } uint256 hash = tx.GetHash(); // Check that all outputs are available and match the outputs in the block itself // exactly. Note that transactions with only provably unspendable outputs won't // have outputs available even in the block itself, so we handle that case // specially with outsEmpty. { CCoins outsEmpty; CCoinsModifier outs = view.ModifyCoins(hash); outs->ClearUnspendable(); CCoins outsBlock(tx, pindex->nHeight); // The CCoins serialization does not serialize negative numbers. // No network rules currently depend on the version here, so an inconsistency is harmless // but it must be corrected before txout nversion ever influences a network rule. if (outsBlock.nVersion < 0) outs->nVersion = outsBlock.nVersion; if (*outs != outsBlock) fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted"); // remove outputs outs->Clear(); } // restore inputs if (!tx.IsCoinBase() && !tx.HasZerocoinSpendInputs()) { // not coinbases or zerocoinspend because they dont have traditional inputs const CTxUndo& txundo = blockUndo.vtxundo[i - 1]; if (txundo.vprevout.size() != tx.vin.size()) return error("DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d", txundo.vprevout.size(), tx.vin.size()); for (unsigned int j = tx.vin.size(); j-- > 0;) { const COutPoint& out = tx.vin[j].prevout; const CTxInUndo& undo = txundo.vprevout[j]; CCoinsModifier coins = view.ModifyCoins(out.hash); if (undo.nHeight != 0) { // undo data contains height: this is the last output of the prevout tx being spent if (!coins->IsPruned()) fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction"); coins->Clear(); coins->fCoinBase = undo.fCoinBase; coins->nHeight = undo.nHeight; coins->nVersion = undo.nVersion; } else { if (coins->IsPruned()) fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction"); } if (coins->IsAvailable(out.n)) fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output"); if (coins->vout.size() < out.n + 1) coins->vout.resize(out.n + 1); coins->vout[out.n] = undo.txout; } } } // move best block pointer to prevout block view.SetBestBlock(pindex->pprev->GetBlockHash()); if (!fVerifyingBlocks && pindex->nHeight <= Params().Zerocoin_Block_Last_Checkpoint()) { //if block is an accumulator checkpoint block, remove checkpoint and checksums from db uint256 nCheckpoint = pindex->nAccumulatorCheckpoint; if(nCheckpoint != pindex->pprev->nAccumulatorCheckpoint) { if(!EraseAccumulatorValues(nCheckpoint, pindex->pprev->nAccumulatorCheckpoint)) return error("DisconnectBlock(): failed to erase checkpoint"); } } if (pfClean) { *pfClean = fClean; return true; } else { return fClean; } } void static FlushBlockFile(bool fFinalize = false) { LOCK(cs_LastBlockFile); CDiskBlockPos posOld(nLastBlockFile, 0); FILE* fileOld = OpenBlockFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize); FileCommit(fileOld); fclose(fileOld); } fileOld = OpenUndoFile(posOld); if (fileOld) { if (fFinalize) TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize); FileCommit(fileOld); fclose(fileOld); } } bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize); static CCheckQueue<CScriptCheck> scriptcheckqueue(128); void ThreadScriptCheck() { RenameThread("pivxl-scriptch"); scriptcheckqueue.Thread(); } void AddWrappedSerialsInflation() { CBlockIndex* pindex = chainActive[Params().Zerocoin_Block_EndFakeSerial()]; if (pindex->nHeight > chainActive.Height()) return; uiInterface.ShowProgress(_("Adding Wrapped Serials supply..."), 0); while (true) { if (pindex->nHeight % 1000 == 0) { LogPrintf("%s : block %d...\n", __func__, pindex->nHeight); int percent = std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().Zerocoin_Block_EndFakeSerial()) * 100 / (chainActive.Height() - Params().Zerocoin_Block_EndFakeSerial())))); uiInterface.ShowProgress(_("Adding Wrapped Serials supply..."), percent); } // Add inflated denominations to block index mapSupply for (auto denom : libzerocoin::zerocoinDenomList) { pindex->mapZerocoinSupply.at(denom) += GetWrapppedSerialInflation(denom); } // Update current block index to disk assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex))); // next block if (pindex->nHeight < chainActive.Height()) pindex = chainActive.Next(pindex); else break; } uiInterface.ShowProgress("", 100); } void RecalculateZPIVMinted() { CBlockIndex *pindex = chainActive[Params().Zerocoin_StartHeight()]; uiInterface.ShowProgress(_("Recalculating minted ZPIV..."), 0); while (true) { // Log Message and feedback message every 1000 blocks if (pindex->nHeight % 1000 == 0) { LogPrintf("%s : block %d...\n", __func__, pindex->nHeight); int percent = std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().Zerocoin_StartHeight()) * 100 / (chainActive.Height() - Params().Zerocoin_StartHeight())))); uiInterface.ShowProgress(_("Recalculating minted ZPIV..."), percent); } //overwrite possibly wrong vMintsInBlock data CBlock block; assert(ReadBlockFromDisk(block, pindex)); std::list<CZerocoinMint> listMints; BlockToZerocoinMintList(block, listMints, true); std::vector<libzerocoin::CoinDenomination> vDenomsBefore = pindex->vMintDenominationsInBlock; pindex->vMintDenominationsInBlock.clear(); for (auto mint : listMints) pindex->vMintDenominationsInBlock.emplace_back(mint.GetDenomination()); if (pindex->nHeight < chainActive.Height()) pindex = chainActive.Next(pindex); else break; } uiInterface.ShowProgress("", 100); } void RecalculateZPIVSpent() { CBlockIndex* pindex = chainActive[Params().Zerocoin_StartHeight()]; uiInterface.ShowProgress(_("Recalculating spent ZPIV..."), 0); while (true) { if (pindex->nHeight % 1000 == 0) { LogPrintf("%s : block %d...\n", __func__, pindex->nHeight); int percent = std::max(1, std::min(99, (int)((double)(pindex->nHeight - Params().Zerocoin_StartHeight()) * 100 / (chainActive.Height() - Params().Zerocoin_StartHeight())))); uiInterface.ShowProgress(_("Recalculating spent ZPIV..."), percent); } //Rewrite zPIV supply CBlock block; assert(ReadBlockFromDisk(block, pindex)); std::list<libzerocoin::CoinDenomination> listDenomsSpent = ZerocoinSpendListFromBlock(block, true); //Reset the supply to previous block pindex->mapZerocoinSupply = pindex->pprev->mapZerocoinSupply; //Add mints to zPIV supply for (auto denom : libzerocoin::zerocoinDenomList) { long nDenomAdded = count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), denom); pindex->mapZerocoinSupply.at(denom) += nDenomAdded; } //Remove spends from zPIV supply for (auto denom : listDenomsSpent) pindex->mapZerocoinSupply.at(denom)--; // Add inflation from Wrapped Serials if block is Zerocoin_Block_EndFakeSerial() if (pindex->nHeight == Params().Zerocoin_Block_EndFakeSerial() + 1) for (auto denom : libzerocoin::zerocoinDenomList) { pindex->mapZerocoinSupply.at(denom) += GetWrapppedSerialInflation(denom); } //Rewrite money supply assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex))); if (pindex->nHeight < chainActive.Height()) pindex = chainActive.Next(pindex); else break; } uiInterface.ShowProgress("", 100); } bool RecalculatePIVSupply(int nHeightStart) { if (nHeightStart > chainActive.Height()) return false; CBlockIndex* pindex = chainActive[nHeightStart]; CAmount nSupplyPrev = pindex->pprev->nMoneySupply; if (nHeightStart == Params().Zerocoin_StartHeight()) nSupplyPrev = CAmount(5449796547496199); uiInterface.ShowProgress(_("Recalculating PIVXL supply..."), 0); while (true) { if (pindex->nHeight % 1000 == 0) { LogPrintf("%s : block %d...\n", __func__, pindex->nHeight); int percent = std::max(1, std::min(99, (int)((double)((pindex->nHeight - nHeightStart) * 100) / (chainActive.Height() - nHeightStart)))); uiInterface.ShowProgress(_("Recalculating PIVXL supply..."), percent); } CBlock block; assert(ReadBlockFromDisk(block, pindex)); CAmount nValueIn = 0; CAmount nValueOut = 0; for (const CTransaction& tx : block.vtx) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (tx.IsCoinBase()) break; if (tx.vin[i].IsZerocoinSpend()) { nValueIn += tx.vin[i].nSequence * COIN; continue; } COutPoint prevout = tx.vin[i].prevout; CTransaction txPrev; uint256 hashBlock; assert(GetTransaction(prevout.hash, txPrev, hashBlock, true)); nValueIn += txPrev.vout[prevout.n].nValue; } for (unsigned int i = 0; i < tx.vout.size(); i++) { if (i == 0 && tx.IsCoinStake()) continue; nValueOut += tx.vout[i].nValue; } } // Rewrite money supply pindex->nMoneySupply = nSupplyPrev + nValueOut - nValueIn; nSupplyPrev = pindex->nMoneySupply; // Add fraudulent funds to the supply and remove any recovered funds. // if (pindex->nHeight == Params().Zerocoin_Block_RecalculateAccumulators()) { // LogPrintf("%s : Original money supply=%s\n", __func__, FormatMoney(pindex->nMoneySupply)); // pindex->nMoneySupply += Params().InvalidAmountFiltered(); // LogPrintf("%s : Adding filtered funds to supply + %s : supply=%s\n", __func__, FormatMoney(Params().InvalidAmountFiltered()), FormatMoney(pindex->nMoneySupply)); // CAmount nLocked = GetInvalidUTXOValue(); // pindex->nMoneySupply -= nLocked; // LogPrintf("%s : Removing locked from supply - %s : supply=%s\n", __func__, FormatMoney(nLocked), FormatMoney(pindex->nMoneySupply)); // } assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex))); if (pindex->nHeight < chainActive.Height()) pindex = chainActive.Next(pindex); else break; } uiInterface.ShowProgress("", 100); return true; } bool ReindexAccumulators(std::list<uint256>& listMissingCheckpoints, std::string& strError) { // PIVXL: recalculate Accumulator Checkpoints that failed to database properly if (!listMissingCheckpoints.empty()) { uiInterface.ShowProgress(_("Calculating missing accumulators..."), 0); LogPrintf("%s : finding missing checkpoints\n", __func__); //search the chain to see when zerocoin started int nZerocoinStart = Params().Zerocoin_Block_V2_Start(); // find each checkpoint that is missing CBlockIndex* pindex = chainActive[nZerocoinStart]; while (pindex && pindex->nHeight <= Params().Zerocoin_Block_Last_Checkpoint()) { uiInterface.ShowProgress(_("Calculating missing accumulators..."), std::max(1, std::min(99, (int)((double)(pindex->nHeight - nZerocoinStart) / (double)(chainActive.Height() - nZerocoinStart) * 100)))); if (ShutdownRequested()) return false; // find checkpoints by iterating through the blockchain beginning with the first zerocoin block if (pindex->nAccumulatorCheckpoint != pindex->pprev->nAccumulatorCheckpoint) { if (find(listMissingCheckpoints.begin(), listMissingCheckpoints.end(), pindex->nAccumulatorCheckpoint) != listMissingCheckpoints.end()) { uint256 nCheckpointCalculated = 0; AccumulatorMap mapAccumulators(Params().Zerocoin_Params(false)); if (!CalculateAccumulatorCheckpoint(pindex->nHeight, nCheckpointCalculated, mapAccumulators)) { // GetCheckpoint could have terminated due to a shutdown request. Check this here. if (ShutdownRequested()) break; strError = _("Failed to calculate accumulator checkpoint"); return error("%s: %s", __func__, strError); } //check that the calculated checkpoint is what is in the index. if (nCheckpointCalculated != pindex->nAccumulatorCheckpoint) { LogPrintf("%s : height=%d calculated_checkpoint=%s actual=%s\n", __func__, pindex->nHeight, nCheckpointCalculated.GetHex(), pindex->nAccumulatorCheckpoint.GetHex()); strError = _("Calculated accumulator checkpoint is not what is recorded by block index"); return error("%s: %s", __func__, strError); } DatabaseChecksums(mapAccumulators); auto it = find(listMissingCheckpoints.begin(), listMissingCheckpoints.end(), pindex->nAccumulatorCheckpoint); listMissingCheckpoints.erase(it); } } pindex = chainActive.Next(pindex); } uiInterface.ShowProgress("", 100); } return true; } bool UpdateZPIVSupply(const CBlock& block, CBlockIndex* pindex, bool fJustCheck) { std::list<CZerocoinMint> listMints; // bool fFilterInvalid = pindex->nHeight >= Params().Zerocoin_Block_RecalculateAccumulators(); bool fFilterInvalid = false; BlockToZerocoinMintList(block, listMints, fFilterInvalid); std::list<libzerocoin::CoinDenomination> listSpends = ZerocoinSpendListFromBlock(block, fFilterInvalid); // Initialize zerocoin supply to the supply from previous block if (pindex->pprev && pindex->pprev->GetBlockHeader().nVersion > 3) { for (auto& denom : libzerocoin::zerocoinDenomList) { pindex->mapZerocoinSupply.at(denom) = pindex->pprev->GetZcMints(denom); } } // Track zerocoin money supply CAmount nAmountZerocoinSpent = 0; pindex->vMintDenominationsInBlock.clear(); if (pindex->pprev) { std::set<uint256> setAddedToWallet; for (auto& m : listMints) { libzerocoin::CoinDenomination denom = m.GetDenomination(); pindex->vMintDenominationsInBlock.push_back(m.GetDenomination()); pindex->mapZerocoinSupply.at(denom)++; //Remove any of our own mints from the mintpool if (!fJustCheck && pwalletMain) { if (pwalletMain->IsMyMint(m.GetValue())) { pwalletMain->UpdateMint(m.GetValue(), pindex->nHeight, m.GetTxHash(), m.GetDenomination()); // Add the transaction to the wallet for (auto& tx : block.vtx) { uint256 txid = tx.GetHash(); if (setAddedToWallet.count(txid)) continue; if (txid == m.GetTxHash()) { CWalletTx wtx(pwalletMain, tx); wtx.nTimeReceived = block.GetBlockTime(); wtx.SetMerkleBranch(block); pwalletMain->AddToWallet(wtx, false, nullptr); setAddedToWallet.insert(txid); } } } } } for (auto& denom : listSpends) { pindex->mapZerocoinSupply.at(denom)--; nAmountZerocoinSpent += libzerocoin::ZerocoinDenominationToAmount(denom); // zerocoin failsafe if (pindex->GetZcMints(denom) < 0) return error("Block contains zerocoins that spend more than are in the available supply to spend"); } } for (auto& denom : libzerocoin::zerocoinDenomList) LogPrint("zero", "%s coins for denomination %d pubcoin %s\n", __func__, denom, pindex->mapZerocoinSupply.at(denom)); // Update Wrapped Serials amount // A one-time event where only the zPIV supply was off (due to serial duplication off-chain on main net) if (Params().NetworkID() == CBaseChainParams::MAIN && pindex->nHeight == Params().Zerocoin_Block_EndFakeSerial() + 1 && pindex->GetZerocoinSupply() < Params().GetSupplyBeforeFakeSerial() + GetWrapppedSerialInflationAmount()) { for (auto denom : libzerocoin::zerocoinDenomList) { pindex->mapZerocoinSupply.at(denom) += GetWrapppedSerialInflation(denom); } } return true; } static int64_t nTimeVerify = 0; static int64_t nTimeConnect = 0; static int64_t nTimeIndex = 0; static int64_t nTimeCallbacks = 0; static int64_t nTimeTotal = 0; bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fAlreadyChecked) { AssertLockHeld(cs_main); // Check it again in case a previous version let a bad block in if (!fAlreadyChecked && !CheckBlock(block, state, !fJustCheck, !fJustCheck)) return false; // verify that the view's current state corresponds to the previous block uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash(); if (hashPrevBlock != view.GetBestBlock()) LogPrintf("%s: hashPrev=%s view=%s\n", __func__, hashPrevBlock.GetHex(), view.GetBestBlock().GetHex()); assert(hashPrevBlock == view.GetBestBlock()); // Special case for the genesis block, skipping connection of its transactions // (its coinbase is unspendable) if (block.GetHash() == Params().HashGenesisBlock()) { view.SetBestBlock(pindex->GetBlockHash()); return true; } if (pindex->nHeight <= Params().LAST_POW_BLOCK() && block.IsProofOfStake()) return state.DoS(100, error("ConnectBlock() : PoS period not active"), REJECT_INVALID, "PoS-early"); if (pindex->nHeight > Params().LAST_POW_BLOCK() && block.IsProofOfWork()) return state.DoS(100, error("ConnectBlock() : PoW period ended"), REJECT_INVALID, "PoW-ended"); bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate(); // If scripts won't be checked anyways, don't bother seeing if CLTV is activated bool fCLTVIsActivated = false; if (fScriptChecks && pindex->pprev) { fCLTVIsActivated = pindex->pprev->nHeight >= Params().BIP65ActivationHeight(); } CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : nullptr); int64_t nTimeStart = GetTimeMicros(); CAmount nFees = 0; int nInputs = 0; unsigned int nSigOps = 0; CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size())); std::vector<std::pair<uint256, CDiskTxPos> > vPos; std::vector<std::pair<libzerocoin::CoinSpend, uint256> > vSpends; std::vector<std::pair<libzerocoin::PublicCoin, uint256> > vMints; vPos.reserve(block.vtx.size()); CBlockUndo blockundo; blockundo.vtxundo.reserve(block.vtx.size() - 1); CAmount nValueOut = 0; CAmount nValueIn = 0; unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT; std::vector<uint256> vSpendsInBlock; uint256 hashBlock = block.GetHash(); for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction& tx = block.vtx[i]; // First check for BIP30. // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction ids entirely. const CCoins* coins = view.AccessCoins(tx.GetHash()); if (coins && !coins->IsPruned()) return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"), REJECT_INVALID, "bad-txns-BIP30"); nInputs += tx.vin.size(); nSigOps += GetLegacySigOpCount(tx); if (nSigOps > nMaxBlockSigOps) return state.DoS(100, error("ConnectBlock() : too many sigops"), REJECT_INVALID, "bad-blk-sigops"); //Temporarily disable zerocoin transactions for maintenance if (block.nTime > sporkManager.GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && !IsInitialBlockDownload() && tx.ContainsZerocoins()) { return state.DoS(100, error("ConnectBlock() : zerocoin transactions are currently in maintenance mode")); } if (tx.HasZerocoinSpendInputs()) { int nHeightTx = 0; uint256 txid = tx.GetHash(); vSpendsInBlock.emplace_back(txid); if (IsTransactionInChain(txid, nHeightTx)) { //when verifying blocks on init, the blocks are scanned without being disconnected - prevent that from causing an error if (!fVerifyingBlocks || (fVerifyingBlocks && pindex->nHeight > nHeightTx)) return state.DoS(100, error("%s : txid %s already exists in block %d , trying to include it again in block %d", __func__, tx.GetHash().GetHex(), nHeightTx, pindex->nHeight), REJECT_INVALID, "bad-txns-inputs-missingorspent"); } //Check for double spending of serial #'s std::set<CBigNum> setSerials; for (const CTxIn& txIn : tx.vin) { bool isPublicSpend = txIn.IsZerocoinPublicSpend(); bool isPrivZerocoinSpend = txIn.IsZerocoinSpend(); if (!isPrivZerocoinSpend && !isPublicSpend) continue; // Check enforcement if (!CheckPublicCoinSpendEnforced(pindex->nHeight, isPublicSpend)){ return false; } if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZPIVModule::ParseZerocoinPublicSpend(txIn, tx, state, publicSpend)){ return false; } nValueIn += publicSpend.getDenomination() * COIN; //queue for db write after the 'justcheck' section has concluded vSpends.emplace_back(std::make_pair(publicSpend, tx.GetHash())); if (!ContextualCheckZerocoinSpend(tx, &publicSpend, pindex, hashBlock)) return state.DoS(100, error("%s: failed to add block %s with invalid public zc spend", __func__, tx.GetHash().GetHex()), REJECT_INVALID); } else { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn); nValueIn += spend.getDenomination() * COIN; //queue for db write after the 'justcheck' section has concluded vSpends.emplace_back(std::make_pair(spend, tx.GetHash())); if (!ContextualCheckZerocoinSpend(tx, &spend, pindex, hashBlock)) return state.DoS(100, error("%s: failed to add block %s with invalid zerocoinspend", __func__, tx.GetHash().GetHex()), REJECT_INVALID); } } // Check that zPIV mints are not already known if (tx.HasZerocoinMintOutputs()) { for (auto& out : tx.vout) { if (!out.IsZerocoinMint()) continue; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.DoS(100, error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); if (!ContextualCheckZerocoinMint(tx, coin, pindex)) return state.DoS(100, error("%s: zerocoin mint failed contextual check", __func__)); vMints.emplace_back(std::make_pair(coin, tx.GetHash())); } } } else if (!tx.IsCoinBase()) { if (!view.HaveInputs(tx)) return state.DoS(100, error("ConnectBlock() : inputs missing/spent"), REJECT_INVALID, "bad-txns-inputs-missingorspent"); // Check that the inputs are not marked as invalid/fraudulent for (const CTxIn& in : tx.vin) { if (!ValidOutPoint(in.prevout, pindex->nHeight)) { return state.DoS(100, error("%s : tried to spend invalid input %s in tx %s", __func__, in.prevout.ToString(), tx.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-inputs"); } } // Check that zPIV mints are not already known if (tx.HasZerocoinMintOutputs()) { for (auto& out : tx.vout) { if (!out.IsZerocoinMint()) continue; libzerocoin::PublicCoin coin(Params().Zerocoin_Params(false)); if (!TxOutToPublicCoin(out, coin, state)) return state.DoS(100, error("%s: failed final check of zerocoinmint for tx %s", __func__, tx.GetHash().GetHex())); if (!ContextualCheckZerocoinMint(tx, coin, pindex)) return state.DoS(100, error("%s: zerocoin mint failed contextual check", __func__)); vMints.emplace_back(std::make_pair(coin, tx.GetHash())); } } // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += GetP2SHSigOpCount(tx, view); if (nSigOps > nMaxBlockSigOps) return state.DoS(100, error("ConnectBlock() : too many sigops"), REJECT_INVALID, "bad-blk-sigops"); if (!tx.IsCoinStake()) nFees += view.GetValueIn(tx) - tx.GetValueOut(); nValueIn += view.GetValueIn(tx); std::vector<CScriptCheck> vChecks; unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG; if (fCLTVIsActivated) flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY; if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL)) return false; control.Add(vChecks); } nValueOut += tx.GetValueOut(); CTxUndo undoDummy; if (i > 0) { blockundo.vtxundo.emplace_back(); } UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight); vPos.emplace_back(tx.GetHash(), pos); pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); } //A one-time event where money supply counts were off and recalculated on a certain block. // if (pindex->nHeight == Params().Zerocoin_Block_RecalculateAccumulators() + 1) { // RecalculateZPIVMinted(); // RecalculateZPIVSpent(); // RecalculatePIVSupply(Params().Zerocoin_StartHeight()); // } //Track zPIV money supply in the block index if (!UpdateZPIVSupply(block, pindex, fJustCheck)) return state.DoS(100, error("%s: Failed to calculate new zPIV supply for block=%s height=%d", __func__, block.GetHash().GetHex(), pindex->nHeight), REJECT_INVALID); // track money supply and mint amount info CAmount nMoneySupplyPrev = pindex->pprev ? pindex->pprev->nMoneySupply : 0; pindex->nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn; pindex->nMint = pindex->nMoneySupply - nMoneySupplyPrev + nFees; int64_t nTime1 = GetTimeMicros(); nTimeConnect += nTime1 - nTimeStart; LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs - 1), nTimeConnect * 0.000001); //PoW phase redistributed fees to miner. PoS stage destroys fees. CAmount nExpectedMint = GetBlockValue(pindex->pprev->nHeight); if (block.IsProofOfWork()) nExpectedMint += nFees; //Check that the block does not overmint if (!IsBlockValueValid(block, nExpectedMint, pindex->nMint)) { return state.DoS(100, error("ConnectBlock() : reward pays too much (actual=%s vs limit=%s)", FormatMoney(pindex->nMint), FormatMoney(nExpectedMint)), REJECT_INVALID, "bad-cb-amount"); } // Ensure that accumulator checkpoints are valid and in the same state as this instance of the chain AccumulatorMap mapAccumulators(Params().Zerocoin_Params(pindex->nHeight < Params().Zerocoin_Block_V2_Start())); if (!ValidateAccumulatorCheckpoint(block, pindex, mapAccumulators)) { if (!ShutdownRequested()) { return state.DoS(100, error("%s: Failed to validate accumulator checkpoint for block=%s height=%d", __func__, block.GetHash().GetHex(), pindex->nHeight), REJECT_INVALID, "bad-acc-checkpoint"); } return error("%s: Failed to validate accumulator checkpoint for block=%s height=%d because wallet is shutting down", __func__, block.GetHash().GetHex(), pindex->nHeight); } if (!control.Wait()) return state.DoS(100, error("%s: CheckQueue failed", __func__), REJECT_INVALID, "block-validation-failed"); int64_t nTime2 = GetTimeMicros(); nTimeVerify += nTime2 - nTimeStart; LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs - 1), nTimeVerify * 0.000001); //IMPORTANT NOTE: Nothing before this point should actually store to disk (or even memory) if (fJustCheck) return true; // Write undo information to disk if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) { if (pindex->GetUndoPos().IsNull()) { CDiskBlockPos diskPosBlock; if (!FindUndoPos(state, pindex->nFile, diskPosBlock, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40)) return error("ConnectBlock() : FindUndoPos failed"); if (!blockundo.WriteToDisk(diskPosBlock, pindex->pprev->GetBlockHash())) return state.Abort("Failed to write undo data"); // update nUndoPos in block index pindex->nUndoPos = diskPosBlock.nPos; pindex->nStatus |= BLOCK_HAVE_UNDO; } pindex->RaiseValidity(BLOCK_VALID_SCRIPTS); setDirtyBlockIndex.insert(pindex); } //Record zPIV serials if (pwalletMain) { std::set<uint256> setAddedTx; for (const std::pair<libzerocoin::CoinSpend, uint256>& pSpend : vSpends) { // Send signal to wallet if this is ours if (pwalletMain->IsMyZerocoinSpend(pSpend.first.getCoinSerialNumber())) { LogPrintf("%s: %s detected zerocoinspend in transaction %s \n", __func__, pSpend.first.getCoinSerialNumber().GetHex(), pSpend.second.GetHex()); pwalletMain->NotifyZerocoinChanged(pwalletMain, pSpend.first.getCoinSerialNumber().GetHex(), "Used", CT_UPDATED); //Don't add the same tx multiple times if (setAddedTx.count(pSpend.second)) continue; //Search block for matching tx, turn into wtx, set merkle branch, add to wallet for (const CTransaction& tx : block.vtx) { if (tx.GetHash() == pSpend.second) { CWalletTx wtx(pwalletMain, tx); wtx.nTimeReceived = pindex->GetBlockTime(); wtx.SetMerkleBranch(block); pwalletMain->AddToWallet(wtx, false, nullptr); setAddedTx.insert(pSpend.second); } } } } } // Flush spend/mint info to disk if (!vSpends.empty() && !zerocoinDB->WriteCoinSpendBatch(vSpends)) return state.Abort(("Failed to record coin serials to database")); if (!vMints.empty() && !zerocoinDB->WriteCoinMintBatch(vMints)) return state.Abort(("Failed to record new mints to database")); //Record accumulator checksums DatabaseChecksums(mapAccumulators); if (fTxIndex) if (!pblocktree->WriteTxIndex(vPos)) return state.Abort("Failed to write transaction index"); // add this block to the view's block chain view.SetBestBlock(pindex->GetBlockHash()); int64_t nTime3 = GetTimeMicros(); nTimeIndex += nTime3 - nTime2; LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001); // Watch for changes to the previous coinbase transaction. static uint256 hashPrevBestCoinBase; GetMainSignals().UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = block.vtx[0].GetHash(); int64_t nTime4 = GetTimeMicros(); nTimeCallbacks += nTime4 - nTime3; LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001); //Continue tracking possible movement of fraudulent funds until they are completely frozen // if (pindex->nHeight >= Params().Zerocoin_Block_FirstFraudulent() && pindex->nHeight <= Params().Zerocoin_Block_RecalculateAccumulators() + 1) // AddInvalidSpendsToMap(block); //Remove zerocoinspends from the pending map for (const uint256& txid : vSpendsInBlock) { auto it = mapZerocoinspends.find(txid); if (it != mapZerocoinspends.end()) mapZerocoinspends.erase(it); } return true; } enum FlushStateMode { FLUSH_STATE_IF_NEEDED, FLUSH_STATE_PERIODIC, FLUSH_STATE_ALWAYS }; /** * Update the on-disk chain state. * The caches and indexes are flushed if either they're too large, forceWrite is set, or * fast is not set and it's been a while since the last write. */ bool static FlushStateToDisk(CValidationState& state, FlushStateMode mode) { LOCK(cs_main); static int64_t nLastWrite = 0; try { if ((mode == FLUSH_STATE_ALWAYS) || ((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) || (mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) { // Typical CCoins structures on disk are around 100 bytes in size. // Pushing a new one to the database can cause it to be written // twice (once in the log, and once in the tables). This is already // an overestimation, as most will delete an existing entry or // overwrite one. Still, use a conservative safety factor of 2. if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize())) return state.Error("out of disk space"); // First make sure all block and undo data is flushed to disk. FlushBlockFile(); // Then update all block file information (which may refer to block and undo files). { std::vector<std::pair<int, const CBlockFileInfo*> > vFiles; vFiles.reserve(setDirtyFileInfo.size()); for (std::set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end(); ) { vFiles.push_back(std::make_pair(*it, &vinfoBlockFile[*it])); setDirtyFileInfo.erase(it++); } std::vector<const CBlockIndex*> vBlocks; vBlocks.reserve(setDirtyBlockIndex.size()); for (std::set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end(); ) { vBlocks.push_back(*it); setDirtyBlockIndex.erase(it++); } if (!pblocktree->WriteBatchSync(vFiles, nLastBlockFile, vBlocks)) { return state.Abort("Files to write to block index database"); } } // Finally flush the chainstate (which may refer to block index entries). if (!pcoinsTip->Flush()) return state.Abort("Failed to write to coin database"); // Update best block in wallet (so we can detect restored wallets). if (mode != FLUSH_STATE_IF_NEEDED) { GetMainSignals().SetBestChain(chainActive.GetLocator()); } nLastWrite = GetTimeMicros(); } } catch (const std::runtime_error& e) { return state.Abort(std::string("System error while flushing: ") + e.what()); } return true; } void FlushStateToDisk() { CValidationState state; FlushStateToDisk(state, FLUSH_STATE_ALWAYS); } /** Update chainActive and related internal data structures. */ void static UpdateTip(CBlockIndex* pindexNew) { chainActive.SetTip(pindexNew); /* Zerocoin minting is disabled * #ifdef ENABLE_WALLET // If turned on AutoZeromint will automatically convert PIVXL to zPIV if (pwalletMain && pwalletMain->isZeromintEnabled()) pwalletMain->AutoZeromint(); #endif // ENABLE_WALLET * */ // New best block nTimeBestReceived = GetTime(); mempool.AddTransactionsUpdated(1); LogPrintf("UpdateTip: new best=%s height=%d version=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), chainActive.Tip()->nVersion, log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0), (unsigned long)chainActive.Tip()->nChainTx, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize()); cvBlockChange.notify_all(); // Check the version of the last 100 blocks to see if we need to upgrade: static bool fWarned = false; if (!IsInitialBlockDownload() && !fWarned) { int nUpgraded = 0; const CBlockIndex* pindex = chainActive.Tip(); for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION); if (nUpgraded > 100 / 2) { // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: strMiscWarning = _("Warning: This version is obsolete, upgrade required!"); CAlert::Notify(strMiscWarning, true); fWarned = true; } } } /** Disconnect chainActive's tip. */ bool static DisconnectTip(CValidationState& state) { CBlockIndex* pindexDelete = chainActive.Tip(); assert(pindexDelete); mempool.check(pcoinsTip); // Read block from disk. CBlock block; if (!ReadBlockFromDisk(block, pindexDelete)) return state.Abort("Failed to read block"); // Apply the block atomically to the chain state. int64_t nStart = GetTimeMicros(); { CCoinsViewCache view(pcoinsTip); if (!DisconnectBlock(block, state, pindexDelete, view)) return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString()); assert(view.Flush()); } LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001); // Write the chain state to disk, if necessary. if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS)) return false; // Resurrect mempool transactions from the disconnected block. for (const CTransaction& tx : block.vtx) { // ignore validation errors in resurrected transactions std::list<CTransaction> removed; CValidationState stateDummy; if (tx.IsCoinBase() || tx.IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL)) mempool.remove(tx, removed, true); } mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight); mempool.check(pcoinsTip); // Update chainActive and related variables. UpdateTip(pindexDelete->pprev); // Let wallets know transactions went from 1-confirmed to // 0-confirmed or conflicted: for (const CTransaction& tx : block.vtx) { SyncWithWallets(tx, NULL); } return true; } static int64_t nTimeReadFromDisk = 0; static int64_t nTimeConnectTotal = 0; static int64_t nTimeFlush = 0; static int64_t nTimeChainState = 0; static int64_t nTimePostConnect = 0; /** * Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock * corresponding to pindexNew, to bypass loading it again from disk. */ bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* pblock, bool fAlreadyChecked) { assert(pindexNew->pprev == chainActive.Tip()); mempool.check(pcoinsTip); CCoinsViewCache view(pcoinsTip); if (pblock == NULL) fAlreadyChecked = false; // Read block from disk. int64_t nTime1 = GetTimeMicros(); CBlock block; if (!pblock) { if (!ReadBlockFromDisk(block, pindexNew)) return state.Abort("Failed to read block"); pblock = &block; } // Apply the block atomically to the chain state. int64_t nTime2 = GetTimeMicros(); nTimeReadFromDisk += nTime2 - nTime1; int64_t nTime3; LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001); { CInv inv(MSG_BLOCK, pindexNew->GetBlockHash()); bool rv = ConnectBlock(*pblock, state, pindexNew, view, false, fAlreadyChecked); GetMainSignals().BlockChecked(*pblock, state); if (!rv) { if (state.IsInvalid()) InvalidBlockFound(pindexNew, state); return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString()); } mapBlockSource.erase(inv.hash); nTime3 = GetTimeMicros(); nTimeConnectTotal += nTime3 - nTime2; LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001); assert(view.Flush()); } int64_t nTime4 = GetTimeMicros(); nTimeFlush += nTime4 - nTime3; LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001); // Write the chain state to disk, if necessary. Always write to disk if this is the first of a new file. FlushStateMode flushMode = FLUSH_STATE_IF_NEEDED; if (pindexNew->pprev && (pindexNew->GetBlockPos().nFile != pindexNew->pprev->GetBlockPos().nFile)) flushMode = FLUSH_STATE_ALWAYS; if (!FlushStateToDisk(state, flushMode)) return false; int64_t nTime5 = GetTimeMicros(); nTimeChainState += nTime5 - nTime4; LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001); // Remove conflicting transactions from the mempool. std::list<CTransaction> txConflicted; mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted); mempool.check(pcoinsTip); // Update chainActive & related variables. UpdateTip(pindexNew); // Tell wallet about transactions that went from mempool // to conflicted: for (const CTransaction& tx : txConflicted) { SyncWithWallets(tx, NULL); } // ... and about transactions that got confirmed: for (const CTransaction& tx : pblock->vtx) { SyncWithWallets(tx, pblock); } int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001); LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001); return true; } bool DisconnectBlocks(int nBlocks) { LOCK(cs_main); CValidationState state; LogPrintf("%s: Got command to replay %d blocks\n", __func__, nBlocks); for (int i = 0; i <= nBlocks; i++) DisconnectTip(state); return true; } void ReprocessBlocks(int nBlocks) { std::map<uint256, int64_t>::iterator it = mapRejectedBlocks.begin(); while (it != mapRejectedBlocks.end()) { //use a window twice as large as is usual for the nBlocks we want to reset if ((*it).second > GetTime() - (nBlocks * Params().TargetSpacing() * 2)) { BlockMap::iterator mi = mapBlockIndex.find((*it).first); if (mi != mapBlockIndex.end() && (*mi).second) { LOCK(cs_main); CBlockIndex* pindex = (*mi).second; LogPrintf("%s - %s\n", __func__, (*it).first.ToString()); CValidationState state; ReconsiderBlock(state, pindex); } } ++it; } CValidationState state; { LOCK(cs_main); DisconnectBlocks(nBlocks); } if (state.IsValid()) { ActivateBestChain(state); } } /* DisconnectBlockAndInputs Remove conflicting blocks for successful SwiftX transaction locks This should be very rare (Probably will never happen) */ // ***TODO*** clean up here bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock) { // All modifications to the coin state will be done in this cache. // Only when all have succeeded, we push it to pcoinsTip. // CCoinsViewCache view(*pcoinsTip, true); CBlockIndex* BlockReading = chainActive.Tip(); CBlockIndex* pindexNew = NULL; bool foundConflictingTx = false; //remove anything conflicting in the memory pool std::list<CTransaction> txConflicted; mempool.removeConflicts(txLock, txConflicted); // List of what to disconnect (typically nothing) std::vector<CBlockIndex*> vDisconnect; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0 && !foundConflictingTx && i < 6; i++) { vDisconnect.push_back(BlockReading); pindexNew = BlockReading->pprev; //new best block CBlock block; if (!ReadBlockFromDisk(block, BlockReading)) return state.Abort(_("Failed to read block")); // Queue memory transactions to resurrect. // We only do this for blocks after the last checkpoint (reorganisation before that // point should only happen with -reindex/-loadblock, or a misbehaving peer. for (const CTransaction& tx : block.vtx) { if (!tx.IsCoinBase()) { for (const CTxIn& in1 : txLock.vin) { for (const CTxIn& in2 : tx.vin) { if (in1.prevout == in2.prevout) foundConflictingTx = true; } } } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } if (!foundConflictingTx) { LogPrintf("DisconnectBlockAndInputs: Can't find a conflicting transaction to inputs\n"); return false; } if (vDisconnect.size() > 0) { LogPrintf("REORGANIZE: Disconnect Conflicting Blocks %lli blocks; %s..\n", vDisconnect.size(), pindexNew->GetBlockHash().ToString()); for (CBlockIndex* pindex : vDisconnect) { LogPrintf(" -- disconnect %s\n", pindex->GetBlockHash().ToString()); DisconnectTip(state); } } return true; } /** * Return the tip of the chain with the most work in it, that isn't * known to be invalid (it's however far from certain to be valid). */ static CBlockIndex* FindMostWorkChain() { do { CBlockIndex* pindexNew = NULL; // Find the best candidate header. { std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin(); if (it == setBlockIndexCandidates.rend()) return NULL; pindexNew = *it; } // Check whether all blocks on the path between the currently active chain and the candidate are valid. // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex* pindexTest = pindexNew; bool fInvalidAncestor = false; while (pindexTest && !chainActive.Contains(pindexTest)) { assert(pindexTest->nChainTx || pindexTest->nHeight == 0); // Pruned nodes may have entries in setBlockIndexCandidates for // which block files have been deleted. Remove those as candidates // for the most work chain if we come across them; we can't switch // to a chain unless we have all the non-active-chain parent blocks. bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK; bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA); if (fFailedChain || fMissingData) { // Candidate chain is not usable (either invalid or missing data) if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork)) pindexBestInvalid = pindexNew; CBlockIndex* pindexFailed = pindexNew; // Remove the entire chain from the set. while (pindexTest != pindexFailed) { if (fFailedChain) { pindexFailed->nStatus |= BLOCK_FAILED_CHILD; } else if (fMissingData) { // If we're missing data, then add back to mapBlocksUnlinked, // so that if the block arrives in the future we can try adding // to setBlockIndexCandidates again. mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed)); } setBlockIndexCandidates.erase(pindexFailed); pindexFailed = pindexFailed->pprev; } setBlockIndexCandidates.erase(pindexTest); fInvalidAncestor = true; break; } pindexTest = pindexTest->pprev; } if (!fInvalidAncestor) return pindexNew; } while (true); } /** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */ static void PruneBlockIndexCandidates() { // Note that we can't delete the current block itself, as we may need to return to it later in case a // reorganization to a better block fails. std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin(); while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) { setBlockIndexCandidates.erase(it++); } // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates. assert(!setBlockIndexCandidates.empty()); } /** * Try to make some progress towards making pindexMostWork the active block. * pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork. */ static bool ActivateBestChainStep(CValidationState& state, CBlockIndex* pindexMostWork, CBlock* pblock, bool fAlreadyChecked) { AssertLockHeld(cs_main); if (pblock == NULL) fAlreadyChecked = false; bool fInvalidFound = false; const CBlockIndex* pindexOldTip = chainActive.Tip(); const CBlockIndex* pindexFork = chainActive.FindFork(pindexMostWork); // Disconnect active blocks which are no longer in the best chain. while (chainActive.Tip() && chainActive.Tip() != pindexFork) { if (!DisconnectTip(state)) return false; } // Build list of new blocks to connect. std::vector<CBlockIndex*> vpindexToConnect; bool fContinue = true; int nHeight = pindexFork ? pindexFork->nHeight : -1; while (fContinue && nHeight != pindexMostWork->nHeight) { // Don't iterate the entire list of potential improvements toward the best tip, as we likely only need // a few blocks along the way. int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight); vpindexToConnect.clear(); vpindexToConnect.reserve(nTargetHeight - nHeight); CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight); while (pindexIter && pindexIter->nHeight != nHeight) { vpindexToConnect.push_back(pindexIter); pindexIter = pindexIter->pprev; } nHeight = nTargetHeight; // Connect new blocks. BOOST_REVERSE_FOREACH (CBlockIndex* pindexConnect, vpindexToConnect) { if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) { if (state.IsInvalid()) { // The block violates a consensus rule. if (!state.CorruptionPossible()) InvalidChainFound(vpindexToConnect.back()); state = CValidationState(); fInvalidFound = true; fContinue = false; break; } else { // A system error occurred (disk space, database error, ...). return false; } } else { PruneBlockIndexCandidates(); if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { // We're in a better position than we were. Return temporarily to release the lock. fContinue = false; break; } } } } // Callbacks/notifications for a new best chain. if (fInvalidFound) CheckForkWarningConditionsOnNewFork(vpindexToConnect.back()); else CheckForkWarningConditions(); return true; } /** * Make the best chain active, in multiple steps. The result is either failure * or an activated best chain. pblock is either NULL or a pointer to a block * that is already loaded (to avoid loading it again from disk). */ bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChecked) { CBlockIndex* pindexNewTip = NULL; CBlockIndex* pindexMostWork = NULL; do { boost::this_thread::interruption_point(); bool fInitialDownload; while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } pindexMostWork = FindMostWorkChain(); // Whether we have anything to do at all. if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip()) return true; if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fAlreadyChecked)) return false; pindexNewTip = chainActive.Tip(); fInitialDownload = IsInitialBlockDownload(); break; } // When we reach this point, we switched to a new tip (stored in pindexNewTip). // Notifications/callbacks that can run without cs_main if (!fInitialDownload) { uint256 hashNewTip = pindexNewTip->GetBlockHash(); // Relay inventory, but don't relay old inventory during initial block download. int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); { LOCK(cs_vNodes); for (CNode* pnode : vNodes) if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip)); } // Notify external listeners about the new tip. // Note: uiInterface, should switch main signals. uiInterface.NotifyBlockTip(hashNewTip); GetMainSignals().UpdatedBlockTip(pindexNewTip); unsigned size = 0; if (pblock) size = GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION); // If the size is over 1 MB notify external listeners, and it is within the last 5 minutes if (size > MAX_BLOCK_SIZE_LEGACY && pblock->GetBlockTime() > GetAdjustedTime() - 300) { uiInterface.NotifyBlockSize(static_cast<int>(size), hashNewTip); } } } while (pindexMostWork != chainActive.Tip()); CheckBlockIndex(); // Write changes periodically to disk, after relay. if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) { return false; } return true; } bool InvalidateBlock(CValidationState& state, CBlockIndex* pindex) { AssertLockHeld(cs_main); // Mark the block itself as invalid. pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); setBlockIndexCandidates.erase(pindex); while (chainActive.Contains(pindex)) { CBlockIndex* pindexWalk = chainActive.Tip(); pindexWalk->nStatus |= BLOCK_FAILED_CHILD; setDirtyBlockIndex.insert(pindexWalk); setBlockIndexCandidates.erase(pindexWalk); // ActivateBestChain considers blocks already in chainActive // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state)) { return false; } } // The resulting new best tip may not be in setBlockIndexCandidates anymore, so // add them again. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { setBlockIndexCandidates.insert(it->second); } it++; } InvalidChainFound(pindex); return true; } bool ReconsiderBlock(CValidationState& state, CBlockIndex* pindex) { AssertLockHeld(cs_main); int nHeight = pindex->nHeight; // Remove the invalidity flag from this block and all its descendants. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) { it->second->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(it->second); if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) { setBlockIndexCandidates.insert(it->second); } if (it->second == pindexBestInvalid) { // Reset invalid block marker if it was pointing to one of those. pindexBestInvalid = NULL; } } it++; } // Remove the invalidity flag from all ancestors too. while (pindex != NULL) { if (pindex->nStatus & BLOCK_FAILED_MASK) { pindex->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(pindex); } pindex = pindex->pprev; } return true; } CBlockIndex* AddToBlockIndex(const CBlock& block) { // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator it = mapBlockIndex.find(hash); if (it != mapBlockIndex.end()) return it->second; // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(block); assert(pindexNew); // We assign the sequence id to blocks only when the full data is available, // to avoid miners withholding blocks but broadcasting headers, to get a // competitive advantage. pindexNew->nSequenceId = 0; BlockMap::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; pindexNew->BuildSkip(); //update previous block pointer pindexNew->pprev->pnext = pindexNew; // ppcoin: compute chain trust score pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(pindexNew->GetStakeEntropyBit())) LogPrintf("AddToBlockIndex() : SetStakeEntropyBit() failed \n"); // ppcoin: record proof-of-stake hash value if (pindexNew->IsProofOfStake()) { if (!mapProofOfStake.count(hash)) LogPrintf("AddToBlockIndex() : hashProofOfStake not found in map \n"); pindexNew->hashProofOfStake = mapProofOfStake[hash]; } if (!Params().IsStakeModifierV2(pindexNew->nHeight)) { uint64_t nStakeModifier = 0; bool fGeneratedStakeModifier = false; if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier)) LogPrintf("AddToBlockIndex() : ComputeNextStakeModifier() failed \n"); pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier); pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew); if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum)) LogPrintf("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=%s \n", pindexNew->nHeight, std::to_string(nStakeModifier)); } else { // compute v2 stake modifier pindexNew->nStakeModifierV2 = ComputeStakeModifier(pindexNew->pprev, block.vtx[1].vin[0].prevout.hash); } } pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew); pindexNew->RaiseValidity(BLOCK_VALID_TREE); if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork) pindexBestHeader = pindexNew; //update previous block pointer if (pindexNew->nHeight) pindexNew->pprev->pnext = pindexNew; setDirtyBlockIndex.insert(pindexNew); return pindexNew; } /** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */ bool ReceivedBlockTransactions(const CBlock& block, CValidationState& state, CBlockIndex* pindexNew, const CDiskBlockPos& pos) { if (block.IsProofOfStake()) pindexNew->SetProofOfStake(); pindexNew->nTx = block.vtx.size(); pindexNew->nChainTx = 0; pindexNew->nFile = pos.nFile; pindexNew->nDataPos = pos.nPos; pindexNew->nUndoPos = 0; pindexNew->nStatus |= BLOCK_HAVE_DATA; pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS); setDirtyBlockIndex.insert(pindexNew); if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) { // If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS. std::deque<CBlockIndex*> queue; queue.push_back(pindexNew); // Recursively process any descendant blocks that now may be eligible to be connected. while (!queue.empty()) { CBlockIndex* pindex = queue.front(); queue.pop_front(); pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx; { LOCK(cs_nBlockSequenceId); pindex->nSequenceId = nBlockSequenceId++; } if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) { setBlockIndexCandidates.insert(pindex); } std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex); while (range.first != range.second) { std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first; queue.push_back(it->second); range.first++; mapBlocksUnlinked.erase(it); } } } else { if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) { mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew)); } } return true; } bool FindBlockPos(CValidationState& state, CDiskBlockPos& pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false) { LOCK(cs_LastBlockFile); unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } if (!fKnown) { while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) { LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString()); FlushBlockFile(true); nFile++; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); } } pos.nFile = nFile; pos.nPos = vinfoBlockFile[nFile].nSize; } nLastBlockFile = nFile; vinfoBlockFile[nFile].AddBlock(nHeight, nTime); if (fKnown) vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize); else vinfoBlockFile[nFile].nSize += nAddSize; if (!fKnown) { unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) { FILE* file = OpenBlockFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error("out of disk space"); } } setDirtyFileInfo.insert(nFile); return true; } bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize) { pos.nFile = nFile; LOCK(cs_LastBlockFile); unsigned int nNewSize; pos.nPos = vinfoBlockFile[nFile].nUndoSize; nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize; setDirtyFileInfo.insert(nFile); unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE; if (nNewChunks > nOldChunks) { if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) { FILE* file = OpenUndoFile(pos); if (file) { LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile); AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos); fclose(file); } } else return state.Error("out of disk space"); } return true; } bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW) { // Check proof of work matches claimed amount if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits)) return state.DoS(50, error("CheckBlockHeader() : proof of work failed"), REJECT_INVALID, "high-hash"); // Version 4 header must be used after Params().Zerocoin_StartHeight(). And never before. // if (block.GetBlockTime() > Params().Zerocoin_StartTime()) { // if(block.nVersion < Params().Zerocoin_HeaderVersion() && Params().NetworkID() != CBaseChainParams::REGTEST) // return state.DoS(50, error("CheckBlockHeader() : block version must be above 4 after ZerocoinStartHeight"), // REJECT_INVALID, "block-version"); // } else { // if (block.nVersion >= Params().Zerocoin_HeaderVersion()) // return state.DoS(50, error("CheckBlockHeader() : block version must be below 4 before ZerocoinStartHeight"), // REJECT_INVALID, "block-version"); // } return true; } bool CheckColdStakeFreeOutput(const CTransaction& tx, const int nHeight) { if (!tx.HasP2CSOutputs()) return true; const unsigned int outs = tx.vout.size(); const CTxOut& lastOut = tx.vout[outs-1]; if (outs >=3 && lastOut.scriptPubKey != tx.vout[outs-2].scriptPubKey) { // last output can either be a mn reward or a budget payment // cold staking is active much after nPublicZCSpends so GetMasternodePayment is always 3 PIVXL. // TODO: double check this if/when MN rewards change if (lastOut.nValue == 3 * COIN) return true; if (budget.IsBudgetPaymentBlock(nHeight) & sporkManager.IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && sporkManager.IsSporkActive(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT)) return true; return error("%s: Wrong cold staking outputs: vout[%d].scriptPubKey (%s) != vout[%d].scriptPubKey (%s) - value: %s", __func__, outs-1, HexStr(lastOut.scriptPubKey), outs-2, HexStr(tx.vout[outs-2].scriptPubKey), FormatMoney(lastOut.nValue).c_str()); } return true; } bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) { // These are checks that are independent of context. const bool IsPoS = block.IsProofOfStake(); LogPrint("debug", "%s: block=%s is proof of stake=%d\n", __func__, block.GetHash().ToString().c_str(), IsPoS); if (block.fChecked) return true; // Check that the header is valid (particularly PoW). This is mostly // redundant with the call in AcceptBlockHeader. if (!CheckBlockHeader(block, state, fCheckPOW && !IsPoS)) return state.DoS(100, error("%s : CheckBlockHeader failed", __func__), REJECT_INVALID, "bad-header", true); // All potential-corruption validation must be done before we do any // transaction validation, as otherwise we may mark the header as invalid // because we receive the wrong transactions for it. // Check the merkle root. if (fCheckMerkleRoot) { bool mutated; uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated); if (block.hashMerkleRoot != hashMerkleRoot2) return state.DoS(100, error("%s : hashMerkleRoot mismatch", __func__), REJECT_INVALID, "bad-txnmrklroot", true); // Check for merkle tree malleability (CVE-2012-2459): repeating sequences // of transactions in a block without affecting the merkle root of a block, // while still invalidating it. if (mutated) return state.DoS(100, error("%s : duplicate transaction", __func__), REJECT_INVALID, "bad-txns-duplicate", true); } // Size limits unsigned int nMaxBlockSize = MAX_BLOCK_SIZE_CURRENT; if (block.vtx.empty() || block.vtx.size() > nMaxBlockSize || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > nMaxBlockSize) return state.DoS(100, error("%s : size limits failed", __func__), REJECT_INVALID, "bad-blk-length"); // First transaction must be coinbase, the rest must not be if (block.vtx.empty() || !block.vtx[0].IsCoinBase()) return state.DoS(100, error("%s : first tx is not coinbase", __func__), REJECT_INVALID, "bad-cb-missing"); for (unsigned int i = 1; i < block.vtx.size(); i++) if (block.vtx[i].IsCoinBase()) return state.DoS(100, error("%s : more than one coinbase", __func__), REJECT_INVALID, "bad-cb-multiple"); if (IsPoS) { // Coinbase output should be empty if proof-of-stake block if (block.vtx[0].vout.size() != 1 || !block.vtx[0].vout[0].IsEmpty()) return state.DoS(100, error("%s : coinbase output not empty for proof-of-stake block", __func__)); // Second transaction must be coinstake, the rest must not be if (block.vtx.empty() || !block.vtx[1].IsCoinStake()) return state.DoS(100, error("%s : second tx is not coinstake", __func__)); for (unsigned int i = 2; i < block.vtx.size(); i++) if (block.vtx[i].IsCoinStake()) return state.DoS(100, error("%s : more than one coinstake", __func__)); } // ----------- swiftTX transaction scanning ----------- if (sporkManager.IsSporkActive(SPORK_3_SWIFTTX_BLOCK_FILTERING)) { for (const CTransaction& tx : block.vtx) { if (!tx.IsCoinBase()) { //only reject blocks when it's based on complete consensus for (const CTxIn& in : tx.vin) { if (mapLockedInputs.count(in.prevout)) { if (mapLockedInputs[in.prevout] != tx.GetHash()) { mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); LogPrintf("%s : found conflicting transaction with transaction lock %s %s\n", __func__, mapLockedInputs[in.prevout].ToString(), tx.GetHash().GetHex()); return state.DoS(0, error("%s : found conflicting transaction with transaction lock", __func__), REJECT_INVALID, "conflicting-tx-ix"); } } } } } } else { LogPrintf("%s : skipping transaction locking checks\n", __func__); } // Cold Staking enforcement (true during sync - reject P2CS outputs when false) bool fColdStakingActive = true; // Zerocoin activation bool fZerocoinActive = block.GetBlockTime() > Params().Zerocoin_StartTime(); // masternode payments / budgets CBlockIndex* pindexPrev = chainActive.Tip(); int nHeight = 0; if (pindexPrev != NULL) { if (pindexPrev->GetBlockHash() == block.hashPrevBlock) { nHeight = pindexPrev->nHeight + 1; } else { //out of order BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi != mapBlockIndex.end() && (*mi).second) nHeight = (*mi).second->nHeight + 1; } // PIVXL // It is entierly possible that we don't have enough data and this could fail // (i.e. the block could indeed be valid). Store the block for later consideration // but issue an initial reject message. // The case also exists that the sending peer could not have enough data to see // that this block is invalid, so don't issue an outright ban. if (nHeight != 0 && !IsInitialBlockDownload()) { // Last output of Cold-Stake is not abused if (IsPoS && !CheckColdStakeFreeOutput(block.vtx[1], nHeight)) { mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("%s : Cold stake outputs not valid", __func__), REJECT_INVALID, "bad-p2cs-outs"); } // set Cold Staking Spork fColdStakingActive = sporkManager.IsSporkActive(SPORK_17_COLDSTAKING_ENFORCEMENT); // check masternode/budget payment if (!IsBlockPayeeValid(block, nHeight)) { mapRejectedBlocks.insert(std::make_pair(block.GetHash(), GetTime())); return state.DoS(0, error("%s : Couldn't find masternode/budget payment", __func__), REJECT_INVALID, "bad-cb-payee"); } } else { if (fDebug) LogPrintf("%s: Masternode payment check skipped on sync - skipping IsBlockPayeeValid()\n", __func__); } } // Check transactions std::vector<CBigNum> vBlockSerials; // TODO: Check if this is ok... blockHeight is always the tip or should we look for the prevHash and get the height? int blockHeight = chainActive.Height() + 1; for (const CTransaction& tx : block.vtx) { if (!CheckTransaction( tx, fZerocoinActive, blockHeight >= Params().Zerocoin_Block_EnforceSerialRange(), state, isBlockBetweenFakeSerialAttackRange(blockHeight), fColdStakingActive )) return error("%s : CheckTransaction failed", __func__); // double check that there are no double spent zPIV spends in this block if (tx.HasZerocoinSpendInputs()) { for (const CTxIn& txIn : tx.vin) { bool isPublicSpend = txIn.IsZerocoinPublicSpend(); if (txIn.IsZerocoinSpend() || isPublicSpend) { libzerocoin::CoinSpend spend; if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZPIVModule::ParseZerocoinPublicSpend(txIn, tx, state, publicSpend)){ return false; } spend = publicSpend; // check that the version matches the one enforced with SPORK_18 (don't ban if it fails) if (!IsInitialBlockDownload() && !CheckPublicCoinSpendVersion(spend.getVersion())) { return state.DoS(0, error("%s : Public Zerocoin spend version %d not accepted. must be version %d.", __func__, spend.getVersion(), CurrentPublicCoinSpendVersion()), REJECT_INVALID, "bad-zcspend-version"); } } else { spend = TxInToZerocoinSpend(txIn); } if (std::count(vBlockSerials.begin(), vBlockSerials.end(), spend.getCoinSerialNumber())) return state.DoS(100, error("%s : Double spending of zPIV serial %s in block\n Block: %s", __func__, spend.getCoinSerialNumber().GetHex(), block.ToString())); vBlockSerials.emplace_back(spend.getCoinSerialNumber()); } } } } unsigned int nSigOps = 0; for (const CTransaction& tx : block.vtx) { nSigOps += GetLegacySigOpCount(tx); } unsigned int nMaxBlockSigOps = fZerocoinActive ? MAX_BLOCK_SIGOPS_CURRENT : MAX_BLOCK_SIGOPS_LEGACY; if (nSigOps > nMaxBlockSigOps) return state.DoS(100, error("%s : out-of-bounds SigOpCount", __func__), REJECT_INVALID, "bad-blk-sigops", true); if (fCheckPOW && fCheckMerkleRoot && fCheckSig) block.fChecked = true; return true; } bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev) { if (pindexPrev == NULL) return error("%s : null pindexPrev for block %s", __func__, block.GetHash().GetHex()); unsigned int nBitsRequired = GetNextWorkRequired(pindexPrev, &block); if ((Params().NetworkID() != CBaseChainParams::REGTEST) && block.IsProofOfWork() && (pindexPrev->nHeight + 1 <= 68589)) { double n1 = ConvertBitsToDouble(block.nBits); double n2 = ConvertBitsToDouble(nBitsRequired); if (std::abs(n1 - n2) > n1 * 0.5) return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, std::abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1); return true; } if (block.nBits != nBitsRequired) { // Pivx Specific reference to the block with the wrong threshold was used. if ((block.nTime == (uint32_t) Params().PivxBadBlockTime()) && (block.nBits == (uint32_t) Params().PivxBadBlocknBits())) { // accept PIVXL block minted with incorrect proof of work threshold return true; } return error("%s : incorrect proof of work at %d", __func__, pindexPrev->nHeight + 1); } return true; } bool CheckBlockTime(const CBlockHeader& block, CValidationState& state, CBlockIndex* const pindexPrev) { // Not enforced on RegTest if (Params().NetworkID() == CBaseChainParams::REGTEST) return true; const int64_t blockTime = block.GetBlockTime(); const int blockHeight = pindexPrev->nHeight + 1; // Check blocktime against future drift (WANT: blk_time <= Now + MaxDrift) if (blockTime > pindexPrev->MaxFutureBlockTime()) return state.Invalid(error("%s : block timestamp too far in the future", __func__), REJECT_INVALID, "time-too-new"); // Check blocktime against prev (WANT: blk_time > MinPastBlockTime) if (blockTime <= pindexPrev->MinPastBlockTime()) return state.DoS(50, error("%s : block timestamp too old", __func__), REJECT_INVALID, "time-too-old"); // Check blocktime mask if (!Params().IsValidBlockTimeStamp(blockTime, blockHeight)) return state.DoS(100, error("%s : block timestamp mask not valid", __func__), REJECT_INVALID, "invalid-time-mask"); // All good return true; } bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* const pindexPrev) { uint256 hash = block.GetHash(); if (hash == Params().HashGenesisBlock()) return true; assert(pindexPrev); int nHeight = pindexPrev->nHeight + 1; //If this is a reorg, check that it is not too deep int nMaxReorgDepth = GetArg("-maxreorg", Params().MaxReorganizationDepth()); if (chainActive.Height() - nHeight >= nMaxReorgDepth) return state.DoS(1, error("%s: forked chain older than max reorganization depth (height %d)", __func__, chainActive.Height() - nHeight)); // Check blocktime (past limit, future limit and mask) if (!CheckBlockTime(block, state, pindexPrev)) return false; // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckBlock(nHeight, hash)) return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight), REJECT_CHECKPOINT, "checkpoint mismatch"); // Don't accept any forks from the main chain prior to last checkpoint CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(); if (pcheckpoint && nHeight < pcheckpoint->nHeight) return state.DoS(0, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight)); // Reject block.nVersion=1, ..., CURRENT_VERSION-1 blocks when 95% (75% on testnet) of the network has upgraded: for (int version = 2; version <= CBlockHeader::CURRENT_VERSION; version++) { if (block.nVersion < version && CBlockIndex::IsSuperMajority(version, pindexPrev, Params().RejectBlockOutdatedMajority())) { return state.Invalid(error("%s : rejected nVersion=%d block", __func__, block.nVersion), REJECT_OBSOLETE, "bad-version"); } } return true; } bool IsBlockHashInChain(const uint256& hashBlock) { if (hashBlock == 0 || !mapBlockIndex.count(hashBlock)) return false; return chainActive.Contains(mapBlockIndex[hashBlock]); } bool IsTransactionInChain(const uint256& txId, int& nHeightTx, CTransaction& tx) { uint256 hashBlock; if (!GetTransaction(txId, tx, hashBlock, true)) return false; if (!IsBlockHashInChain(hashBlock)) return false; nHeightTx = mapBlockIndex.at(hashBlock)->nHeight; return true; } bool IsTransactionInChain(const uint256& txId, int& nHeightTx) { CTransaction tx; return IsTransactionInChain(txId, nHeightTx, tx); } bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex* const pindexPrev) { const int nHeight = pindexPrev == nullptr ? 0 : pindexPrev->nHeight + 1; // Check that all transactions are finalized for (const CTransaction& tx : block.vtx) if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) { return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal"); } // Enforce block.nVersion=2 rule that the coinbase starts with serialized block height if (pindexPrev) { // pindexPrev is only null on the first block which is a version 1 block. CScript expect = CScript() << nHeight; if (block.vtx[0].vin[0].scriptSig.size() < expect.size() || !std::equal(expect.begin(), expect.end(), block.vtx[0].vin[0].scriptSig.begin())) { return state.DoS(100, error("%s : block height mismatch in coinbase", __func__), REJECT_INVALID, "bad-cb-height"); } } return true; } bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex** ppindex) { AssertLockHeld(cs_main); // Check for duplicate uint256 hash = block.GetHash(); BlockMap::iterator miSelf = mapBlockIndex.find(hash); CBlockIndex* pindex = NULL; // TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES if (miSelf != mapBlockIndex.end()) { // Block header is already known. pindex = miSelf->second; if (ppindex) *ppindex = pindex; if (pindex->nStatus & BLOCK_FAILED_MASK) return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate"); return true; } if (!CheckBlockHeader(block, state, false)) { LogPrintf("AcceptBlockHeader(): CheckBlockHeader failed \n"); return false; } // Get prev block index CBlockIndex* pindexPrev = NULL; if (hash != Params().HashGenesisBlock()) { BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.GetHex()), 0, "bad-prevblk"); pindexPrev = (*mi).second; if (pindexPrev->nStatus & BLOCK_FAILED_MASK) { //If this "invalid" block is an exact match from the checkpoints, then reconsider it if (pindex && Checkpoints::CheckBlock(pindex->nHeight - 1, block.hashPrevBlock, true)) { LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(), pindexPrev->nHeight); CValidationState statePrev; ReconsiderBlock(statePrev, pindexPrev); if (statePrev.IsValid()) { ActivateBestChain(statePrev); return true; } } return state.DoS(100, error("%s : prev block height=%d hash=%s is invalid, unable to add block %s", __func__, pindexPrev->nHeight, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()), REJECT_INVALID, "bad-prevblk"); } } if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; if (pindex == NULL) pindex = AddToBlockIndex(block); if (ppindex) *ppindex = pindex; return true; } bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp, bool fAlreadyCheckedBlock) { AssertLockHeld(cs_main); CBlockIndex*& pindex = *ppindex; // Get prev block index CBlockIndex* pindexPrev = NULL; if (block.GetHash() != Params().HashGenesisBlock()) { BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi == mapBlockIndex.end()) return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.GetHex()), 0, "bad-prevblk"); pindexPrev = (*mi).second; if (pindexPrev->nStatus & BLOCK_FAILED_MASK) { //If this "invalid" block is an exact match from the checkpoints, then reconsider it if (Checkpoints::CheckBlock(pindexPrev->nHeight, block.hashPrevBlock, true)) { LogPrintf("%s : Reconsidering block %s height %d\n", __func__, pindexPrev->GetBlockHash().GetHex(), pindexPrev->nHeight); CValidationState statePrev; ReconsiderBlock(statePrev, pindexPrev); if (statePrev.IsValid()) { ActivateBestChain(statePrev); return true; } } return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()), REJECT_INVALID, "bad-prevblk"); } } if (block.GetHash() != Params().HashGenesisBlock() && !CheckWork(block, pindexPrev)) return false; bool isPoS = false; if (block.IsProofOfStake()) { isPoS = true; uint256 hashProofOfStake = 0; std::unique_ptr<CStakeInput> stake; if (!CheckProofOfStake(block, hashProofOfStake, stake, pindexPrev->nHeight)) return state.DoS(100, error("%s: proof of stake check failed", __func__)); if (!stake) return error("%s: null stake ptr", __func__); uint256 hash = block.GetHash(); if(!mapProofOfStake.count(hash)) // add to mapProofOfStake mapProofOfStake.insert(std::make_pair(hash, hashProofOfStake)); } if (!AcceptBlockHeader(block, state, &pindex)) return false; if (pindex->nStatus & BLOCK_HAVE_DATA) { // TODO: deal better with duplicate blocks. // return state.DoS(20, error("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate"); LogPrintf("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()); return true; } if ((!fAlreadyCheckedBlock && !CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) { if (state.IsInvalid() && !state.CorruptionPossible()) { pindex->nStatus |= BLOCK_FAILED_VALID; setDirtyBlockIndex.insert(pindex); } return false; } int nHeight = pindex->nHeight; int splitHeight = -1; if (isPoS) { LOCK(cs_main); // Blocks arrives in order, so if prev block is not the tip then we are on a fork. // Extra info: duplicated blocks are skipping this checks, so we don't have to worry about those here. bool isBlockFromFork = pindexPrev != nullptr && chainActive.Tip() != pindexPrev; // Coin stake CTransaction &stakeTxIn = block.vtx[1]; // Inputs std::vector<CTxIn> pivInputs; std::vector<CTxIn> zPIVInputs; for (const CTxIn& stakeIn : stakeTxIn.vin) { if(stakeIn.IsZerocoinSpend()){ zPIVInputs.push_back(stakeIn); }else{ pivInputs.push_back(stakeIn); } } const bool hasPIVInputs = !pivInputs.empty(); const bool hasZPIVInputs = !zPIVInputs.empty(); // ZC started after PoS. // Check for serial double spent on the same block, TODO: Move this to the proper method.. std::vector<CBigNum> inBlockSerials; for (const CTransaction& tx : block.vtx) { for (const CTxIn& in: tx.vin) { if(nHeight >= Params().Zerocoin_StartHeight()) { bool isPublicSpend = in.IsZerocoinPublicSpend(); bool isPrivZerocoinSpend = in.IsZerocoinSpend(); if (isPrivZerocoinSpend || isPublicSpend) { // Check enforcement if (!CheckPublicCoinSpendEnforced(pindex->nHeight, isPublicSpend)){ return false; } libzerocoin::CoinSpend spend; if (isPublicSpend) { libzerocoin::ZerocoinParams* params = Params().Zerocoin_Params(false); PublicCoinSpend publicSpend(params); if (!ZPIVModule::ParseZerocoinPublicSpend(in, tx, state, publicSpend)){ return false; } spend = publicSpend; } else { spend = TxInToZerocoinSpend(in); } // Check for serials double spending in the same block if (std::find(inBlockSerials.begin(), inBlockSerials.end(), spend.getCoinSerialNumber()) != inBlockSerials.end()) { return state.DoS(100, error("%s: serial double spent on the same block", __func__)); } inBlockSerials.push_back(spend.getCoinSerialNumber()); } } if(tx.IsCoinStake()) continue; if(hasPIVInputs) // Check if coinstake input is double spent inside the same block for (const CTxIn& pivIn : pivInputs){ if(pivIn.prevout == in.prevout){ // double spent coinstake input inside block return error("%s: double spent coinstake input inside block", __func__); } } } } inBlockSerials.clear(); // Check whether is a fork or not if (isBlockFromFork) { // Start at the block we're adding on to CBlockIndex *prev = pindexPrev; CBlock bl; if (!ReadBlockFromDisk(bl, prev)) return error("%s: previous block %s not on disk", __func__, prev->GetBlockHash().GetHex()); std::vector<CBigNum> vBlockSerials; int readBlock = 0; // Go backwards on the forked chain up to the split while (!chainActive.Contains(prev)) { // Increase amount of read blocks readBlock++; // Check if the forked chain is longer than the max reorg limit if (readBlock == Params().MaxReorganizationDepth()) { // TODO: Remove this chain from disk. return error("%s: forked chain longer than maximum reorg limit", __func__); } // Loop through every input from said block for (const CTransaction &t : bl.vtx) { for (const CTxIn &in: t.vin) { // Loop through every input of the staking tx for (const CTxIn &stakeIn : pivInputs) { // if it's already spent // First regular staking check if (hasPIVInputs) { if (stakeIn.prevout == in.prevout) { return state.DoS(100, error("%s: input already spent on a previous block", __func__)); } // Second, if there is zPoS staking then store the serials for later check if(in.IsZerocoinSpend()){ vBlockSerials.push_back(TxInToZerocoinSpend(in).getCoinSerialNumber()); } } } } } // Prev block prev = prev->pprev; if (!ReadBlockFromDisk(bl, prev)) // Previous block not on disk return error("%s: previous block %s not on disk", __func__, prev->GetBlockHash().GetHex()); } // Split height splitHeight = prev->nHeight; // Now that this loop if completed. Check if we have zPIV inputs. if(hasZPIVInputs){ for (const CTxIn& zPivInput : zPIVInputs) { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(zPivInput); // First check if the serials were not already spent on the forked blocks. CBigNum coinSerial = spend.getCoinSerialNumber(); for(const CBigNum& serial : vBlockSerials){ if(serial == coinSerial){ return state.DoS(100, error("%s: serial double spent on fork", __func__)); } } // Now check if the serial exists before the chain split. int nHeightTx = 0; if (IsSerialInBlockchain(spend.getCoinSerialNumber(), nHeightTx)){ // if the height is nHeightTx > chainSplit means that the spent occurred after the chain split if(nHeightTx <= splitHeight) return state.DoS(100, error("%s: serial double spent on main chain", __func__)); } if (!ContextualCheckZerocoinSpendNoSerialCheck(stakeTxIn, &spend, pindex, 0)) return state.DoS(100,error("%s: forked chain ContextualCheckZerocoinSpend failed for tx %s", __func__, stakeTxIn.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); // Now only the ZKP left.. // As the spend maturity is 200, the acc value must be accumulated, otherwise it's not ready to be spent CBigNum bnAccumulatorValue = 0; if (!zerocoinDB->ReadAccumulatorValue(spend.getAccumulatorChecksum(), bnAccumulatorValue)) { return state.DoS(100, error("%s: stake zerocoinspend not ready to be spent", __func__)); } libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(chainActive.Height() < Params().Zerocoin_Block_V2_Start()), spend.getDenomination(), bnAccumulatorValue); //Check that the coinspend is valid bool isInInvalidRange = isBlockBetweenFakeSerialAttackRange(pindex->nHeight); if(!spend.Verify(accumulator, !isInInvalidRange)) return state.DoS(100, error("%s: zerocoin spend did not verify", __func__)); } } } // If the stake is not a zPoS then let's check if the inputs were spent on the main chain const CCoinsViewCache coins(pcoinsTip); if(!stakeTxIn.HasZerocoinSpendInputs()) { for (const CTxIn& in: stakeTxIn.vin) { const CCoins* coin = coins.AccessCoins(in.prevout.hash); if(!coin && !isBlockFromFork){ // No coins on the main chain return error("%s: coin stake inputs not available on main chain, received height %d vs current %d", __func__, nHeight, chainActive.Height()); } if(coin && !coin->IsAvailable(in.prevout.n)){ if(!isBlockFromFork){ // Coins not available return error("%s: coin stake inputs already spent in main chain", __func__); } } } } else { if(!isBlockFromFork) for (const CTxIn& zPivInput : zPIVInputs) { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(zPivInput); if (!ContextualCheckZerocoinSpend(stakeTxIn, &spend, pindex, 0)) return state.DoS(100,error("%s: main chain ContextualCheckZerocoinSpend failed for tx %s", __func__, stakeTxIn.GetHash().GetHex()), REJECT_INVALID, "bad-txns-invalid-zpiv"); } } } // Write block to history file try { unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; if (dbp != NULL) blockPos = *dbp; if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, block.GetBlockTime(), dbp != NULL)) return error("AcceptBlock() : FindBlockPos failed"); if (dbp == NULL) if (!WriteBlockToDisk(block, blockPos)) return state.Abort("Failed to write block"); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("AcceptBlock() : ReceivedBlockTransactions failed"); } catch (const std::runtime_error& e) { return state.Abort(std::string("System error: ") + e.what()); } return true; } bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired) { unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority(); unsigned int nFound = 0; for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } return (nFound >= nRequired); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } CBlockIndex* CBlockIndex::GetAncestor(int height) { if (height > nHeight || height < 0) return NULL; CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { return const_cast<CBlockIndex*>(this)->GetAncestor(height); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } bool ProcessNewBlock(CValidationState& state, CNode* pfrom, CBlock* pblock, CDiskBlockPos* dbp) { // Preliminary checks int64_t nStartTime = GetTimeMillis(); // check block bool checked = CheckBlock(*pblock, state); if (!CheckBlockSignature(*pblock)) return error("%s : bad proof-of-stake block signature", __func__); if (pblock->GetHash() != Params().HashGenesisBlock() && pfrom != NULL) { //if we get this far, check if the prev block is our prev block, if not then request sync and return false BlockMap::iterator mi = mapBlockIndex.find(pblock->hashPrevBlock); if (mi == mapBlockIndex.end()) { pfrom->PushMessage("getblocks", chainActive.GetLocator(), uint256(0)); return false; } } { LOCK(cs_main); MarkBlockAsReceived(pblock->GetHash()); if (!checked) { return error ("%s : CheckBlock FAILED for block %s", __func__, pblock->GetHash().GetHex()); } // Store to disk CBlockIndex* pindex = nullptr; bool ret = AcceptBlock(*pblock, state, &pindex, dbp, checked); if (pindex && pfrom) { mapBlockSource[pindex->GetBlockHash ()] = pfrom->GetId (); } CheckBlockIndex (); if (!ret) { // Check spamming if(pindex && pfrom && GetBoolArg("-blockspamfilter", DEFAULT_BLOCK_SPAM_FILTER)) { CNodeState *nodestate = State(pfrom->GetId()); if(nodestate != nullptr) { nodestate->nodeBlocks.onBlockReceived(pindex->nHeight); bool nodeStatus = true; // UpdateState will return false if the node is attacking us or update the score and return true. nodeStatus = nodestate->nodeBlocks.updateState(state, nodeStatus); int nDoS = 0; if (state.IsInvalid(nDoS)) { if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); nodeStatus = false; } if (!nodeStatus) return error("%s : AcceptBlock FAILED - block spam protection", __func__); } } return error("%s : AcceptBlock FAILED", __func__); } } if (!ActivateBestChain(state, pblock, checked)) return error("%s : ActivateBestChain failed", __func__); if (!fLiteMode) { if (masternodeSync.RequestedMasternodeAssets > MASTERNODE_SYNC_LIST) { obfuScationPool.NewBlock(); masternodePayments.ProcessBlock(GetHeight() + 10); budget.NewBlock(); } } if (pwalletMain) { // If turned on MultiSend will send a transaction (or more) on the after maturity of a stake if (pwalletMain->isMultiSendEnabled()) pwalletMain->MultiSend(); // If turned on Auto Combine will scan wallet for dust to combine if (pwalletMain->fCombineDust) pwalletMain->AutoCombineDust(); } LogPrintf("%s : ACCEPTED Block %ld in %ld milliseconds with size=%d\n", __func__, GetHeight(), GetTimeMillis() - nStartTime, pblock->GetSerializeSize(SER_DISK, CLIENT_VERSION)); return true; } bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot) { AssertLockHeld(cs_main); assert(pindexPrev); if (pindexPrev != chainActive.Tip()) { LogPrintf("%s : No longer working on chain tip\n", __func__); return false; } CCoinsViewCache viewNew(pcoinsTip); CBlockIndex indexDummy(block); indexDummy.pprev = pindexPrev; indexDummy.nHeight = pindexPrev->nHeight + 1; // NOTE: CheckBlockHeader is called by CheckBlock if (!ContextualCheckBlockHeader(block, state, pindexPrev)) return false; if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot)) return false; if (!ContextualCheckBlock(block, state, pindexPrev)) return false; if (!ConnectBlock(block, state, &indexDummy, viewNew, true)) return false; assert(state.IsValid()); return true; } bool AbortNode(const std::string& strMessage, const std::string& userMessage) { strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox( userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return false; } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = boost::filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) return AbortNode("Disk space is low!", _("Error: Disk space is low!")); return true; } FILE* OpenDiskFile(const CDiskBlockPos& pos, const char* prefix, bool fReadOnly) { if (pos.IsNull()) return NULL; boost::filesystem::path path = GetBlockPosFilename(pos, prefix); boost::filesystem::create_directories(path.parent_path()); FILE* file = fopen(path.string().c_str(), "rb+"); if (!file && !fReadOnly) file = fopen(path.string().c_str(), "wb+"); if (!file) { LogPrintf("Unable to open file %s\n", path.string()); return NULL; } if (pos.nPos) { if (fseek(file, pos.nPos, SEEK_SET)) { LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string()); fclose(file); return NULL; } } return file; } FILE* OpenBlockFile(const CDiskBlockPos& pos, bool fReadOnly) { return OpenDiskFile(pos, "blk", fReadOnly); } FILE* OpenUndoFile(const CDiskBlockPos& pos, bool fReadOnly) { return OpenDiskFile(pos, "rev", fReadOnly); } boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos& pos, const char* prefix) { return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile); } CBlockIndex* InsertBlockIndex(uint256 hash) { if (hash == 0) return NULL; // Return existing BlockMap::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) return (*mi).second; // Create new CBlockIndex* pindexNew = new CBlockIndex(); if (!pindexNew) throw std::runtime_error("LoadBlockIndex() : new CBlockIndex failed"); mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first; pindexNew->phashBlock = &((*mi).first); return pindexNew; } bool static LoadBlockIndexDB(std::string& strError) { if (!pblocktree->LoadBlockIndexGuts()) return false; boost::this_thread::interruption_point(); // Calculate nChainWork std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight; vSortedByHeight.reserve(mapBlockIndex.size()); for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) { CBlockIndex* pindex = item.second; vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex)); } std::sort(vSortedByHeight.begin(), vSortedByHeight.end()); for (const PAIRTYPE(int, CBlockIndex*) & item : vSortedByHeight) { // Stop if shutdown was requested if (ShutdownRequested()) return false; CBlockIndex* pindex = item.second; pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex); if (pindex->nStatus & BLOCK_HAVE_DATA) { if (pindex->pprev) { if (pindex->pprev->nChainTx) { pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx; } else { pindex->nChainTx = 0; mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex)); } } else { pindex->nChainTx = pindex->nTx; } } if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL)) setBlockIndexCandidates.insert(pindex); if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork)) pindexBestInvalid = pindex; if (pindex->pprev) pindex->BuildSkip(); if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex))) pindexBestHeader = pindex; } // Load block file info pblocktree->ReadLastBlockFile(nLastBlockFile); vinfoBlockFile.resize(nLastBlockFile + 1); LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile); for (int nFile = 0; nFile <= nLastBlockFile; nFile++) { pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]); } LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString()); for (int nFile = nLastBlockFile + 1; true; nFile++) { CBlockFileInfo info; if (pblocktree->ReadBlockFileInfo(nFile, info)) { vinfoBlockFile.push_back(info); } else { break; } } // Check presence of blk files LogPrintf("Checking all blk files are present...\n"); std::set<int> setBlkDataFiles; for (const std::pair<const uint256, CBlockIndex*>& item : mapBlockIndex) { CBlockIndex* pindex = item.second; if (pindex->nStatus & BLOCK_HAVE_DATA) { setBlkDataFiles.insert(pindex->nFile); } } for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) { CDiskBlockPos pos(*it, 0); if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) { return false; } } //Check if the shutdown procedure was followed on last client exit bool fLastShutdownWasPrepared = true; pblocktree->ReadFlag("shutdown", fLastShutdownWasPrepared); LogPrintf("%s: Last shutdown was prepared: %s\n", __func__, fLastShutdownWasPrepared); // Check whether we need to continue reindexing bool fReindexing = false; pblocktree->ReadReindexing(fReindexing); fReindex |= fReindexing; // Check whether we have a transaction index pblocktree->ReadFlag("txindex", fTxIndex); LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled"); // If this is written true before the next client init, then we know the shutdown process failed pblocktree->WriteFlag("shutdown", false); // Load pointer to end of best chain BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock()); if (it == mapBlockIndex.end()) return true; chainActive.SetTip(it->second); PruneBlockIndexCandidates(); LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n", chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()), Checkpoints::GuessVerificationProgress(chainActive.Tip())); return true; } CVerifyDB::CVerifyDB() { uiInterface.ShowProgress(_("Verifying blocks..."), 0); } CVerifyDB::~CVerifyDB() { uiInterface.ShowProgress("", 100); } bool CVerifyDB::VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth) { LOCK(cs_main); if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL) return true; // Verify blocks in the best chain if (nCheckDepth <= 0) nCheckDepth = 1000000000; // suffices until the year 19000 if (nCheckDepth > chainActive.Height()) nCheckDepth = chainActive.Height(); nCheckLevel = std::max(0, std::min(4, nCheckLevel)); LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CCoinsViewCache coins(coinsview); CBlockIndex* pindexState = chainActive.Tip(); CBlockIndex* pindexFailure = NULL; int nGoodTransactions = 0; CValidationState state; for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100))))); if (pindex->nHeight < chainActive.Height() - nCheckDepth) break; CBlock block; // check level 0: read from disk if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 1: verify block validity if (nCheckLevel >= 1 && !CheckBlock(block, state)) return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); // check level 2: verify undo validity if (nCheckLevel >= 2 && pindex) { CBlockUndo undo; CDiskBlockPos pos = pindex->GetUndoPos(); if (!pos.IsNull()) { if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash())) return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); } } // check level 3: check for inconsistencies during memory-only disconnect of tip blocks if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) { bool fClean = true; if (!DisconnectBlock(block, state, pindex, coins, &fClean)) return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); pindexState = pindex->pprev; if (!fClean) { nGoodTransactions = 0; pindexFailure = pindex; } else nGoodTransactions += block.vtx.size(); } if (ShutdownRequested()) return true; } if (pindexFailure) return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { CBlockIndex* pindex = pindexState; while (pindex != chainActive.Tip()) { boost::this_thread::interruption_point(); uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50)))); pindex = chainActive.Next(pindex); CBlock block; if (!ReadBlockFromDisk(block, pindex)) return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); if (!ConnectBlock(block, state, pindex, coins, false)) return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); } } LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions); return true; } void UnloadBlockIndex() { LOCK(cs_main); setBlockIndexCandidates.clear(); chainActive.SetTip(NULL); pindexBestInvalid = NULL; pindexBestHeader = NULL; mempool.clear(); mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); nSyncStarted = 0; mapBlocksUnlinked.clear(); vinfoBlockFile.clear(); nLastBlockFile = 0; nBlockSequenceId = 1; mapBlockSource.clear(); mapBlocksInFlight.clear(); nQueuedValidatedHeaders = 0; nPreferredDownload = 0; setDirtyBlockIndex.clear(); setDirtyFileInfo.clear(); mapNodeState.clear(); for (BlockMap::value_type& entry : mapBlockIndex) { delete entry.second; } mapBlockIndex.clear(); } bool LoadBlockIndex(std::string& strError) { // Load block index from databases if (!fReindex && !LoadBlockIndexDB(strError)) return false; return true; } bool InitBlockIndex() { LOCK(cs_main); // Check whether we're already initialized if (chainActive.Genesis() != NULL) return true; // Use the provided setting for -txindex in the new database fTxIndex = GetBoolArg("-txindex", true); pblocktree->WriteFlag("txindex", fTxIndex); LogPrintf("Initializing databases...\n"); // Only add the genesis block if not reindexing (in which case we reuse the one already on disk) if (!fReindex) { try { CBlock& block = const_cast<CBlock&>(Params().GenesisBlock()); // Start new block file unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION); CDiskBlockPos blockPos; CValidationState state; if (!FindBlockPos(state, blockPos, nBlockSize + 8, 0, block.GetBlockTime())) return error("LoadBlockIndex() : FindBlockPos failed"); if (!WriteBlockToDisk(block, blockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); CBlockIndex* pindex = AddToBlockIndex(block); if (!ReceivedBlockTransactions(block, state, pindex, blockPos)) return error("LoadBlockIndex() : genesis block not accepted"); if (!ActivateBestChain(state, &block)) return error("LoadBlockIndex() : genesis block cannot be activated"); // Force a chainstate write so that when we VerifyDB in a moment, it doesnt check stale data return FlushStateToDisk(state, FLUSH_STATE_ALWAYS); } catch (const std::runtime_error& e) { return error("LoadBlockIndex() : failed to initialize block database: %s", e.what()); } } return true; } bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp) { // Map of disk positions for blocks with unknown parent (only used for reindex) static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent; int64_t nStart = GetTimeMillis(); int nLoaded = 0; try { // This takes over fileIn and calls fclose() on it in the CBufferedFile destructor CBufferedFile blkdat(fileIn, 2 * MAX_BLOCK_SIZE_CURRENT, MAX_BLOCK_SIZE_CURRENT + 8, SER_DISK, CLIENT_VERSION); uint64_t nRewind = blkdat.GetPos(); while (!blkdat.eof()) { boost::this_thread::interruption_point(); blkdat.SetPos(nRewind); nRewind++; // start one byte further next time, in case of failure blkdat.SetLimit(); // remove former limit unsigned int nSize = 0; try { // locate a header unsigned char buf[MESSAGE_START_SIZE]; blkdat.FindByte(Params().MessageStart()[0]); nRewind = blkdat.GetPos() + 1; blkdat >> FLATDATA(buf); if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE)) continue; // read size blkdat >> nSize; if (nSize < 80 || nSize > MAX_BLOCK_SIZE_CURRENT) continue; } catch (const std::exception&) { // no valid block header found; don't complain break; } try { // read block uint64_t nBlockPos = blkdat.GetPos(); if (dbp) dbp->nPos = nBlockPos; blkdat.SetLimit(nBlockPos + nSize); blkdat.SetPos(nBlockPos); CBlock block; blkdat >> block; nRewind = blkdat.GetPos(); // detect out of order blocks, and store them for later uint256 hash = block.GetHash(); if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) { LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(), block.hashPrevBlock.ToString()); if (dbp) mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp)); continue; } // process in case the block isn't known yet if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) { CValidationState state; if (ProcessNewBlock(state, NULL, &block, dbp)) nLoaded++; if (state.IsError()) break; } else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) { LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight); } // Recursively process earlier encountered successors of this block std::deque<uint256> queue; queue.push_back(hash); while (!queue.empty()) { uint256 head = queue.front(); queue.pop_front(); std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head); while (range.first != range.second) { std::multimap<uint256, CDiskBlockPos>::iterator it = range.first; if (ReadBlockFromDisk(block, it->second)) { LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(), head.ToString()); CValidationState dummy; if (ProcessNewBlock(dummy, NULL, &block, &it->second)) { nLoaded++; queue.push_back(block.GetHash()); } } range.first++; mapBlocksUnknownParent.erase(it); } } } catch (const std::exception& e) { LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what()); } } } catch (const std::runtime_error& e) { AbortNode(std::string("System error: ") + e.what()); } if (nLoaded > 0) LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } void static CheckBlockIndex() { if (!fCheckBlockIndex) { return; } LOCK(cs_main); // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when // iterating the block tree require that chainActive has been initialized.) if (chainActive.Height() < 0) { assert(mapBlockIndex.size() <= 1); return; } // Build forward-pointing map of the entire block tree. std::multimap<CBlockIndex*, CBlockIndex*> forward; for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) { forward.insert(std::make_pair(it->second->pprev, it->second)); } assert(forward.size() == mapBlockIndex.size()); std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL); CBlockIndex* pindex = rangeGenesis.first->second; rangeGenesis.first++; assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL. // Iterate over the entire block tree, using depth-first search. // Along the way, remember whether there are blocks on the path from genesis // block being explored which are the first to have certain properties. size_t nNodes = 0; int nHeight = 0; CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid. CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA. CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not). CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not). CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not). while (pindex != NULL) { nNodes++; if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex; if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex; if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex; if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex; if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex; // Begin: actual consistency checks. if (pindex->pprev == NULL) { // Genesis block checks. assert(pindex->GetBlockHash() == Params().HashGenesisBlock()); // Genesis block's hash must match. assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block. } // HAVE_DATA is equivalent to VALID_TRANSACTIONS and equivalent to nTx > 0 (we stored the number of transactions in the block) assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0)); assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0)); if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked // All parents having data is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set. assert((pindexFirstMissing != NULL) == (pindex->nChainTx == 0)); // nChainTx == 0 is used to signal that all parent block's transaction data is available. assert(pindex->nHeight == nHeight); // nHeight must be consistent. assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's. assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks. assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid if (pindexFirstInvalid == NULL) { // Checks for not-invalid blocks. assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents. } if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstMissing == NULL) { if (pindexFirstInvalid == NULL) { // If this block sorts at least as good as the current tip and is valid, it must be in setBlockIndexCandidates. assert(setBlockIndexCandidates.count(pindex)); } } else { // If this block sorts worse than the current tip, it cannot be in setBlockIndexCandidates. assert(setBlockIndexCandidates.count(pindex) == 0); } // Check whether this block is in mapBlocksUnlinked. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev); bool foundInUnlinked = false; while (rangeUnlinked.first != rangeUnlinked.second) { assert(rangeUnlinked.first->first == pindex->pprev); if (rangeUnlinked.first->second == pindex) { foundInUnlinked = true; break; } rangeUnlinked.first++; } if (pindex->pprev && pindex->nStatus & BLOCK_HAVE_DATA && pindexFirstMissing != NULL) { if (pindexFirstInvalid == NULL) { // If this block has block data available, some parent doesn't, and has no invalid parents, it must be in mapBlocksUnlinked. assert(foundInUnlinked); } } else { // If this block does not have block data available, or all parents do, it cannot be in mapBlocksUnlinked. assert(!foundInUnlinked); } // assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow // End: actual consistency checks. // Try descending into the first subnode. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = forward.equal_range(pindex); if (range.first != range.second) { // A subnode was found. pindex = range.first->second; nHeight++; continue; } // This is a leaf node. // Move upwards until we reach a node of which we have not yet visited the last child. while (pindex) { // We are going to either move to a parent or a sibling of pindex. // If pindex was the first with a certain property, unset the corresponding variable. if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL; if (pindex == pindexFirstMissing) pindexFirstMissing = NULL; if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL; if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL; if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL; // Find our parent. CBlockIndex* pindexPar = pindex->pprev; // Find which child we just visited. std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar); while (rangePar.first->second != pindex) { assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child. rangePar.first++; } // Proceed to the next one. rangePar.first++; if (rangePar.first != rangePar.second) { // Move to the sibling. pindex = rangePar.first->second; break; } else { // Move up further. pindex = pindexPar; nHeight--; continue; } } } // Check that we actually traversed the entire map. assert(nNodes == forward.size()); } ////////////////////////////////////////////////////////////////////////////// // // CAlert // std::string GetWarnings(std::string strFor) { int nPriority = 0; std::string strStatusBar; std::string strRPC; if (!CLIENT_VERSION_IS_RELEASE) strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!"); if (GetBoolArg("-testsafemode", false)) strStatusBar = strRPC = "testsafemode enabled"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } if (fLargeWorkForkFound) { nPriority = 2000; strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues."); } else if (fLargeWorkInvalidChainFound) { nPriority = 2000; strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade."); } // Alerts { LOCK(cs_mapAlerts); for (PAIRTYPE(const uint256, CAlert) & item : mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; txInMap = mempool.exists(inv.hash); return txInMap || mapOrphanTransactions.count(inv.hash) || pcoinsTip->HaveCoins(inv.hash); } case MSG_DSTX: return mapObfuscationBroadcastTxes.count(inv.hash); case MSG_PUBCOINS: case MSG_BLOCK: return mapBlockIndex.count(inv.hash); case MSG_TXLOCK_REQUEST: return mapTxLockReq.count(inv.hash) || mapTxLockReqRejected.count(inv.hash); case MSG_TXLOCK_VOTE: return mapTxLockVote.count(inv.hash); case MSG_SPORK: return mapSporks.count(inv.hash); case MSG_MASTERNODE_WINNER: if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) { masternodeSync.AddedMasternodeWinner(inv.hash); return true; } return false; case MSG_BUDGET_VOTE: if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) { masternodeSync.AddedBudgetItem(inv.hash); return true; } return false; case MSG_BUDGET_PROPOSAL: if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) { masternodeSync.AddedBudgetItem(inv.hash); return true; } return false; case MSG_BUDGET_FINALIZED_VOTE: if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) { masternodeSync.AddedBudgetItem(inv.hash); return true; } return false; case MSG_BUDGET_FINALIZED: if (budget.mapSeenFinalizedBudgets.count(inv.hash)) { masternodeSync.AddedBudgetItem(inv.hash); return true; } return false; case MSG_MASTERNODE_ANNOUNCE: if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) { masternodeSync.AddedMasternodeList(inv.hash); return true; } return false; case MSG_MASTERNODE_PING: return mnodeman.mapSeenMasternodePing.count(inv.hash); } // Don't know what it is, just say we already got one return true; } void static ProcessGetData(CNode* pfrom) { std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); std::vector<CInv> vNotFound; LOCK(cs_main); while (it != pfrom->vRecvGetData.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; const CInv& inv = *it; { boost::this_thread::interruption_point(); it++; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) { bool send = false; BlockMap::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { if (chainActive.Contains(mi->second)) { send = true; } else { // To prevent fingerprinting attacks, only send blocks outside of the active // chain if they are valid, and no more than a max reorg depth than the best header // chain we know about. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && (chainActive.Height() - mi->second->nHeight < Params().MaxReorganizationDepth()); if (!send) { LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId()); } } } // Don't send not-validated blocks if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) { // Send block from disk CBlock block; if (!ReadBlockFromDisk(block, (*mi).second)) assert(!"cannot load block from disk"); if (inv.type == MSG_BLOCK) pfrom->PushMessage("block", block); else // MSG_FILTERED_BLOCK) { LOCK(pfrom->cs_filter); if (pfrom->pfilter) { CMerkleBlock merkleBlock(block, *pfrom->pfilter); pfrom->PushMessage("merkleblock", merkleBlock); // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see // This avoids hurting performance by pointlessly requiring a round-trip // Note that there is currently no way for a node to request any single transactions we didnt send here - // they must either disconnect and retry or request the full block. // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair<unsigned int, uint256> PairType; for (PairType& pair : merkleBlock.vMatchedTxn) if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second))) pfrom->PushMessage("tx", block.vtx[pair.first]); } // else // no response } // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. std::vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory bool pushed = false; { LOCK(cs_mapRelay); std::map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { pfrom->PushMessage(inv.GetCommand(), (*mi).second); pushed = true; } } if (!pushed && inv.type == MSG_TX) { CTransaction tx; if (mempool.lookup(inv.hash, tx)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << tx; pfrom->PushMessage("tx", ss); pushed = true; } } if(nLocalServices & NODE_BLOOM_LIGHT_ZC) { if (!pushed && inv.type == MSG_PUBCOINS) { //std::cout << "asking for pubcoins, requested block hash: " << inv.hash.GetHex() << std::endl; bool send = false; BlockMap::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { if (chainActive.Contains(mi->second)) { send = true; } else { // To prevent fingerprinting attacks, only send blocks outside of the active // chain if they are valid, and no more than a max reorg depth than the best header // chain we know about. send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) && (chainActive.Height() - mi->second->nHeight < Params().MaxReorganizationDepth()); if (!send) { LogPrintf( "ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId()); } } } // Don't send not-validated blocks if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) { try { std::list<libzerocoin::PublicCoin> pubcoins = GetPubcoinFromBlock((*mi).second); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(2000); ss << inv.hash.Get32(); ss << pubcoins.size(); for (const libzerocoin::PublicCoin &pubcoin : pubcoins) { ss << pubcoin.getValue(); } pfrom->PushMessage("pubcoins", ss); pushed = true; } catch (const std::exception &e) { PrintExceptionContinue(&e, "ProcessMessages()"); } } } } if (!pushed && inv.type == MSG_TXLOCK_VOTE) { if (mapTxLockVote.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapTxLockVote[inv.hash]; pfrom->PushMessage("txlvote", ss); pushed = true; } } if (!pushed && inv.type == MSG_TXLOCK_REQUEST) { if (mapTxLockReq.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapTxLockReq[inv.hash]; pfrom->PushMessage("ix", ss); pushed = true; } } if (!pushed && inv.type == MSG_SPORK) { if (mapSporks.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapSporks[inv.hash]; pfrom->PushMessage("spork", ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_WINNER) { if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << masternodePayments.mapMasternodePayeeVotes[inv.hash]; pfrom->PushMessage("mnw", ss); pushed = true; } } if (!pushed && inv.type == MSG_BUDGET_VOTE) { if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << budget.mapSeenMasternodeBudgetVotes[inv.hash]; pfrom->PushMessage("mvote", ss); pushed = true; } } if (!pushed && inv.type == MSG_BUDGET_PROPOSAL) { if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << budget.mapSeenMasternodeBudgetProposals[inv.hash]; pfrom->PushMessage("mprop", ss); pushed = true; } } if (!pushed && inv.type == MSG_BUDGET_FINALIZED_VOTE) { if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << budget.mapSeenFinalizedBudgetVotes[inv.hash]; pfrom->PushMessage("fbvote", ss); pushed = true; } } if (!pushed && inv.type == MSG_BUDGET_FINALIZED) { if (budget.mapSeenFinalizedBudgets.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << budget.mapSeenFinalizedBudgets[inv.hash]; pfrom->PushMessage("fbs", ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_ANNOUNCE) { if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnodeman.mapSeenMasternodeBroadcast[inv.hash]; pfrom->PushMessage("mnb", ss); pushed = true; } } if (!pushed && inv.type == MSG_MASTERNODE_PING) { if (mnodeman.mapSeenMasternodePing.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mnodeman.mapSeenMasternodePing[inv.hash]; pfrom->PushMessage("mnp", ss); pushed = true; } } if (!pushed && inv.type == MSG_DSTX) { if (mapObfuscationBroadcastTxes.count(inv.hash)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << mapObfuscationBroadcastTxes[inv.hash].tx << mapObfuscationBroadcastTxes[inv.hash].vin << mapObfuscationBroadcastTxes[inv.hash].vchSig << mapObfuscationBroadcastTxes[inv.hash].sigTime; pfrom->PushMessage("dstx", ss); pushed = true; } } if (!pushed) { vNotFound.push_back(inv); } } // Track requests for our stuff. GetMainSignals().Inventory(inv.hash); if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) break; } } pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. Currently only SPV clients actually care // about this message: it's needed when they are recursively walking the // dependencies of relevant unconfirmed transactions. SPV clients want to // do that because they want to know about (and store and rebroadcast and // risk analyze) the dependencies of transactions relevant to them, without // having to download the entire memory pool. pfrom->PushMessage("notfound", vNotFound); } } bool fRequestedSporksIDB = false; bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv, int64_t nTimeReceived) { LogPrint("net", "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, std::string("Duplicate version message")); LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; } int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->DisconnectOldProtocol(ActiveProtocol(), strCommand)) return false; if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) { vRecv >> LIMITED_STRING(pfrom->strSubVer, MAX_SUBVERSION_LENGTH); pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer); } if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (!vRecv.empty()) vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message else pfrom->fRelayTxes = true; // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString()); pfrom->fDisconnect = true; return true; } // PIVXL: We use certain sporks during IBD, so check to see if they are // available. If not, ask the first peer connected for them. // TODO: Move this to an instant broadcast of the sporks. bool fMissingSporks = !pSporkDB->SporkExists(SPORK_14_NEW_PROTOCOL_ENFORCEMENT) || !pSporkDB->SporkExists(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) || !pSporkDB->SporkExists(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) || !pSporkDB->SporkExists(SPORK_17_COLDSTAKING_ENFORCEMENT) || !pSporkDB->SporkExists(SPORK_18_ZEROCOIN_PUBLICSPEND_V4); if (fMissingSporks || !fRequestedSporksIDB){ LogPrintf("asking peer for sporks\n"); pfrom->PushMessage("getsporks"); fRequestedSporksIDB = true; } pfrom->addrLocal = addrMe; if (pfrom->fInbound && addrMe.IsRoutable()) { SeenLocal(addrMe); } // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); // Potentially mark this peer as a preferred download peer. UpdatePreferredDownload(pfrom, State(pfrom->GetId())); // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (fListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); FastRandomContext insecure_rand; if (addr.IsRoutable()) { LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr, insecure_rand); } else if (IsPeerAddrLocalGood(pfrom)) { addr.SetIP(pfrom->addrLocal); LogPrintf("ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr, insecure_rand); } } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Relay alerts { LOCK(cs_mapAlerts); for (PAIRTYPE(const uint256, CAlert) & item : mapAlerts) item.second.RelayTo(pfrom); } std::string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n", pfrom->cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->id, remoteAddr); int64_t nTimeOffset = nTime - GetTime(); pfrom->nTimeOffset = nTimeOffset; const int nTimeSlotLength = Params().TimeSlotLength(); if (abs64(nTimeOffset) < 2 * nTimeSlotLength) { pfrom->fSuccessfullyConnected = true; AddTimeData(pfrom->addr, nTimeOffset, nTimeSlotLength); } else { LogPrintf("timeOffset (%d seconds) too large. Disconnecting node %s\n", nTimeOffset, pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; CheckOffsetDisconnectedPeers(pfrom->addr); } } else if (pfrom->nVersion == 0) { // Must have a version message before anything else LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; } else if (strCommand == "verack") { pfrom->SetRecvVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION)); // Mark this node as currently connected, so we update its timestamp later. if (pfrom->fNetworkNode) { LOCK(cs_main); State(pfrom->GetId())->fCurrentlyConnected = true; } } else if (strCommand == "addr") { std::vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20); return error("message addr size() = %u", vAddr.size()); } // Store the new addresses std::vector<CAddress> vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; for (CAddress& addr : vAddr) { boost::this_thread::interruption_point(); if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64_t hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); std::multimap<uint256, CNode*> mapMix; for (CNode* pnode : vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(std::make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) FastRandomContext insecure_rand; for (std::multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr, insecure_rand); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20); return error("message inv size() = %u", vInv.size()); } LOCK(cs_main); std::vector<CInv> vToFetch; for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv& inv = vInv[nInv]; boost::this_thread::interruption_point(); pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(inv); LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id); if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK) pfrom->AskFor(inv); if (inv.type == MSG_BLOCK) { UpdateBlockAvailability(pfrom->GetId(), inv.hash); if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) { // Add this to the list of blocks to request vToFetch.push_back(inv); LogPrint("net", "getblocks (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id); } } // Track requests for our stuff GetMainSignals().Inventory(inv.hash); if (pfrom->nSendSize > (SendBufferSize() * 2)) { Misbehaving(pfrom->GetId(), 50); return error("send buffer size() = %u", pfrom->nSendSize); } } if (!vToFetch.empty()) pfrom->PushMessage("getdata", vToFetch); } else if (strCommand == "getdata") { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20); return error("message getdata size() = %u", vInv.size()); } if (fDebug || (vInv.size() != 1)) LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id); if ((fDebug && vInv.size() > 0) || (vInv.size() == 1)) LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id); pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom); } else if (strCommand == "getblocks" || strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; LOCK(cs_main); // Find the last block the caller has in the main chain CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); // Send the rest of the chain if (pindex) pindex = chainActive.Next(pindex); int nLimit = 500; LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop == uint256(0) ? "end" : hashStop.ToString(), nLimit, pfrom->id); for (; pindex; pindex = chainActive.Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "headers" && Params().HeadersFirstSyncingActive()) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; LOCK(cs_main); if (IsInitialBlockDownload()) return true; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block BlockMap::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = FindForkInGlobalIndex(chainActive, locator); if (pindex) pindex = chainActive.Next(pindex); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end std::vector<CBlock> vHeaders; int nLimit = MAX_HEADERS_RESULTS; if (fDebug) LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id); for (; pindex; pindex = chainActive.Next(pindex)) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx" || strCommand == "dstx") { std::vector<uint256> vWorkQueue; std::vector<uint256> vEraseQueue; CTransaction tx; //masternode signed transaction bool ignoreFees = false; CTxIn vin; std::vector<unsigned char> vchSig; int64_t sigTime; if (strCommand == "tx") { vRecv >> tx; } else if (strCommand == "dstx") { //these allow masternodes to publish a limited amount of free transactions vRecv >> tx >> vin >> vchSig >> sigTime; CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { if (!pmn->allowFreeTx) { //multiple peers can send us a valid masternode transaction if (fDebug) LogPrintf("dstx: Masternode sending too many transactions %s\n", tx.GetHash().ToString()); return true; } std::string strMessage = tx.GetHash().ToString() + std::to_string(sigTime); std::string errorMessage = ""; if (!CMessageSigner::VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { return error("dstx: Got bad masternode address signature %s, error: %s", vin.ToString(), errorMessage); } LogPrintf("dstx: Got Masternode transaction %s\n", tx.GetHash().ToString()); ignoreFees = true; pmn->allowFreeTx = false; if (!mapObfuscationBroadcastTxes.count(tx.GetHash())) { CObfuscationBroadcastTx dstx; dstx.tx = tx; dstx.vin = vin; dstx.vchSig = vchSig; dstx.sigTime = sigTime; mapObfuscationBroadcastTxes.insert(std::make_pair(tx.GetHash(), dstx)); } } } CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); LOCK(cs_main); bool fMissingInputs = false; bool fMissingZerocoinInputs = false; CValidationState state; mapAlreadyAskedFor.erase(inv); if (!tx.HasZerocoinSpendInputs() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs, false, ignoreFees)) { mempool.check(pcoinsTip); RelayTransaction(tx); vWorkQueue.push_back(inv.hash); LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n", pfrom->id, pfrom->cleanSubVer, tx.GetHash().ToString(), mempool.mapTx.size()); // Recursively process any orphan transactions that depended on this one std::set<NodeId> setMisbehaving; for(unsigned int i = 0; i < vWorkQueue.size(); i++) { std::map<uint256, std::set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]); if(itByPrev == mapOrphanTransactionsByPrev.end()) continue; for(std::set<uint256>::iterator mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) { const uint256 &orphanHash = *mi; const CTransaction &orphanTx = mapOrphanTransactions[orphanHash].tx; NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer; bool fMissingInputs2 = false; // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get // anyone relaying LegitTxX banned) CValidationState stateDummy; if(setMisbehaving.count(fromPeer)) continue; if(AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) { LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString()); RelayTransaction(orphanTx); vWorkQueue.push_back(orphanHash); vEraseQueue.push_back(orphanHash); } else if(!fMissingInputs2) { int nDos = 0; if(stateDummy.IsInvalid(nDos) && nDos > 0) { // Punish peer that gave us an invalid orphan tx Misbehaving(fromPeer, nDos); setMisbehaving.insert(fromPeer); LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString()); } // Has inputs but not accepted to mempool // Probably non-standard or insufficient fee/priority LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString()); vEraseQueue.push_back(orphanHash); } mempool.check(pcoinsTip); } } for (uint256 hash : vEraseQueue) EraseOrphanTx(hash); } else if (tx.HasZerocoinSpendInputs() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingZerocoinInputs, false, ignoreFees)) { //Presstab: ZCoin has a bunch of code commented out here. Is this something that should have more going on? //Also there is nothing that handles fMissingZerocoinInputs. Does there need to be? RelayTransaction(tx); LogPrint("mempool", "AcceptToMemoryPool: Zerocoinspend peer=%d %s : accepted %s (poolsz %u)\n", pfrom->id, pfrom->cleanSubVer, tx.GetHash().ToString(), mempool.mapTx.size()); } else if (fMissingInputs) { AddOrphanTx(tx, pfrom->GetId()); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS)); unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx); if (nEvicted > 0) LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted); } else if (pfrom->fWhitelisted) { // Always relay transactions received from whitelisted peers, even // if they are already in the mempool (allowing the node to function // as a gateway for nodes hidden behind it). RelayTransaction(tx); } if (strCommand == "dstx") { CInv inv(MSG_DSTX, tx.GetHash()); RelayInv(inv); } int nDoS = 0; if (state.IsInvalid(nDoS)) { LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(), pfrom->id, pfrom->cleanSubVer, state.GetRejectReason()); pfrom->PushMessage("reject", strCommand, state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); } } else if (strCommand == "headers" && Params().HeadersFirstSyncingActive() && !fImporting && !fReindex) // Ignore headers received while importing { std::vector<CBlockHeader> headers; // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20); return error("headers message size = %u", nCount); } headers.resize(nCount); for (unsigned int n = 0; n < nCount; n++) { vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } LOCK(cs_main); if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. return true; } CBlockIndex* pindexLast = NULL; for (const CBlockHeader& header : headers) { CValidationState state; if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) { Misbehaving(pfrom->GetId(), 20); return error("non-continuous headers sequence"); } /*TODO: this has a CBlock cast on it so that it will compile. There should be a solution for this * before headers are reimplemented on mainnet */ if (!AcceptBlockHeader((CBlock)header, state, &pindexLast)) { int nDoS; if (state.IsInvalid(nDoS)) { if (nDoS > 0) Misbehaving(pfrom->GetId(), nDoS); std::string strError = "invalid header received " + header.GetHash().ToString(); return error(strError.c_str()); } } } if (pindexLast) UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash()); if (nCount == MAX_HEADERS_RESULTS && pindexLast) { // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue // from there instead. LogPrintf("more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight); pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256(0)); } CheckBlockIndex(); } else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing { CBlock block; vRecv >> block; uint256 hashBlock = block.GetHash(); CInv inv(MSG_BLOCK, hashBlock); LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id); //sometimes we will be sent their most recent block and its not the one we want, in that case tell where we are if (!mapBlockIndex.count(block.hashPrevBlock)) { if (find(pfrom->vBlockRequested.begin(), pfrom->vBlockRequested.end(), hashBlock) != pfrom->vBlockRequested.end()) { //we already asked for this block, so lets work backwards and ask for the previous block pfrom->PushMessage("getblocks", chainActive.GetLocator(), block.hashPrevBlock); pfrom->vBlockRequested.push_back(block.hashPrevBlock); } else { //ask to sync to this block pfrom->PushMessage("getblocks", chainActive.GetLocator(), hashBlock); pfrom->vBlockRequested.push_back(hashBlock); } } else { pfrom->AddInventoryKnown(inv); CValidationState state; if (!mapBlockIndex.count(block.GetHash())) { ProcessNewBlock(state, pfrom, &block); int nDoS; if(state.IsInvalid(nDoS)) { pfrom->PushMessage("reject", strCommand, state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash); if(nDoS > 0) { TRY_LOCK(cs_main, lockMain); if(lockMain) Misbehaving(pfrom->GetId(), nDoS); } } //disconnect this node if its old protocol version pfrom->DisconnectOldProtocol(ActiveProtocol(), strCommand); } else { LogPrint("net", "%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__, block.GetHash().GetHex()); } } } else if (strCommand == "accvalue"){ if(nLocalServices & NODE_BLOOM_LIGHT_ZC) { try { int height; libzerocoin::CoinDenomination den; vRecv >> height; vRecv >> den; CBigNum bnAccValue = 0; //std::cout << "asking for checkpoint value in height: " << height << ", den: " << den << std::endl; if (!GetAccumulatorValue(height, den, bnAccValue)) { LogPrint("zpiv", "peer misbehaving for request an invalid acc checkpoint \n", __func__); Misbehaving(pfrom->GetId(), 50); } else { //std::cout << "Sending acc value, with checksum: " << GetChecksum(bnAccValue) << " for " // << bnAccValue.GetDec() << std::endl; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << bnAccValue; ss << height; pfrom->PushMessage("accvalueresponse", ss); } } catch (const std::exception& e) { // TODO: Response with an error? PrintExceptionContinue(&e, "ProcessMessages()"); } } } else if (strCommand == "genwit") { if(nLocalServices & NODE_BLOOM_LIGHT_ZC) { try { CGenWit gen; vRecv >> gen; gen.setPfrom(pfrom); if (gen.isValid(chainActive.Height())) { if (!lightWorker.addWitWork(gen)) { LogPrint("zpiv", "%s : add genwit request failed \n", __func__); CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); // Invalid request only returns the message without a result. ss << gen.getRequestNum(); pfrom->PushMessage("pubcoins", ss); } } else { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); // Invalid request only returns the message without a result. ss << gen.getRequestNum(); pfrom->PushMessage("pubcoins", ss); } } catch (const std::exception& e) { // TODO: Response with an error? PrintExceptionContinue(&e, "ProcessMessages()"); } } } // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. // Making users (which are behind NAT and can only make outgoing connections) ignore // getaddr message mitigates the attack. else if ((strCommand == "getaddr") && (pfrom->fInbound)) { pfrom->vAddrToSend.clear(); std::vector<CAddress> vAddr = addrman.GetAddr(); FastRandomContext insecure_rand; for (const CAddress& addr : vAddr) pfrom->PushAddress(addr, insecure_rand); } else if (strCommand == "mempool") { LOCK2(cs_main, pfrom->cs_filter); std::vector<uint256> vtxid; mempool.queryHashes(vtxid); std::vector<CInv> vInv; for (uint256& hash : vtxid) { CInv inv(MSG_TX, hash); CTransaction tx; bool fInMemPool = mempool.lookup(hash, tx); if (!fInMemPool) continue; // another thread removed since queryHashes, maybe... if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) || (!pfrom->pfilter)) vInv.push_back(inv); if (vInv.size() == MAX_INV_SZ) { pfrom->PushMessage("inv", vInv); vInv.clear(); } } if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "pong") { int64_t pingUsecEnd = nTimeReceived; uint64_t nonce = 0; size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; if (nAvail >= sizeof(nonce)) { vRecv >> nonce; // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (pfrom->nPingNonceSent != 0) { if (nonce == pfrom->nPingNonceSent) { // Matching pong received, this ping is no longer outstanding bPingFinished = true; int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart; if (pingUsecTime > 0) { // Successful ping time measurement, replace previous pfrom->nPingUsecTime = pingUsecTime; } else { // This should never happen sProblem = "Timing mishap"; } } else { // Nonce mismatches are normal when pings are overlapping sProblem = "Nonce mismatch"; if (nonce == 0) { // This is most likely a bug in another implementation somewhere, cancel this ping bPingFinished = true; sProblem = "Nonce zero"; } } } else { sProblem = "Unsolicited pong without ping"; } } else { // This is most likely a bug in another implementation somewhere, cancel this ping bPingFinished = true; sProblem = "Short payload"; } if (!(sProblem.empty())) { LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n", pfrom->id, pfrom->cleanSubVer, sProblem, pfrom->nPingNonceSent, nonce, nAvail); } if (bPingFinished) { pfrom->nPingNonceSent = 0; } } else if (fAlerts && strCommand == "alert") { CAlert alert; vRecv >> alert; uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); for (CNode* pnode : vNodes) alert.RelayTo(pnode); } } else { // Small DoS penalty so peers that send us lots of // duplicate/expired/invalid-signature/whatever alerts // eventually get banned. // This isn't a Misbehaving(100) (immediate ban) because the // peer might be an older or different implementation with // a different signature key, etc. LOCK(cs_main); Misbehaving(pfrom->GetId(), 10); } } } else if (!(nLocalServices & NODE_BLOOM) && (strCommand == "filterload" || strCommand == "filteradd" || strCommand == "filterclear")) { LogPrintf("bloom message=%s\n", strCommand); LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } else if (strCommand == "filterload") { CBloomFilter filter; vRecv >> filter; if (!filter.IsWithinSizeConstraints()) { // There is no excuse for sending a too-large filter LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } else { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = new CBloomFilter(filter); pfrom->pfilter->UpdateEmptyFull(); } pfrom->fRelayTxes = true; } else if (strCommand == "filteradd") { std::vector<unsigned char> vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } else { LOCK(pfrom->cs_filter); if (pfrom->pfilter) pfrom->pfilter->insert(vData); else { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } } } else if (strCommand == "filterclear") { LOCK(pfrom->cs_filter); delete pfrom->pfilter; pfrom->pfilter = new CBloomFilter(); pfrom->fRelayTxes = true; } else if (strCommand == "reject") { if (fDebug) { try { std::string strMsg; unsigned char ccode; std::string strReason; vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); std::ostringstream ss; ss << strMsg << " code " << itostr(ccode) << ": " << strReason; if (strMsg == "block" || strMsg == "tx") { uint256 hash; vRecv >> hash; ss << ": hash " << hash.ToString(); } LogPrint("net", "Reject %s\n", SanitizeString(ss.str())); } catch (const std::ios_base::failure& e) { // Avoid feedback loops by preventing reject messages from triggering a new reject message. LogPrint("net", "Unparseable reject message received\n"); } } } else { //probably one the extensions mnodeman.ProcessMessage(pfrom, strCommand, vRecv); budget.ProcessMessage(pfrom, strCommand, vRecv); masternodePayments.ProcessMessageMasternodePayments(pfrom, strCommand, vRecv); ProcessMessageSwiftTX(pfrom, strCommand, vRecv); sporkManager.ProcessSpork(pfrom, strCommand, vRecv); masternodeSync.ProcessMessage(pfrom, strCommand, vRecv); } return true; } // Note: whenever a protocol update is needed toggle between both implementations (comment out the formerly active one) // so we can leave the existing clients untouched (old SPORK will stay on so they don't see even older clients). // Those old clients won't react to the changes of the other (new) SPORK because at the time of their implementation // it was the one which was commented out int ActiveProtocol() { // SPORK_14 was used for 70917 (v3.4), commented out now. //if (sporkManager.IsSporkActive(SPORK_14_NEW_PROTOCOL_ENFORCEMENT)) // return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT; // SPORK_15 is used for 70918 (v4.0+) if (sporkManager.IsSporkActive(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2)) return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT; return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT; } // requires LOCK(cs_vRecvMsg) bool ProcessMessages(CNode* pfrom) { //if (fDebug) // LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fOk = true; if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom); // this maintains the order of responses if (!pfrom->vRecvGetData.empty()) return fOk; std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; // get next message CNetMessage& msg = *it; //if (fDebug) // LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n", // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); // end, if an incomplete message is found if (!msg.complete()) break; // at this point, any failure means we can delete the current message it++; // Scan for message start if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) { LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id); fOk = false; break; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid()) { LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id); continue; } std::string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Process message bool fRet = false; try { fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime); boost::this_thread::interruption_point(); } catch (const std::ios_base::failure& e) { pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, std::string("error parsing message")); if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id); break; } // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); return fOk; } bool SendMessages(CNode* pto, bool fSendTrickle) { { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // // Message: ping // bool pingSend = false; if (pto->fPingQueued) { // RPC ping request by user pingSend = true; } if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) { // Ping automatically sent as a latency probe & keepalive. pingSend = true; } if (pingSend) { uint64_t nonce = 0; while (nonce == 0) { GetRandBytes((unsigned char*)&nonce, sizeof(nonce)); } pto->fPingQueued = false; pto->nPingUsecStart = GetTimeMicros(); if (pto->nVersion > BIP0031_VERSION) { pto->nPingNonceSent = nonce; pto->PushMessage("ping", nonce); } else { // Peer is too old to support ping command with nonce, pong will never arrive. pto->nPingNonceSent = 0; pto->PushMessage("ping"); } } TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState() if (!lockMain) return true; // Address refresh broadcast static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { LOCK(cs_vNodes); for (CNode* pnode : vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address AdvertiseLocal(pnode); } if (!vNodes.empty()) nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { std::vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); for (const CAddress& addr : pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } CNodeState& state = *State(pto->GetId()); if (state.fShouldBan) { if (pto->fWhitelisted) LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString()); else { pto->fDisconnect = true; if (pto->addr.IsLocal()) LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString()); else { CNode::Ban(pto->addr, BanReasonNodeMisbehaving); } } state.fShouldBan = false; } for (const CBlockReject& reject : state.rejects) pto->PushMessage("reject", (std::string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock); state.rejects.clear(); // Start block sync if (pindexBestHeader == NULL) pindexBestHeader = chainActive.Tip(); bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do. if (!state.fSyncStarted && !pto->fClient && fFetch /*&& !fImporting*/ && !fReindex) { // Only actively request headers from a single peer, unless we're close to end of initial download. if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin state.fSyncStarted = true; nSyncStarted++; //CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader; //LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight); //pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256(0)); pto->PushMessage("getblocks", chainActive.GetLocator(chainActive.Tip()), uint256(0)); } } // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. if (!fReindex /*&& !fImporting && !IsInitialBlockDownload()*/) { GetMainSignals().Broadcast(); } // // Message: inventory // std::vector<CInv> vInv; std::vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); for (const CInv& inv : pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // Detect whether we're stalling int64_t nNow = GetTimeMicros(); if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { // Stalling only triggers when the block download window cannot move. During normal steady state, // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection // should only happen during initial block download. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id); pto->fDisconnect = true; } // In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval // (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to // timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link // being saturated. We only count validated in-flight blocks so peers can't advertise nonexisting block hashes // to unreasonably increase our timeout. if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) { LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id); pto->fDisconnect = true; } // // Message: getdata (blocks) // std::vector<CInv> vGetData; if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { std::vector<CBlockIndex*> vToDownload; NodeId staller = -1; FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller); for (CBlockIndex* pindex : vToDownload) { vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex); LogPrintf("Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), pindex->nHeight, pto->id); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { State(staller)->nStallingSince = nNow; LogPrint("net", "Stall started peer=%d\n", staller); } } } // // Message: getdata (non-blocks) // while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(inv)) { if (fDebug) LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; } bool CBlockUndo::WriteToDisk(CDiskBlockPos& pos, const uint256& hashBlock) { // Open history file to append CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("CBlockUndo::WriteToDisk : OpenUndoFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(Params().MessageStart()) << nSize; // Write undo data long fileOutPos = ftell(fileout.Get()); if (fileOutPos < 0) return error("CBlockUndo::WriteToDisk : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << *this; // calculate & write checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; fileout << hasher.GetHash(); return true; } bool CBlockUndo::ReadFromDisk(const CDiskBlockPos& pos, const uint256& hashBlock) { // Open history file to read CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed"); // Read block uint256 hashChecksum; try { filein >> *this; filein >> hashChecksum; } catch (const std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } // Verify checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; if (hashChecksum != hasher.GetHash()) return error("CBlockUndo::ReadFromDisk : Checksum mismatch"); return true; } std::string CBlockFileInfo::ToString() const { return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast)); } class CMainCleanup { public: CMainCleanup() {} ~CMainCleanup() { // block headers BlockMap::iterator it1 = mapBlockIndex.begin(); for (; it1 != mapBlockIndex.end(); it1++) delete (*it1).second; mapBlockIndex.clear(); // orphan transactions mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); } } instance_of_cmaincleanup;
/*========================================================================= Program: ParaView Module: pqApplyBehavior.cxx Copyright (c) 2005,2006 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #include "pqApplyBehavior.h" #include "pqActiveObjects.h" #include "pqApplicationCore.h" #include "pqDataRepresentation.h" #include "pqPipelineFilter.h" #include "pqPropertiesPanel.h" #include "pqProxyModifiedStateUndoElement.h" #include "pqRenderView.h" #include "pqServerManagerModel.h" #include "pqUndoStack.h" #include "vtkDataObject.h" #include "vtkNew.h" #include "vtkPVDataInformation.h" #include "vtkPVGeneralSettings.h" #include "vtkSMAnimationSceneProxy.h" #include "vtkSMParaViewPipelineControllerWithRendering.h" #include "vtkSMPropertyHelper.h" #include "vtkSMPVRepresentationProxy.h" #include "vtkSMSourceProxy.h" #include "vtkSMTransferFunctionManager.h" #include "vtkSMViewProxy.h" #include "vtkWeakPointer.h" #include <QtDebug> #include <QSet> #include <QList> class pqApplyBehavior::pqInternals { public: typedef QPair<vtkWeakPointer<vtkSMRepresentationProxy>, vtkWeakPointer<vtkSMViewProxy> > PairType; QList<PairType> NewlyCreatedRepresentations; }; //----------------------------------------------------------------------------- pqApplyBehavior::pqApplyBehavior(QObject* parentObject) : Superclass(parentObject), Internals(new pqApplyBehavior::pqInternals()) { } //----------------------------------------------------------------------------- pqApplyBehavior::~pqApplyBehavior() { } //----------------------------------------------------------------------------- void pqApplyBehavior::registerPanel(pqPropertiesPanel* panel) { Q_ASSERT(panel); this->connect(panel, SIGNAL(applied(pqProxy*)), SLOT(onApplied(pqProxy*))); this->connect(panel, SIGNAL(applied()), SLOT(onApplied())); } //----------------------------------------------------------------------------- void pqApplyBehavior::unregisterPanel(pqPropertiesPanel* panel) { Q_ASSERT(panel); this->disconnect(panel); } //----------------------------------------------------------------------------- void pqApplyBehavior::onApplied(pqProxy* proxy) { pqPropertiesPanel* panel = qobject_cast<pqPropertiesPanel*>(this->sender()); if (panel) { this->applied(panel, proxy); } } //----------------------------------------------------------------------------- void pqApplyBehavior::onApplied() { pqPropertiesPanel* panel = qobject_cast<pqPropertiesPanel*>(this->sender()); if (panel) { this->applied(panel); } } //----------------------------------------------------------------------------- void pqApplyBehavior::applied(pqPropertiesPanel*, pqProxy* pqproxy) { pqPipelineSource *pqsource = qobject_cast<pqPipelineSource*>(pqproxy); if (pqsource == NULL) { return; } Q_ASSERT(pqsource); if (pqsource->modifiedState() == pqProxy::UNINITIALIZED) { // if this is first apply after creation, show the data in the view. this->showData(pqsource, pqActiveObjects::instance().activeView()); // add undo-element to ensure this state change happens when // undoing/redoing. pqProxyModifiedStateUndoElement* undoElement = pqProxyModifiedStateUndoElement::New(); undoElement->SetSession(pqsource->getServer()->session()); undoElement->MadeUnmodified(pqsource); ADD_UNDO_ELEM(undoElement); undoElement->Delete(); } pqsource->setModifiedState(pqProxy::UNMODIFIED); } //----------------------------------------------------------------------------- void pqApplyBehavior::applied(pqPropertiesPanel*) { //--------------------------------------------------------------------------- // Update animation timesteps. vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; vtkSMAnimationSceneProxy::UpdateAnimationUsingDataTimeSteps( controller->GetAnimationScene( pqActiveObjects::instance().activeServer()->session())); QList<pqView*> dirty_views; //--------------------------------------------------------------------------- // find views that need updating and update them. pqServerManagerModel* smmodel = pqApplicationCore::instance()->getServerManagerModel(); foreach (pqView* view, smmodel->findItems<pqView*>()) { if (view && view->getViewProxy()->GetNeedsUpdate()) { dirty_views.push_back(view); } } //--------------------------------------------------------------------------- // Update all the views separately. This ensures that all pipelines are // up-to-date before we render as we may need to change some rendering // properties like color transfer functions before the actual render. foreach (pqView* view, dirty_views) { view->getViewProxy()->Update(); } vtkPVGeneralSettings* gsettings = vtkPVGeneralSettings::GetInstance(); foreach (const pqInternals::PairType& pair, this->Internals->NewlyCreatedRepresentations) { vtkSMRepresentationProxy* reprProxy = pair.first; vtkSMViewProxy* viewProxy = pair.second; // If not scalar coloring, we make an attempt to color using // 'vtkBlockColors' array, if present. if (vtkSMPVRepresentationProxy::SafeDownCast(reprProxy) && vtkSMPVRepresentationProxy::GetUsingScalarColoring(reprProxy) == false && reprProxy->GetRepresentedDataInformation()->GetArrayInformation( "vtkBlockColors", vtkDataObject::FIELD) != NULL) { vtkSMPVRepresentationProxy::SetScalarColoring(reprProxy, "vtkBlockColors", vtkDataObject::FIELD); if (gsettings->GetScalarBarMode() == vtkPVGeneralSettings::AUTOMATICALLY_SHOW_AND_HIDE_SCALAR_BARS) { vtkSMPVRepresentationProxy::SetScalarBarVisibility(reprProxy, viewProxy, true); } } } //--------------------------------------------------------------------------- // If user chose it, update all transfer function data range. // FIXME: This should happen for all servers available. vtkNew<vtkSMTransferFunctionManager> tmgr; int mode = gsettings->GetTransferFunctionResetMode(); switch (mode) { case vtkPVGeneralSettings::RESET_ON_APPLY: case vtkPVGeneralSettings::RESET_ON_APPLY_AND_TIMESTEP: tmgr->ResetAllTransferFunctionRangesUsingCurrentData( pqActiveObjects::instance().activeServer()->proxyManager(), false); break; case vtkPVGeneralSettings::GROW_ON_APPLY: case vtkPVGeneralSettings::GROW_ON_APPLY_AND_TIMESTEP: default: tmgr->ResetAllTransferFunctionRangesUsingCurrentData( pqActiveObjects::instance().activeServer()->proxyManager(), /*extend*/true); break; } //--------------------------------------------------------------------------- // Perform the render on visible views. foreach (pqView* view, dirty_views) { if (view->widget()->isVisible()) { view->forceRender(); } } this->Internals->NewlyCreatedRepresentations.clear(); } //----------------------------------------------------------------------------- void pqApplyBehavior::showData(pqPipelineSource* source, pqView* view) { // HACK: Skip catalyst proxies. if (source->getServer()->getResource().scheme() == "catalyst") { return; } vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; pqServerManagerModel* smmodel = pqApplicationCore::instance()->getServerManagerModel(); vtkSMViewProxy* currentViewProxy = view? view->getViewProxy() : NULL; QSet<vtkSMProxy*> updated_views; // create representations for all output ports. for (int outputPort = 0; outputPort < source->getNumberOfOutputPorts(); outputPort++) { vtkSMViewProxy* preferredView = controller->ShowInPreferredView( vtkSMSourceProxy::SafeDownCast(source->getProxy()), outputPort, currentViewProxy); if (!preferredView) { continue; } updated_views.insert(preferredView); // reset camera if this is the only visible dataset. pqView* pqPreferredView = smmodel->findItem<pqView*>(preferredView); Q_ASSERT(pqPreferredView); if (preferredView != currentViewProxy) { // implying a new view was created, always reset that. pqPreferredView->resetDisplay(); } else if (view && view->getNumberOfVisibleDataRepresentations() == 1) { // old view is being used, reset only if this is the only representation. view->resetDisplay(); } // reset interaction mode for render views. Not a huge fan, but we'll fix // this some other time. if (pqRenderView* rview = qobject_cast<pqRenderView*>(pqPreferredView)) { if (rview->getNumberOfVisibleDataRepresentations() == 1) { rview->updateInteractionMode(source->getOutputPort(outputPort)); } } if (preferredView == currentViewProxy) { // Hide input, since the data wasn't shown in a new view, but an existing // view. if (pqPipelineFilter *filter = qobject_cast<pqPipelineFilter *>(source)) { this->hideInputIfRequired(filter, view); } } vtkSMRepresentationProxy* reprProxy = preferredView->FindRepresentation( source->getSourceProxy(), outputPort); // show scalar bar, if applicable. vtkPVGeneralSettings* gsettings = vtkPVGeneralSettings::GetInstance(); if (gsettings->GetScalarBarMode() == vtkPVGeneralSettings::AUTOMATICALLY_SHOW_AND_HIDE_SCALAR_BARS) { if (vtkSMPVRepresentationProxy::GetUsingScalarColoring(reprProxy)) { vtkSMPVRepresentationProxy::SetScalarBarVisibility(reprProxy, preferredView, true); } } // Save the newly created representation for further fine-tuning in // pqApplyBehavior::applied(). this->Internals->NewlyCreatedRepresentations.push_back( pqInternals::PairType(reprProxy, preferredView)); } } //----------------------------------------------------------------------------- void pqApplyBehavior::hideInputIfRequired(pqPipelineFilter* filter, pqView* view) { int replace_input = filter->replaceInput(); if (replace_input > 0) { vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; // hide input source. QList<pqOutputPort*> inputs = filter->getAllInputs(); foreach (pqOutputPort* input, inputs) { pqDataRepresentation* inputRepr = input->getRepresentation(view); if (inputRepr) { if (replace_input == 2) { // Conditionally turn off the input. The input should be turned // off if the representation is surface and the opacity is 1. QString reprType = vtkSMPropertyHelper( inputRepr->getProxy(), "Representation", /*quiet=*/ true).GetAsString(); double opacity = vtkSMPropertyHelper( inputRepr->getProxy(), "Opacity", /*quiet=*/ true).GetAsDouble(); if ((reprType != "Surface" && reprType != "Surface With Edges") || (opacity != 0.0 && opacity < 1.0)) { continue; } } // we use the controller API so that the scalar bars are updated as // needed. controller->SetVisibility(input->getSourceProxy(), input->getPortNumber(), view->getViewProxy(), false); } } } }
/* example/example-operator-overloading.cpp -- operator overloading Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "example.h" #include <pybind11/operators.h> class Vector2 { public: Vector2(float x, float y) : x(x), y(y) { std::cout << "Value constructor" << std::endl; } Vector2(const Vector2 &v) : x(v.x), y(v.y) { std::cout << "Copy constructor" << std::endl; } Vector2(Vector2 &&v) : x(v.x), y(v.y) { std::cout << "Move constructor" << std::endl; v.x = v.y = 0; } ~Vector2() { std::cout << "Destructor." << std::endl; } std::string toString() const { return "[" + std::to_string(x) + ", " + std::to_string(y) + "]"; } void operator=(const Vector2 &v) { cout << "Assignment operator" << endl; x = v.x; y = v.y; } void operator=(Vector2 &&v) { cout << "Move assignment operator" << endl; x = v.x; y = v.y; v.x = v.y = 0; } Vector2 operator+(const Vector2 &v) const { return Vector2(x + v.x, y + v.y); } Vector2 operator-(const Vector2 &v) const { return Vector2(x - v.x, y - v.y); } Vector2 operator-(float value) const { return Vector2(x - value, y - value); } Vector2 operator+(float value) const { return Vector2(x + value, y + value); } Vector2 operator*(float value) const { return Vector2(x * value, y * value); } Vector2 operator/(float value) const { return Vector2(x / value, y / value); } Vector2& operator+=(const Vector2 &v) { x += v.x; y += v.y; return *this; } Vector2& operator-=(const Vector2 &v) { x -= v.x; y -= v.y; return *this; } Vector2& operator*=(float v) { x *= v; y *= v; return *this; } Vector2& operator/=(float v) { x /= v; y /= v; return *this; } friend Vector2 operator+(float f, const Vector2 &v) { return Vector2(f + v.x, f + v.y); } friend Vector2 operator-(float f, const Vector2 &v) { return Vector2(f - v.x, f - v.y); } friend Vector2 operator*(float f, const Vector2 &v) { return Vector2(f * v.x, f * v.y); } friend Vector2 operator/(float f, const Vector2 &v) { return Vector2(f / v.x, f / v.y); } private: float x, y; }; void init_ex_operator_overloading(py::module &m) { py::class_<Vector2>(m, "Vector2") .def(py::init<float, float>()) .def(py::self + py::self) .def(py::self + float()) .def(py::self - py::self) .def(py::self - float()) .def(py::self * float()) .def(py::self / float()) .def(py::self += py::self) .def(py::self -= py::self) .def(py::self *= float()) .def(py::self /= float()) .def(float() + py::self) .def(float() - py::self) .def(float() * py::self) .def(float() / py::self) .def("__str__", &Vector2::toString); m.attr("Vector") = m.attr("Vector2"); }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "precomp.h" extern "C" IMAGE_DOS_HEADER __ImageBase; using namespace WEX::Logging; using namespace WEX::Common; // This class is intended to test boundary conditions for: // SetConsoleActiveScreenBuffer class BufferTests { BEGIN_TEST_CLASS(BufferTests) TEST_CLASS_PROPERTY(L"IsolationLevel", L"Method") END_TEST_CLASS() TEST_METHOD(TestSetConsoleActiveScreenBufferInvalid); TEST_METHOD(TestCookedReadOnNonShareableScreenBuffer); BEGIN_TEST_METHOD(TestWritingInactiveScreenBuffer) TEST_METHOD_PROPERTY(L"Data:UseVtOutput", L"{true, false}") END_TEST_METHOD() TEST_METHOD(ScrollLargeBufferPerformance); TEST_METHOD(ChafaGifPerformance); }; void BufferTests::TestSetConsoleActiveScreenBufferInvalid() { VERIFY_WIN32_BOOL_FAILED(SetConsoleActiveScreenBuffer(INVALID_HANDLE_VALUE)); VERIFY_WIN32_BOOL_FAILED(SetConsoleActiveScreenBuffer(nullptr)); } void BufferTests::TestCookedReadOnNonShareableScreenBuffer() { Log::Comment(L"Get original handles"); const auto in = GetStdInputHandle(); const auto out = GetStdOutputHandle(); Log::Comment(L"Ensure cooked input is on (line input mode) and echoing to the screen."); DWORD inMode = 0; VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleMode(in, &inMode)); inMode |= ENABLE_LINE_INPUT; inMode |= ENABLE_ECHO_INPUT; VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleMode(in, inMode)); Log::Comment(L"Create alternate buffer that is read/writeable but not shareable."); const auto otherBuffer = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, // This says non-shareable nullptr, CONSOLE_TEXTMODE_BUFFER, nullptr); VERIFY_WIN32_BOOL_SUCCEEDED(INVALID_HANDLE_VALUE != otherBuffer); Log::Comment(L"Set the alternate buffer as active."); VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleActiveScreenBuffer(otherBuffer)); // On a cooked read with echoing, the act of reading from the buffer will cause a handle to be // taken to the active output buffer such that the cooked/line reading handler can display // what is being typed on the screen as it is being typed before the enter key is hit. // This should fail because we've denied anyone sharing access with us and we hold the primary // active handle above. Log::Comment(L"Perform a read operation to attempt to take handle to output buffer and hopefully fail."); char buffer[1]; DWORD read = 0; SetLastError(S_OK); VERIFY_WIN32_BOOL_FAILED(ReadFile(in, buffer, sizeof(buffer), &read, nullptr)); VERIFY_ARE_EQUAL(static_cast<DWORD>(ERROR_SHARING_VIOLATION), GetLastError()); Log::Comment(L"Put the buffer back."); VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleActiveScreenBuffer(out)); Log::Comment(L"Close the alternate buffer."); VERIFY_WIN32_BOOL_SUCCEEDED(CloseHandle(otherBuffer)); Sleep(2000); Log::Comment(L"Ensure that the console didn't die/crash"); VERIFY_IS_TRUE(IsConsoleStillRunning()); } void BufferTests::TestWritingInactiveScreenBuffer() { bool useVtOutput; VERIFY_SUCCEEDED_RETURN(WEX::TestExecution::TestData::TryGetValue(L"UseVtOutput", useVtOutput), L"Get whether this test should check VT output mode."); const std::wstring primary(L"You should see me"); const std::wstring alternative(L"You should NOT see me!"); const std::wstring newline(L"\n"); Log::Comment(L"Set up the output mode to either use VT processing or not (see test parameter)"); const auto out = GetStdHandle(STD_OUTPUT_HANDLE); DWORD mode; VERIFY_WIN32_BOOL_SUCCEEDED(GetConsoleMode(out, &mode)); WI_UpdateFlag(mode, ENABLE_VIRTUAL_TERMINAL_PROCESSING, useVtOutput); VERIFY_WIN32_BOOL_SUCCEEDED(SetConsoleMode(out, mode)); Log::Comment(L"Write one line of text to the active/main output buffer."); DWORD written = 0; // Ok in legacy mode, ok in modern mode VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, primary.data(), gsl::narrow<DWORD>(primary.size()), &written, nullptr)); VERIFY_ARE_EQUAL(primary.size(), written); Log::Comment(L"Write a newline character to move the cursor down to the left most cell on the next line down."); // write a newline too to move the cursor down written = 0; VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(out, newline.data(), gsl::narrow<DWORD>(newline.size()), &written, nullptr)); VERIFY_ARE_EQUAL(newline.size(), written); Log::Comment(L"Create an alternative backing screen buffer that we will NOT be setting as active."); const auto handle = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CONSOLE_TEXTMODE_BUFFER, nullptr); VERIFY_IS_NOT_NULL(handle); // Ok in legacy mode, NOT ok in modern mode. Log::Comment(L"Try to write a second line of different text but to the alternative backing screen buffer."); written = 0; VERIFY_WIN32_BOOL_SUCCEEDED(WriteConsoleW(handle, alternative.data(), gsl::narrow<DWORD>(alternative.size()), &written, nullptr)); VERIFY_ARE_EQUAL(alternative.size(), written); std::unique_ptr<wchar_t[]> primaryBuffer = std::make_unique<wchar_t[]>(primary.size()); std::unique_ptr<wchar_t[]> alternativeBuffer = std::make_unique<wchar_t[]>(alternative.size()); Log::Comment(L"Read the first line out of the main/visible screen buffer. It should contain the first thing we wrote."); DWORD read = 0; VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, primaryBuffer.get(), gsl::narrow<DWORD>(primary.size()), { 0, 0 }, &read)); VERIFY_ARE_EQUAL(primary.size(), read); VERIFY_ARE_EQUAL(String(primary.data()), String(primaryBuffer.get(), gsl::narrow<int>(primary.size()))); Log::Comment(L"Read the second line out of the main/visible screen buffer. It should be full of blanks. The second thing we wrote wasn't to this buffer so it shouldn't show."); const std::wstring alternativeExpected(alternative.size(), L'\x20'); read = 0; VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(out, alternativeBuffer.get(), gsl::narrow<DWORD>(alternative.size()), { 0, 1 }, &read)); VERIFY_ARE_EQUAL(alternative.size(), read); VERIFY_ARE_EQUAL(String(alternativeExpected.data()), String(alternativeBuffer.get(), gsl::narrow<int>(alternative.size()))); Log::Comment(L"Now read the first line from the alternative/non-visible screen buffer. It should contain the second thing we wrote."); read = 0; VERIFY_WIN32_BOOL_SUCCEEDED(ReadConsoleOutputCharacterW(handle, alternativeBuffer.get(), gsl::narrow<DWORD>(alternative.size()), { 0, 0 }, &read)); VERIFY_ARE_EQUAL(alternative.size(), read); VERIFY_ARE_EQUAL(String(alternative.data()), String(alternativeBuffer.get(), gsl::narrow<int>(alternative.size()))); } void BufferTests::ScrollLargeBufferPerformance() { // Cribbed from https://github.com/Microsoft/console/issues/279 issue report. BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"IsPerfTest", L"true") END_TEST_METHOD_PROPERTIES() const auto Out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO Info; GetConsoleScreenBufferInfo(Out, &Info); // We need a large buffer Info.dwSize.Y = 9999; SetConsoleScreenBufferSize(Out, Info.dwSize); SetConsoleCursorPosition(Out, { 0, Info.dwSize.Y - 1 }); Log::Comment(L"Working. Please wait..."); const auto count = 20; const auto WindowHeight = Info.srWindow.Bottom - Info.srWindow.Top + 1; // Set this to false to scroll the entire buffer. The issue will disappear! const auto ScrollOnlyInvisibleArea = true; const SMALL_RECT Rect{ 0, 0, Info.dwSize.X - 1, static_cast<short>(Info.dwSize.Y - (ScrollOnlyInvisibleArea ? WindowHeight : 0) - 1) }; const CHAR_INFO CharInfo{ '^', Info.wAttributes }; const auto now = std::chrono::steady_clock::now(); // Scroll the buffer 1 line up several times for (int i = 0; i != count; ++i) { ScrollConsoleScreenBuffer(Out, &Rect, nullptr, { 0, -1 }, &CharInfo); } const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - now).count(); SetConsoleCursorPosition(Out, { 0, Info.dwSize.Y - 1 }); Log::Comment(String().Format(L"%d calls took %d ms. Avg %d ms per call", count, delta, delta / count)); } void BufferTests::ChafaGifPerformance() { BEGIN_TEST_METHOD_PROPERTIES() TEST_METHOD_PROPERTY(L"IsPerfTest", L"true") END_TEST_METHOD_PROPERTIES() const auto Out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO Info; GetConsoleScreenBufferInfo(Out, &Info); // We need a large buffer Info.dwSize.Y = 9999; SetConsoleScreenBufferSize(Out, Info.dwSize); SetConsoleCursorPosition(Out, { 0 }); DWORD Mode = 0; GetConsoleMode(Out, &Mode); Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; SetConsoleMode(Out, Mode); SetConsoleOutputCP(CP_UTF8); // Taken from: https://blog.kowalczyk.info/article/zy/Embedding-binary-resources-on-Windows.html HGLOBAL res_handle = nullptr; HRSRC res; char* res_data; DWORD res_size; // NOTE: providing g_hInstance is important, NULL might not work HMODULE hModule = (HMODULE)&__ImageBase; res = FindResource(hModule, MAKEINTRESOURCE(CHAFA_CONTENT), RT_RCDATA); if (!res) { VERIFY_FAIL(L"Couldn't find resource."); return; } res_handle = LoadResource(hModule, res); if (!res_handle) { VERIFY_FAIL(L"Couldn't load resource."); return; } res_data = (char*)LockResource(res_handle); res_size = SizeofResource(hModule, res); /* you can now use the resource data */ Log::Comment(L"Working. Please wait..."); const auto now = std::chrono::steady_clock::now(); DWORD count = 0; for (DWORD pos = 0; pos < res_size; pos += 1000) { DWORD written = 0; WriteConsoleA(Out, res_data + pos, std::min<DWORD>(1000, res_size - pos), &written, nullptr); count++; } const auto delta = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - now).count(); Log::Comment(String().Format(L"%d calls took %d ms. Avg %d ms per call", count, delta, delta / count)); }
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "nnfw_api_internal.h" #include "nnfw_version.h" // Double-check enum value changes #define STATIC_ASSERT_ENUM_CHECK(ENUM, VAL) static_assert((ENUM) == (VAL), #ENUM " has changed") STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_FLOAT32, 0); STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_INT32, 1); STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_QUANT8_ASYMM, 2); STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_BOOL, 3); STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_UINT8, 4); STATIC_ASSERT_ENUM_CHECK(NNFW_TYPE_TENSOR_INT64, 5); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_NO_ERROR, 0); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_ERROR, 1); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_UNEXPECTED_NULL, 2); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_INVALID_STATE, 3); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_OUT_OF_MEMORY, 4); STATIC_ASSERT_ENUM_CHECK(NNFW_STATUS_INSUFFICIENT_OUTPUT_SIZE, 5); STATIC_ASSERT_ENUM_CHECK(NNFW_LAYOUT_NONE, 0); STATIC_ASSERT_ENUM_CHECK(NNFW_LAYOUT_CHANNELS_LAST, 1); STATIC_ASSERT_ENUM_CHECK(NNFW_LAYOUT_CHANNELS_FIRST, 2); STATIC_ASSERT_ENUM_CHECK(NNFW_INFO_ID_VERSION, 0); #undef STATIC_ASSERT_ENUM_CHECK #define NNFW_RETURN_ERROR_IF_NULL(p) \ do \ { \ if ((p) == NULL) \ return NNFW_STATUS_UNEXPECTED_NULL; \ } while (0) /* * Create a new session instance * * @param session the session to be created * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_create_session(nnfw_session **session) { NNFW_RETURN_ERROR_IF_NULL(session); *session = new (std::nothrow) nnfw_session(); if (*session == nullptr) return NNFW_STATUS_OUT_OF_MEMORY; return NNFW_STATUS_NO_ERROR; } /* * Close a session instance * * @param session the session to be closed * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_close_session(nnfw_session *session) { delete session; return NNFW_STATUS_NO_ERROR; } /* * Load model from nnpackage file or directory * * @param session nnfw_session loading the given nnpackage file/dir * @param package_file_path path to the nnpackage file or unzipped directory to be loaded * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_load_model_from_file(nnfw_session *session, const char *pacakge_file_path) { NNFW_RETURN_ERROR_IF_NULL(session); return session->load_model_from_file(pacakge_file_path); } /* * Prepare session to be ready for inference * This phase may finalize model compilation, scheduling, and additional settings. * * @param session the session to be prepared * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_prepare(nnfw_session *session) { NNFW_RETURN_ERROR_IF_NULL(session); return session->prepare(); } /* * Run inference * * @param session the session to run inference * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_run(nnfw_session *session) { NNFW_RETURN_ERROR_IF_NULL(session); return session->run(); } NNFW_STATUS nnfw_run_async(nnfw_session *session) { NNFW_RETURN_ERROR_IF_NULL(session); return session->run_async(); } NNFW_STATUS nnfw_await(nnfw_session *session) { NNFW_RETURN_ERROR_IF_NULL(session); return session->await(); } /* * Set input * * @param session session to the input is to be set * @param index index of input to be set (0-indexed) * @param type type of the input * @param buffer raw buffer for input * @param length size of bytes of input * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_set_input(nnfw_session *session, uint32_t index, NNFW_TYPE type, const void *buffer, size_t length) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_input(index, type, buffer, length); } /* * Set output * * @param session session from inference output is to be extracted * @param index index of output to be set (0-indexed) * @param type type of the output * @param buffer raw buffer for output * @param length size of bytes of output * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_set_output(nnfw_session *session, uint32_t index, NNFW_TYPE type, void *buffer, size_t length) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_output(index, type, buffer, length); } /* * Get the number of inputs * * @param[in] session session from input information is to be extracted * @param[out] number variable which the number of inputs is put into * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_input_size(nnfw_session *session, uint32_t *number) { NNFW_RETURN_ERROR_IF_NULL(session); return session->input_size(number); } /* * Get the number of outputs * * @param[in] session session from output information is to be extracted * @param[out] number variable which the number of outputs is put into * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_output_size(nnfw_session *session, uint32_t *number) { NNFW_RETURN_ERROR_IF_NULL(session); return session->output_size(number); } /* * Set the layout of an input * @note The input that does not call this has NNFW_LAYOUT_CHANNELS_LAST layout * * @param[in] session session from inference input is to be extracted * @param[in] index index of input to be set (0-indexed) * @param[in] layout layout to set to target input * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_set_input_layout(nnfw_session *session, uint32_t index, NNFW_LAYOUT layout) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_input_layout(index, layout); } /* * Set the layout of an output * @note The output that does not call this has NNFW_LAYOUT_CHANNELS_LAST layout * * @param[in] session session from inference output is to be extracted * @param[in] index index of output to be set (0-indexed) * @param[in] layout layout to set to target output * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_set_output_layout(nnfw_session *session, uint32_t index, NNFW_LAYOUT layout) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_output_layout(index, layout); } /* * Get i-th input tensor info * * @param[in] session session from input information is to be extracted * @param[in] index index of input * @param[out] tensor_info nnfw_tensor_info * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_input_tensorinfo(nnfw_session *session, uint32_t index, nnfw_tensorinfo *tensor_info) { NNFW_RETURN_ERROR_IF_NULL(session); return session->input_tensorinfo(index, tensor_info); } /* * Get i-th output tensor info * * @param[in] session session from output information is to be extracted * @param[in] index index of output * @param[out] tensor_info nnfw_tensor_info * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_output_tensorinfo(nnfw_session *session, uint32_t index, nnfw_tensorinfo *tensor_info) { NNFW_RETURN_ERROR_IF_NULL(session); return session->output_tensorinfo(index, tensor_info); } /* * Register custom operation * @param session session to register this operation * @param id operation id * @param info registration info ( eval function, etc. ) * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_register_custom_op_info(nnfw_session *session, const char *id, custom_kernel_registration_info *info) { NNFW_RETURN_ERROR_IF_NULL(session); return session->register_custom_operation(id, info->eval_function); } NNFW_STATUS nnfw_apply_tensorinfo(nnfw_session *session, uint32_t index, nnfw_tensorinfo tensor_info) { NNFW_RETURN_ERROR_IF_NULL(session); return session->apply_tensorinfo(index, tensor_info); } NNFW_STATUS nnfw_set_input_tensorinfo(nnfw_session *session, uint32_t index, const nnfw_tensorinfo *tensor_info) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_input_tensorinfo(index, tensor_info); } /* * Set available backends * * @param[in] session session to which a avilable backends are set * @param[in] backends available backends on which nnfw uses */ NNFW_STATUS nnfw_set_available_backends(nnfw_session *session, const char *backends) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_available_backends(backends); } /* * Set the operation's backend * * @param[in] session session to be modified * @param[in] op operation to be set * @param[in] backend bakcend on which operation run * * @return NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_set_op_backend(nnfw_session *session, const char *op, const char *backend) { NNFW_RETURN_ERROR_IF_NULL(session); return session->set_op_backend(op, backend); } /* * Retrieve uint32 type of nnfw information for given information ID. * * @param[in] session session to be queried on * @param[in] information ID to be queried * @param[out] val uint32 value to be returned * * @return @c NNFW_STATUS_NO_ERROR if successful */ NNFW_STATUS nnfw_query_info_u32(nnfw_session *session, NNFW_INFO_ID id, uint32_t *val) { (void)session; switch (id) { case NNFW_INFO_ID_VERSION: if (val) { *val = NNFW_VERSION; return NNFW_STATUS_NO_ERROR; } break; default: return NNFW_STATUS_ERROR; } // It should not be reached. return NNFW_STATUS_ERROR; } NNFW_STATUS nnfw_load_circle_from_buffer(nnfw_session *session, uint8_t *buffer, size_t size) { NNFW_RETURN_ERROR_IF_NULL(session); return session->load_circle_from_buffer(buffer, size); } NNFW_STATUS nnfw_input_tensorindex(nnfw_session *session, const char *tensorname, uint32_t *index) { NNFW_RETURN_ERROR_IF_NULL(session); return session->input_tensorindex(tensorname, index); } NNFW_STATUS nnfw_output_tensorindex(nnfw_session *session, const char *tensorname, uint32_t *index) { NNFW_RETURN_ERROR_IF_NULL(session); return session->output_tensorindex(tensorname, index); }
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Frontend.FrontEnd_C.OnMatchStarted // (BlueprintAuthorityOnly, Event, Public, BlueprintEvent) void AFrontEnd_C::OnMatchStarted() { static auto fn = UObject::FindObject<UFunction>("Function Frontend.FrontEnd_C.OnMatchStarted"); AFrontEnd_C_OnMatchStarted_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Frontend.FrontEnd_C.ReceiveBeginPlay // (Event, Protected, BlueprintEvent) void AFrontEnd_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function Frontend.FrontEnd_C.ReceiveBeginPlay"); AFrontEnd_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Frontend.FrontEnd_C.EnableTutorial // (BlueprintCallable, BlueprintEvent) void AFrontEnd_C::EnableTutorial() { static auto fn = UObject::FindObject<UFunction>("Function Frontend.FrontEnd_C.EnableTutorial"); AFrontEnd_C_EnableTutorial_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Frontend.FrontEnd_C.ExecuteUbergraph_FrontEnd // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void AFrontEnd_C::ExecuteUbergraph_FrontEnd(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Frontend.FrontEnd_C.ExecuteUbergraph_FrontEnd"); AFrontEnd_C_ExecuteUbergraph_FrontEnd_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
// lm/lm-lib-test.cc // // Copyright 2009-2011 Gilles Boulianne. // // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. /// @addtogroup LanguageModel /// @{ /** * @file lm-lib-test.cc * @brief Unit tests for language model code. */ #include <iostream> #include <string> #include <sstream> #include "lm/kaldi-lm.h" namespace kaldi { // hard-coded symbols (for now) #define startOfSentence "<s>" #define endOfSentence "</s>" #define epsilon "<eps>" #define MAX_SENTENCE_LENGTH 1000 /// @brief Recursively prints all complete paths starting at s and their score. static LangModelFst::LmWeight PrintCompletePath(fst::SymbolTable *pst, fst::StdVectorFst *pfst, fst::StdArc::StateId s, LangModelFst::LmWeight score) { fst::ArcIterator<fst::StdVectorFst> ai(*pfst, s); for (ai.Reset(); !ai.Done(); ai.Next()) { std::cout << pst->Find(ai.Value().ilabel) << " "; fst::StdArc::Weight w = score; // initialize with current score // reset weight to 0 if we are going through the initial state again if (s == pfst->Start()) { w = fst::StdArc::Weight::One(); } std::cout << " \tcurrent score " << w; w = fst::Times(w, ai.Value().weight); // add in value from current arc std::cout << " added arc " << ai.Value().weight; fst::StdArc::Weight fw = pfst->Final(ai.Value().nextstate); if (fw != fst::StdArc::Weight::Zero()) { w = fst::Times(w, fw); // add in destination state weight if final std::cout << " added state weight " << w << '\n'; } std::cout << '\n'; score = PrintCompletePath(pst, pfst, ai.Value().nextstate, w); } // test this after recursive call in case there are arcs out of a final state if (pfst->Final(s) == fst::StdArc::Weight::One()) { // we hit final state, stop there // std::cout << " total score: " << score << '\n'; } return score; } /// @brief Recursively prints all complete paths starting from initial state. static LangModelFst::LmWeight PrintCompletePaths(fst::SymbolTable *pst, fst::StdVectorFst *pfst) { KALDI_ASSERT(pst); KALDI_ASSERT(pfst); KALDI_ASSERT(pfst->Start() >=0); return PrintCompletePath(pst, pfst, pfst->Start(), fst::StdArc::Weight::One()); } /// @brief Creates an FST that generates any sequence of symbols /// taken from given symbol table. /// This FST is then associated with given symbol table. static fst::StdVectorFst* CreateGenFst(fst::SymbolTable *pst) { fst::StdArc::StateId initId, midId, finalId; fst::StdVectorFst *genFst = new fst::StdVectorFst; pst->AddSymbol(epsilon); // added if not there int64 boslab = pst->AddSymbol(startOfSentence); // added if not there int64 eoslab = pst->AddSymbol(endOfSentence); // added if not there genFst->SetInputSymbols(pst); genFst->SetOutputSymbols(pst); initId = genFst->AddState(); midId = genFst->AddState(); finalId = genFst->AddState(); genFst->SetStart(initId); // initial state genFst->SetFinal(finalId, fst::StdArc::Weight::One()); // final state genFst->AddArc(initId, fst::StdArc(boslab, boslab, 0, midId)); genFst->AddArc(midId, fst::StdArc(eoslab, eoslab, 0, finalId)); // add a loop for each symbol except epsilon, begin and end of sentence fst::SymbolTableIterator si(*pst); for (si.Reset(); !si.Done(); si.Next()) { if (si.Value() == boslab || si.Value() == eoslab || si.Value() == 0) continue; genFst->AddArc(midId, fst::StdArc(si.Value(), si.Value(), 0, midId)); } return genFst; } /// @brief Randomly generates ntests paths with uniform distribution. static fst::StdVectorFst* CreateRandPathFst(int n, fst::StdVectorFst *genFst) { typedef fst::UniformArcSelector<fst::StdArc> UniformSelector; int nTrials = 50; UniformSelector uniform_sel; fst::RandGenOptions<UniformSelector > opts(uniform_sel, MAX_SENTENCE_LENGTH, n); for (int i = 0; i < nTrials; i++) { fst::StdVectorFst *tmpFst = new fst::StdVectorFst; RandGen(*genFst, tmpFst, opts); if (tmpFst->Properties(fst::kCoAccessible, true)) { // std::cout << "Got valid random path after " << i << " tries" << '\n'; return tmpFst; } // not good, try another delete tmpFst; } // couldn't generate it within allowed trials std::cerr << " Warning: couldn't generate complete paths within " << nTrials; std::cerr << " trials and " << MAX_SENTENCE_LENGTH << " max length" << '\n'; return NULL; } /// @brief Tests if all paths generated from genFst are included in testFst. static bool coverageTests(fst::StdVectorFst *genFst, fst::StdVectorFst *testFst, int ntests) { bool success = true; #ifdef KALDI_PARANOID KALDI_ASSERT(genFst != NULL); KALDI_ASSERT(testFst != NULL); #endif std::cout << "Generating " << ntests << " tests"; std::cout.flush(); // randomly generate ntests paths with uniform distribution fst::StdVectorFst *pathFst = CreateRandPathFst(ntests, genFst); if (!pathFst) return false; // compose paths with language model fst fst::StdVectorFst *outFst = new fst::StdVectorFst; // std::cout << "Path FST " << '\n'; // printFirstCompletePath(pst, pathFst, pathFst->Start()); Compose(*pathFst, *testFst, outFst); // Composition result must have ntests arcs out of initial state int narcs = outFst->NumArcs(outFst->Start()); std::cout << ", composition has " << narcs << " arcs out of start state" << '\n'; if (narcs != ntests) success = false; // std::cout << "Out FST " << '\n'; // printFirstCompletePath(pst, outFst, outFst->Start()); delete pathFst; delete outFst; return success; } /// @brief Tests read and write methods. bool TestLmTableReadWrite(int nTests, const string &infile, const string &outfile) { bool success = true; // reading test: create a language model FST from input file std::cout << "LangModelFst test: read file " << infile << '\n'; LangModelFst lm; if (!lm.Read(infile, kArpaLm)) return false; // first create an FST that generates // any sequence of symbols taken from symbol table fst::StdVectorFst *genFst = CreateGenFst(lm.GetFst()->MutableInputSymbols()); // see if path generated in this FST are covered by the LM FST std::cout << "For any sequence of symbols found in symbol table:" << '\n'; if (coverageTests(genFst, lm.GetFst(), nTests)) { std::cout << "PASSED"; } else { std::cout << "FAILED"; success = false; } std::cout <<'\n'; // writing test: write out FST, read it back in a new lm // reading doesn't provide symbol tables automatically ? std::cout << "LangModelFst test: write to " << outfile; std::cout << " and read it back" << '\n'; // std::cout << "lm input symbol table:" << '\n'; // lm.GetFst()->InputSymbols()->WriteText(std::cout); // std::cout << "lm output symbol table:" << '\n'; // lm.GetFst()->OutputSymbols()->WriteText(std::cout); lm.Write(outfile); std::cout << "LangModelFst test: read from " << outfile << '\n'; LangModelFst lm2; if (!lm2.Read(outfile, kFst)) return false; // std::cout << "lm2 output symbol table:" << '\n'; // lm2.GetFst()->InputSymbols()->WriteText(std::cout); // std::cout << "lm2 output symbol table:" << '\n'; // lm2.GetFst()->OutputSymbols()->WriteText(std::cout); // generate random sequences from the original LM // and see if they are covered by the FST that was just read std::cout << "For any complete path in original LM:" << '\n'; if (coverageTests(lm.GetFst(), lm2.GetFst(), nTests)) { std::cout << "PASSED"; } else { std::cout << "FAILED"; success = false; } std::cout <<'\n'; delete genFst; return success; } /// @brief Tests correctness of path weights. bool TestLmTableEvalScore(const string &inpfile, const string &intext, const string &refScoreFile) { bool success = true; // read in reference score std::ifstream strm(refScoreFile.c_str(), std::ifstream::in); LangModelFst::LmWeight refScore; strm >> refScore; std::cout << "Reference score is " << refScore << '\n'; std::cout << "LangModelFst test: score text strings with LM " << intext << '\n'; // use original log base for testing LangModelFst lm; if (!lm.Read(inpfile, kArpaLm, NULL, false)) return false; std::cout << "LangModelFst test: read text strings " << intext << '\n'; // here specify symbol table to be used so composition works LangModelFst txtString; if (!txtString.Read(intext, kTextString, lm.GetFst()->MutableInputSymbols())) { return false; } // PrintCompletePaths(txtString.GetFst()->InputSymbols(), txtString.GetFst()); // std::cout << "Fst string input symbol table:" << '\n'; // txtString.GetFst()->OutputSymbols()->WriteText(std::cout); // std::cout << "Fst string output symbol table:" << '\n'; // txtString.GetFst()->OutputSymbols()->WriteText(std::cout); // compose paths with language model fst fst::StdVectorFst composedFst; fst::ComposeFstOptions < fst::StdArc, fst::Matcher<fst::StdFst >, fst::MatchComposeFilter< fst::Matcher<fst::StdFst > > > copts; copts.gc_limit = 0; // Cache only the last state for fastest copy. composedFst = fst::ComposeFst<fst::StdArc>(*txtString.GetFst(), *lm.GetFst(), copts); composedFst.Write("composed.fst"); // find best path score fst::StdVectorFst *bestFst = new fst::StdVectorFst; fst::ShortestPath(composedFst, bestFst, 1); std::cout << "Best path has " << bestFst->NumStates() << " states" << '\n'; LangModelFst::LmWeight testScore = PrintCompletePaths( bestFst->MutableInputSymbols(), bestFst); std::cout << "Complete path score is " << testScore << '\n'; if (testScore.Value() <= refScore.Value()) { std::cout << "PASSED"; } else { std::cout << "FAILED"; success = false; } std::cout <<'\n'; delete bestFst; unlink("composed.fst"); return success; } } // end namespace kaldi int main(int argc, char *argv[]) { int ntests; bool success = true; std::string infile = "input.arpa"; std::string outfile = "output.fst"; // Note that for these tests to work, language models must be acceptors // (i.e. have same symbol table for input and output) since we // compose them with one another ntests = 20; std::cout << "Testing small arpa file with missing backoffs" << '\n'; infile = "missing_backoffs.arpa"; success &= kaldi::TestLmTableReadWrite(ntests, infile, outfile); std::cout << "Testing small arpa file with unused backoffs" << '\n'; infile = "unused_backoffs.arpa"; success &= kaldi::TestLmTableReadWrite(ntests, infile, outfile); std::cout << "Testing normal small arpa file" << '\n'; infile = "input.arpa"; success &= kaldi::TestLmTableReadWrite(ntests, infile, outfile); ntests = 2; // note that we use latest value of 'infile' as the tested language model for (int i = 1; i <= ntests; i++) { std::ostringstream intext(""); std::ostringstream refscore(""); // these inputN.txt sentences have been scored // by an external LM tool with results in inputN.score intext << "input" << i << ".txt"; refscore << "input" << i << ".score"; success &= kaldi::TestLmTableEvalScore(infile, intext.str(), refscore.str()); } unlink("output.fst"); exit(success ? 0 : 1); } /// @}
// // page_table.hpp // #ifndef _PAGE_TABLE_HPP #define _PAGE_TABLE_HPP #include "bits.hpp" #include "debug.hpp" #include "dx/status.h" #include "dx/types.h" #include "hal/page_table_entry.hpp" #include "new.hpp" // // Every page table has exactly 1024 entries. See the Intel documentation // const uint32_t ENTRIES_PER_PAGE_TABLE = 1024; #pragma pack(1) /// /// Intel processors use a two-level paging structure. This the "page table", /// the second-level structure. /// class page_table_c; typedef page_table_c * page_table_cp; typedef page_table_cp * page_table_cpp; typedef page_table_c & page_table_cr; class page_table_c { private: page_table_entry_c entry[ ENTRIES_PER_PAGE_TABLE ]; /// /// Return the index into this page table corresponding to the given /// virtual address.. Assumes that the address lies within the memory /// range described by this page table. No side effects. /// static inline uint32_t calculate_index(const void_tp address) { uint32_t index = (intptr_t(address) & PAGE_TABLE_INDEX_MASK) >> PAGE_TABLE_INDEX_SHIFT; ASSERT(index < ENTRIES_PER_PAGE_TABLE); return(index); } protected: public: page_table_c() { ASSERT(sizeof(*this) == sizeof(uint32_t) * ENTRIES_PER_PAGE_TABLE); ASSERT(is_aligned(this, PAGE_SIZE)); return; } ~page_table_c() { return; } //@free pages, etc? /// /// Return the entry in this page table corresponding to this /// address /// page_table_entry_cp find_entry(const void_tp address) { uint32_t index = calculate_index(address); return(&entry[index]); } /// /// Starting at given virtual address, scan through the page table /// looking for the first page marked "present" /// /// @param address -- the virtual address where the search should /// begin; on success, this value contains the virtual address where /// the search succeeded /// /// @return a pointer to the first present/valid entry at or beyond /// the starting address; or NULL if all remaining entries are invalid. /// page_table_entry_cp find_present_entry(void_tpp address) { page_table_entry_cp present_entry = NULL; uint32_t index = calculate_index(*address); uint8_tp page = uint8_tp(*address); // Scan all of the remaining entries in this page table while(index < ENTRIES_PER_PAGE_TABLE) { if (entry[index].is_present()) { // This page is present/valid, so return its address // and its corresponding page table entry to the caller *address = page; present_entry = &entry[index]; break; } // The current page is not-present, so keep searching index++; page += PAGE_SIZE; } return(present_entry); } /// /// Page tables must always be page-aligned; and should be zero'd /// so that the CPU does not mistake their prior contents entries in /// the table. As a convenience, and to avoid allocation errors, /// automatically inject the required new() flags. The default /// ::delete() can reclaim this memory on deletion. /// static void_tp operator new(size_t size) { ASSERT(size == sizeof(page_table_c)); return ::operator new(size, MEMORY_ZERO | MEMORY_ALIGN_PAGE); } }; #pragma pack() #endif
#include "face.hpp" #include "face_types.hpp" extern "C" { Result<cv::Ptr<cv::face::BIF>*> cv_face_createBIF_int_int(int num_bands, int num_rotations) { try { cv::Ptr<cv::face::BIF> ret = cv::face::createBIF(num_bands, num_rotations); return Ok(new cv::Ptr<cv::face::BIF>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::face::BIF>*>)) } Result<cv::Ptr<cv::face::BasicFaceRecognizer>*> cv_face_createEigenFaceRecognizer_int_double(int num_components, double threshold) { try { cv::Ptr<cv::face::BasicFaceRecognizer> ret = cv::face::createEigenFaceRecognizer(num_components, threshold); return Ok(new cv::Ptr<cv::face::BasicFaceRecognizer>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::face::BasicFaceRecognizer>*>)) } Result<cv::Ptr<cv::face::BasicFaceRecognizer>*> cv_face_createFisherFaceRecognizer_int_double(int num_components, double threshold) { try { cv::Ptr<cv::face::BasicFaceRecognizer> ret = cv::face::createFisherFaceRecognizer(num_components, threshold); return Ok(new cv::Ptr<cv::face::BasicFaceRecognizer>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::face::BasicFaceRecognizer>*>)) } Result<cv::Ptr<cv::face::LBPHFaceRecognizer>*> cv_face_createLBPHFaceRecognizer_int_int_int_int_double(int radius, int neighbors, int grid_x, int grid_y, double threshold) { try { cv::Ptr<cv::face::LBPHFaceRecognizer> ret = cv::face::createLBPHFaceRecognizer(radius, neighbors, grid_x, grid_y, threshold); return Ok(new cv::Ptr<cv::face::LBPHFaceRecognizer>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::face::LBPHFaceRecognizer>*>)) } Result<int> cv_face_BIF_getNumBands_const(const cv::face::BIF* instance) { try { int ret = instance->getNumBands(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result<int> cv_face_BIF_getNumRotations_const(const cv::face::BIF* instance) { try { int ret = instance->getNumRotations(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_BIF_compute_const_const__InputArrayR_const__OutputArrayR(const cv::face::BIF* instance, const cv::_InputArray* image, const cv::_OutputArray* features) { try { instance->compute(*image, *features); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_BasicFaceRecognizer_getNumComponents_const(const cv::face::BasicFaceRecognizer* instance) { try { int ret = instance->getNumComponents(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_BasicFaceRecognizer_setNumComponents_int(cv::face::BasicFaceRecognizer* instance, int val) { try { instance->setNumComponents(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<double> cv_face_BasicFaceRecognizer_getThreshold_const(const cv::face::BasicFaceRecognizer* instance) { try { double ret = instance->getThreshold(); return Ok<double>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result_void cv_face_BasicFaceRecognizer_setThreshold_double(cv::face::BasicFaceRecognizer* instance, double val) { try { instance->setThreshold(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<std::vector<cv::Mat>*> cv_face_BasicFaceRecognizer_getProjections_const(const cv::face::BasicFaceRecognizer* instance) { try { std::vector<cv::Mat> ret = instance->getProjections(); return Ok(new std::vector<cv::Mat>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<std::vector<cv::Mat>*>)) } Result<cv::Mat*> cv_face_BasicFaceRecognizer_getLabels_const(const cv::face::BasicFaceRecognizer* instance) { try { cv::Mat ret = instance->getLabels(); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result<cv::Mat*> cv_face_BasicFaceRecognizer_getEigenValues_const(const cv::face::BasicFaceRecognizer* instance) { try { cv::Mat ret = instance->getEigenValues(); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result<cv::Mat*> cv_face_BasicFaceRecognizer_getEigenVectors_const(const cv::face::BasicFaceRecognizer* instance) { try { cv::Mat ret = instance->getEigenVectors(); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result<cv::Mat*> cv_face_BasicFaceRecognizer_getMean_const(const cv::face::BasicFaceRecognizer* instance) { try { cv::Mat ret = instance->getMean(); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result_void cv_face_FaceRecognizer_train_const__InputArrayR_const__InputArrayR(cv::face::FaceRecognizer* instance, const cv::_InputArray* src, const cv::_InputArray* labels) { try { instance->train(*src, *labels); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_update_const__InputArrayR_const__InputArrayR(cv::face::FaceRecognizer* instance, const cv::_InputArray* src, const cv::_InputArray* labels) { try { instance->update(*src, *labels); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_FaceRecognizer_predict_const_const__InputArrayR(const cv::face::FaceRecognizer* instance, const cv::_InputArray* src) { try { int ret = instance->predict(*src); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_FaceRecognizer_predict_const_const__InputArrayR_intR_doubleR(const cv::face::FaceRecognizer* instance, const cv::_InputArray* src, int* label, double* confidence) { try { instance->predict(*src, *label, *confidence); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_predict_const_const__InputArrayR_Ptr_PredictCollector_(const cv::face::FaceRecognizer* instance, const cv::_InputArray* src, cv::Ptr<cv::face::PredictCollector>* collector) { try { instance->predict(*src, *collector); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_save_const_const_StringR(const cv::face::FaceRecognizer* instance, const char* filename) { try { instance->save(cv::String(filename)); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_load_const_StringR(cv::face::FaceRecognizer* instance, const char* filename) { try { instance->load(cv::String(filename)); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_save_const_FileStorageR(const cv::face::FaceRecognizer* instance, cv::FileStorage* fs) { try { instance->save(*fs); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_load_const_FileStorageR(cv::face::FaceRecognizer* instance, const cv::FileStorage* fs) { try { instance->load(*fs); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result_void cv_face_FaceRecognizer_setLabelInfo_int_const_StringR(cv::face::FaceRecognizer* instance, int label, const char* strInfo) { try { instance->setLabelInfo(label, cv::String(strInfo)); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<void*> cv_face_FaceRecognizer_getLabelInfo_const_int(const cv::face::FaceRecognizer* instance, int label) { try { cv::String ret = instance->getLabelInfo(label); return Ok(ocvrs_create_string(ret.c_str())); } OCVRS_CATCH(OCVRS_TYPE(Result<void*>)) } Result<std::vector<int>*> cv_face_FaceRecognizer_getLabelsByString_const_const_StringR(const cv::face::FaceRecognizer* instance, const char* str) { try { std::vector<int> ret = instance->getLabelsByString(cv::String(str)); return Ok(new std::vector<int>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<std::vector<int>*>)) } Result<double> cv_face_FaceRecognizer_getThreshold_const(const cv::face::FaceRecognizer* instance) { try { double ret = instance->getThreshold(); return Ok<double>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result_void cv_face_FaceRecognizer_setThreshold_double(cv::face::FaceRecognizer* instance, double val) { try { instance->setThreshold(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_LBPHFaceRecognizer_getGridX_const(const cv::face::LBPHFaceRecognizer* instance) { try { int ret = instance->getGridX(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_LBPHFaceRecognizer_setGridX_int(cv::face::LBPHFaceRecognizer* instance, int val) { try { instance->setGridX(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_LBPHFaceRecognizer_getGridY_const(const cv::face::LBPHFaceRecognizer* instance) { try { int ret = instance->getGridY(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_LBPHFaceRecognizer_setGridY_int(cv::face::LBPHFaceRecognizer* instance, int val) { try { instance->setGridY(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_LBPHFaceRecognizer_getRadius_const(const cv::face::LBPHFaceRecognizer* instance) { try { int ret = instance->getRadius(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_LBPHFaceRecognizer_setRadius_int(cv::face::LBPHFaceRecognizer* instance, int val) { try { instance->setRadius(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<int> cv_face_LBPHFaceRecognizer_getNeighbors_const(const cv::face::LBPHFaceRecognizer* instance) { try { int ret = instance->getNeighbors(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result_void cv_face_LBPHFaceRecognizer_setNeighbors_int(cv::face::LBPHFaceRecognizer* instance, int val) { try { instance->setNeighbors(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<double> cv_face_LBPHFaceRecognizer_getThreshold_const(const cv::face::LBPHFaceRecognizer* instance) { try { double ret = instance->getThreshold(); return Ok<double>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result_void cv_face_LBPHFaceRecognizer_setThreshold_double(cv::face::LBPHFaceRecognizer* instance, double val) { try { instance->setThreshold(val); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<std::vector<cv::Mat>*> cv_face_LBPHFaceRecognizer_getHistograms_const(const cv::face::LBPHFaceRecognizer* instance) { try { std::vector<cv::Mat> ret = instance->getHistograms(); return Ok(new std::vector<cv::Mat>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<std::vector<cv::Mat>*>)) } Result<cv::Mat*> cv_face_LBPHFaceRecognizer_getLabels_const(const cv::face::LBPHFaceRecognizer* instance) { try { cv::Mat ret = instance->getLabels(); return Ok(new cv::Mat(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Mat*>)) } Result_void cv_face_PredictCollector_init_size_t(cv::face::PredictCollector* instance, size_t size) { try { instance->init(size); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<bool> cv_face_PredictCollector_collect_int_double(cv::face::PredictCollector* instance, int label, double dist) { try { bool ret = instance->collect(label, dist); return Ok<bool>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<bool>)) } void cv_StandardCollector_delete(cv::face::StandardCollector* instance) { delete instance; } Result<cv::face::StandardCollector*> cv_face_StandardCollector_StandardCollector_double(double threshold_) { try { cv::face::StandardCollector* ret = new cv::face::StandardCollector(threshold_); return Ok<cv::face::StandardCollector*>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::face::StandardCollector*>)) } Result_void cv_face_StandardCollector_init_size_t(cv::face::StandardCollector* instance, size_t size) { try { instance->init(size); return Ok(); } OCVRS_CATCH(OCVRS_TYPE(Result_void)) } Result<bool> cv_face_StandardCollector_collect_int_double(cv::face::StandardCollector* instance, int label, double dist) { try { bool ret = instance->collect(label, dist); return Ok<bool>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<bool>)) } Result<int> cv_face_StandardCollector_getMinLabel_const(const cv::face::StandardCollector* instance) { try { int ret = instance->getMinLabel(); return Ok<int>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<int>)) } Result<double> cv_face_StandardCollector_getMinDist_const(const cv::face::StandardCollector* instance) { try { double ret = instance->getMinDist(); return Ok<double>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<double>)) } Result<cv::Ptr<cv::face::StandardCollector>*> cv_face_StandardCollector_create_double(double threshold) { try { cv::Ptr<cv::face::StandardCollector> ret = cv::face::StandardCollector::create(threshold); return Ok(new cv::Ptr<cv::face::StandardCollector>(ret)); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::Ptr<cv::face::StandardCollector>*>)) } Result<cv::face::StandardCollector::PredictResult> cv_face_StandardCollector_PredictResult_PredictResult_int_double(int label_, double distance_) { try { cv::face::StandardCollector::PredictResult ret(label_, distance_); return Ok<cv::face::StandardCollector::PredictResult>(ret); } OCVRS_CATCH(OCVRS_TYPE(Result<cv::face::StandardCollector::PredictResult>)) } }
//==----- accessor_property_list.hpp --- SYCL accessor property list -------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #pragma once #include <CL/sycl/detail/defines_elementary.hpp> __SYCL_WARNING("CL/sycl/ONEAPI/accessor_property_list.hpp usage is " "deprecated, include " "sycl/ext/oneapi/accessor_property_list.hpp instead") #include <sycl/ext/oneapi/accessor_property_list.hpp>
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <valarray> // template<class T> class valarray; // template<class T> // valarray<bool> // operator||(const T& x, const valarray<T>& y); #include <valarray> #include <cassert> #include <cstddef> #include "test_macros.h" int main(int, char**) { { typedef int T; T a2[] = {1, 2, 3, 4, 0}; bool a3[] = {true, true, true, true, true}; const unsigned N = sizeof(a2)/sizeof(a2[0]); std::valarray<T> v2(a2, N); std::valarray<bool> v3 = 5 || v2; assert(v2.size() == v3.size()); for (std::size_t i = 0; i < v3.size(); ++i) assert(v3[i] == a3[i]); } { typedef int T; T a2[] = {1, 2, 3, 4, 0}; bool a3[] = {true, true, true, true, false}; const unsigned N = sizeof(a2)/sizeof(a2[0]); std::valarray<T> v2(a2, N); std::valarray<bool> v3 = 0 || v2; assert(v2.size() == v3.size()); for (std::size_t i = 0; i < v3.size(); ++i) assert(v3[i] == a3[i]); } return 0; }
// =========================================================================== // 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 2017 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/memory/amount_of_physical_memory.hpp" #include <unistd.h> namespace breath_ns { long long amount_of_physical_memory() { long const pages = sysconf( _SC_PHYS_PAGES ) ; long const page_size = sysconf( _SC_PAGE_SIZE ) ; return static_cast< long long >( pages ) * static_cast< long long >( page_size ) / 1024 ; } } // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
#include "simit-test.h" #include "init.h" #include "graph.h" using namespace std; using namespace simit; TEST(system, add) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_swapped_vectors) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_func) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_func_results) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_named_tuples) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_blocked) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b.set(v0, 1.0); b.set(v1, 2.0); b.set(v2, 3.0); Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e.set(e0, 1.0); e.set(e1, 2.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); // Check that outputs are correct ASSERT_EQ(6.0, a.get(v0)); ASSERT_EQ(22.0, a.get(v1)); ASSERT_EQ(26.0, a.get(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(v0)); ASSERT_EQ(2.0, b.get(v1)); ASSERT_EQ(3.0, b.get(v2)); } TEST(system, add_blocked_inout) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b.set(v0, 1.0); b.set(v1, 2.0); b.set(v2, 3.0); Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e.set(e0, 1.0); e.set(e1, 2.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); // Check that outputs are correct ASSERT_EQ(6.0, a.get(v0)); ASSERT_EQ(22.0, a.get(v1)); ASSERT_EQ(26.0, a.get(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(v0)); ASSERT_EQ(2.0, b.get(v1)); ASSERT_EQ(3.0, b.get(v2)); } TEST(system, add_double_blocked) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b.set(v0, 1.0); b.set(v1, 2.0); b.set(v2, 3.0); Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e.set(e0, 1.0); e.set(e1, 2.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); // Check that outputs are correct ASSERT_EQ(12.0, a.get(v0)); ASSERT_EQ(44.0, a.get(v1)); ASSERT_EQ(52.0, a.get(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(v0)); ASSERT_EQ(2.0, b.get(v1)); ASSERT_EQ(3.0, b.get(v2)); } TEST(system, add_stencil) { // Points Set points; FieldRef<simit_float> b = points.addField<simit_float>("b"); FieldRef<simit_float> c = points.addField<simit_float>("c"); // Springs Set springs(points,{3,2}); // rectangular grid FieldRef<simit_float> a = springs.addField<simit_float>("a"); // Build points ElementRef p00 = springs.getGridPoint({0,0}); ElementRef p01 = springs.getGridPoint({1,0}); ElementRef p02 = springs.getGridPoint({2,0}); ElementRef p10 = springs.getGridPoint({0,1}); ElementRef p11 = springs.getGridPoint({1,1}); ElementRef p12 = springs.getGridPoint({2,1}); b.set(p00, 1.0); b.set(p01, 2.0); b.set(p02, 3.0); b.set(p10, 4.0); b.set(p11, 5.0); b.set(p12, 6.0); // Taint c c.set(p00, 42.0); c.set(p12, 42.0); // Build springs ElementRef s000 = springs.getGridEdge({0,0},0); ElementRef s001 = springs.getGridEdge({1,0},0); ElementRef s002 = springs.getGridEdge({2,0},0); ElementRef s010 = springs.getGridEdge({0,1},0); ElementRef s011 = springs.getGridEdge({1,1},0); ElementRef s012 = springs.getGridEdge({2,1},0); ElementRef s100 = springs.getGridEdge({0,0},1); ElementRef s101 = springs.getGridEdge({1,0},1); ElementRef s102 = springs.getGridEdge({2,0},1); ElementRef s110 = springs.getGridEdge({0,1},1); ElementRef s111 = springs.getGridEdge({1,1},1); ElementRef s112 = springs.getGridEdge({2,1},1); a.set(s000, 1.0); a.set(s001, 2.0); a.set(s002, 3.0); a.set(s010, 4.0); a.set(s011, 5.0); a.set(s012, 6.0); a.set(s100, 7.0); a.set(s101, 8.0); a.set(s102, 9.0); a.set(s110, 10.0); a.set(s111, 11.0); a.set(s112, 12.0); // Build springs 2 Set springs2(points,points); FieldRef<simit_float> a2 = springs2.addField<simit_float>("a"); ElementRef t0 = springs2.add(p00,p12); ElementRef t1 = springs2.add(p10,p02); a2.set(t0, 0.5); a2.set(t1, 1.5); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("points", &points); func.bind("springs", &springs); func.bind("springs2", &springs2); func.runSafe(); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(p00)); ASSERT_EQ(2.0, b.get(p01)); ASSERT_EQ(3.0, b.get(p02)); ASSERT_EQ(4.0, b.get(p10)); ASSERT_EQ(5.0, b.get(p11)); ASSERT_EQ(6.0, b.get(p12)); // Check that outputs are correct ASSERT_EQ(103.5, (simit_float)c.get(p00)); ASSERT_EQ(146.0, (simit_float)c.get(p01)); ASSERT_EQ(221.5, (simit_float)c.get(p02)); ASSERT_EQ(191.5, (simit_float)c.get(p10)); ASSERT_EQ(224.0, (simit_float)c.get(p11)); ASSERT_EQ(307.5, (simit_float)c.get(p12)); } TEST(system, DISABLED_add_stencil_indexless) { // HACK: Set kIndexlessStencils to true for this type of test kIndexlessStencils = true; // Points Set points; FieldRef<simit_float> b = points.addField<simit_float>("b"); FieldRef<simit_float> c = points.addField<simit_float>("c"); // Springs Set springs(points,{3,2}); // rectangular grid FieldRef<simit_float> a = springs.addField<simit_float>("a"); // Build points ElementRef p00 = springs.getGridPoint({0,0}); ElementRef p01 = springs.getGridPoint({1,0}); ElementRef p02 = springs.getGridPoint({2,0}); ElementRef p10 = springs.getGridPoint({0,1}); ElementRef p11 = springs.getGridPoint({1,1}); ElementRef p12 = springs.getGridPoint({2,1}); b.set(p00, 1.0); b.set(p01, 2.0); b.set(p02, 3.0); b.set(p10, 4.0); b.set(p11, 5.0); b.set(p12, 6.0); // Taint c c.set(p00, 42.0); c.set(p12, 42.0); // Build springs ElementRef s000 = springs.getGridEdge({0,0},0); ElementRef s001 = springs.getGridEdge({1,0},0); ElementRef s002 = springs.getGridEdge({2,0},0); ElementRef s010 = springs.getGridEdge({0,1},0); ElementRef s011 = springs.getGridEdge({1,1},0); ElementRef s012 = springs.getGridEdge({2,1},0); ElementRef s100 = springs.getGridEdge({0,0},1); ElementRef s101 = springs.getGridEdge({1,0},1); ElementRef s102 = springs.getGridEdge({2,0},1); ElementRef s110 = springs.getGridEdge({0,1},1); ElementRef s111 = springs.getGridEdge({1,1},1); ElementRef s112 = springs.getGridEdge({2,1},1); a.set(s000, 1.0); a.set(s001, 2.0); a.set(s002, 3.0); a.set(s010, 4.0); a.set(s011, 5.0); a.set(s012, 6.0); a.set(s100, 7.0); a.set(s101, 8.0); a.set(s102, 9.0); a.set(s110, 10.0); a.set(s111, 11.0); a.set(s112, 12.0); // Build springs 2 Set springs2(points,points); FieldRef<simit_float> a2 = springs2.addField<simit_float>("a"); ElementRef t0 = springs2.add(p00,p12); ElementRef t1 = springs2.add(p10,p02); a2.set(t0, 0.5); a2.set(t1, 1.5); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("points", &points); func.bind("springs", &springs); func.bind("springs2", &springs2); func.runSafe(); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(p00)); ASSERT_EQ(2.0, b.get(p01)); ASSERT_EQ(3.0, b.get(p02)); ASSERT_EQ(4.0, b.get(p10)); ASSERT_EQ(5.0, b.get(p11)); ASSERT_EQ(6.0, b.get(p12)); // Check that outputs are correct ASSERT_EQ(103.5, (simit_float)c.get(p00)); ASSERT_EQ(146.0, (simit_float)c.get(p01)); ASSERT_EQ(221.5, (simit_float)c.get(p02)); ASSERT_EQ(191.5, (simit_float)c.get(p10)); ASSERT_EQ(224.0, (simit_float)c.get(p11)); ASSERT_EQ(307.5, (simit_float)c.get(p12)); kIndexlessStencils = false; } TEST(system, add_generics) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(26.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, add_twice) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b.set(v0, 1.0); b.set(v1, 2.0); b.set(v2, 3.0); Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e.set(e0, 1.0); e.set(e1, 2.0); Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f.set(f0, 4.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(19.0, a.get(v0)); ASSERT_EQ(13.0, a.get(v1)); ASSERT_EQ(26.0, a.get(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(v0)); ASSERT_EQ(2.0, b.get(v1)); ASSERT_EQ(3.0, b.get(v2)); } TEST(system, add_transpose) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); e(e0) = 1.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(24.0, (double)a(v0)); ASSERT_EQ(5.0, (double)a(v1)); ASSERT_EQ(28.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, gemm) { // Points Set points; FieldRef<simit_float> b = points.addField<simit_float>("b"); FieldRef<simit_float> c = points.addField<simit_float>("c"); ElementRef p0 = points.add(); ElementRef p1 = points.add(); ElementRef p2 = points.add(); b.set(p0, 1.0); b.set(p1, 2.0); b.set(p2, 3.0); c.set(p0, 22.0); c.set(p1, 35.0); c.set(p2, 42.0); // Springs Set springs(points,points); FieldRef<simit_float> a = springs.addField<simit_float>("a"); ElementRef s0 = springs.add(p0,p1); ElementRef s1 = springs.add(p1,p2); a.set(s0, 1.0); a.set(s1, 2.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("points", &points); func.bind("springs", &springs); func.runSafe(); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b.get(p0)); ASSERT_EQ(2.0, (double)b.get(p1)); ASSERT_EQ(3.0, (double)b.get(p2)); // Check that outputs are correct ASSERT_EQ(18158.0, (double)c.get(p0)); ASSERT_EQ(22674.0, (double)c.get(p1)); ASSERT_EQ(25276.0, (double)c.get(p2)); } TEST(DISABLED_system, gemm_blocked) { // Points Set points; FieldRef<simit_float,2> b = points.addField<simit_float,2>("b"); FieldRef<simit_float,2> c = points.addField<simit_float,2>("c"); FieldRef<simit_float,2,2> d = points.addField<simit_float,2,2>("d"); ElementRef p0 = points.add(); ElementRef p1 = points.add(); ElementRef p2 = points.add(); b.set(p0, {1.0, 2.0}); b.set(p1, {3.0, 4.0}); b.set(p2, {5.0, 6.0}); d.set(p0, {1.0, 2.0, 3.0, 4.0}); d.set(p1, {2.0, 3.0, 4.0, 5.0}); d.set(p2, {3.0, 4.0, 5.0, 6.0}); // Taint c c.set(p0, {42.0, 42.0}); c.set(p2, {42.0, 42.0}); // Springs Set springs(points,points); FieldRef<simit_float,2,2> a = springs.addField<simit_float,2,2>("a"); ElementRef s0 = springs.add(p0,p1); ElementRef s1 = springs.add(p1,p2); a.set(s0, {1.0, 2.0, 3.0, 4.0}); a.set(s1, {5.0, 6.0, 7.0, 8.0}); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("points", &points); func.bind("springs", &springs); func.runSafe(); // Check that outputs are correct // TODO: add support for comparing a tensorref like so: b0 == {1.0, 2.0, 3.0} TensorRef<simit_float,2> c0 = c.get(p0); ASSERT_EQ(4048.0, c0(0)); ASSERT_EQ(8288.0, c0(1)); TensorRef<simit_float,2> c1 = c.get(p1); ASSERT_EQ(13502.0, c1(0)); ASSERT_EQ(21958.0, c1(1)); TensorRef<simit_float,2> c2 = c.get(p2); ASSERT_EQ(16544.0, c2(0)); ASSERT_EQ(11120.0, c2(1)); } TEST(system, sub) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b(v0) = 1.0; b(v1) = 2.0; b(v2) = 3.0; Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e(e0) = 1.0; e(e1) = 2.0; Set F(V,V); FieldRef<simit_float> f = F.addField<simit_float>("e"); ElementRef f0 = F.add(v0,v2); f(f0) = 4.0; // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.bind("F", &F); func.runSafe(); // Check that outputs are correct ASSERT_EQ(-13.0, (double)a(v0)); ASSERT_EQ(13.0, (double)a(v1)); ASSERT_EQ(-6.0, (double)a(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, (double)b(v0)); ASSERT_EQ(2.0, (double)b(v1)); ASSERT_EQ(3.0, (double)b(v2)); } TEST(system, sub_blocked) { Set V; FieldRef<simit_float> a = V.addField<simit_float>("a"); FieldRef<simit_float> b = V.addField<simit_float>("b"); ElementRef v0 = V.add(); ElementRef v1 = V.add(); ElementRef v2 = V.add(); b.set(v0, 1.0); b.set(v1, 2.0); b.set(v2, 3.0); Set E(V,V); FieldRef<simit_float> e = E.addField<simit_float>("e"); ElementRef e0 = E.add(v0,v1); ElementRef e1 = E.add(v1,v2); e.set(e0, 1.0); e.set(e1, 2.0); // Compile program and bind arguments Function func = loadFunction(TEST_FILE_NAME, "main"); if (!func.defined()) FAIL(); func.bind("V", &V); func.bind("E", &E); func.runSafe(); // Check that outputs are correct ASSERT_EQ(-2.0, a.get(v0)); ASSERT_EQ(-6.0, a.get(v1)); ASSERT_EQ(10.0, a.get(v2)); // Check that inputs are preserved ASSERT_EQ(1.0, b.get(v0)); ASSERT_EQ(2.0, b.get(v1)); ASSERT_EQ(3.0, b.get(v2)); }
// Created on: 1995-03-09 // Created by: Laurent PAINNOT // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRep_Polygon3D_HeaderFile #define _BRep_Polygon3D_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <BRep_CurveRepresentation.hxx> #include <Standard_Boolean.hxx> class Poly_Polygon3D; class Standard_DomainError; class TopLoc_Location; class BRep_CurveRepresentation; class BRep_Polygon3D; DEFINE_STANDARD_HANDLE(BRep_Polygon3D, BRep_CurveRepresentation) //! Representation by a 3D polygon. class BRep_Polygon3D : public BRep_CurveRepresentation { public: Standard_EXPORT BRep_Polygon3D(const Handle(Poly_Polygon3D)& P, const TopLoc_Location& L); //! Returns True. Standard_EXPORT virtual Standard_Boolean IsPolygon3D() const Standard_OVERRIDE; Standard_EXPORT virtual const Handle(Poly_Polygon3D)& Polygon3D() const Standard_OVERRIDE; Standard_EXPORT virtual void Polygon3D (const Handle(Poly_Polygon3D)& P) Standard_OVERRIDE; //! Return a copy of this representation. Standard_EXPORT Handle(BRep_CurveRepresentation) Copy() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(BRep_Polygon3D,BRep_CurveRepresentation) protected: private: Handle(Poly_Polygon3D) myPolygon3D; }; #endif // _BRep_Polygon3D_HeaderFile
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2020 The PIVX developers // Copyright (c) 2021 The DECENOMY Core Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/pivx-config.h" #endif #include "qt/pivx/pivxgui.h" #include "clientmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "intro.h" #include "net.h" #include "networkstyle.h" #include "optionsmodel.h" #include "qt/pivx/splash.h" #include "qt/pivx/welcomecontentwidget.h" #include "utilitydialog.h" #include "winshutdownmonitor.h" #ifdef ENABLE_WALLET #include "paymentserver.h" #include "walletmodel.h" #endif #include "masternodeconfig.h" #include "fs.h" #include "init.h" #include "main.h" #include "rpc/server.h" #include "guiinterface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <stdint.h> #include <boost/thread.hpp> #include <QApplication> #include <QDebug> #include <QLibraryInfo> #include <QLocale> #include <QMessageBox> #include <QProcess> #include <QSettings> #include <QThread> #include <QTimer> #include <QTranslator> #include <QFontDatabase> #if defined(QT_STATICPLUGIN) #include <QtPlugin> #if defined(QT_QPA_PLATFORM_XCB) Q_IMPORT_PLUGIN(QXcbIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_WINDOWS) Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin); #elif defined(QT_QPA_PLATFORM_COCOA) Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin); #endif Q_IMPORT_PLUGIN(QSvgPlugin); Q_IMPORT_PLUGIN(QSvgIconPlugin); Q_IMPORT_PLUGIN(QGifPlugin); #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) Q_DECLARE_METATYPE(CAmount) static void InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("pivx-core", psz).toStdString(); } static QString GetLangTerritory(bool forceLangFromSetting = false) { QSettings settings; // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = QLocale::system().name(); // 2) Language from QSettings QString lang_territory_qsettings = settings.value("language", "").toString(); if (!lang_territory_qsettings.isEmpty()) lang_territory = lang_territory_qsettings; // 3) -lang command line argument lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString())); return (forceLangFromSetting) ? lang_territory_qsettings : lang_territory; } /** Set up translations */ static void initTranslations(QTranslator& qtTranslatorBase, QTranslator& qtTranslator, QTranslator& translatorBase, QTranslator& translator, bool forceLangFromSettings = false) { // Remove old translators QApplication::removeTranslator(&qtTranslatorBase); QApplication::removeTranslator(&qtTranslator); QApplication::removeTranslator(&translatorBase); QApplication::removeTranslator(&translator); // Get desired locale (e.g. "de_DE") // 1) System default language QString lang_territory = GetLangTerritory(forceLangFromSettings); // Convert to "de" only by truncating "_DE" QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) QApplication::installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in pivx.qrc) if (translatorBase.load(lang, ":/translations/")) QApplication::installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in pivx.qrc) if (translator.load(lang_territory, ":/translations/")) QApplication::installTranslator(&translator); } /* qDebug() message handler --> debug.log */ void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg) { Q_UNUSED(context); if (type == QtDebugMsg) { LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString()); } else { LogPrintf("GUI: %s\n", msg.toStdString()); } } /** Class encapsulating Peony Core startup and shutdown. * Allows running startup and shutdown in a different thread from the UI thread. */ class BitcoinCore : public QObject { Q_OBJECT public: explicit BitcoinCore(); public Q_SLOTS: void initialize(); void shutdown(); void restart(QStringList args); Q_SIGNALS: void initializeResult(int retval); void shutdownResult(int retval); void runawayException(const QString& message); private: /// Flag indicating a restart bool execute_restart; /// Pass fatal exception message to UI thread void handleRunawayException(const std::exception* e); }; /** Main PNY application object */ class BitcoinApplication : public QApplication { Q_OBJECT public: explicit BitcoinApplication(int& argc, char** argv); ~BitcoinApplication(); #ifdef ENABLE_WALLET /// Create payment server void createPaymentServer(); #endif /// parameter interaction/setup based on rules void parameterSetup(); /// Create options model void createOptionsModel(); /// Create main window void createWindow(const NetworkStyle* networkStyle); /// Create splash screen void createSplashScreen(const NetworkStyle* networkStyle); /// Create tutorial screen bool createTutorialScreen(); /// Request core initialization void requestInitialize(); /// Request core shutdown void requestShutdown(); /// Get process return value int getReturnValue() { return returnValue; } /// Get window identifier of QMainWindow (PIVXGUI) WId getMainWinId() const; public Q_SLOTS: void initializeResult(int retval); void shutdownResult(int retval); /// Handle runaway exceptions. Shows a message box with the problem and quits the program. void handleRunawayException(const QString& message); void updateTranslation(bool forceLangFromSettings = false); Q_SIGNALS: void requestedInitialize(); void requestedRestart(QStringList args); void requestedShutdown(); void stopThread(); void splashFinished(QWidget* window); private: QThread* coreThread; OptionsModel* optionsModel; ClientModel* clientModel; PIVXGUI* window; QTimer* pollShutdownTimer; #ifdef ENABLE_WALLET PaymentServer* paymentServer; WalletModel* walletModel; #endif int returnValue; QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; void startThread(); }; #include "pivx.moc" BitcoinCore::BitcoinCore() : QObject() { } void BitcoinCore::handleRunawayException(const std::exception* e) { PrintExceptionContinue(e, "Runaway exception"); Q_EMIT runawayException(QString::fromStdString(strMiscWarning)); } void BitcoinCore::initialize() { execute_restart = true; try { qDebug() << __func__ << ": Running AppInit2 in thread"; int rv = AppInit2(); Q_EMIT initializeResult(rv); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } void BitcoinCore::restart(QStringList args) { if (execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button execute_restart = false; try { qDebug() << __func__ << ": Running Restart in thread"; Interrupt(); PrepareShutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); CExplicitNetCleanup::callCleanup(); QProcess::startDetached(QApplication::applicationFilePath(), args); qDebug() << __func__ << ": Restart initiated..."; QApplication::quit(); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } } void BitcoinCore::shutdown() { try { qDebug() << __func__ << ": Running Shutdown in thread"; Interrupt(); Shutdown(); qDebug() << __func__ << ": Shutdown finished"; Q_EMIT shutdownResult(1); } catch (const std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } } BitcoinApplication::BitcoinApplication(int& argc, char** argv) : QApplication(argc, argv), coreThread(0), optionsModel(0), clientModel(0), window(0), pollShutdownTimer(0), #ifdef ENABLE_WALLET paymentServer(0), walletModel(0), #endif returnValue(0) { setQuitOnLastWindowClosed(false); } BitcoinApplication::~BitcoinApplication() { if (coreThread) { qDebug() << __func__ << ": Stopping thread"; Q_EMIT stopThread(); coreThread->wait(); qDebug() << __func__ << ": Stopped thread"; } delete window; window = 0; #ifdef ENABLE_WALLET delete paymentServer; paymentServer = 0; #endif // Delete Qt-settings if user clicked on "Reset Options" QSettings settings; if (optionsModel && optionsModel->resetSettings) { settings.clear(); settings.sync(); } delete optionsModel; optionsModel = 0; } #ifdef ENABLE_WALLET void BitcoinApplication::createPaymentServer() { paymentServer = new PaymentServer(this); } #endif void BitcoinApplication::createOptionsModel() { optionsModel = new OptionsModel(); } void BitcoinApplication::createWindow(const NetworkStyle* networkStyle) { window = new PIVXGUI(networkStyle, 0); pollShutdownTimer = new QTimer(window); connect(pollShutdownTimer, &QTimer::timeout, window, &PIVXGUI::detectShutdown); pollShutdownTimer->start(200); } void BitcoinApplication::createSplashScreen(const NetworkStyle* networkStyle) { Splash* splash = new Splash(0, networkStyle); // We don't hold a direct pointer to the splash screen after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); connect(this, &BitcoinApplication::splashFinished, splash, &Splash::slotFinish); connect(this, &BitcoinApplication::requestedShutdown, splash, &QWidget::close); } bool BitcoinApplication::createTutorialScreen() { WelcomeContentWidget* widget = new WelcomeContentWidget(); connect(widget, &WelcomeContentWidget::onLanguageSelected, [this](){ updateTranslation(true); }); widget->exec(); bool ret = widget->isOk; widget->deleteLater(); return ret; } void BitcoinApplication::updateTranslation(bool forceLangFromSettings){ // Re-initialize translations after change them initTranslations(this->qtTranslatorBase, this->qtTranslator, this->translatorBase, this->translator, forceLangFromSettings); } void BitcoinApplication::startThread() { if (coreThread) return; coreThread = new QThread(this); BitcoinCore* executor = new BitcoinCore(); executor->moveToThread(coreThread); /* communication to and from thread */ connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult); connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult); connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException); connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize); connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown); connect(window, &PIVXGUI::requestedRestart, executor, &BitcoinCore::restart); /* make sure executor object is deleted in its own thread */ connect(this, &BitcoinApplication::stopThread, executor, &QObject::deleteLater); connect(this, &BitcoinApplication::stopThread, coreThread, &QThread::quit); coreThread->start(); } void BitcoinApplication::parameterSetup() { // Default printtoconsole to false for the GUI. GUI programs should not // print to the console unnecessarily. SoftSetBoolArg("-printtoconsole", false); InitLogging(); InitParameterInteraction(); } void BitcoinApplication::requestInitialize() { qDebug() << __func__ << ": Requesting initialize"; startThread(); Q_EMIT requestedInitialize(); } void BitcoinApplication::requestShutdown() { qDebug() << __func__ << ": Requesting shutdown"; startThread(); window->hide(); window->setClientModel(0); pollShutdownTimer->stop(); #ifdef ENABLE_WALLET window->removeAllWallets(); delete walletModel; walletModel = 0; #endif delete clientModel; clientModel = 0; // Show a simple window indicating shutdown status ShutdownWindow::showShutdownWindow(window); // Request shutdown from core thread Q_EMIT requestedShutdown(); } void BitcoinApplication::initializeResult(int retval) { qDebug() << __func__ << ": Initialization result: " << retval; // Set exit result: 0 if successful, 1 if failure returnValue = retval ? 0 : 1; if (retval) { #ifdef ENABLE_WALLET PaymentServer::LoadRootCAs(); paymentServer->setOptionsModel(optionsModel); #endif clientModel = new ClientModel(optionsModel); window->setClientModel(clientModel); #ifdef ENABLE_WALLET if (pwalletMain) { walletModel = new WalletModel(pwalletMain, optionsModel); window->addWallet(PIVXGUI::DEFAULT_WALLET, walletModel); window->setCurrentWallet(PIVXGUI::DEFAULT_WALLET); connect(walletModel, &WalletModel::coinsSent, paymentServer, &PaymentServer::fetchPaymentACK); } #endif // If -min option passed, start window minimized. if (GetBoolArg("-min", false)) { window->showMinimized(); } else { window->show(); } Q_EMIT splashFinished(window); #ifdef ENABLE_WALLET // Now that initialization/startup is done, process any command-line // Peony: URIs or payment requests: //connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &PIVXGUI::handlePaymentRequest); connect(window, &PIVXGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile); connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) { window->message(title, message, style); }); QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady); #endif } else { quit(); // Exit main loop } } void BitcoinApplication::shutdownResult(int retval) { qDebug() << __func__ << ": Shutdown result: " << retval; quit(); // Exit main loop after shutdown finished } void BitcoinApplication::handleRunawayException(const QString& message) { QMessageBox::critical(0, "Runaway exception", QObject::tr("A fatal error occurred. Peony can no longer continue safely and will quit.") + QString("\n\n") + message); ::exit(1); } WId BitcoinApplication::getMainWinId() const { if (!window) return 0; return window->winId(); } #ifndef BITCOIN_QT_TEST int main(int argc, char* argv[]) { SetupEnvironment(); /// 1. Parse command-line options. These take precedence over anything else. // Command-line options take precedence: ParseParameters(argc, argv); // Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory /// 2. Basic Qt initialization (not dependent on parameters or configuration) Q_INIT_RESOURCE(pivx_locale); Q_INIT_RESOURCE(pivx); //TODO to set this up we need to review all the UI measurements to be relative to the screen DPI // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #if QT_VERSION >= 0x050600 //TODO to set this up we need to review all the UI measurements to be relative to the screen DPI QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MAC QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif BitcoinApplication app(argc, argv); // Custom fonts. QFontDatabase::addApplicationFont(":/font/Nunito-Black.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-BlackItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-Bold.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-BoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-ExtraBold.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-ExtraBoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-ExtraLight.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-ExtraLightItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-Italic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-Light.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-LightItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-Regular.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-SemiBold.ttf"); QFontDatabase::addApplicationFont(":/font/Nunito-SemiBoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Black.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-BlackItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Bold.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-BoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-ExtraBold.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-ExtraBoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-ExtraLight.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-ExtraLightItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Italic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Light.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-LightItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Regular.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-SemiBold.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-SemiBoldItalic.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-Thin.ttf"); QFontDatabase::addApplicationFont(":/font/Montserrat-ThinItalic.ttf"); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType<bool*>(); // Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType) // IMPORTANT if it is no longer a typedef use the normal variant above qRegisterMetaType<CAmount>("CAmount"); /// 3. Application identification // must be set before OptionsModel is initialized or translations are loaded, // as it is used to locate QSettings QApplication::setOrganizationName(QAPP_ORG_NAME); QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN); QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT); GUIUtil::SubstituteFonts(GetLangTerritory()); /// 4. Initialization of translations, so that intro dialog is in user's language // Now that QSettings are accessible, initialize translations //initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator); app.updateTranslation(); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { HelpMessageDialog help(NULL, mapArgs.count("-version")); help.showOrPrint(); return 1; } /// 5. Now that settings and translations are available, ask user for data directory // User language is set up: pick a data directory if (!Intro::pickDataDirectory()) return 0; /// 6. Determine availability of data directory and parse peony.conf /// - Do not call GetDataDir(true) before this step finishes if (!fs::is_directory(GetDataDir(false))) { QMessageBox::critical(0, QObject::tr("Peony"), QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (const std::exception& e) { QMessageBox::critical(0, QObject::tr("Peony"), QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what())); return 0; } /// 7. Determine network (and switch to network specific options) // - Do not call Params() before this step // - Do this after parsing the configuration file, as the network can be switched there // - QSettings() will use the new application name after this, resulting in network-specific settings // - Needs to be done before createOptionsModel // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { QMessageBox::critical(0, QObject::tr("Peony"), QObject::tr("Error: Invalid combination of -regtest and -testnet.")); return 1; } #ifdef ENABLE_WALLET // Parse URIs on command line -- this can affect Params() PaymentServer::ipcParseCommandLine(argc, argv); #endif QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString()))); assert(!networkStyle.isNull()); // Allow for separate UI settings for testnets QApplication::setApplicationName(networkStyle->getAppName()); // Re-initialize translations after changing application name (language in network-specific settings can be different) app.updateTranslation(); #ifdef ENABLE_WALLET /// 7a. parse masternode.conf std::string strErr; if (!masternodeConfig.read(strErr)) { QMessageBox::critical(0, QObject::tr("Peony"), QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str())); return 0; } /// 8. URI IPC sending // - Do this early as we don't want to bother initializing if we are just calling IPC // - Do this *after* setting up the data directory, as the data directory hash is used in the name // of the server. // - Do this after creating app and setting up translations, so errors are // translated properly. if (PaymentServer::ipcSendCommandLine()) exit(0); // Start up the payment server early, too, so impatient users that click on // peony: links repeatedly have their payment requests routed to this process: app.createPaymentServer(); #endif /// 9. Main GUI initialization // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); #if defined(Q_OS_WIN) // Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION) qApp->installNativeEventFilter(new WinShutdownMonitor()); #endif // Install qDebug() message handler to route to debug.log qInstallMessageHandler(DebugMessageHandler); // Allow parameter interaction before we create the options model app.parameterSetup(); // Load GUI settings from QSettings app.createOptionsModel(); // Subscribe to global signals from core uiInterface.InitMessage.connect(InitMessage); bool ret = true; #ifdef ENABLE_WALLET // Check if the wallet exists or need to be created std::string strWalletFile = GetArg("-wallet", DEFAULT_WALLET_DAT); std::string strDataDir = GetDataDir().string(); // Wallet file must be a plain filename without a directory fs::path wallet_file_path(strWalletFile); if (strWalletFile != wallet_file_path.filename().string()) { throw std::runtime_error(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir)); } fs::path pathBootstrap = GetDataDir() / strWalletFile; if (!fs::exists(pathBootstrap)) { // wallet doesn't exist, popup tutorial screen. ret = app.createTutorialScreen(); } #endif if(!ret){ // wallet not loaded. return 0; } if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false)) app.createSplashScreen(networkStyle.data()); try { app.createWindow(networkStyle.data()); app.requestInitialize(); #if defined(Q_OS_WIN) WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("Peony didn't yet exit safely..."), (HWND)app.getMainWinId()); #endif app.exec(); app.requestShutdown(); app.exec(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } catch (...) { PrintExceptionContinue(NULL, "Runaway exception"); app.handleRunawayException(QString::fromStdString(strMiscWarning)); } return app.getReturnValue(); } #endif // BITCOIN_QT_TEST
#define DEBUG 1 /** * File : B.cpp * Author : Kazune Takahashi * Created : 5/19/2020, 3:28:47 PM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int main() { int N, D; cin >> N >> D; vector<vector<int>> X(N, vector<int>(D)); for (auto i = 0; i < N; ++i) { for (auto j = 0; j < D; ++j) { cin >> X[i][j]; } } int ans{0}; for (auto i = 0; i < N; ++i) { for (auto j = i + 1; j < N; ++j) { int dist{0}; for (auto k = 0; k < D; ++k) { int t{X[i][k] - X[j][k]}; dist += t * t; } int norm{static_cast<int>(sqrt(dist) + 0.5)}; if (norm * norm == dist) { ++ans; } } } cout << ans << endl; }
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode.h" #include "addrman.h" #include "masternodeman.h" #include "obfuscation.h" #include "sync.h" #include "util.h" #include <boost/lexical_cast.hpp> // keep track of the scanning errors I've seen map<uint256, int> mapSeenMasternodeScanningErrors; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { if (chainActive.Tip() == NULL) return false; if (nBlockHeight == 0) nBlockHeight = chainActive.Tip()->nHeight; if (mapCacheBlockHashes.count(nBlockHeight)) { hash = mapCacheBlockHashes[nBlockHeight]; return true; } const CBlockIndex* BlockLastSolved = chainActive.Tip(); const CBlockIndex* BlockReading = chainActive.Tip(); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight) return false; int nBlocksAgo = 0; if (nBlockHeight > 0) nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight; assert(nBlocksAgo >= 0); int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nBlocksAgo) { hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } CMasternode::CMasternode() { LOCK(cs); vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternode& other) { LOCK(cs); vin = other.vin; addr = other.addr; pubKeyCollateralAddress = other.pubKeyCollateralAddress; pubKeyMasternode = other.pubKeyMasternode; sig = other.sig; activeState = other.activeState; sigTime = other.sigTime; lastPing = other.lastPing; cacheInputAge = other.cacheInputAge; cacheInputAgeBlock = other.cacheInputAgeBlock; unitTest = other.unitTest; allowFreeTx = other.allowFreeTx; nActiveState = MASTERNODE_ENABLED, protocolVersion = other.protocolVersion; nLastDsq = other.nLastDsq; nScanningErrorCount = other.nScanningErrorCount; nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight; lastTimeChecked = 0; nLastDsee = other.nLastDsee; // temporary, do not save. Remove after migration to v12 nLastDseep = other.nLastDseep; // temporary, do not save. Remove after migration to v12 } CMasternode::CMasternode(const CMasternodeBroadcast& mnb) { LOCK(cs); vin = mnb.vin; addr = mnb.addr; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; pubKeyMasternode = mnb.pubKeyMasternode; sig = mnb.sig; activeState = MASTERNODE_ENABLED; sigTime = mnb.sigTime; lastPing = mnb.lastPing; cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = MASTERNODE_ENABLED, protocolVersion = mnb.protocolVersion; nLastDsq = mnb.nLastDsq; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } // // When a new masternode broadcast is sent, update our information // bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb) { if (mnb.sigTime > sigTime) { pubKeyMasternode = mnb.pubKeyMasternode; pubKeyCollateralAddress = mnb.pubKeyCollateralAddress; sigTime = mnb.sigTime; sig = mnb.sig; protocolVersion = mnb.protocolVersion; addr = mnb.addr; lastTimeChecked = 0; int nDoS = 0; if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = mnb.lastPing; mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing)); } return true; } return false; } // // Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight) { if (chainActive.Tip() == NULL) return 0; uint256 hash = 0; uint256 aux = vin.prevout.hash + vin.prevout.n; if (!GetBlockHash(hash, nBlockHeight)) { LogPrint("masternode","CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return 0; } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } void CMasternode::Check(bool forceCheck) { if (ShutdownRequested()) return; if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return; lastTimeChecked = GetTime(); //once spent, stop doing the checks if (activeState == MASTERNODE_VIN_SPENT) return; if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) { activeState = MASTERNODE_REMOVE; return; } if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { activeState = MASTERNODE_EXPIRED; return; } if (!unitTest) { CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut((GetMstrNodCollateral(chainActive.Height())-0.01) * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { activeState = MASTERNODE_VIN_SPENT; return; } } } activeState = MASTERNODE_ENABLED; // OK } int64_t CMasternode::SecondsSincePayment() { CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); int64_t sec = (GetAdjustedTime() - GetLastPaid()); int64_t month = 60 * 60 * 24 * 30; if (sec < month) return sec; //if it's less than 30 days, give seconds CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // return some deterministic value for unknown/unpaid but force it to be more than 30 days old return month + hash.GetCompact(false); } int64_t CMasternode::GetLastPaid() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return false; CScript mnpayee; mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // use a deterministic offset to break a tie -- 2.5 minutes int64_t nOffset = hash.GetCompact(false) % 150; if (chainActive.Tip() == NULL) return false; const CBlockIndex* BlockReading = chainActive.Tip(); int nMnCount = mnodeman.CountEnabled() * 1.25; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nMnCount) { return 0; } n++; if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) { /* Search for this payee, with at least 2 votes. This will aid in consensus allowing the network to converge on the same payees quickly, then keep the same schedule. */ if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { return BlockReading->nTime + nOffset; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return 0; } std::string CMasternode::GetStatus() { switch (nActiveState) { case CMasternode::MASTERNODE_PRE_ENABLED: return "PRE_ENABLED"; case CMasternode::MASTERNODE_ENABLED: return "ENABLED"; case CMasternode::MASTERNODE_EXPIRED: return "EXPIRED"; case CMasternode::MASTERNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; case CMasternode::MASTERNODE_REMOVE: return "REMOVE"; case CMasternode::MASTERNODE_WATCHDOG_EXPIRED: return "WATCHDOG_EXPIRED"; case CMasternode::MASTERNODE_POSE_BAN: return "POSE_BAN"; default: return "UNKNOWN"; } } bool CMasternode::IsValidNetAddr() { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkID() == CBaseChainParams::REGTEST || (IsReachable(addr) && addr.IsRoutable()); } CMasternodeBroadcast::CMasternodeBroadcast() { vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyMasternode1 = CPubKey(); sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int protocolVersionIn) { vin = newVin; addr = newAddr; pubKeyCollateralAddress = pubKeyCollateralAddressNew; pubKeyMasternode = pubKeyMasternodeNew; sig = std::vector<unsigned char>(); activeState = MASTERNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = CMasternodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = protocolVersionIn; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; } CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn) { vin = mn.vin; addr = mn.addr; pubKeyCollateralAddress = mn.pubKeyCollateralAddress; pubKeyMasternode = mn.pubKeyMasternode; sig = mn.sig; activeState = mn.activeState; sigTime = mn.sigTime; lastPing = mn.lastPing; cacheInputAge = mn.cacheInputAge; cacheInputAgeBlock = mn.cacheInputAgeBlock; unitTest = mn.unitTest; allowFreeTx = mn.allowFreeTx; protocolVersion = mn.protocolVersion; nLastDsq = mn.nLastDsq; nScanningErrorCount = mn.nScanningErrorCount; nLastScanningErrorBlockHeight = mn.nLastScanningErrorBlockHeight; } bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline) { CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyMasternodeNew; CKey keyMasternodeNew; //need correct blocks to send ping if (!fOffline && !masternodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode"; LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!obfuScationSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } if (!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } CService service = CService(strService); int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if (Params().NetworkID() == CBaseChainParams::MAIN) { if (service.GetPort() != mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } } else if (service.GetPort() == mainnetDefaultPort) { strErrorRet = strprintf("Invalid port %u for masternode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; } return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet); } bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n", CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), pubKeyMasternodeNew.GetID().ToString()); CMasternodePing mnp(txin); if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) { strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION); if (!mnbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address %s, masternode=%s", mnbRet.addr.ToStringIP (), txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } mnbRet.lastPing = mnp; if (!mnbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.hash.ToString()); LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); return false; } return true; } bool CMasternodeBroadcast::CheckAndUpdate(int& nDos) { // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","mnb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion); if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) { LogPrint("masternode","mnb - ignoring outdated Masternode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrint("masternode","mnb - pubkey the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID()); if (pubkeyScript2.size() != 25) { LogPrint("masternode","mnb - pubkey2 the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrint("masternode","mnb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString()); return false; } std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) { LogPrint("masternode","mnb - Got bad Masternode address signature\n"); nDos = 100; return false; } if (Params().NetworkID() == CBaseChainParams::MAIN) { if (addr.GetPort() != 29711) return false; } else if (addr.GetPort() == 29711) return false; //search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts CMasternode* pmn = mnodeman.Find(vin); // no such masternode, nothing to update if (pmn == NULL) return true; else { // this broadcast older than we have, it's bad. if (pmn->sigTime > sigTime) { LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (existing broadcast is at %d)\n", sigTime, vin.prevout.hash.ToString(), pmn->sigTime); return false; } // masternode is not enabled yet/already, nothing to update if (!pmn->IsEnabled()) return true; } // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if (pmn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) { //take the newest entry LogPrint("masternode","mnb - Got updated entry for %s\n", vin.prevout.hash.ToString()); if (pmn->UpdateFromNewBroadcast((*this))) { pmn->Check(); if (pmn->IsEnabled()) Relay(); } masternodeSync.AddedMasternodeList(GetHash()); } return true; } bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS) { // we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us if (fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode) return true; // search existing Masternode list CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL) { // nothing to do here if we already know about this masternode and it's enabled if (pmn->IsEnabled()) return true; // if it's not enabled, remove old MN first and continue else mnodeman.Remove(pmn->vin); } CValidationState state; CMutableTransaction tx = CMutableTransaction(); CTxOut vout = CTxOut((GetMstrNodCollateral(chainActive.Height())-0.01) * COIN, obfuScationPool.collateralPubKey); tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not mnb fault, let it to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { //set nDos state.IsInvalid(nDoS); return false; } } LogPrint("masternode", "mnb - Accepted Masternode entry\n"); if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) { LogPrint("masternode","mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); // maybe we miss few blocks, let this mnb to be checked again later mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); masternodeSync.mapSeenSyncMNB.erase(GetHash()); return false; } // verify that sig time is legit in past // should be at least not earlier than block when 10000 savenode tx got MASTERNODE_MIN_CONFIRMATIONS uint256 hashBlock = 0; CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, hashBlock, true); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pMNIndex = (*mi).second; // block for 10000 savenode tx -> 1 confirmation CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS if (pConfIndex->GetBlockTime() > sigTime) { LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\n", sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime()); return false; } } LogPrint("masternode","mnb - Got NEW Masternode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime); CMasternode mn(*this); mnodeman.Add(mn); // if it matches our Masternode privkey, then we've been remotely activated if (pubKeyMasternode == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) { activeMasternode.EnableHotColdMasterNode(vin, addr); } bool isLocal = addr.IsRFC1918() || addr.IsLocal(); if (Params().NetworkID() == CBaseChainParams::REGTEST) isLocal = false; if (!isLocal) Relay(); return true; } void CMasternodeBroadcast::Relay() { CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash()); RelayInv(inv); } bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress) { std::string errorMessage; std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); sigTime = GetAdjustedTime(); std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) { LogPrint("masternode","CMasternodeBroadcast::Sign() - Error: %s\n", errorMessage); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodeBroadcast::Sign() - Error: %s\n", errorMessage); return false; } return true; } CMasternodePing::CMasternodePing() { vin = CTxIn(); blockHash = uint256(0); sigTime = 0; vchSig = std::vector<unsigned char>(); } CMasternodePing::CMasternodePing(CTxIn& newVin) { vin = newVin; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector<unsigned char>(); } bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { std::string errorMessage; std::string strMasterNodeSignMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage); return false; } return true; } bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled) { if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the past %s - %d %d \n", vin.prevout.hash.ToString(), sigTime, GetAdjustedTime()); nDos = 1; return false; } LogPrint("masternode","CMasternodePing::CheckAndUpdate - New Ping - %s - %lli\n", blockHash.ToString(), sigTime); // see if we have this Masternode CMasternode* pmn = mnodeman.Find(vin); if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) { if (fRequireEnabled && !pmn->IsEnabled()) return false; // LogPrint("masternode","mnping - Found corresponding mn for vin: %s\n", vin.ToString()); // update only if there is no known ping for this masternode or // last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) { std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime); std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Got bad Masternode address signature %s\n", vin.prevout.hash.ToString()); nDos = 33; return false; } BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi != mapBlockIndex.end() && (*mi).second) { if ((*mi).second->nHeight < chainActive.Height() - 24) { LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is too old\n", vin.prevout.hash.ToString(), blockHash.ToString()); // Do nothing here (no Masternode update, no mnping relay) // Let this node to be visible but fail to accept mnping return false; } } else { if (fDebug) LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is unknown\n", vin.prevout.hash.ToString(), blockHash.ToString()); // maybe we stuck so we shouldn't ban this node, just fail to accept it // TODO: or should we also request this block? return false; } pmn->lastPing = *this; //mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) { mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this; } pmn->Check(true); if (!pmn->IsEnabled()) return false; LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping accepted, vin: %s\n", vin.prevout.hash.ToString()); Relay(); return true; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping arrived too early, vin: %s\n", vin.prevout.hash.ToString()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Couldn't find compatible Masternode entry, vin: %s\n", vin.prevout.hash.ToString()); return false; } void CMasternodePing::Relay() { CInv inv(MSG_MASTERNODE_PING, GetHash()); RelayInv(inv); }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2010 Universita' di Firenze, Italy * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Tommaso Pecorella (tommaso.pecorella@unifi.it) * Author: Valerio Sartini (valesar@gmail.com) */ #include "ns3/log.h" #include "topology-reader.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("TopologyReader"); NS_OBJECT_ENSURE_REGISTERED (TopologyReader); TypeId TopologyReader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::TopologyReader") .SetParent<Object> () ; return tid; } TopologyReader::TopologyReader () { NS_LOG_FUNCTION (this); } TopologyReader::~TopologyReader () { NS_LOG_FUNCTION (this); } void TopologyReader::SetFileName (const std::string &fileName) { m_fileName = fileName; } std::string TopologyReader::GetFileName () const { return m_fileName; } /* Manipulating the address block */ TopologyReader::ConstLinksIterator TopologyReader::LinksBegin (void) const { return m_linksList.begin (); } TopologyReader::ConstLinksIterator TopologyReader::LinksEnd (void) const { return m_linksList.end (); } int TopologyReader::LinksSize (void) const { return m_linksList.size (); } bool TopologyReader::LinksEmpty (void) const { return m_linksList.empty (); } void TopologyReader::AddLink (Link link) { m_linksList.push_back (link); return; } TopologyReader::Link::Link ( Ptr<Node> fromPtr, const std::string &fromName, Ptr<Node> toPtr, const std::string &toName ) { m_fromPtr = fromPtr; m_fromName = fromName; m_toPtr = toPtr; m_toName = toName; } TopologyReader::Link::Link () { } Ptr<Node> TopologyReader::Link::GetFromNode (void) const { return m_fromPtr; } std::string TopologyReader::Link::GetFromNodeName (void) const { return m_fromName; } Ptr<Node> TopologyReader::Link::GetToNode (void) const { return m_toPtr; } std::string TopologyReader::Link::GetToNodeName (void) const { return m_toName; } std::string TopologyReader::Link::GetAttribute (const std::string &name) const { NS_ASSERT_MSG (m_linkAttr.find (name) != m_linkAttr.end (), "Requested topology link attribute not found"); return m_linkAttr.find (name)->second; } bool TopologyReader::Link::GetAttributeFailSafe (const std::string &name, std::string &value) const { if ( m_linkAttr.find (name) == m_linkAttr.end () ) { return false; } value = m_linkAttr.find (name)->second; return true; } void TopologyReader::Link::SetAttribute (const std::string &name, const std::string &value) { m_linkAttr[name] = value; } TopologyReader::Link::ConstAttributesIterator TopologyReader::Link::AttributesBegin (void) const { return m_linkAttr.begin (); } TopologyReader::Link::ConstAttributesIterator TopologyReader::Link::AttributesEnd (void) const { return m_linkAttr.end (); } } /* namespace ns3 */
// Copyright 2016 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 "services/ui/ws/window_server_test_impl.h" #include "services/ui/public/interfaces/window_tree.mojom.h" #include "services/ui/ws/server_window.h" #include "services/ui/ws/server_window_compositor_frame_sink_manager.h" #include "services/ui/ws/window_server.h" #include "services/ui/ws/window_tree.h" namespace ui { namespace ws { namespace { bool WindowHasValidFrame(const ServerWindow* window) { const ServerWindowCompositorFrameSinkManager* manager = window->compositor_frame_sink_manager(); return manager && !manager->GetLatestFrameSize().IsEmpty(); } } // namespace WindowServerTestImpl::WindowServerTestImpl(WindowServer* window_server) : window_server_(window_server) {} WindowServerTestImpl::~WindowServerTestImpl() {} void WindowServerTestImpl::OnWindowPaint( const std::string& name, const EnsureClientHasDrawnWindowCallback& cb, ServerWindow* window) { WindowTree* tree = window_server_->GetTreeWithClientName(name); if (!tree) return; if (tree->HasRoot(window) && WindowHasValidFrame(window)) { cb.Run(true); window_server_->SetPaintCallback(base::Callback<void(ServerWindow*)>()); } } void WindowServerTestImpl::EnsureClientHasDrawnWindow( const std::string& client_name, const EnsureClientHasDrawnWindowCallback& callback) { WindowTree* tree = window_server_->GetTreeWithClientName(client_name); if (tree) { for (const ServerWindow* window : tree->roots()) { if (WindowHasValidFrame(window)) { callback.Run(true); return; } } } window_server_->SetPaintCallback( base::Bind(&WindowServerTestImpl::OnWindowPaint, base::Unretained(this), client_name, std::move(callback))); } } // namespace ws } // namespace ui
/* Copyright (c) 2011, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <libtorrent/error_code.hpp> #include <libtorrent/bdecode.hpp> #include <libtorrent/upnp.hpp> #include <libtorrent/socks5_stream.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; using boost::system::error_category; void bind_error_code() { class_<boost::system::error_category, boost::noncopyable>("error_category", no_init) .def("name", &error_category::name) .def("message", &error_category::message) .def(self == self) .def(self < self) .def(self != self) ; class_<error_code>("error_code") .def(init<>()) .def("message", &error_code::message) .def("value", &error_code::value) .def("clear", &error_code::clear) .def("category", &error_code::category , return_internal_reference<>()) .def("assign", &error_code::assign) ; def("get_libtorrent_category", &get_libtorrent_category , return_internal_reference<>()); def("get_upnp_category", &get_upnp_category , return_internal_reference<>()); def("get_http_category", &get_http_category , return_internal_reference<>()); def("get_socks_category", &get_socks_category , return_internal_reference<>()); #if TORRENT_USE_I2P def("get_i2p_category", &get_i2p_category , return_internal_reference<>()); #endif def("get_bdecode_category", &get_bdecode_category , return_internal_reference<>()); def("generic_category", &boost::system::generic_category , return_internal_reference<>()); def("system_category", &boost::system::system_category , return_internal_reference<>()); }
/**************************************************************************************** * @author: kzvd4729 created: Dec/05/2019 13:44 * solution_verdict: Wrong answer on test 1 language: GNU C++14 * run_time: 15 ms memory_used: 117200 KB * problem: https://codeforces.com/contest/852/problem/G ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; int tr[5*N+2][6],sz; void add(string s) { int now=0; for(auto x:s) { int c=x-'a'; if(!tr[now][c])tr[now][c]=++sz; now=tr[now][c]; } tr[now][5]++; } string s; int get(int i,int now) { if(i==s.size())return tr[now][5]; if(s[i]=='?') { int sum=get(i+1,now); for(int j=0;j<5;j++) if(tr[now][j])sum+=get(i+1,tr[now][j]); return sum; } else { int c=s[i]-'a';//cout<<c<<endl; if(tr[now][c])return get(i+1,tr[now][c]); } } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,m;cin>>n>>m; for(int i=1;i<=n;i++) { cin>>s;add(s); } for(int i=1;i<=m;i++) { cin>>s;cout<<get(0,0)<<endl; } return 0; }
#include "lstm_unit_dnnlowp_op.h" #include "caffe2/core/tensor_int8.h" #include "caffe2/quantization/server/dnnlowp.h" #include "caffe2/quantization/server/sigmoid.h" #include "caffe2/quantization/server/tanh.h" namespace caffe2 { using namespace std; using namespace dnnlowp; template <typename T> LSTMUnitDNNLowPOp<T>::LSTMUnitDNNLowPOp( const OperatorDef& operator_def, Workspace* ws) : LSTMUnitOp<CPUContext>(operator_def, ws), drop_states_( OperatorBase::template GetSingleArgument<bool>("drop_states", false)), qfactory_(GetQuantizationFactoryOf(this)) {} template <typename T> LSTMUnitDNNLowPOp<T>::~LSTMUnitDNNLowPOp() { if (measure_quantization_error_) { ReportQuantizationError(this, cell_quantization_error_stats_); ReportQuantizationError(this, hidden_quantization_error_stats_); } } template <typename T> OpWrapper<LSTMUnitOp<CPUContext>, T>* LSTMUnitDNNLowPOp<T>::Fp32Op_() { if (!fp32_op_) { fp32_op_.reset( new OpWrapper<LSTMUnitOp<CPUContext>, T>(this, qfactory_.get())); } return fp32_op_.get(); } template <typename T> const TensorCPU& LSTMUnitDNNLowPOp<T>::InputTensorCPU_(int idx) { return InputIsType<int8::Int8TensorCPU>(idx) ? OperatorBase::Input<int8::Int8TensorCPU>(idx).t : Input(idx); } template <typename T> TensorCPU* LSTMUnitDNNLowPOp<T>::OutputTensorCPU_(int idx) { if (dequantize_output_) { return Output(idx); } else { return &Outputs()[idx]->template GetMutable<int8::Int8TensorCPU>()->t; } } template <typename T> static void LSTMUnit( int N, int D, int t, const T* H_prev, const T* C_prev, const T* X, const int32_t* seqLengths, bool drop_states, T* C, T* H, const int32_t forget_bias, const Sigmoid<T>& sigmoid, const Tanh<T>& tanh, const TensorQuantizationParams& X_qparams, const TensorQuantizationParams& C_in_qparams, const TensorQuantizationParams& C_out_qparams, const TensorQuantizationParams& H_in_qparams, const TensorQuantizationParams& H_out_qparams, QuantizationFactory* qfactory) { const TensorQuantizationParams sigmoid_in_qparams = sigmoid.GetInputQuantizationParams(); const TensorQuantizationParams sigmoid_out_qparams = sigmoid.GetOutputQuantizationParams(); const TensorQuantizationParams tanh_in_qparams = tanh.GetInputQuantizationParams(); const TensorQuantizationParams tanh_out_qparams = tanh.GetOutputQuantizationParams(); RequantizationParams h_in_to_out_params = qfactory->ChooseRequantizationMultiplier( H_in_qparams.scale / H_out_qparams.scale, H_out_qparams); RequantizationParams c_in_to_out_params = qfactory->ChooseRequantizationMultiplier( C_in_qparams.scale / C_out_qparams.scale, C_out_qparams); float sigmoid_scale = sigmoid_out_qparams.scale; float tanh_scale = tanh_out_qparams.scale; int32_t sigmoid_zero_point = sigmoid_out_qparams.zero_point; int32_t tanh_zero_point = tanh_out_qparams.zero_point; RequantizationParams x_to_sigmoid_params = qfactory->ChooseRequantizationMultiplier( X_qparams.scale / sigmoid_in_qparams.scale, sigmoid_in_qparams); RequantizationParams x_to_tanh_params = qfactory->ChooseRequantizationMultiplier( X_qparams.scale / tanh_in_qparams.scale, tanh_in_qparams); RequantizationParams c_to_tanh_params = qfactory->ChooseRequantizationMultiplier( C_in_qparams.scale / tanh_scale, tanh_out_qparams); RequantizationParams c_out_requantization_params = qfactory->ChooseRequantizationMultiplier( sigmoid_scale * tanh_scale / C_out_qparams.scale, C_out_qparams); RequantizationParams c_tanh_requantization_params = qfactory->ChooseRequantizationMultiplier( sigmoid_scale * tanh_scale / tanh_in_qparams.scale, tanh_in_qparams); RequantizationParams h_requantization_params = qfactory->ChooseRequantizationMultiplier( sigmoid_scale * tanh_scale / H_out_qparams.scale, H_out_qparams); for (int n = 0; n < N; ++n) { const bool valid = t < seqLengths[n]; for (int d = 0; d < D; ++d) { if (!valid) { if (drop_states) { H[d] = H_out_qparams.zero_point; C[d] = C_out_qparams.zero_point; } else { H[d] = fbgemm::Requantize<T>( H_prev[d] - H_in_qparams.zero_point, h_in_to_out_params); C[d] = fbgemm::Requantize<T>( C_prev[d] - C_in_qparams.zero_point, c_in_to_out_params); } } else { T i_in = fbgemm::Requantize<T>( X[d] - X_qparams.zero_point, x_to_sigmoid_params); T f_in = fbgemm::Requantize<T>( X[1 * D + d] + forget_bias - 2 * X_qparams.zero_point, x_to_sigmoid_params); T o_in = fbgemm::Requantize<T>( X[2 * D + d] - X_qparams.zero_point, x_to_sigmoid_params); T g_in = fbgemm::Requantize<T>( X[3 * D + d] - X_qparams.zero_point, x_to_tanh_params); const T i = sigmoid.Compute(i_in); const T f = sigmoid.Compute(f_in); const T o = sigmoid.Compute(o_in); const T g = tanh.Compute(g_in); const T c_prev = C_prev[d]; // f_times_c_prev.scale = sigmoid_out.scale * c.scale int32_t f_times_c_prev = ((int32_t)f - sigmoid_zero_point) * ((int32_t)c_prev - C_in_qparams.zero_point); // i_times_g.scale = sigmoid_out.scale * tanh_out.scale // (higher resolution than f_times_c since often tanh.scale < c.scale) int32_t i_times_g = ((int32_t)i - sigmoid_zero_point) * ((int32_t)g - tanh_zero_point); // c_temp.scale = sigmoid_out.scale * tanh_out.scale int32_t f_times_c_prev_rescaled = fbgemm::Requantize<int32_t>( f_times_c_prev, 0, c_to_tanh_params.real_multiplier, 32, true /*signed*/); int32_t c_temp = f_times_c_prev_rescaled + i_times_g; // scale back to c.scale C[d] = fbgemm::Requantize<T>(c_temp, c_out_requantization_params); T c_tanh_input = fbgemm::Requantize<T>(c_temp, c_tanh_requantization_params); T host_tanh_c = tanh.Compute(c_tanh_input); // o_times_host_tanh_c.scale = sigmoid_out.scale * tanh_out.scale int32_t o_times_host_tanh_c = ((int32_t)o - sigmoid_zero_point) * ((int32_t)host_tanh_c - tanh_zero_point); H[d] = fbgemm::Requantize<T>(o_times_host_tanh_c, h_requantization_params); } } H_prev += D; C_prev += D; X += 4 * D; C += D; H += D; } } template <typename T> bool LSTMUnitDNNLowPOp<T>::GetQuantizationParameters_() { using namespace dnnlowp; H_in_qparams_ = GetInputTensorQuantizationParamsOf(this, HIDDEN_T_M_1, qfactory_.get()); C_in_qparams_ = GetInputTensorQuantizationParamsOf(this, CELL_T_M_1, qfactory_.get()); // G is only used as an input to tanh or sigmoid G_in_qparams_ = qfactory_->ChooseQuantizationParams( std::min( sigmoid_.GetInputQuantizationParams().Min(), tanh_.GetInputQuantizationParams().Min()), std::max( sigmoid_.GetInputQuantizationParams().Max(), tanh_.GetInputQuantizationParams().Max())); if (HasStaticQuantization(this, HIDDEN_T)) { H_out_qparams_ = GetStaticQuantizationParamsOf(this, HIDDEN_T); } if (HasStaticQuantization(this, CELL_T)) { C_out_qparams_ = GetStaticQuantizationParamsOf(this, CELL_T); } if (!HasStaticQuantization(this, HIDDEN_T) || !HasStaticQuantization(this, CELL_T)) { Fp32Op_()->DequantizeInput(); if (!Fp32Op_()->Get()->RunOnDevice()) { return false; } if (!HasStaticQuantization(this, HIDDEN_T)) { H_out_qparams_ = Fp32Op_()->GetOutputQuantizationParams(qfactory_.get(), HIDDEN_T); } if (!HasStaticQuantization(this, CELL_T)) { C_out_qparams_ = Fp32Op_()->GetOutputQuantizationParams(qfactory_.get(), CELL_T); } } return true; } template <typename T> bool LSTMUnitDNNLowPOp<T>::RunOnDevice() { if (!arguments_parsed_) { ParseDNNLowPOperatorArguments( this, &dequantize_output_, &measure_quantization_error_); arguments_parsed_ = true; } GetQuantizationParameters_(); // Extract N const auto N = InputTensorCPU_(CELL_T_M_1).size(1); // Gates: 1xNxG const auto G = InputTensorCPU_(GATES).size(2); const auto D = InputTensorCPU_(CELL_T_M_1).size(2); CAFFE_ENFORCE_EQ(4 * D, G); // Quantize H_prev if needed vector<T> H_prev_temp; const T* H_prev = QuantizeInputIfNeeded(this, HIDDEN_T_M_1, H_in_qparams_, H_prev_temp); // Quantize C_prev if needed vector<T> C_prev_temp; const T* C_prev = QuantizeInputIfNeeded(this, CELL_T_M_1, C_in_qparams_, C_prev_temp); // Quantize X if needed vector<T> X_temp; const T* X = QuantizeInputIfNeeded(this, GATES, G_in_qparams_, X_temp); // first 3D input to sigmoid, last D input to tanh const size_t TIMESTEP = SEQ_LENGTHS + 1; CAFFE_ENFORCE_EQ(Input(SEQ_LENGTHS).size(), N); const auto* seqLengths = Input(SEQ_LENGTHS).template data<int32_t>(); const auto t = static_cast<OperatorBase*>(this) ->Input<Tensor>(TIMESTEP, CPU) .template data<int32_t>()[0]; OutputTensorCPU_(CELL_T)->ResizeLike(InputTensorCPU_(CELL_T_M_1)); OutputTensorCPU_(HIDDEN_T)->ResizeLike(InputTensorCPU_(CELL_T_M_1)); vector<uint8_t> Ctemp, Htemp; uint8_t *Cdata, *Hdata; if (dequantize_output_) { Ctemp.resize(OutputTensorCPU_(CELL_T)->size()); Cdata = Ctemp.data(); Htemp.resize(OutputTensorCPU_(HIDDEN_T)->size()); Hdata = Htemp.data(); } else { Cdata = OutputTensorCPU_(CELL_T)->template mutable_data<uint8_t>(); Hdata = OutputTensorCPU_(HIDDEN_T)->template mutable_data<uint8_t>(); } int32_t forget_bias_quantized = fbgemm::Quantize<int32_t>(forget_bias_, G_in_qparams_); LSTMUnit( N, D, t, H_prev, C_prev, X, seqLengths, drop_states_, Cdata, Hdata, forget_bias_quantized, sigmoid_, tanh_, G_in_qparams_, C_in_qparams_, C_out_qparams_, H_in_qparams_, H_out_qparams_, qfactory_.get()); if (dequantize_output_) { fbgemm::Dequantize<T>( Cdata, OutputTensorCPU_(CELL_T)->template mutable_data<float>(), Ctemp.size(), C_out_qparams_); fbgemm::Dequantize<T>( Hdata, OutputTensorCPU_(HIDDEN_T)->template mutable_data<float>(), Htemp.size(), H_out_qparams_); if (measure_quantization_error_) { MeasureQuantizationError( OutputTensorCPU_(CELL_T)->template mutable_data<float>(), Fp32Op_()->Get()->Output(CELL_T)->template data<float>(), OutputTensorCPU_(CELL_T)->size(), &cell_quantization_error_stats_); MeasureQuantizationError( OutputTensorCPU_(HIDDEN_T)->template mutable_data<float>(), Fp32Op_()->Get()->Output(HIDDEN_T)->template data<float>(), OutputTensorCPU_(HIDDEN_T)->size(), &hidden_quantization_error_stats_); } } else { PropagateOutputTensorQuantizationParams(this, HIDDEN_T, H_out_qparams_); PropagateOutputTensorQuantizationParams(this, CELL_T, C_out_qparams_); } return true; } REGISTER_CPU_OPERATOR_WITH_ENGINE( LSTMUnit, DNNLOWP, LSTMUnitDNNLowPOp<uint8_t>); REGISTER_CPU_OPERATOR_WITH_ENGINE( Int8LSTMUnit, DNNLOWP, LSTMUnitDNNLowPOp<uint8_t>); } // namespace caffe2
// Copyright 2013 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 "chrome/browser/chromeos/extensions/wallpaper_function_base.h" #include "base/macros.h" #include "base/memory/ref_counted_memory.h" #include "base/metrics/histogram_macros.h" #include "base/synchronization/cancellation_flag.h" #include "base/task_scheduler/lazy_task_runner.h" #include "base/task_scheduler/task_traits.h" #include "chrome/browser/image_decoder.h" #include "chrome/grit/generated_resources.h" #include "chromeos/login/login_state.h" #include "content/public/browser/browser_thread.h" #include "ui/base/l10n/l10n_util.h" #include "ui/gfx/codec/jpeg_codec.h" #include "ui/gfx/image/image_skia_operations.h" using content::BrowserThread; namespace wallpaper_api_util { namespace { // Keeps in sync (same order) with WallpaperLayout enum in header file. const char* const kWallpaperLayoutArrays[] = { "CENTER", "CENTER_CROPPED", "STRETCH", "TILE" }; const int kWallpaperLayoutCount = arraysize(kWallpaperLayoutArrays); base::LazySequencedTaskRunner g_blocking_task_runner = LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER( base::TaskTraits(base::MayBlock(), base::TaskPriority::USER_BLOCKING, base::TaskShutdownBehavior::BLOCK_SHUTDOWN)); base::LazySequencedTaskRunner g_non_blocking_task_runner = LAZY_SEQUENCED_TASK_RUNNER_INITIALIZER( base::TaskTraits(base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN)); } // namespace const char kCancelWallpaperMessage[] = "Set wallpaper was canceled."; ash::WallpaperLayout GetLayoutEnum(const std::string& layout) { for (int i = 0; i < kWallpaperLayoutCount; i++) { if (layout.compare(kWallpaperLayoutArrays[i]) == 0) return static_cast<ash::WallpaperLayout>(i); } // Default to use CENTER layout. return ash::WALLPAPER_LAYOUT_CENTER; } void RecordCustomWallpaperLayout(const ash::WallpaperLayout& layout) { UMA_HISTOGRAM_ENUMERATION("Ash.Wallpaper.CustomLayout", layout, ash::NUM_WALLPAPER_LAYOUT); } } // namespace wallpaper_api_util class WallpaperFunctionBase::UnsafeWallpaperDecoder : public ImageDecoder::ImageRequest { public: explicit UnsafeWallpaperDecoder(scoped_refptr<WallpaperFunctionBase> function) : function_(function) {} void Start(const std::vector<char>& image_data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // This function can only be called after user login. It is fine to use // unsafe image decoder here. Before user login, a robust jpeg decoder will // be used. CHECK(chromeos::LoginState::Get()->IsUserLoggedIn()); std::string image_data_str(image_data.begin(), image_data.end()); ImageDecoder::StartWithOptions(this, image_data_str, ImageDecoder::DEFAULT_CODEC, true); } void Cancel() { cancel_flag_.Set(); } void OnImageDecoded(const SkBitmap& decoded_image) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Make the SkBitmap immutable as we won't modify it. This is important // because otherwise it gets duplicated during painting, wasting memory. SkBitmap immutable(decoded_image); immutable.setImmutable(); gfx::ImageSkia final_image = gfx::ImageSkia::CreateFrom1xBitmap(immutable); final_image.MakeThreadSafe(); if (cancel_flag_.IsSet()) { function_->OnCancel(); delete this; return; } function_->OnWallpaperDecoded(final_image); delete this; } void OnDecodeImageFailed() override { DCHECK_CURRENTLY_ON(BrowserThread::UI); function_->OnFailure( l10n_util::GetStringUTF8(IDS_WALLPAPER_MANAGER_INVALID_WALLPAPER)); delete this; } private: scoped_refptr<WallpaperFunctionBase> function_; base::CancellationFlag cancel_flag_; DISALLOW_COPY_AND_ASSIGN(UnsafeWallpaperDecoder); }; WallpaperFunctionBase::UnsafeWallpaperDecoder* WallpaperFunctionBase::unsafe_wallpaper_decoder_; const int WallpaperFunctionBase::kWallpaperThumbnailWidth = 108; const int WallpaperFunctionBase::kWallpaperThumbnailHeight = 68; WallpaperFunctionBase::WallpaperFunctionBase() = default; WallpaperFunctionBase::~WallpaperFunctionBase() = default; base::SequencedTaskRunner* WallpaperFunctionBase::GetBlockingTaskRunner() { return wallpaper_api_util::g_blocking_task_runner.Get().get(); } base::SequencedTaskRunner* WallpaperFunctionBase::GetNonBlockingTaskRunner() { return wallpaper_api_util::g_non_blocking_task_runner.Get().get(); } void WallpaperFunctionBase::AssertCalledOnWallpaperSequence( base::SequencedTaskRunner* task_runner) { #if DCHECK_IS_ON() DCHECK(task_runner->RunsTasksInCurrentSequence()); #endif } void WallpaperFunctionBase::StartDecode(const std::vector<char>& data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (unsafe_wallpaper_decoder_) unsafe_wallpaper_decoder_->Cancel(); unsafe_wallpaper_decoder_ = new UnsafeWallpaperDecoder(this); unsafe_wallpaper_decoder_->Start(data); } void WallpaperFunctionBase::OnCancel() { unsafe_wallpaper_decoder_ = nullptr; Respond(Error(wallpaper_api_util::kCancelWallpaperMessage)); } void WallpaperFunctionBase::OnFailure(const std::string& error) { unsafe_wallpaper_decoder_ = nullptr; Respond(Error(error)); } void WallpaperFunctionBase::GenerateThumbnail( const gfx::ImageSkia& image, const gfx::Size& size, scoped_refptr<base::RefCountedBytes>* thumbnail_data_out) { *thumbnail_data_out = new base::RefCountedBytes(); gfx::ImageSkia thumbnail_image = gfx::ImageSkiaOperations::CreateResizedImage( image, skia::ImageOperations::RESIZE_LANCZOS3, size); gfx::JPEGCodec::Encode(*thumbnail_image.bitmap(), 90 /*quality=*/, &(*thumbnail_data_out)->data()); }
// named_write.hpp // Boost Logging library // // Author: John Torjo, www.torjo.com // // Copyright (C) 2007 John Torjo (see www.torjo.com for email) // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org for updates, documentation, and revision history. // See http://www.torjo.com/log2/ for more details #pragma once #include <pika/config.hpp> #include <pika/logging/format/destinations.hpp> #include <pika/logging/format/formatters.hpp> #include <cstddef> #include <memory> #include <sstream> #include <string> #include <utility> #include <vector> namespace pika { namespace util { namespace logging { namespace detail { template <typename T> struct named { std::string name; T value; }; template <typename C, typename S> typename C::iterator find_named(C& c, S const& name) { for (auto iter = c.begin(), end = c.end(); iter != end; ++iter) { if (iter->name == name) return iter; } return c.end(); } /** @brief Allows you to contain multiple formatters, and specify a %spacer between them. You have a %spacer string, and within it, you can escape your contained formatters. @code #include <pika/logging/format/formatter/named.hpp> @endcode This allows you: - to hold multiple formatters - each formatter is given a name, when being added - you have a %spacer string, which contains what is to be prepended or appended to the string (by default, prepended) - a formatter is escaped with @c '\%' chars, like this @c "%name%" - if you want to write the @c '\%', just double it, like this: <tt>"this %% gets written"</tt> Example: @code #define L_ PIKA_LOG_USE_LOG_IF_FILTER(g_l(), g_log_filter()->is_enabled() ) g_l()->writer().add_formatter( formatter::named("[%index%] %time% (T%thread%) ") .add( "index", formatter::idx()) .add( "thread", formatter::thread_id()) .add( "time", formatter::time("$mm")) ); @endcode Assuming you'd use the above in code @code int i = 1; L_ << "this is so cool " << i++; L_ << "this is so cool again " << i++; @endcode You could have an output like this: @code [1] 53 (T3536) this is so cool 1 [2] 54 (T3536) this is so cool again 2 @endcode */ struct named_formatters { PIKA_NON_COPYABLE(named_formatters); using ptr_type = std::unique_ptr<formatter::manipulator>; named_formatters() = default; named_formatters& string(std::string const& str) { format_string = str; compute_write_steps(); return *this; } void add(std::string const& name, ptr_type p) { auto iter = find_named(formatters, name); if (iter != formatters.end()) iter->value = PIKA_MOVE(p); else formatters.push_back(named<ptr_type>{name, PIKA_MOVE(p)}); compute_write_steps(); } // NOLINTBEGIN(bugprone-easily-swappable-parameters) void configure( std::string const& name, std::string const& configure_str) // NOLINTEND(bugprone-easily-swappable-parameters) { auto iter = find_named(formatters, name); if (iter != formatters.end()) iter->value->configure(configure_str); } void operator()(std::stringstream& out, message const& msg) const { for (auto const& step : write_steps) { out << step.prefix; if (step.fmt) { if (step.fmt == (formatter::manipulator*) -1) out << msg; else (*step.fmt)(out); } } } private: // recomputes the write steps - note that this takes place after // each operation for instance, the user might have first set the // string and later added the formatters PIKA_EXPORT void compute_write_steps(); private: struct write_step { write_step(std::string const& prefix_, formatter::manipulator* fmt_) : prefix(prefix_) , fmt(fmt_) { } std::string prefix; // could be null - in case formatter not found by name, or it's // the last step formatter::manipulator* fmt; }; std::vector<named<ptr_type>> formatters; std::vector<write_step> write_steps; std::string format_string; }; /** @brief Allows you to contain multiple destinations, give each such destination a name. Then, at run-time, you can specify a format string which will specify which destinations to be called, and on what order. This allows you: - to hold multiple destinations - each destination is given a name, when being added. The name <b>must not</b> contain spaces and must not start with '+'/'-' signs - you have a %format string, which contains what destinations to be called, and on which order The %format string contains destination names, separated by space. When a message is written to this destination, I parse the format string. When a name is encountered, if there's a destination corresponding to this name, I will call it. Example: @code g_l()->writer().add_destination( destination::named_destinations("cout out debug") .add( "cout", destination::cout()) .add( "debug", destination::dbg_window() ) .add( "out", destination::file("out.txt")) ); @endcode In the above code, we'll write to 3 destinations, in the following order: - first, to the console - second, to the out.txt file - third, to the debug window @section If you deal with config files As an extra feature: - if a name starts with '-' is ignored - if a name starts with '+', is included. This is useful if you want to set this format string in a config file. The good thing is that this way you can easily turn on/off certain destinations, while seeing all the available destinations as well. Example: \n <tt>+out_file -debug_window +console</tt> \n In the above example, I know that the available destinations are @c out_file, @c debug_window and @c console, but I'm not writing to @c debug_window. */ struct named_destinations { PIKA_NON_COPYABLE(named_destinations); using ptr_type = std::unique_ptr<destination::manipulator>; named_destinations() = default; named_destinations& string(std::string const& str) { format_string = str; compute_write_steps(); return *this; } void add(std::string const& name, ptr_type p) { auto iter = find_named(destinations, name); if (iter != destinations.end()) iter->value = PIKA_MOVE(p); else destinations.push_back(named<ptr_type>{name, PIKA_MOVE(p)}); compute_write_steps(); } // NOLINTBEGIN(bugprone-easily-swappable-parameters) void configure( std::string const& name, std::string const& configure_str) // NOLINTEND(bugprone-easily-swappable-parameters) { auto iter = find_named(destinations, name); if (iter != destinations.end()) iter->value->configure(configure_str); } void operator()(const message& msg) const { for (auto const& step : write_steps) (*step)(msg); } private: // recomputes the write steps - note that this takes place after // each operation for instance, the user might have first set the // string and later added the formatters PIKA_EXPORT void compute_write_steps(); private: std::vector<named<ptr_type>> destinations; std::vector<destination::manipulator*> write_steps; std::string format_string; }; }}}} // namespace pika::util::logging::detail namespace pika { namespace util { namespace logging { namespace writer { /** @brief Composed of a named formatter and a named destinations. Thus, you can specify the formatting and destinations as strings @code #include <pika/logging/format/named_write.hpp> @endcode Contains a very easy interface for using @ref manipulator "formatters and destinations": - at construction, specify 2 params: the %formatter string and the destinations string Setting the @ref manipulator "formatters and destinations" to write to is extremely simple: @code // Set the formatters (first param) and destinatins (second step) in one step g_l()->writer().write("%time%($hh:$mm.$ss.$mili) [%idx%] |\n", "cout file(out.txt) debug"); // set the formatter(s) g_l()->writer().format("%time%($hh:$mm.$ss.$mili) [%idx%] |\n"); // set the destination(s) g_l()->writer().destination("cout file(out.txt) debug"); @endcode @section format_string_syntax The syntax of the format string - The format string specifies how the message is to be logged - Every formatter is escaped using <tt>%</tt><em>fmt</em><tt>%</tt> - Available formatters: - <tt>"%idx%"</tt> - writes the index of the message (formatter::idx) - <tt>"%time%"</tt> - writes the time (formatter::high_precision_time) - <tt>"%thread_id%"</tt> - writes the thread id (formatter::thread_id) - if you want to write @c "%", double it, like this: @c "%%" - @c "|" is used to specify the original message. What is before it, is prepended to the message, what is after, is appended to the message - If a formatter is configurable, append @em (params) to it - For now, only @c "%time%" is configurable. For instance, @c "%time%($hh:$mm.$ss.$mili)" writes time like @c "21:14.24.674" Example: @code "%time%($hh:$mm.$ss.$mili) [%idx%] |\n" @endcode The output can look like: @code 21:03.17.243 [1] this is so cool 21:03.17.243 [2] first error 21:03.17.243 [3] hello, world @endcode @section dest_string_syntax The syntax of the destinations string - The syntax of the destination string specifies where the message is to be logged - Every destination is specified by name - Separate destinations by space (' ') - Available destinations - <tt>"cout"</tt> - writes to std::cout (destination::cout) - <tt>"cerr"</tt> - writes to std::cerr (destination::cerr) - <tt>"debug"</tt> - writes to the debug window: OutputDebugString in Windows, console on Linux (destination::dbg_window) - <tt>"file"</tt> - writes to a file (destination::file) - If a destination is configurable, append @em (params) to it - Right now, @c "file" is configurable - Append <tt>(</tt><em>filename</em><tt>)</tt> to them to specify the file name. Example: @c "file(out.txt)" will write to the out.txt file Examples: - <tt>"file(out.txt) cout"</tt> - will write to a file called out.txt and to cout - <tt>"cout debug"</tt> - will write to cout and debug window (see above) @note If you want to output to 2 files, don't use "file(one.txt) file(two.txt)". This will just configure "file" twice, ending up with writing only to "two.txt" file. @param format_write_ the underlying format writer */ struct named_write { PIKA_EXPORT named_write(); /** @brief sets the format string: what should be before, and what after the original message, separated by "|" Example: \n "[%idx%] |\n" - this writes "[%idx%] " before the message, and "\n" after the message If "|" is not present, the whole message is prepended to the message */ void format(std::string const& format_str) { m_format_str = format_str; configure_formatter(format_str); }; /** @brief sets the destinations string - where should logged messages * be outputted */ void destination(std::string const& destination_str) { m_destination_str = destination_str; configure_destination(destination_str); } /** @brief Specifies the formats and destinations in one step */ // NOLINTBEGIN(bugprone-easily-swappable-parameters) void write( std::string const& format_str, std::string const& destination_str) // NOLINTEND(bugprone-easily-swappable-parameters) { format(format_str); destination(destination_str); } void operator()(message const& msg) const { std::stringstream out; m_format(out, msg); #if defined(PIKA_COMPUTE_HOST_CODE) message formatted(PIKA_MOVE(out)); m_destination(formatted); #endif } /** @brief Replaces a formatter from the named formatter. You can use this, for instance, when you want to share a formatter between multiple named writers. */ template <typename Formatter> void set_formatter(std::string const& name, Formatter fmt) { m_format.add( name, detail::named_formatters::ptr_type(new Formatter(fmt))); } template <typename Formatter, typename... Args> void set_formatter(std::string const& name, Args&&... args) { m_format.add(name, Formatter::make(PIKA_FORWARD(Args, args)...)); } /** @brief Replaces a destination from the named destination. You can use this, for instance, when you want to share a destination between multiple named writers. */ template <typename Destination> void set_destination(std::string const& name, Destination dest) { m_destination.add(name, detail::named_destinations::ptr_type(new Destination(dest))); } template <typename Destination, typename... Args> void set_destination(std::string const& name, Args&&... args) { m_destination.add( name, Destination::make(PIKA_FORWARD(Args, args)...)); } private: PIKA_EXPORT void configure_formatter(std::string const& format); PIKA_EXPORT void configure_destination(std::string const& format); private: detail::named_formatters m_format; detail::named_destinations m_destination; std::string m_format_str; std::string m_destination_str; }; }}}} // namespace pika::util::logging::writer
// Copyright 2015 the V8 project 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 "src/v8.h" #include "src/interpreter/bytecode-array-builder.h" #include "src/interpreter/bytecode-array-iterator.h" #include "test/unittests/test-utils.h" namespace v8 { namespace internal { namespace interpreter { class BytecodeArrayIteratorTest : public TestWithIsolateAndZone { public: BytecodeArrayIteratorTest() {} ~BytecodeArrayIteratorTest() override {} }; TEST_F(BytecodeArrayIteratorTest, IteratesBytecodeArray) { // Use a builder to create an array with containing multiple bytecodes // with 0, 1 and 2 operands. BytecodeArrayBuilder builder(isolate(), zone(), 3, 3, 0); Factory* factory = isolate()->factory(); Handle<HeapObject> heap_num_0 = factory->NewHeapNumber(2.718); Handle<HeapObject> heap_num_1 = factory->NewHeapNumber(2147483647); Smi* zero = Smi::kZero; Smi* smi_0 = Smi::FromInt(64); Smi* smi_1 = Smi::FromInt(-65536); Register reg_0(0); Register reg_1(1); RegisterList pair(0, 2); RegisterList triple(0, 3); Register param = Register::FromParameterIndex(2, builder.parameter_count()); Handle<String> name = factory->NewStringFromStaticChars("abc"); int name_index = 2; int feedback_slot = 97; builder.LoadLiteral(heap_num_0) .StoreAccumulatorInRegister(reg_0) .LoadLiteral(heap_num_1) .StoreAccumulatorInRegister(reg_0) .LoadLiteral(zero) .StoreAccumulatorInRegister(reg_0) .LoadLiteral(smi_0) .StackCheck(0) .StoreAccumulatorInRegister(reg_0) .LoadLiteral(smi_1) .StackCheck(1) .StoreAccumulatorInRegister(reg_1) .LoadAccumulatorWithRegister(reg_0) .BinaryOperation(Token::Value::ADD, reg_0, 2) .StoreAccumulatorInRegister(reg_1) .LoadNamedProperty(reg_1, name, feedback_slot) .BinaryOperation(Token::Value::ADD, reg_0, 3) .StoreAccumulatorInRegister(param) .CallRuntimeForPair(Runtime::kLoadLookupSlotForCall, param, pair) .ForInPrepare(reg_0, triple) .CallRuntime(Runtime::kLoadIC_Miss, reg_0) .Debugger() .LoadGlobal(0x10000000, TypeofMode::NOT_INSIDE_TYPEOF) .Return(); // Test iterator sees the expected output from the builder. BytecodeArrayIterator iterator(builder.ToBytecodeArray(isolate())); const int kPrefixByteSize = 1; int offset = 0; CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaConstant); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK(iterator.GetConstantForIndexOperand(0).is_identical_to(heap_num_0)); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaConstant, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaConstant); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK(iterator.GetConstantForIndexOperand(0).is_identical_to(heap_num_1)); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaConstant, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaZero); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaZero, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaSmi); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(Smi::FromInt(iterator.GetImmediateOperand(0)), smi_0); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaSmi, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStackCheck); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(Bytecodes::NumberOfOperands(iterator.current_bytecode()), 0); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStackCheck, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaSmi); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kQuadruple); CHECK_EQ(Smi::FromInt(iterator.GetImmediateOperand(0)), smi_1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaSmi, OperandScale::kQuadruple) + kPrefixByteSize; iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStackCheck); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(Bytecodes::NumberOfOperands(iterator.current_bytecode()), 0); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStackCheck, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_1.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kAdd); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kAdd, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_1.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaNamedProperty); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_1.index()); CHECK_EQ(iterator.GetIndexOperand(1), name_index); CHECK_EQ(iterator.GetIndexOperand(2), feedback_slot); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kLdaNamedProperty, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kAdd); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kAdd, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kStar); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), param.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kStar, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kCallRuntimeForPair); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRuntimeIdOperand(0), Runtime::kLoadLookupSlotForCall); CHECK_EQ(iterator.GetRegisterOperand(1).index(), param.index()); CHECK_EQ(iterator.GetRegisterOperandRange(1), 1); CHECK_EQ(iterator.GetRegisterCountOperand(2), 1); CHECK_EQ(iterator.GetRegisterOperand(3).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(3), 2); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kCallRuntimeForPair, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kForInPrepare); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRegisterOperand(0).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(0), 1); CHECK_EQ(iterator.GetRegisterOperand(1).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterOperandRange(1), 3); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kForInPrepare, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kCallRuntime); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK_EQ(iterator.GetRuntimeIdOperand(0), Runtime::kLoadIC_Miss); CHECK_EQ(iterator.GetRegisterOperand(1).index(), reg_0.index()); CHECK_EQ(iterator.GetRegisterCountOperand(2), 1); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kCallRuntime, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kDebugger); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK(!iterator.done()); offset += Bytecodes::Size(Bytecode::kDebugger, OperandScale::kSingle); iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kLdaGlobal); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kQuadruple); CHECK_EQ(iterator.current_bytecode_size(), 6); CHECK_EQ(iterator.GetIndexOperand(0), 0x10000000); offset += Bytecodes::Size(Bytecode::kLdaGlobal, OperandScale::kQuadruple) + kPrefixByteSize; iterator.Advance(); CHECK_EQ(iterator.current_bytecode(), Bytecode::kReturn); CHECK_EQ(iterator.current_offset(), offset); CHECK_EQ(iterator.current_operand_scale(), OperandScale::kSingle); CHECK(!iterator.done()); iterator.Advance(); CHECK(iterator.done()); } } // namespace interpreter } // namespace internal } // namespace v8
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by Leonhard Spiegelberg first on 5/24/18 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #include "gtest/gtest.h" #include "TestUtils.h" #include <Context.h> #include <Utils.h> #include <vector> //#include <boost/filesystem> #include <fstream> #include <boost/filesystem/operations.hpp> using namespace tuplex; TEST(CSVDataset, NonexistingFile) { Context c(testOptions()); auto v = c.csv("../resources/doesnotexist.csv").collectAsVector(); EXPECT_EQ(v.size(), 0); } TEST(CSVDataset, ParseWithoutHeader) { Context c(testOptions()); auto v = c.csv("../resources/test.csv").collectAsVector(); EXPECT_EQ(v.size(), 3); } // construct fake file & check whether right order is returned TEST(CSVDataSet, ParseWithMultiplePartitions) { python::initInterpreter(); python::unlockGIL(); // write temp file FILE *fp = fopen("test.csv", "w"); ASSERT_TRUE(fp); fprintf(fp, "columnA,columnB\n"); auto N = 50000; for(int i = 0; i < N; ++i) { fprintf(fp, "%d,%d\n", i, i % 7); } fclose(fp); Context c(microTestOptions()); auto v = c.csv("test.csv").mapColumn("columnB", UDF("lambda x: x * x")).collectAsVector(); ASSERT_EQ(v.size(), N); printRows(v); // make sure order is correct! for(int i = 0; i < N; ++i) { EXPECT_EQ(v[i].getInt(0), i); EXPECT_EQ(v[i].getInt(1), (i % 7) * (i % 7)); } python::lockGIL(); python::closeInterpreter(); } TEST(CSVDataSet, ParseWithMultiplePartitionsLimit) { python::initInterpreter(); python::unlockGIL(); // write temp file FILE *fp = fopen("test.csv", "w"); ASSERT_TRUE(fp); fprintf(fp, "columnA,columnB\n"); auto N = 50000; for(int i = 0; i < N; ++i) { fprintf(fp, "%d,%d\n", i, i % 7); } fclose(fp); size_t limit = 5; Context c(microTestOptions()); auto v = c.csv("test.csv").mapColumn("columnB", UDF("lambda x: x * x")).takeAsVector(limit); ASSERT_EQ(v.size(), limit); printRows(v); // make sure order is correct! for(int i = 0; i < limit; ++i) { EXPECT_EQ(v[i].getInt(0), i); EXPECT_EQ(v[i].getInt(1), (i % 7) * (i % 7)); } python::lockGIL(); python::closeInterpreter(); } //// //// Created by Leonhard Spiegelberg on 5/24/18. //// //#include "gtest/gtest.h" //#include <Context.h> //#include <Utils.h> //#include <vector> // // // // // //// cases //// c some char (not " or ,) //// assume cursor is in the middle //// c c c ==> can't decide //// c c " ==> can't decide //// c c , ==> can decide by looking next char // //// c " c ==> invalid //// c " " ==> in quoted field //// c " , ==> can decide (next field) // //// c , c ==> unquoted field starts after //// c , " ==> quoted field starts //// c , , // //// " c c //// " c " //// " c , // //// " " c //// " " " //// " " , // //// " , c //// " , " //// " , , // //// , c c //// , c " //// , c , // //// , " c //// , " " //// , " , // //// , , c //// , , " //// , , , // // ////const char* findNextCellStart(const char *start, const char *ptr, const char *end, char delimiter, char quotechar) { //// //// // need to find status of parser at current position //// auto p = ptr; //// auto prev = ptr - 1; //// auto next = ptr + 1; //// //// if(*prev != quotechar && *p == quotechar && *next == quotechar) { //// // p is in quoted cell //// } //// //// if(*prev == ) //// //// //// return nullptr; ////} // //WHAT TODO: // //small files: one thread parses them //larger files: chunk them and parse them in two passes: //pass 1) determine start / end of tasks --> i.e. this is one task, it spawns other tasks. //pass 2) thread pool. // ///*! // * starts to scan from the given position up until end to determine cell start // * @param ptr // * @param end // * @param delimiter // * @param quotechar // * @return nullptr if no cell begin was reached // */ ////const char* findNextCellStart(const char *start, const char *ptr, const char *end, char delimiter, char quotechar) { //// // difficulty is to determine whether current ptr is in quoted cell or not. //// // this is actually not possible to determine without searching both directions //// //// assert(ptr < end); //// //// // NEW DESIGN: //// //// int numQuoteCharsSeen = 0; //// // need to determine initial count of quote chars seen //// // i.e. scan to the left //// if(*ptr != quotechar) //// numQuoteCharsSeen = 0; //// else { //// // important with start. //// const char *p = ptr - 1; //// numQuoteCharsSeen = 0; //// while(p >= start && *p == quotechar) { //// numQuoteCharsSeen++; //// p--; //// } //// } //// int qcs = numQuoteCharsSeen; // used for searching //// //// // now go through the data until the end //// // lookahead 1 for quoted //// const char *p = ptr; //// const char *quoted_pos = nullptr; //// while(p < end - 1) { //// //// // update how many quote chars have been seen //// if(*p == quotechar) //// qcs++; //// else //// qcs = 0; //// //// auto pp = p + 1; //// //// // case I: ", with , being the current one //// if((qcs & 0x1) //// && *p == quotechar //// && *pp == delimiter) { //// //pquoted = p + 2; //// return p + 2; //// } //// //// // case II: "\n or "\r with \n or \r being the current char //// if((qcs & 0x1) //// && *p == quotechar //// && (*pp == '\n' || *pp == '\r')) { //// //// // for this to be a valid end of line //// // the next char must be either a non quote char, end must be reached or an odd number of quotechars to follow //// auto ppp = p + 2; //// if(ppp == end) //// return p + 2; //// else if(ppp < end) { //// if(quotechar == *ppp) { //// int qqcs = 1; //// while(ppp < end && *ppp == quotechar) { //// ++ppp; //// qqcs++; //// } //// //// // odd number? //// if(qqcs & 0x1) //// return p + 2; //// // else, continue search... //// //// } else { //// // not a quote char, save to compare with unquoted //// quoted_pos = p; //// } //// } else { //// // can't decide where cell is... //// return nullptr; //// } //// } //// //// ++p; //// } //// //// // special case: //// // ends with " --> //// if(*(end - 1) == quotechar) //// return end + 1; //// //// // now search for , or EOF iff no quoted version was found //// p = ptr; //// const char *unquoted_pos = nullptr; //// while(p < end && !unquoted_pos) { //// // if delimiter or newline is found, break //// if(*p == delimiter) //// unquoted_pos = p + 1; //// if(*p == '\n' || *p == '\r') //// unquoted_pos = p + 1; //// ++p; //// } //// //// // comparing against //// if(quoted_pos && unquoted_pos) { //// // return larger //// return quoted_pos + 2; //// } //// //// return unquoted_pos; //// //// // nothing found... //// // return end + 1 //// return end + 1; ////} // //// multiple test strings for determining cell start position //TEST(CSVParser, CellStartUnquotedCell) { // std::string test = "Hello world,NEXT"; // for(int i = 0; i < strlen("Hello world"); ++i) { // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("Hello world") + 1); // } // //} // //TEST(CSVParser, CellStartQuotedCell) { // std::string test = "\"Hello world\",NEXT"; // for(int i = 0; i < strlen("\"Hello world\""); ++i) { // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("\"Hello world\"") + 1); // } // //} // //TEST(CSVParser, CellStartQuotedCellAtEOF) { // std::string test = "\"Hello world\""; // for(int i = 0; i < strlen("\"Hello world\""); ++i) { // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("\"Hello world\"")); // } // //} // //TEST(CSVParser, CellStartQuotedCellAtEnd) { // std::string test = "\"Hello world\"\n\"test\"\n"; // for(int i = 0; i < strlen("\"Hello world\""); ++i) { // std::cout<<"i: "<<i<<std::endl; // i = 12; // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("\"Hello world\"") + 1); // } //} // //TEST(CSVParser, CellStartQuotedCellAtWithSpecialChars) { // std::string test = "\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\",NEXT"; // for(int i = 0; i < strlen("\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\""); ++i) { // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\"") + 1); // } //} // //TEST(CSVParser, CellStartQuotedCellAtWithSpecialCharsAtEnd) { // std::string test = "\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\""; // for(int i = 0; i < strlen("\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\""); ++i) { // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + strlen("\"\n\n\"\",\"\"\"\",,\n\"\"\n\"\"\"\",\"\"\n,,\"") + 1); // } //} // //TEST(CSVParser, CellMixed) { // std::string test = "a,b,\"\"\"\",c"; // std::vector<int> ref{2, 2, 4, 4, 9, 9, 9, 9, 10, 10}; // for(int i = 0; i < test.length(); ++i) { // std::cout<<"i "<<i<<std::endl; // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + ref[i]); // } //} // //TEST(CSVParser, CellStartSmallCSVFile) { // std::string test = "a,b\n" // "1,\"ha \n" // "\"\"ha\"\" \n" // "ha\"\n" // "3,4"; // std::vector<int> ref{2, 2, 4, 4, // 6, 6, 23, 23, 23, 23, 23, // 23, 23, 23, 23, 23, 23, 23, 23, // 23, 23, 23, 23, // 24, 24, 25}; // for(int i = 0; i < test.length(); ++i) { // std::cout<<"i "<<i<<std::endl; // auto cell_start = findNextCellStart(test.c_str(), // test.c_str() + i, // test.c_str() + test.length(), // ',', // '"'); // EXPECT_EQ(cell_start, test.c_str() + ref[i]); // } //} // // //// So, the problem is as following: //// It is not possible to determine the start position of a cell //// --> only solution: fetch next row start from current cell (pretend to be in quoted cell). //// attempt parse. If fails, start over with fetching next row from current cell (pretend to be in unquoted cell) //// --> parse again //// one of these should work. If not, then again, skip to next row. After this is done, go to next row.
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2017-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file Route.cpp /// @author Daniel Krajzewicz /// @author Mario Krumnow /// @author Jakob Erdmann /// @author Michael Behrisch /// @author Robert Hilbrich /// @date 30.05.2012 /// // C++ TraCI client API implementation /****************************************************************************/ #include <config.h> #include <microsim/MSNet.h> #include <microsim/MSEdge.h> #include <microsim/MSRoute.h> #include <libsumo/TraCIConstants.h> #include "Helper.h" #include "Route.h" namespace libsumo { // =========================================================================== // static member initializations // =========================================================================== SubscriptionResults Route::mySubscriptionResults; ContextSubscriptionResults Route::myContextSubscriptionResults; // =========================================================================== // static member definitions // =========================================================================== std::vector<std::string> Route::getIDList() { std::vector<std::string> ids; MSRoute::insertIDs(ids); return ids; } std::vector<std::string> Route::getEdges(const std::string& routeID) { const MSRoute* r = getRoute(routeID); std::vector<std::string> ids; for (ConstMSEdgeVector::const_iterator i = r->getEdges().begin(); i != r->getEdges().end(); ++i) { ids.push_back((*i)->getID()); } return ids; } int Route::getIDCount() { return (int)getIDList().size(); } std::string Route::getParameter(const std::string& routeID, const std::string& param) { const MSRoute* r = getRoute(routeID); return r->getParameter(param, ""); } LIBSUMO_GET_PARAMETER_WITH_KEY_IMPLEMENTATION(Route) void Route::setParameter(const std::string& routeID, const std::string& key, const std::string& value) { MSRoute* r = const_cast<MSRoute*>(getRoute(routeID)); r->setParameter(key, value); } void Route::add(const std::string& routeID, const std::vector<std::string>& edgeIDs) { ConstMSEdgeVector edges; if (edgeIDs.size() == 0) { throw TraCIException("Cannot add route '" + routeID + "' without edges."); } for (std::vector<std::string>::const_iterator ei = edgeIDs.begin(); ei != edgeIDs.end(); ++ei) { MSEdge* edge = MSEdge::dictionary(*ei); if (edge == nullptr) { throw TraCIException("Unknown edge '" + *ei + "' in route."); } edges.push_back(edge); } const std::vector<SUMOVehicleParameter::Stop> stops; if (!MSRoute::dictionary(routeID, new MSRoute(routeID, edges, true, nullptr, stops))) { throw TraCIException("Could not add route."); } } LIBSUMO_SUBSCRIPTION_IMPLEMENTATION(Route, ROUTE) const MSRoute* Route::getRoute(const std::string& id) { const MSRoute* r = MSRoute::dictionary(id); if (r == nullptr) { throw TraCIException("Route '" + id + "' is not known"); } return r; } std::shared_ptr<VariableWrapper> Route::makeWrapper() { return std::make_shared<Helper::SubscriptionWrapper>(handleVariable, mySubscriptionResults, myContextSubscriptionResults); } bool Route::handleVariable(const std::string& objID, const int variable, VariableWrapper* wrapper) { switch (variable) { case TRACI_ID_LIST: return wrapper->wrapStringList(objID, variable, getIDList()); case ID_COUNT: return wrapper->wrapInt(objID, variable, getIDCount()); case VAR_EDGES: return wrapper->wrapStringList(objID, variable, getEdges(objID)); default: return false; } } } /****************************************************************************/
// // Generators.hpp // Homework4 // // Created by Zander Nickle on 6/12/18. // Copyright © 2018 Zander Nickle. All rights reserved. // #ifndef Generators_h #define Generators_h #pragma once #include "Point.hpp" #include <random> /* These generators just have 1 method: generate point. They take a template parameter for the dimension and some constructor parameters for other stuff */ //Uniformly (evenly) distributed random points template<int Dimension> struct UniformGenerator{ UniformGenerator(float min_, float max_) :min(min_), max(max_), rd{}, gen(rd()), dis(min_, max_) {} Point<Dimension> generatePoint(){ std::array<float, Dimension> data; for(int i = 0; i < Dimension; ++i){ data[i] = dis(gen); } return Point<Dimension>{data}; } private: float min, max; std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen; //Standard mersenne_twister_engine seeded with rd() std::uniform_real_distribution<> dis; }; //Normally (Gaussian) distributed random points. These will be clumped around mean. Spread is determined by stdDev template<int Dimension> struct GaussianGenerator{ GaussianGenerator(float mean_, float stdDev_) :mean(mean_), stdDev(stdDev_), rd{}, gen(rd()), dis(mean_, stdDev_) {} Point<Dimension> generatePoint(){ std::array<float, Dimension> data; for(int i = 0; i < Dimension; ++i){ data[i] = dis(gen); } return Point<Dimension>{data}; } private: float mean, stdDev; std::random_device rd; //Will be used to obtain a seed for the random number engine std::mt19937 gen; //Standard mersenne_twister_engine seeded with rd() std::normal_distribution<> dis; }; /*This function is useful for generating points to store/query, and points to use for KNN/Range queries The struct just groups the 2 point sets together. */ template <int Dimension> struct TrialData{ std::vector<Point<Dimension> > training, testing; }; template<int Dimension, typename Generator> TrialData<Dimension> getTrialData(int trainingSize, int testingSize, Generator& gen){ TrialData<Dimension> ret; for(int i = 0; i < trainingSize; ++i){ ret.training.push_back(gen.generatePoint()); } for(int i = 0; i < testingSize; ++i){ ret.testing.push_back(gen.generatePoint()); } return ret; } #endif /* Generators_h */
#include <iostream> #include <stack> #include <map> using namespace std; class Solution { public: map<char,uint8_t> embrace_class; Solution(){ embrace_class['('] = 0; embrace_class['['] = 1; embrace_class['{'] = 2; embrace_class[')'] = 3; embrace_class[']'] = 4; embrace_class['}'] = 5; } bool isValid(string s) { stack<char> storage; if(s.empty()) return true; string::iterator iter = s.begin(); while (iter!=s.end()) { if (embrace_class[*iter] < 3) storage.push(*iter); else if(storage.empty()) return false; else if(embrace_class[*iter] == (embrace_class[storage.top()] + 3)) storage.pop(); else return false; iter++; } if (storage.empty()) return true; else return false; } }; int main( ) { Solution test; bool result = test.isValid("[]"); cout << result << endl; return 0; }
/////////////////////////////////////////////////////////////////////////////// // Name: stefindr.cpp // Purpose: wxSTEditorFindReplaceData // Author: John Labenski, parts taken from wxGuide by Otto Wyss // Modified by: // Created: 11/05/2002 // RCS-ID: // Copyright: (c) John Labenski, Otto Wyss // Licence: wxWidgets licence /////////////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "wx/stedit/stefindr.h" #include "wx/stedit/stedit.h" #include "wx/stedit/steart.h" #include "stedlgs_wdr.h" #include "wxext.h" #include <wx/arrimpl.cpp> WX_DEFINE_OBJARRAY( wxArraySTEditorFoundStringData ); //----------------------------------------------------------------------------- // Static functions for prepending strings to wxArrayString and wxComboBoxes //----------------------------------------------------------------------------- bool wxSTEPrependArrayString(const wxString &str, wxArrayString &strArray, int max_count) { const int idx = strArray.Index(str); if (idx == 0) return false; if (idx != wxNOT_FOUND) strArray.RemoveAt(idx); strArray.Insert(str, 0); if ((max_count > 0) && ((int)strArray.GetCount() > max_count)) strArray.RemoveAt(max_count, strArray.GetCount()-max_count); return true; } bool wxSTEPrependComboBoxString(const wxString &str, wxComboBox *combo, int max_strings) { wxCHECK_MSG(combo, false, wxT("Invalid combobox in wxSTEPrependComboBoxString")); int pos = combo->FindString(str); if (pos == 0) return false; if (pos != wxNOT_FOUND) combo->Delete(pos); combo->Insert(str, 0); combo->SetSelection(0); if (max_strings > 0) { while ((int)combo->GetCount() > max_strings) combo->Delete(combo->GetCount()-1); } return true; } void wxSTEInitComboBoxStrings(const wxArrayString& values, wxComboBox* combo) { wxCHECK_RET(combo, wxT("Invalid combobox in wxSTEInitComboBoxStrings")); combo->Clear(); for (size_t n = 0; n < values.GetCount(); n++) combo->Append(values[n]); if (combo->GetCount() > 0) combo->SetSelection(0); } void wxSTEInitMenuStrings(const wxArrayString& values, wxMenu* menu, int start_win_id, int max_count) { wxCHECK_RET(menu, wxT("Invalid wxMenu in wxSTEInitMenuStrings")); int value_count = values.GetCount(); for (int n = 0; n < max_count; n++) { int win_id = n + start_win_id; wxMenuItem* menuItem = menu->FindItem(win_id); if (n >= value_count) { if (menuItem != NULL) menu->Remove(win_id); } else if (menuItem != NULL) { menuItem->SetItemLabel(values[n]); } else { menu->Append(win_id, values[n]); } } } //----------------------------------------------------------------------------- // wxSearchCtrl update functions //----------------------------------------------------------------------------- void wxSTEUpdateSearchCtrl(wxToolBar* toolBar, wxWindowID win_id, const wxSTEditorFindReplaceData* findReplaceData) { if (toolBar == NULL) return; wxControl* ctrl = toolBar->FindControl(win_id); if (ctrl == NULL) return; wxSearchCtrl* searchCtrl = wxDynamicCast(ctrl, wxSearchCtrl); if (searchCtrl == NULL) return; wxSTEUpdateSearchCtrl(searchCtrl, findReplaceData); } void wxSTEUpdateSearchCtrl(wxSearchCtrl* searchCtrl, const wxSTEditorFindReplaceData* findReplaceData) { if ((searchCtrl == NULL) || (findReplaceData == NULL)) return; wxString findString(findReplaceData->GetFindString()); if (searchCtrl->GetValue() != findString) searchCtrl->SetValue(findString); if (searchCtrl->GetMenu() != NULL) { const wxArrayString& findStrings = findReplaceData->GetFindStrings(); wxSTEInitMenuStrings(findStrings, searchCtrl->GetMenu(), ID_STE_TOOLBAR_SEARCHCTRL_MENU0, ID_STE_TOOLBAR_SEARCHCTRL_MENU__LAST-ID_STE_TOOLBAR_SEARCHCTRL_MENU0); } } //----------------------------------------------------------------------------- // wxSTEditorFoundStringData //----------------------------------------------------------------------------- wxSTEditorFoundStringData::wxSTEditorFoundStringData() :wxStringClientData(), m_line_number(0), m_line_start_pos(0), m_file_start_pos(0), m_string_length(0) { } wxSTEditorFoundStringData::wxSTEditorFoundStringData(const wxFileName& fileName, int line_number, int line_start_pos, int file_start_pos, int string_length, const wxString& text) :wxStringClientData(text), m_fileName(fileName), m_line_number(line_number), m_line_start_pos(line_start_pos), m_file_start_pos(file_start_pos), m_string_length(string_length) { } wxString wxSTEditorFoundStringData::ToString() const { return wxString::Format(wxT("%s|%d|%d|%d|%d>"), m_fileName.GetFullPath().wx_str(), m_line_number, m_line_start_pos, m_file_start_pos, m_string_length) + GetLineString(); } bool wxSTEditorFoundStringData::FromString(const wxString& findAllString) { wxString s(findAllString); long value = 0; m_fileName = s.BeforeFirst(wxT('|')); s = s.AfterFirst(wxT('|')); if (s.BeforeFirst(wxT('|')).ToLong(&value)) { m_line_number = (int)value; s = s.AfterFirst(wxT('|')); } else return false; if (s.BeforeFirst(wxT('|')).ToLong(&value)) { m_line_start_pos = (int)value; s = s.AfterFirst(wxT('|')); } else return false; if (s.BeforeFirst(wxT('|')).ToLong(&value)) { m_file_start_pos = (int)value; s = s.AfterFirst(wxT('|')); } else return false; if (s.BeforeFirst(wxT('>')).ToLong(&value)) { m_string_length = (int)value; SetLineString(s.AfterFirst(wxT('>'))); } else return false; return true; } //----------------------------------------------------------------------------- // wxSTEditorFindReplaceData //----------------------------------------------------------------------------- // static wxSTEditorFindReplaceData wxSTEditorFindReplaceData::sm_findReplaceData(wxFR_DOWN|STE_FR_WRAPAROUND); wxSTEditorFindReplaceData::wxSTEditorFindReplaceData(wxUint32 flags) :wxFindReplaceData(), m_max_strings(10), m_loaded_config(false), m_dialogSize(wxDefaultSize) { SetFlags(flags); } // static int wxSTEditorFindReplaceData::STEToScintillaFindFlags(int ste_flags) { int sci_flags = 0; if (STE_HASBIT(ste_flags, STE_FR_MATCHCASE)) sci_flags |= wxSTC_FIND_MATCHCASE; if (STE_HASBIT(ste_flags, STE_FR_WHOLEWORD)) sci_flags |= wxSTC_FIND_WHOLEWORD; if (STE_HASBIT(ste_flags, STE_FR_WORDSTART)) sci_flags |= wxSTC_FIND_WORDSTART; if (STE_HASBIT(ste_flags, STE_FR_REGEXP )) sci_flags |= wxSTC_FIND_REGEXP; if (STE_HASBIT(ste_flags, STE_FR_POSIX )) sci_flags |= wxSTC_FIND_POSIX; return sci_flags; } // static int wxSTEditorFindReplaceData::ScintillaToSTEFindFlags(int sci_flags) { int ste_flags = 0; if (STE_HASBIT(sci_flags, wxSTC_FIND_MATCHCASE)) ste_flags |= STE_FR_MATCHCASE; if (STE_HASBIT(sci_flags, wxSTC_FIND_WHOLEWORD)) ste_flags |= STE_FR_WHOLEWORD; if (STE_HASBIT(sci_flags, wxSTC_FIND_WORDSTART)) ste_flags |= STE_FR_WORDSTART; if (STE_HASBIT(sci_flags, wxSTC_FIND_REGEXP )) ste_flags |= STE_FR_REGEXP; if (STE_HASBIT(sci_flags, wxSTC_FIND_POSIX )) ste_flags |= STE_FR_POSIX; return ste_flags; } // static bool wxSTEditorFindReplaceData::GotoFindAllString(const wxSTEditorFoundStringData& foundStringData, wxSTEditor* editor) { wxCHECK_MSG(editor, false, wxT("Invalid wxSTEditor to goto line in.")); // sanity check, maybe just go to the end if the doc if now shorter? if (foundStringData.GetFileName() == editor->GetFileName()) { if (foundStringData.GetFileStartPosition()+foundStringData.GetStringLength() <= editor->GetLength()) { editor->GotoPos(foundStringData.GetFileStartPosition()); editor->SetSelection(foundStringData.GetFileStartPosition(), foundStringData.GetFileStartPosition()+foundStringData.GetStringLength()); } else editor->GotoPos(editor->GetLength()); // move the cursor, hopefully they'll remember that they changed the file. return true; // we at least moved the cursor } return false; } bool wxSTEditorFindReplaceData::LoadConfig(wxConfigBase &config, const wxString &configPath) { m_loaded_config = true; // maybe it failed, but we tried at least once wxString key(wxSTEditorOptions::FixConfigPath(configPath, false)); long val = 0; if (config.Read(key + wxT("/FindFlags"), &val)) { SetFlags(int(val)); return true; } return false; } void wxSTEditorFindReplaceData::SaveConfig(wxConfigBase &config, const wxString &configPath) const { wxString key(wxSTEditorOptions::FixConfigPath(configPath, false)); config.Write(key + wxT("/FindFlags"), GetFlags()); } //----------------------------------------------------------------------------- // wxSTEditorFindResultsEditor //----------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxSTEditorFindResultsEditor, wxSTEditor) BEGIN_EVENT_TABLE(wxSTEditorFindResultsEditor, wxSTEditor) EVT_STC_MARGINCLICK (wxID_ANY, wxSTEditorFindResultsEditor::OnMarginClick) EVT_STEDITOR_MARGINDCLICK(wxID_ANY, wxSTEditorFindResultsEditor::OnMarginClick) EVT_STC_DOUBLECLICK (wxID_ANY, wxSTEditorFindResultsEditor::OnMarginClick) END_EVENT_TABLE() void wxSTEditorFindResultsEditor::Init() { m_targetWin = NULL; } bool wxSTEditorFindResultsEditor::Create(wxWindow *parent, wxWindowID winid, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { if (!wxSTEditor::Create(parent, winid, pos, size, style, name)) return false; SetStyleBits(5); // want to show indicators //SetMarginType(STE_MARGIN_NUMBER, wxSTC_MARGIN_NUMBER); //SetMarginWidth(STE_MARGIN_NUMBER, TextWidth(wxSTC_STYLE_LINENUMBER, wxT("_9999"))); //SetMarginSensitive(STE_MARGIN_NUMBER, true); // don't select line SetMarginWidth(STE_MARGIN_MARKER, 16); SetMarginSensitive(STE_MARGIN_MARKER, true); // don't select line //SetMarginWidth(STE_MARGIN_FOLD, 16); //SetMarginSensitive(STE_MARGIN_FOLD, true); // don't select line // edge colour //SetEdgeMode(wxSTC_EDGE_LINE); //SetEdgeColumn(7); SetReadOnly(true); SetLanguage(STE_LANG_NULL); return true; } wxSTEditorFindResultsEditor::~wxSTEditorFindResultsEditor() { if (wxSTEditorFindReplacePanel::GetFindResultsEditor() == this) wxSTEditorFindReplacePanel::SetFindResultsEditor(NULL); } void wxSTEditorFindResultsEditor::CreateOptions(const wxSTEditorOptions& options) { wxSTEditor::CreateOptions(options); } void wxSTEditorFindResultsEditor::CreateOptionsFromEditorOptions(const wxSTEditorOptions& editorOptions) { wxSTEditorOptions options; options.SetEditorStyles(editorOptions.GetEditorStyles()); options.SetEditorLangs(editorOptions.GetEditorLangs()); options.SetFindReplaceData(editorOptions.GetFindReplaceData(), true); // Nahhh, probaby best to use the simple default menu //options.SetEditorOptions(STE_CREATE_POPUPMENU|STE_CREATE_ACCELTABLE); //wxSTEditorMenuManager* steMM = new wxSTEditorMenuManager(STE_MENU_READONLY); //options.SetMenuManager(steMM, false); CreateOptions(options); } void wxSTEditorFindResultsEditor::SetResults(const wxSTEditorFindReplaceData& findReplaceData) { m_findReplaceData = findReplaceData; const wxArraySTEditorFoundStringData& foundStringArray = m_findReplaceData.GetFoundStringArray(); size_t n, count = foundStringArray.GetCount(); m_lineArrayMap.Clear(); ClearAll(); ClearAllIndicators(); if (count < 1) { SetReadOnly(false); SetText(wxEmptyString); SetReadOnly(true); return; } IndicatorSetStyle(wxSTC_INDIC0_MASK, wxSTC_INDIC_ROUNDBOX); IndicatorSetForeground(wxSTC_INDIC0_MASK, *wxRED); wxSTEditorStyles::GetGlobalEditorStyles().SetEditorStyle( 3, STE_STYLE_STRING, this, false); wxSTEditorStyles::GetGlobalEditorStyles().SetEditorStyle( 4, STE_STYLE_NUMBER, this, false); int pos = 0; wxFileName lastFileName; wxString str; SetReadOnly(false); for (n = 0; n < count; n++) { if (foundStringArray[n].GetFileName() != lastFileName) { lastFileName = foundStringArray[n].GetFileName(); pos = GetLength(); SetFoldLevel(LineFromPosition(pos), 0); wxString fileNameString(foundStringArray[n].GetFileName().GetFullPath()); m_lineArrayMap.Add(-1); AppendText(fileNameString + wxT("\n")); StartStyling(pos, 31); SetStyling(fileNameString.Length(), 3); } m_lineArrayMap.Add(n); pos = GetLength(); SetFoldLevel(LineFromPosition(pos), 1); wxString lineString(wxString::Format(wxT("%5d"), foundStringArray[n].GetLineNumber()+1)); AppendText(lineString); StartStyling(pos, 31); SetStyling(lineString.Length(), 4); pos = GetLength(); AppendText(wxT(" : ") + foundStringArray[n].GetLineString()); SetIndicator(pos + 3 + (foundStringArray[n].GetFileStartPosition()-foundStringArray[n].GetLineStartPosition()), foundStringArray[n].GetStringLength(), wxSTC_INDIC2_MASK); } SetReadOnly(true); ColouriseDocument(); //IndicateAllStrings(m_findReplaceData.GetFindString(), // m_findReplaceData.GetFlags(), // wxSTC_INDIC0_MASK); // Tell our parents that we have new results in case we're hidden if (GetLength() > 0) { wxCommandEvent event(wxEVT_STEFIND_RESULTS_NEED_SHOWN, GetId()); event.SetEventObject(this); GetEventHandler()->ProcessEvent(event); } } void wxSTEditorFindResultsEditor::OnMarginClick( wxStyledTextEvent &event ) { //if (!m_created) return; // set after editor is fully created if (event.GetEventType() == wxEVT_STEDITOR_MARGINDCLICK) return; STE_TextPos pos = event.GetPosition(); if (event.GetEventType() == wxEVT_STC_DOUBLECLICK) // event pos not set correctly pos = GetCurrentPos(); int line = LineFromPosition(pos); if (GetLine(line).Strip(wxString::both).IsEmpty()) return; MarkerDeleteAll(STE_MARKER_BOOKMARK); if ((line < 0) || (line >= (int)m_lineArrayMap.GetCount()) || (m_lineArrayMap[line] < 0)) return; int findall_index = m_lineArrayMap[line]; MarkerAdd(line, STE_MARKER_BOOKMARK); wxFindDialogEvent findEvent(wxEVT_STEFIND_GOTO, GetId()); findEvent.SetEventObject(this); findEvent.SetFindString(m_findReplaceData.GetFoundStringArray()[findall_index].ToString()); findEvent.SetFlags(m_findReplaceData.GetFlags()); findEvent.SetExtraLong(findall_index); //Send(findEvent); if (m_targetWin) m_targetWin->GetEventHandler()->ProcessEvent(findEvent); else GetParent()->GetEventHandler()->ProcessEvent(findEvent); } //----------------------------------------------------------------------------- // wxSTEditorFindReplacePanel //----------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(wxSTEditorFindReplacePanel, wxPanel) wxSTEditorFindResultsEditor* wxSTEditorFindReplacePanel::sm_findResultsEditor = NULL; BEGIN_EVENT_TABLE(wxSTEditorFindReplacePanel, wxPanel) EVT_TEXT (ID_STEDLG_FIND_COMBO, wxSTEditorFindReplacePanel::OnFindComboText) EVT_TEXT (ID_STEDLG_REPLACE_COMBO, wxSTEditorFindReplacePanel::OnFindComboText) EVT_CHECKBOX (wxID_ANY, wxSTEditorFindReplacePanel::OnCheckBox) EVT_RADIOBOX (wxID_ANY, wxSTEditorFindReplacePanel::OnCheckBox) EVT_RADIOBUTTON (wxID_ANY, wxSTEditorFindReplacePanel::OnCheckBox) EVT_BUTTON (wxID_ANY, wxSTEditorFindReplacePanel::OnButton) EVT_MENU (wxID_ANY, wxSTEditorFindReplacePanel::OnMenu) #ifdef __WXMSW__ EVT_IDLE (wxSTEditorFindReplacePanel::OnIdle) #endif //EVT_ACTIVATE (wxSTEditorFindReplacePanel::OnActivate) END_EVENT_TABLE() wxSTEditorFindReplacePanel::~wxSTEditorFindReplacePanel() { m_findCombo = NULL; m_replaceCombo = NULL; delete m_insertMenu; } void wxSTEditorFindReplacePanel::Init() { m_created = false; m_ignore_activation = false; m_targetWin = NULL; m_flags = 0; m_findReplaceData = NULL; m_find_insert_pos = 0; m_replace_insert_pos = 0; m_findCombo = NULL; m_replaceCombo = NULL; m_wholewordCheckBox = NULL; m_matchcaseCheckBox = NULL; m_backwardsCheckBox = NULL; m_wordstartCheckBox = NULL; m_regexpFindCheckBox = NULL; m_wraparoundCheckBox = NULL; m_findallCheckBox = NULL; m_bookmarkallCheckBox = NULL; m_scopewholeRadioButton = NULL; m_scopecursorRadioButton = NULL; m_scopealldocsRadioButton = NULL; m_findButton = NULL; m_replaceButton = NULL; m_replaceFindButton = NULL; m_replaceAllButton = NULL; m_insertMenu = NULL; m_resultEditor = NULL; } wxSizer *FindSizerSizer(wxSizer *sizer, wxSizer *topSizer) { wxSizerItemList &sizerList = topSizer->GetChildren(); for (wxSizerItemList::iterator it = sizerList.begin(); it != sizerList.end(); it++) { wxSizerItem *item = *it; if (item->IsSizer()) { if (item->GetSizer() == sizer) return topSizer; else { wxSizer *foundSizer = FindSizerSizer(sizer, item->GetSizer()); if (foundSizer) return foundSizer; } } } return NULL; } wxSizer *FindSizerWindow(wxWindow *win, wxSizer *topSizer) { wxSizerItemList &sizerList = topSizer->GetChildren(); for (wxSizerItemList::iterator it = sizerList.begin(); it != sizerList.end(); it++) { wxSizerItem *item = *it; if (item->IsWindow() && (item->GetWindow() == win)) return topSizer; else if (item->IsSizer()) { wxSizer *foundSizer = FindSizerWindow(win, item->GetSizer()); if (foundSizer) return foundSizer; } } return NULL; } bool wxSTEditorFindReplacePanel::Create(wxWindow *parent, wxWindowID winid, wxSTEditorFindReplaceData *data, const wxPoint& pos, const wxSize& size, long style, const wxString& name) { if ( !wxPanel::Create(parent, winid, pos, size, style, name) ) return false; wxSizer* frSizer = wxSTEditorFindReplaceSizer(this, false, false); m_findCombo = wxStaticCast(FindWindow(ID_STEDLG_FIND_COMBO ), wxComboBox); m_replaceCombo = wxStaticCast(FindWindow(ID_STEDLG_REPLACE_COMBO), wxComboBox); m_wholewordCheckBox = wxStaticCast(FindWindow(ID_STEDLG_WHOLEWORD_CHECKBOX ), wxCheckBox); m_matchcaseCheckBox = wxStaticCast(FindWindow(ID_STEDLG_MATCHCASE_CHECKBOX ), wxCheckBox); m_backwardsCheckBox = wxStaticCast(FindWindow(ID_STEDLG_BACKWARDS_CHECKBOX ), wxCheckBox); m_wordstartCheckBox = wxStaticCast(FindWindow(ID_STEDLG_WORDSTART_CHECKBOX ), wxCheckBox); m_regexpFindCheckBox = wxStaticCast(FindWindow(ID_STEDLG_REGEXP_FIND_CHECKBOX), wxCheckBox); m_wraparoundCheckBox = wxStaticCast(FindWindow(ID_STEDLG_WRAP_CHECKBOX ), wxCheckBox); m_findallCheckBox = wxStaticCast(FindWindow(ID_STEDLG_FINDALL_CHECKBOX ), wxCheckBox); m_bookmarkallCheckBox = wxStaticCast(FindWindow(ID_STEDLG_BOOKMARKALL_CHECKBOX), wxCheckBox); m_scopewholeRadioButton = wxStaticCast(FindWindow(ID_STEDLG_SCOPEWHOLE_RADIOBUTTON ), wxRadioButton); m_scopecursorRadioButton = wxStaticCast(FindWindow(ID_STEDLG_SCOPECURSOR_RADIOBUTTON ), wxRadioButton); m_scopealldocsRadioButton = wxStaticCast(FindWindow(ID_STEDLG_SCOPEALLDOCS_RADIOBUTTON), wxRadioButton); m_findButton = wxStaticCast(FindWindow(ID_STEDLG_FIND_BUTTON ), wxButton); m_replaceButton = wxStaticCast(FindWindow(ID_STEDLG_REPLACE_BUTTON ), wxButton); m_replaceFindButton = wxStaticCast(FindWindow(ID_STEDLG_REPLACEFIND_BUTTON), wxButton); m_replaceAllButton = wxStaticCast(FindWindow(ID_STEDLG_REPLACEALL_BUTTON ), wxButton); m_insertMenu = wxSTEditorMenuManager::CreateInsertCharsMenu(NULL, STE_MENU_INSERTCHARS_CHARS|STE_MENU_INSERTCHARS_REGEXP); if (!data) { Enable(false); return false; } // Set the data and update the button state based on its values SetData(data); if (HasFlag(STE_FR_NOUPDOWN)) { m_backwardsCheckBox->SetValue(false); FindSizerWindow(m_backwardsCheckBox, frSizer)->Show(m_backwardsCheckBox, false); } if (HasFlag(STE_FR_NOMATCHCASE)) { m_matchcaseCheckBox->SetValue(true); FindSizerWindow(m_matchcaseCheckBox, frSizer)->Show(m_matchcaseCheckBox, false); } if (HasFlag(STE_FR_NOWHOLEWORD)) { m_wholewordCheckBox->SetValue(false); FindSizerWindow(m_wholewordCheckBox, frSizer)->Show(m_wholewordCheckBox, false); } if (HasFlag(STE_FR_NOWORDSTART)) { m_wordstartCheckBox->SetValue(false); FindSizerWindow(m_wordstartCheckBox, frSizer)->Show(m_wordstartCheckBox, false); } if (HasFlag(STE_FR_NOWRAPAROUND)) { m_wraparoundCheckBox->SetValue(false); FindSizerWindow(m_wraparoundCheckBox, frSizer)->Show(m_wraparoundCheckBox, false); } if (HasFlag(STE_FR_NOREGEXP)) { m_regexpFindCheckBox->SetValue(false); FindSizerWindow(m_regexpFindCheckBox, frSizer)->Show(m_regexpFindCheckBox, false); } if (HasFlag(STE_FR_NOALLDOCS)) { m_scopealldocsRadioButton->Show(false); // you can't find in all docs, remove that flag, set find from cursor if ( m_findReplaceData->HasFlag(STE_FR_ALLDOCS) || (!m_findReplaceData->HasFlag(STE_FR_WHOLEDOC) && !m_findReplaceData->HasFlag(STE_FR_FROMCURSOR)) ) m_findReplaceData->SetFlags((m_findReplaceData->GetFlags() & ~STE_FR_SEARCH_MASK) | STE_FR_FROMCURSOR); } if (HasFlag(STE_FR_NOFINDALL)) { m_findallCheckBox->SetValue(false); m_findallCheckBox->Show(false); } if (HasFlag(STE_FR_NOBOOKMARKALL)) { m_bookmarkallCheckBox->SetValue(false); m_bookmarkallCheckBox->Show(false); } if (!HasFlag(wxFR_REPLACEDIALOG)) { wxSizer *sizer = FindSizerWindow(m_replaceCombo, frSizer); if (sizer) { sizer->Show(FindWindow(ID_STEDLG_REPLACE_TEXT), false); sizer->Show(m_replaceCombo, false); sizer->Show(FindWindow(ID_STEDLG_REPLACE_BITMAPBUTTON), false); } wxSizer *replaceSizer = FindSizerWindow(m_replaceButton, frSizer); sizer = FindSizerSizer(replaceSizer, frSizer); if (sizer) sizer->Hide(replaceSizer); } wxFlexGridSizer *rootSizer = new wxFlexGridSizer( 1, 0, 0 ); rootSizer->AddGrowableCol( 0 ); rootSizer->AddGrowableRow( 1 ); rootSizer->Add(frSizer, 0, wxGROW, 0); m_resultEditor = new wxSTEditorFindResultsEditor(this, wxID_ANY); m_resultEditor->Show(false); rootSizer->Add(m_resultEditor, 1, wxGROW, 0); //rootSizer->Show(m_resultEditor, m_findReplaceData->HasFlag(STE_FR_FINDALL)); SetSizer(rootSizer); rootSizer->Layout(); Layout(); rootSizer->SetSizeHints( this ); //rootSizer->Fit( this ); m_created = true; FindWindow(wxID_CANCEL)->SetLabel(wxGetStockLabel(wxID_CLOSE, wxSTOCK_NOFLAGS)); UpdateFindFlags(); UpdateButtons(); m_findCombo->SetFocus(); return true; } void wxSTEditorFindReplacePanel::SetData(wxSTEditorFindReplaceData *data) { wxCHECK_RET(data, wxT("Invalid find replace data in wxSTEditorFindReplaceDialog::SetData")); m_findReplaceData = data; // setup the find/replace comboboxes wxSTEInitComboBoxStrings(m_findReplaceData->GetFindStrings(), m_findCombo); wxSTEInitComboBoxStrings(m_findReplaceData->GetReplaceStrings(), m_replaceCombo); // setup the options checkboxes int flags = m_findReplaceData->GetFlags(); m_wholewordCheckBox->SetValue(STE_HASBIT(flags, wxFR_WHOLEWORD)); m_matchcaseCheckBox->SetValue(STE_HASBIT(flags, wxFR_MATCHCASE)); m_backwardsCheckBox->SetValue(!STE_HASBIT(flags, wxFR_DOWN)); m_wordstartCheckBox->SetValue(STE_HASBIT(flags, STE_FR_WORDSTART)); m_regexpFindCheckBox->SetValue(STE_HASBIT(flags, STE_FR_REGEXP)); m_wraparoundCheckBox->SetValue(STE_HASBIT(flags, STE_FR_WRAPAROUND)); m_findallCheckBox->SetValue(STE_HASBIT(flags, STE_FR_FINDALL)); m_bookmarkallCheckBox->SetValue(STE_HASBIT(flags, STE_FR_BOOKMARKALL)); // setup the scope radio buttons if (STE_HASBIT(flags, STE_FR_FROMCURSOR)) m_scopecursorRadioButton->SetValue(true); else if (STE_HASBIT(flags, STE_FR_ALLDOCS)) m_scopealldocsRadioButton->SetValue(true); else m_scopewholeRadioButton->SetValue(true); } wxWindow* wxSTEditorFindReplacePanel::GetTargetWindow() const { return m_targetWin ? m_targetWin : GetParent(); } wxSTEditor* wxSTEditorFindReplacePanel::GetEditor() const { wxWindow* targetWindow = GetTargetWindow(); wxSTEditor* edit = NULL; if (targetWindow) { if (wxDynamicCast(targetWindow, wxSTEditorNotebook)) edit = wxDynamicCast(targetWindow, wxSTEditorNotebook)->GetEditor(); else if (wxDynamicCast(targetWindow, wxSTEditorSplitter)) edit = wxDynamicCast(targetWindow, wxSTEditorSplitter)->GetEditor(); else if (wxDynamicCast(targetWindow, wxSTEditor)) edit = wxDynamicCast(targetWindow, wxSTEditor); } return edit; } void wxSTEditorFindReplacePanel::SendEvent(const wxEventType& evtType) { wxFindDialogEvent event(evtType, GetId()); event.SetEventObject(this); event.SetFindString(m_findCombo->GetValue()); event.SetFlags(GetFindFlags()); event.SetExtraLong(-1); if (evtType != wxEVT_COMMAND_FIND_CLOSE) wxSTEPrependComboBoxString(m_findCombo->GetValue(), m_findCombo, m_findReplaceData->GetMaxStrings()); if ( HasFlag(wxFR_REPLACEDIALOG) ) { wxSTEPrependComboBoxString(m_replaceCombo->GetValue(), m_replaceCombo, m_findReplaceData->GetMaxStrings()); event.SetReplaceString(m_replaceCombo->GetValue()); } Send(event); } void wxSTEditorFindReplacePanel::Send(wxFindDialogEvent& event) { // we copy the data to dialog->GetData() as well m_findReplaceData->SetFlags(event.GetFlags()); m_findReplaceData->SetFindString(event.GetFindString()); if (event.GetFindString().Length()) m_findReplaceData->AddFindString(event.GetFindString()); if ( HasFlag(wxFR_REPLACEDIALOG) && (event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE || event.GetEventType() == wxEVT_COMMAND_FIND_REPLACE_ALL) ) { m_findReplaceData->SetReplaceString(event.GetReplaceString()); m_findReplaceData->AddReplaceString(event.GetReplaceString()); } // translate wxEVT_COMMAND_FIND_NEXT to wxEVT_COMMAND_FIND if needed if ( event.GetEventType() == wxEVT_COMMAND_FIND_NEXT ) { if ( m_findReplaceData->GetFindString() != m_lastSearch ) { event.SetEventType(wxEVT_COMMAND_FIND); m_lastSearch = m_findReplaceData->GetFindString(); } } wxSTEditorFindResultsEditor* resultsEditor = GetFindResultsEditor() ? GetFindResultsEditor() : m_resultEditor; if (m_findReplaceData->HasFlag(STE_FR_FINDALL) && resultsEditor && ((event.GetEventType() == wxEVT_COMMAND_FIND) || (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT))) { m_findReplaceData->GetFoundStringArray().Clear(); resultsEditor->SetResults(*m_findReplaceData); } wxWindow *target = GetTargetWindow(); // first send event to ourselves then to the target if ( !GetEventHandler()->ProcessEvent(event) && target ) { // the event is not propagated upwards to the parent automatically // because the dialog is a top level window, so do it manually as // in 9 cases of 10 the message must be processed by the dialog // owner and not the dialog itself target->GetEventHandler()->ProcessEvent(event); } if (m_findReplaceData->HasFlag(STE_FR_FINDALL) && resultsEditor && ((event.GetEventType() == wxEVT_COMMAND_FIND) || (event.GetEventType() == wxEVT_COMMAND_FIND_NEXT))) { resultsEditor->SetTargetWindow(GetTargetWindow()); resultsEditor->SetResults(*m_findReplaceData); } wxWindow* focusWin = FindFocus(); // restore the focus to the text editor, not the find results editor if (resultsEditor && (resultsEditor == focusWin) && (GetTargetWindow() != NULL)) { wxSTEditorNotebook* steNotebook = wxDynamicCast(GetTargetWindow(), wxSTEditorNotebook); if (steNotebook && steNotebook->GetEditor()) steNotebook->GetEditor()->SetFocus(); else GetTargetWindow()->SetFocus(); } UpdateButtons(); } void wxSTEditorFindReplacePanel::OnButton(wxCommandEvent& event) { switch (event.GetId()) { case ID_STEDLG_FIND_BITMAPBUTTON : { // set the clientdata of the menu to the combo it's for, see OnMenu wxRect r = ((wxWindow*)event.GetEventObject())->GetRect(); m_insertMenu->SetClientData((void*)m_findCombo); m_insertMenu->Enable(ID_STEDLG_MENU_INSERTMENURE, m_regexpFindCheckBox->IsChecked()); PopupMenu(m_insertMenu, r.GetRight(), r.GetTop()); break; } case ID_STEDLG_REPLACE_BITMAPBUTTON : { wxRect r = ((wxWindow*)event.GetEventObject())->GetRect(); m_insertMenu->SetClientData((void*)m_replaceCombo); m_insertMenu->Enable(ID_STEDLG_MENU_INSERTMENURE, m_regexpFindCheckBox->IsChecked()); PopupMenu(m_insertMenu, r.GetRight(), r.GetTop()); break; } case ID_STEDLG_FIND_BUTTON : SendEvent(wxEVT_COMMAND_FIND_NEXT); break; case ID_STEDLG_REPLACE_BUTTON : SendEvent(wxEVT_COMMAND_FIND_REPLACE); break; case ID_STEDLG_REPLACEFIND_BUTTON : SendEvent(wxEVT_COMMAND_FIND_REPLACE); SendEvent(wxEVT_COMMAND_FIND_NEXT); break; case ID_STEDLG_REPLACEALL_BUTTON : SendEvent(wxEVT_COMMAND_FIND_REPLACE_ALL); break; case wxID_CANCEL : SendEvent(wxEVT_COMMAND_FIND_CLOSE); event.Skip(); break; default : break; } } void wxSTEditorFindReplacePanel::OnMenu(wxCommandEvent& event) { wxString c; int ipos = 0; switch (event.GetId()) { case ID_STEDLG_INSERTMENU_TAB : c = wxT("\t"); break; case ID_STEDLG_INSERTMENU_CR : c = wxT("\r"); break; case ID_STEDLG_INSERTMENU_LF : c = wxT("\n"); break; case ID_STEDLG_INSERTMENURE_ANYCHAR : c = wxT("."); break; case ID_STEDLG_INSERTMENURE_RANGE : c = wxT("[]"); ipos = -1; break; case ID_STEDLG_INSERTMENURE_NOTRANGE : c = wxT("[^]"); ipos = -1; break; case ID_STEDLG_INSERTMENURE_BEGINLINE : c = wxT("^"); break; case ID_STEDLG_INSERTMENURE_ENDLINE : c = wxT("$"); break; case ID_STEDLG_INSERTMENURE_TAGEXPR : { if (!STE_HASBIT(GetFindFlags(), STE_FR_POSIX)) { c = wxT("\\(\\)"); ipos = -2; } else { c = wxT("()"); ipos = -1; } break; } case ID_STEDLG_INSERTMENURE_0MATCHES : c = wxT("*"); break; case ID_STEDLG_INSERTMENURE_1MATCHES : c = wxT("+"); break; case ID_STEDLG_INSERTMENURE_01MATCHES : c = wxT("?"); break; case ID_STEDLG_INSERTMENURE_ALPHANUM : c = wxT("[a-zA-Z0-9]"); break; case ID_STEDLG_INSERTMENURE_ALPHA : c = wxT("[a-zA-Z]"); break; case ID_STEDLG_INSERTMENURE_NUMERIC : c = wxT("[0-9]"); break; case ID_STEDLG_INSERTMENURE_TAB : c = wxT("\\t"); break; default : break; } if (c.Length()) // this must have been for the m_insertMenu { wxComboBox* cBox = wxStaticCast(m_insertMenu->GetClientData(), wxComboBox); wxCHECK_RET(cBox, wxT("Unexpected missing control")); #ifdef __WXMSW__ // See comment in OnIdle(), MSW forgets insertion point after losing focus wxTextPos pos = (cBox == m_findCombo) ? m_find_insert_pos : m_replace_insert_pos; #else wxTextPos pos = cBox->GetInsertionPoint(); #endif wxString s = cBox->GetValue(); if (pos >= int(s.Length())) s += c; else if (pos == 0) s = c + s; else s = s.Mid(0, pos) + c + s.Mid(pos); cBox->SetValue(s); cBox->SetFocus(); cBox->SetInsertionPoint(pos + (int)c.Length() + ipos); m_ignore_activation = true; } } void wxSTEditorFindReplacePanel::OnActivate(wxActivateEvent &event) { event.Skip(); if (event.GetActive()) { if (!m_ignore_activation) SelectFindString(); UpdateButtons(); } m_ignore_activation = false; } void wxSTEditorFindReplacePanel::OnIdle(wxIdleEvent &event) { if (IsShown()) { // This is a really ugly hack because the combo forgets its insertion // point in MSW whenever it loses focus wxWindow* focus = FindFocus(); if (m_findCombo && (focus == m_findCombo)) m_find_insert_pos = m_findCombo->GetInsertionPoint(); if (m_replaceCombo && (focus == m_replaceCombo)) m_replace_insert_pos = m_replaceCombo->GetInsertionPoint(); } event.Skip(); } void wxSTEditorFindReplacePanel::UpdateFindFlags() { m_flags = 0; if (m_matchcaseCheckBox->GetValue()) m_flags |= wxFR_MATCHCASE; if (m_wholewordCheckBox->GetValue()) m_flags |= wxFR_WHOLEWORD; if (!m_backwardsCheckBox->GetValue()) m_flags |= wxFR_DOWN; if (m_wordstartCheckBox->GetValue()) m_flags |= STE_FR_WORDSTART; if (m_regexpFindCheckBox->GetValue()) m_flags |= STE_FR_REGEXP; if (m_wraparoundCheckBox->GetValue()) m_flags |= STE_FR_WRAPAROUND; if (m_findallCheckBox->GetValue()) m_flags |= STE_FR_FINDALL; if (m_bookmarkallCheckBox->GetValue()) m_flags |= STE_FR_BOOKMARKALL; if (m_scopewholeRadioButton->GetValue()) m_flags |= STE_FR_WHOLEDOC; else if (m_scopecursorRadioButton->GetValue()) m_flags |= STE_FR_FROMCURSOR; else if (m_scopealldocsRadioButton->GetValue()) m_flags |= STE_FR_ALLDOCS; if (!GetFindResultsEditor() && m_resultEditor && (m_resultEditor->IsShown() != STE_HASBIT(m_flags, STE_FR_FINDALL))) { InvalidateBestSize(); SetMinSize(wxSize(10, 10)); GetSizer()->SetMinSize(wxSize(10, 10)); GetSizer()->Show(m_resultEditor, STE_HASBIT(m_flags, STE_FR_FINDALL)); GetSizer()->Layout(); GetSizer()->SetSizeHints(this); } } void wxSTEditorFindReplacePanel::SelectFindString() { wxString value = m_findCombo->GetValue(); if (value.Len() > 0u) m_findCombo->SetSelection(0, (int)value.Len()); } void wxSTEditorFindReplacePanel::OnFindComboText(wxCommandEvent& WXUNUSED(event)) { UpdateButtons(); } void wxSTEditorFindReplacePanel::OnCheckBox(wxCommandEvent &event) { UpdateFindFlags(); UpdateButtons(); event.Skip(); } // FIXME - This is a hack for a bug in GTK (not wxWidgets) where if you enable // a button you cannot click on it without capturing and releasing the mouse. void wxSTE_WIN_ENABLE(wxWindow* win, bool enable) { if (win && (win->IsEnabled() != enable)) { win->Enable(enable); #ifdef __WXGTK__ if (enable && win->IsShown()) { if (!win->HasCapture()) win->CaptureMouse(); if (win->HasCapture()) win->ReleaseMouse(); } #endif // __WXGTK__ } } void wxSTEditorFindReplacePanel::UpdateButtons() { if (!m_created) return; // skip initial events sent from combobox in GTK // Can't search backwards when using regexp if (m_regexpFindCheckBox->GetValue() && m_backwardsCheckBox->IsEnabled()) { m_backwardsCheckBox->SetValue(false); m_backwardsCheckBox->Enable(false); } else if (!m_regexpFindCheckBox->GetValue() && !m_backwardsCheckBox->IsEnabled()) { m_backwardsCheckBox->Enable(true); } // update the find/replace button state const wxString findStr = m_findCombo->GetValue(); bool enable = findStr.Length() > 0u; wxSTEditor *edit = GetEditor(); int flags = GetFindFlags(); if (enable) { bool changed = edit ? ((edit->GetFindString() != findStr)||(edit->GetFindFlags() != flags)) : true; enable &= ((edit && edit->CanFind()) ? true : changed); } wxSTE_WIN_ENABLE(m_findButton, enable); if (HasFlag(wxFR_REPLACEDIALOG)) { // Don't want recursive find if (m_findReplaceData->StringCmp(findStr, m_replaceCombo->GetValue(), flags)) enable = false; wxSTE_WIN_ENABLE(m_replaceAllButton, enable); wxString selText = edit ? edit->GetSelectedText() : wxString(wxEmptyString); // can only replace if already selecting the "find" text if (enable && edit && !edit->SelectionIsFindString(findStr, flags)) enable = false; else if (!m_regexpFindCheckBox->IsChecked() && !m_findReplaceData->StringCmp(findStr, selText, flags)) enable = false; wxSTE_WIN_ENABLE(m_replaceButton, enable); wxSTE_WIN_ENABLE(m_replaceFindButton, enable); } } //----------------------------------------------------------------------------- // wxSTEditorFindReplaceDialog //----------------------------------------------------------------------------- const wxString wxSTEditorFindReplaceDialogNameStr = wxT("wxSTEditorFindReplaceDialogNameStr"); IMPLEMENT_DYNAMIC_CLASS(wxSTEditorFindReplaceDialog, wxDialog) BEGIN_EVENT_TABLE(wxSTEditorFindReplaceDialog, wxDialog) EVT_BUTTON (wxID_ANY, wxSTEditorFindReplaceDialog::OnButton) EVT_CHECKBOX (wxID_ANY, wxSTEditorFindReplaceDialog::OnButton) EVT_SIZE (wxSTEditorFindReplaceDialog::OnSize) EVT_ACTIVATE (wxSTEditorFindReplaceDialog::OnActivate) EVT_CLOSE (wxSTEditorFindReplaceDialog::OnCloseWindow) END_EVENT_TABLE() wxSTEditorFindReplaceDialog::~wxSTEditorFindReplaceDialog() {} void wxSTEditorFindReplaceDialog::Init() { m_findReplacePanel = NULL; } bool wxSTEditorFindReplaceDialog::Create(wxWindow *parent, wxSTEditorFindReplaceData *data, const wxString& title, int style, const wxString &name) { if (!wxDialog::Create(parent, ID_STE_FINDREPLACE_DIALOG, title, wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE_RESIZE | wxFRAME_FLOAT_ON_PARENT | style, name)) //wxDEFAULT_FRAME_STYLE | wxRESIZE_BORDER | wxFRAME_FLOAT_ON_PARENT | style, { return false; } m_findReplacePanel = new wxSTEditorFindReplacePanel(this, wxID_ANY, data, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER | style); m_findReplacePanel->SetTargetWindow(parent); // assume this, they can override later // use sizer since child file replace panel will use it to resize us //wxFlexGridSizer* rootSizer = new wxFlexGridSizer(1, 0, 0); //rootSizer->AddGrowableCol( 0 ); //rootSizer->AddGrowableRow( 0 ); wxBoxSizer* rootSizer = new wxBoxSizer(wxVERTICAL); rootSizer->Add(m_findReplacePanel, 1, wxGROW); SetSizer(rootSizer); rootSizer->SetSizeHints(this); // set the last user set size, but only if it's bigger than the size we // are already wxSize dialogSize = data ? data->GetDialogSize() : wxDefaultSize; wxSize size = GetSize(); if (m_findReplacePanel->m_resultEditor && m_findReplacePanel->m_resultEditor->IsShown() && (dialogSize != wxDefaultSize) && ((dialogSize.x > size.x) || (dialogSize.y > size.y))) { SetSize(wxMax(dialogSize.x, size.x), wxMax(dialogSize.y, size.y)); } Centre(); SetIcon(wxArtProvider::GetIcon((style & wxFR_REPLACEDIALOG) ? wxART_STEDIT_REPLACE : wxART_STEDIT_FIND, wxART_FRAME_ICON)); return true; } void wxSTEditorFindReplaceDialog::OnCloseWindow(wxCloseEvent &event) { if (m_findReplacePanel) m_findReplacePanel->SendEvent(wxEVT_COMMAND_FIND_CLOSE); event.Skip(); } void wxSTEditorFindReplaceDialog::OnActivate(wxActivateEvent &event) { event.Skip(); if (event.GetActive() && m_findReplacePanel) m_findReplacePanel->OnActivate(event); } void wxSTEditorFindReplaceDialog::OnButton(wxCommandEvent& event) { switch (event.GetId()) { case ID_STEDLG_FINDALL_CHECKBOX : { // wxWidgets needs help resizing the shown/hidden results editor // This ugly hack works in any case //wxSize s = GetSize(); //wxSize minSize = m_findReplacePanel->GetSize(); //wxPrintf(wxT("DLG %d %d %d %d\n"), s.GetWidth(), s.GetHeight(), minSize.GetWidth(), minSize.GetHeight()); InvalidateBestSize(); SetMinSize(wxSize(10,10)); GetSizer()->SetMinSize(wxSize(10,10)); m_findReplacePanel->GetSizer()->SetSizeHints(this); break; } case wxID_CANCEL : Destroy(); default : event.Skip(); } } void wxSTEditorFindReplaceDialog::OnSize(wxSizeEvent &event) { /* if (GetSize() != m_findReplacePanel->GetSizer()->CalcMin()) { InvalidateBestSize(); SetMinSize(wxSize(10,10)); GetSizer()->SetMinSize(wxSize(10,10)); m_findReplacePanel->GetSizer()->SetMinSize(wxSize(10,10)); m_findReplacePanel->GetSizer()->SetSizeHints(m_findReplacePanel); GetSizer()->SetSizeHints(this); //SetClientSize(GetSizer()->CalcMin()); } else */ // remember the size of the find dialog for find all if (m_findReplacePanel && m_findReplacePanel->GetData() && m_findReplacePanel->m_resultEditor && m_findReplacePanel->m_resultEditor->IsShown()) { m_findReplacePanel->GetData()->SetDialogSize(GetSize()); } event.Skip(); //wxPrintf(wxT("wxSTEditorFindReplaceDialog::OnSize %d %d %d %d\n"), GetSize().x, GetSize().y, event.GetSize().x, event.GetSize().y); }
#include <algorithm> #include <assert.h> #include <siar_plugins/plugin_siar_wheels_piston.h> #include <gazebo/math/gzmath.hh> #include <sdf/sdf.hh> #include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/Vector3.h> #include <std_msgs/Float32.h> #include <nav_msgs/GetMap.h> #include <nav_msgs/Odometry.h> #include <boost/bind.hpp> #include <boost/thread/mutex.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include <gazebo/gazebo_config.h> #include "siar_driver/SiarStatus.h" namespace gazebo { enum { RIGHT, LEFT, }; GazeboRosWheelsPiston::GazeboRosWheelsPiston() { } // Destructor GazeboRosWheelsPiston::~GazeboRosWheelsPiston() { delete rosnode_; delete transform_broadcaster_; delete inter_va; delete inter_vr; } // Load the controller void GazeboRosWheelsPiston::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf) { this->parent = _parent; this->world = _parent->GetWorld(); if (!_sdf->HasElement("robotNamespace")) { ROS_INFO("GazeboRosWheelsPiston Plugin missing <robotNamespace>, defaults to \"%s\"", this->robot_namespace_.c_str()); } else { this->robot_namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>() + "/"; } //this->left_joint_names_ = "left_joint"; if (!_sdf->HasElement("leftJoints")) { gzthrow("Have to specify space separated left side joint names via <leftJoints> tag!"); } else { std::string joint_string = _sdf->GetElement("leftJoints")->Get<std::string>(); boost::split( joint_names_[LEFT], joint_string, boost::is_any_of(" ") ); } //this->right_joint_names_ = "right_joint"; if (!_sdf->HasElement("rightJoints")) { gzthrow("Have to specify space separated right side joint names via <rightJoints> tag!"); } else { std::string joint_string = _sdf->GetElement("rightJoints")->Get<std::string>(); boost::split( joint_names_[RIGHT], joint_string, boost::is_any_of(" ") ); } this->init_wheel_separation_ = 0.62; if (!_sdf->HasElement("initWheelSeparation")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <initWheelSeparation>, defaults to %f", this->robot_namespace_.c_str(), this->init_wheel_separation_); } else { this->init_wheel_separation_ = _sdf->GetElement("initWheelSeparation")->Get<double>(); } this->wheel_diameter_ = 0.25; if (!_sdf->HasElement("wheelDiameter")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <wheelDiameter>, defaults to %f", this->robot_namespace_.c_str(), this->wheel_diameter_); } else { this->wheel_diameter_ = _sdf->GetElement("wheelDiameter")->Get<double>(); } this->speed_factor_ = 1.0; if (!_sdf->HasElement("speedFactor")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <speedFactor>, defaults to %f", this->robot_namespace_.c_str(), this->speed_factor_); } else { this->speed_factor_ = _sdf->GetElement("speedFactor")->Get<double>(); } this->torque = 15.0; if (!_sdf->HasElement("torque")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <torque>, defaults to %f", this->robot_namespace_.c_str(), this->torque); } else { this->torque = _sdf->GetElement("torque")->Get<double>(); } this->command_topic_ = "cmd_vel"; if (!_sdf->HasElement("commandTopic")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <commandTopic>, defaults to \"%s\"", this->robot_namespace_.c_str(), this->command_topic_.c_str()); } else { this->command_topic_ = _sdf->GetElement("commandTopic")->Get<std::string>(); } this->odometry_topic_ = "odom"; if (!_sdf->HasElement("odometryTopic")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <odometryTopic>, defaults to \"%s\"", this->robot_namespace_.c_str(), this->odometry_topic_.c_str()); } else { this->odometry_topic_ = _sdf->GetElement("odometryTopic")->Get<std::string>(); } this->odometry_frame_ = "odom"; if (!_sdf->HasElement("odometryFrame")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <odometryFrame>, defaults to \"%s\"", this->robot_namespace_.c_str(), this->odometry_frame_.c_str()); } else { this->odometry_frame_ = _sdf->GetElement("odometryFrame")->Get<std::string>(); } this->robot_base_frame_ = "base_footprint"; if (!_sdf->HasElement("robotBaseFrame")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <robotBaseFrame>, defaults to \"%s\"", this->robot_namespace_.c_str(), this->robot_base_frame_.c_str()); } else { this->robot_base_frame_ = _sdf->GetElement("robotBaseFrame")->Get<std::string>(); } this->update_rate_ = 100.0; if (!_sdf->HasElement("updateRate")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <updateRate>, defaults to %f", this->robot_namespace_.c_str(), this->update_rate_); } else { this->update_rate_ = _sdf->GetElement("updateRate")->Get<double>(); } this->publish_odometry_tf_ = true; if (!_sdf->HasElement("publishOdometryTf")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <publishOdometryTf>, defaults to %s", this->robot_namespace_.c_str(), this->publish_odometry_tf_ ? "true" : "false"); } else { this->publish_odometry_tf_ = _sdf->GetElement("publishOdometryTf")->Get<bool>(); } this->publish_odometry_msg_ = true; if (!_sdf->HasElement("publishOdometryMsg")) { ROS_WARN("GazeboRosWheelsPiston Plugin (ns = %s) missing <publishOdometryMsg>, defaults to %s", this->robot_namespace_.c_str(), this->publish_odometry_msg_ ? "true" : "false"); } else { this->publish_odometry_msg_ = _sdf->GetElement("publishOdometryMsg")->Get<bool>(); } // Initialize update rate stuff if (this->update_rate_ > 0.0) { this->update_period_ = 1.0 / this->update_rate_; } else { this->update_period_ = 0.0; } last_update_time_ = this->world->GetSimTime(); // Initialize velocity stuff wheel_speed_[RIGHT] = 0; wheel_speed_[LEFT] = 0; x_ = 0; rot_ = 0; alive_ = true; for (size_t side = 0; side < 2; ++side) { for (size_t i = 0; i < joint_names_[side].size(); ++i) { joints_[side].push_back(this->parent->GetJoint(joint_names_[side][i])); if (!joints_[side][i]) { char error[200]; snprintf(error, 200, "GazeboRosWheelsPiston Plugin (ns = %s) couldn't get hinge joint named \"%s\"", this->robot_namespace_.c_str(), joint_names_[side][i].c_str()); gzthrow(error); } #if (GAZEBO_MAJOR_VERSION > 4) joints_[side][i]->SetEffortLimit(0, torque); #else joints_[side][i]->SetMaxForce(0, torque); #endif } } // Get the SIAR relevant links & joint l_c_wheel_ = this->parent->GetLink("wheel_left_1"); r_c_wheel_ = this->parent->GetLink("wheel_right_1"); electronics_center = this->parent->GetLink("box_battery"); arm_siar_base_ = this->parent->GetLink("arm_siar_base"); arm_link_1_1_ = this->parent->GetLink("arm_siar_long_1_1"); arm_link_1_2_ = this->parent->GetLink("arm_siar_long_1_2"); //**** arm_link_2_1_ = this->parent->GetLink("arm_siar_long_2_1"); arm_link_2_2_ = this->parent->GetLink("arm_siar_long_2_2"); arm_link_3_ = this->parent->GetLink("arm_siar_base_3"); arm_link_4_ = this->parent->GetLink("arm_siar_base_4"); this -> piston_main_1_ = this->parent->GetJoint("move_piston_1_1"); this -> piston_main_2_ = this->parent->GetJoint("move_piston_1_2"); this -> hinge_arm_right_1_1_ = this->parent->GetJoint("hinge_arm_right_1_1"); this -> hinge_arm_right_1_2_ = this->parent->GetJoint("hinge_arm_right_1_2"); this -> hinge_arm_left_1_1_ = this->parent->GetJoint("hinge_arm_left_1_1"); this -> hinge_arm_left_1_2_ = this->parent->GetJoint("hinge_arm_left_1_2"); this -> axis_wheel_right_1_ = this->parent->GetJoint("move_axis_wheel_right_1"); this -> axis_wheel_right_2_ = this->parent->GetJoint("move_axis_wheel_right_2"); this -> axis_wheel_right_3_ = this->parent->GetJoint("move_axis_wheel_right_3"); this -> axis_wheel_left_1_ = this->parent->GetJoint("move_axis_wheel_left_1"); this -> axis_wheel_left_2_ = this->parent->GetJoint("move_axis_wheel_left_2"); this -> axis_wheel_left_3_ = this->parent->GetJoint("move_axis_wheel_left_3"); this -> axis_arm_1_ = this->parent->GetJoint("move_arm_4"); this -> axis_arm_3_1_ = this->parent->GetJoint("move_arm_3_1"); this -> axis_arm_3_2_ = this->parent->GetJoint("move_arm_3_2"); // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) { ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. " << "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)"); return; } rosnode_ = new ros::NodeHandle(this->robot_namespace_); // Load parameter to calculate interpolation if (!rosnode_->getParam("/cmd_vel_file", cmd_vel_file)) { cmd_vel_file = "/cmd_vel_file"; } if (!rosnode_->getParam("/vr_file", vr_file)) { vr_file = "/vr_file"; } if (!rosnode_->getParam("/va_file", va_file)) { va_file = "/va_file"; } inter_vr = new functions::LinearInterpolator(cmd_vel_file, vr_file); inter_va = new functions::LinearInterpolator(cmd_vel_file, va_file); //ROS_INFO("Starting GazeboRosWheelsPiston Plugin (ns = %s). Cmd_file= %s. iNTERPOL: %d!", this->robot_namespace_.c_str(), cmd_vel_file.c_str(), (int)inter_va->size()); tf_prefix_ = tf::getPrefixParam(*rosnode_); transform_broadcaster_ = new tf::TransformBroadcaster(); // ROS: Subscribe to the velocity command topic (usually "cmd_vel") ros::SubscribeOptions so = ros::SubscribeOptions::create<geometry_msgs::Twist>(command_topic_, 1, boost::bind(&GazeboRosWheelsPiston::cmdVelCallback, this, _1), ros::VoidPtr(), &queue_); cmd_vel_subscriber_ = rosnode_->subscribe(so); // ROS: Subscribe to the velocity command topic (usually "cmd_vel") so = ros::SubscribeOptions::create<std_msgs::Float32>("vel_state", 1, boost::bind(&GazeboRosWheelsPiston::velStateCallback, this, _1), ros::VoidPtr(), &queue_); vel_state_subscriber_ = rosnode_->subscribe(so); // SIAR: create elec pos subscriber so = ros::SubscribeOptions::create<std_msgs::Float32>("width_pos", 1, boost::bind(&GazeboRosWheelsPiston::elecPosCallback, this, _1), ros::VoidPtr(), &queue_); move_Piston_subscriber_= rosnode_->subscribe(so); // SIAR: create arm_bool subscriber (This change the width) so = ros::SubscribeOptions::create<std_msgs::Bool>("arm_bool", 1, boost::bind(&GazeboRosWheelsPiston::armCentralPosCallback, this, _1), ros::VoidPtr(), &queue_); arm_central_subscriber_= rosnode_->subscribe(so); // SIAR: create arm_mode to move the robotics Arm so = ros::SubscribeOptions::create<std_msgs::Bool>("arm_mode", 1, boost::bind(&GazeboRosWheelsPiston::moveArmPosCallback, this, _1), ros::VoidPtr(), &queue_); move_arm_subscriber_= rosnode_->subscribe(so); // SIAR: create arm_mode to move the robotics Arm so = ros::SubscribeOptions::create<std_msgs::Bool>("arm_as_mode", 1, boost::bind(&GazeboRosWheelsPiston::moveArmPosASCallback, this, _1), ros::VoidPtr(), &queue_); move_arm_as_subscriber_= rosnode_->subscribe(so); // SIAR: create arm_mode to move pan from robotics Arm so = ros::SubscribeOptions::create<std_msgs::Float32>("arm_pan", 1, boost::bind(&GazeboRosWheelsPiston::movePanArmCallback, this, _1), ros::VoidPtr(), &queue_); move_pan_arm_subscriber_= rosnode_->subscribe(so); // SIAR: create arm_mode to move tilt from robotics Arm so = ros::SubscribeOptions::create<std_msgs::Float32>("arm_tilt", 1, boost::bind(&GazeboRosWheelsPiston::moveTiltArmCallback, this, _1), ros::VoidPtr(), &queue_); move_tilt_arm_subscriber_= rosnode_->subscribe(so); // INitialize publishers odometry_publisher_ = rosnode_->advertise<nav_msgs::Odometry>(odometry_topic_, 1); width_publisher_ = rosnode_->advertise<std_msgs::Float32>("width", 1); pos_electronicBox_publisher_ = rosnode_->advertise<geometry_msgs::Vector3>("pos_ElectronicBox", 1); pos_centerMidWheels_publisher_ = rosnode_->advertise<geometry_msgs::Vector3>("pos_centerMidWheels_", 1); pos_vecBoxWheel_publisher_ = rosnode_->advertise<geometry_msgs::Vector3>("pos_vecBoxWheel_", 1); pos_vecUnitOrient_publisher_ = rosnode_->advertise<geometry_msgs::Vector3>("pos_vecUnitOrient_", 1); dis_box_centralaxis_publisher_= rosnode_->advertise<std_msgs::Float32>("dis_box_centralaxis_", 1); elec_pos_publisher_= rosnode_->advertise<std_msgs::Float32>("elec_pos", 1); siar_status_publisher_= rosnode_->advertise<siar_driver::SiarStatus>("siar_status",1); tf_base_link_publisher_= rosnode_->advertise<geometry_msgs::Vector3>("tf_base_link",1); arm_ang_rad_pan_publisher_= rosnode_->advertise<std_msgs::Float32>("arm_ang_rad_pan",1); arm_ang_rad_tilt_publisher_= rosnode_->advertise<std_msgs::Float32>("arm_ang_rad_tilt",1); // start custom queue for diff drive this->callback_queue_thread_ = boost::thread(boost::bind(&GazeboRosWheelsPiston::QueueThread, this)); // listen to the update event (broadcast every simulation iteration) this->update_connection_ = event::Events::ConnectWorldUpdateBegin( boost::bind(&GazeboRosWheelsPiston::UpdateChild, this)); // Initial values move_Piston_cmd_=1; move_Piston_aux_=1; elec_pos_cmd_ = 0; arm_central_cmd_=false; vel_state_cmd_=0; move_pan_arm_add_ = 0.0; move_tilt_arm_add_ = 0.0; move_elevation_arm_aux_ = 0; auxiliar_tilt = 0; limit_angle_pan = 1.57; limit_angle_tilt = 0.6; // limit_angle_tilt = 1.8; // Count for pub odom tf count_pub_odom = 0; } // Update the controller void GazeboRosWheelsPiston::UpdateChild() { common::Time current_time = this->world->GetSimTime(); double seconds_since_last_update = (current_time - last_update_time_).Double(); if (seconds_since_last_update > update_period_) { if (this->publish_odometry_tf_ || this->publish_odometry_msg_) { publishOdometry(seconds_since_last_update); } //Publish the SiarStatus siar_driver::SiarStatus msg; msg.width = width_; msg.electronics_x = (-1*elec_pos_cmd_); siar_status_publisher_.publish(msg); //Calculate Value of distance between Wheels updateWidth(); std_msgs::Float32 width_msg; width_msg.data = width_; width_publisher_.publish(width_msg); //Obtain Value of the distance between Center Robot and Electronic Box updateElecPos(); tfBaseLink(); this->pid_hinge_arm_right_left = common::PID(100, 5.0, 5.0); this->pid_hinge_arm = common::PID(0.1, 0.0, 0.02); this->pid_hinge_arm_2 = common::PID(0.1, 0.0, 0.02); //To control the width of SIAR this-> parent ->GetJointController()->SetPositionPID(this->hinge_arm_right_1_1_->GetScopedName(), this->pid_hinge_arm_right_left); this-> parent ->GetJointController()->SetPositionPID(this->hinge_arm_right_1_2_->GetScopedName(), this->pid_hinge_arm_right_left); this-> parent ->GetJointController()->SetPositionPID(this->hinge_arm_left_1_1_->GetScopedName(), this->pid_hinge_arm_right_left); this-> parent ->GetJointController()->SetPositionPID(this->hinge_arm_left_1_2_->GetScopedName(), this->pid_hinge_arm_right_left); this-> parent ->GetJointController()->SetPositionTarget(this->hinge_arm_right_1_1_->GetScopedName(), -1.2* elec_pos_cmd_); this-> parent ->GetJointController()->SetPositionTarget(this->hinge_arm_right_1_2_->GetScopedName(), -1.2* elec_pos_cmd_); this-> parent ->GetJointController()->SetPositionTarget(this->hinge_arm_left_1_1_->GetScopedName(), 1.2* elec_pos_cmd_); this-> parent ->GetJointController()->SetPositionTarget(this->hinge_arm_left_1_2_->GetScopedName(), 1.2* elec_pos_cmd_); // Here to limit the first option move_Piston_cmd_ = 1 like value, because it is given problem like initial value if ( (move_Piston_cmd_ == 0) || move_Piston_aux_ == 0) { elec_pos_cmd_ = move_Piston_cmd_ ; move_Piston_aux_= 0; } //Publish the position of electronics_center std_msgs::Float32 elec_pos_msg; elec_pos_msg.data = (-1*elec_pos_cmd_); elec_pos_publisher_.publish(elec_pos_msg); //Publish the position of electronics_center std_msgs::Float32 arm_ang_rad_pan_msg; arm_ang_rad_pan_msg.data = (move_pan_arm_add_); arm_ang_rad_pan_publisher_.publish(arm_ang_rad_pan_msg); std_msgs::Float32 arm_ang_rad_tilt_msg; arm_ang_rad_tilt_msg.data = (move_tilt_arm_add_); arm_ang_rad_tilt_publisher_.publish(arm_ang_rad_tilt_msg); // Update robot in case new velocities have been requested or to control arm this-> parent ->GetJointController()->SetPositionPID(this->axis_arm_1_->GetScopedName(), this->pid_hinge_arm); this-> parent ->GetJointController()->SetPositionTarget(this->axis_arm_1_->GetScopedName(), move_pan_arm_add_); this-> parent ->GetJointController()->SetPositionPID(this->axis_arm_3_1_->GetScopedName(), this->pid_hinge_arm); this-> parent ->GetJointController()->SetPositionTarget(this->axis_arm_3_1_->GetScopedName(), 1*move_tilt_arm_add_); this-> parent ->GetJointController()->SetPositionPID(this->axis_arm_3_2_->GetScopedName(), this->pid_hinge_arm); this-> parent ->GetJointController()->SetPositionTarget(this->axis_arm_3_2_->GetScopedName(), 1*move_tilt_arm_add_); // Turnning in pan (limit_angle_pan = 1.5707) if ((move_pan_arm_add_ < limit_angle_pan && move_pan_arm_add_ > -limit_angle_pan) && (move_pan_arm_cmd_ != 0.0)) { move_pan_arm_add_ = move_pan_arm_add_ + (move_pan_arm_cmd_ * 0.01); } if (move_pan_arm_add_ >= limit_angle_pan) { move_pan_arm_add_ = limit_angle_pan - 0.01; } if (move_pan_arm_add_ <= -limit_angle_pan) { move_pan_arm_add_ = -limit_angle_pan + 0.01; } // Turnning in tilt (limit_angle_tilt = 0.6) if ((move_tilt_arm_add_ < limit_angle_tilt && move_tilt_arm_add_ > -limit_angle_tilt) && (move_tilt_arm_cmd_ != 0.0)) { move_tilt_arm_add_ = move_tilt_arm_add_ + (move_tilt_arm_cmd_ * 0.01); //Give a initial potition in (limit_angle_tilt - 0.1 = 1.7) } if (move_tilt_arm_add_ >= limit_angle_tilt) { move_tilt_arm_add_ = limit_angle_tilt - 0.01; } if (move_tilt_arm_add_ <= -limit_angle_tilt) { move_tilt_arm_add_ = -limit_angle_tilt + 0.01; } getWheelVelocities(); for (size_t side = 0; side < 2; ++side){ for (size_t i = 0; i < joints_[side].size(); ++i) { joints_[side][i]->SetVelocity(0, wheel_speed_[side] / (0.5 * wheel_diameter_)); } } last_update_time_+= common::Time(update_period_); } } // Finalize the controller void GazeboRosWheelsPiston::FiniChild() { alive_ = false; queue_.clear(); queue_.disable(); rosnode_->shutdown(); callback_queue_thread_.join(); } void GazeboRosWheelsPiston::getWheelVelocities() { boost::mutex::scoped_lock scoped_lock(lock); double coef_vr,coef_va; //Values interpolation to have same proportion of odomTopic and cmd_vel coef_vr = inter_vr->interpolate(fabs(x_)); coef_va = inter_va->interpolate(fabs(rot_)); double vr = x_ * (coef_vr); double va = rot_ * (coef_va); wheel_speed_[LEFT] = speed_factor_*(2.0*vr - va * width_ / (2.0*0.125)); wheel_speed_[RIGHT] = speed_factor_*(2.0*vr + va * width_ / (2.0*0.125)); } void GazeboRosWheelsPiston::updateWidth() { math::Vector3 dis = l_c_wheel_->GetWorldCoGPose().pos - r_c_wheel_->GetWorldCoGPose().pos; width_ = sqrt(((l_c_wheel_->GetWorldCoGPose().pos.x - r_c_wheel_->GetWorldCoGPose().pos.x) * (l_c_wheel_->GetWorldCoGPose().pos.x - r_c_wheel_->GetWorldCoGPose().pos.x)) + ((l_c_wheel_->GetWorldCoGPose().pos.y - r_c_wheel_->GetWorldCoGPose().pos.y) * (l_c_wheel_->GetWorldCoGPose().pos.y - r_c_wheel_->GetWorldCoGPose().pos.y))) + 0.10001; } void GazeboRosWheelsPiston::updateElecPos() { math::Vector3 rl, rr,u,pe; // convert velocity to child_frame_id (aka base_footprint) math::Pose pose = this->parent->GetWorldPose(); float yaw = pose.rot.GetYaw(); rb.x = electronics_center->GetWorldCoGPose().pos.x; rb.y = electronics_center->GetWorldCoGPose().pos.y; rb.z = electronics_center->GetWorldCoGPose().pos.z; rl.x = l_c_wheel_->GetWorldCoGPose().pos.x; rl.y = l_c_wheel_->GetWorldCoGPose().pos.y; rl.z = l_c_wheel_->GetWorldCoGPose().pos.z - 0.125; rr.x = r_c_wheel_->GetWorldCoGPose().pos.x; rr.y = r_c_wheel_->GetWorldCoGPose().pos.y; rr.z = r_c_wheel_->GetWorldCoGPose().pos.z - 0.125; rm = (rl + rr) * 0.5; pe= rb - rm; u.x= cos (yaw); u.y= sin (yaw); u.z= 0; // HERE IS NECESARY TO CHECK HOW TO PRESENT THE FUNCTION DOT PRODUCT TO APPLY dis_box_centralaxis_ = (pe.x*u.x+pe.y*u.y+pe.z*u.z)*10; //Get the position of Electronic Box geometry_msgs::Vector3 pos_electronicBox_msg; pos_electronicBox_msg.x = electronics_center->GetWorldCoGPose().pos.x; pos_electronicBox_msg.y = electronics_center->GetWorldCoGPose().pos.y; pos_electronicBox_msg.z = 0; pos_electronicBox_publisher_.publish(pos_electronicBox_msg); //Get the Vector Central Between Middle Wheels geometry_msgs::Vector3 pos_centerMidWheels_msg; pos_centerMidWheels_msg.x = rm.x; pos_centerMidWheels_msg.y = rm.y; pos_centerMidWheels_msg.z = rm.z; pos_centerMidWheels_publisher_.publish(pos_centerMidWheels_msg); //Get Vector Diference XY between center Electronic Box and Centor Central Middle Wheels geometry_msgs::Vector3 pos_vecBoxWheel_msg; pos_vecBoxWheel_msg.x = pe.x; pos_vecBoxWheel_msg.y = pe.y; pos_vecBoxWheel_msg.z = pe.z; pos_vecBoxWheel_publisher_.publish(pos_vecBoxWheel_msg); //Get unit Vector parrallel with orientation of Robot geometry_msgs::Vector3 pos_vecUnitOrient_msg; pos_vecUnitOrient_msg.x = u.x; pos_vecUnitOrient_msg.y = u.y; pos_vecUnitOrient_msg.z = u.z; pos_vecUnitOrient_publisher_.publish(pos_vecUnitOrient_msg); //Get Dot Product between Vector unit orientation and Vector Diference XY std_msgs::Float32 dis_box_centralaxis_msg; dis_box_centralaxis_msg.data = (dis_box_centralaxis_); dis_box_centralaxis_publisher_.publish(dis_box_centralaxis_msg); } void GazeboRosWheelsPiston::cmdVelCallback( const geometry_msgs::Twist::ConstPtr& cmd_msg) { boost::mutex::scoped_lock scoped_lock(lock); x_ = cmd_msg->linear.x; rot_ = cmd_msg->angular.z; } void GazeboRosWheelsPiston::elecPosCallback ( const std_msgs::Float32::ConstPtr& move_Piston_msg) { boost::mutex::scoped_lock scoped_lock(lock); move_Piston_cmd_ = move_Piston_msg->data; } void GazeboRosWheelsPiston::armCentralPosCallback ( const std_msgs::Bool::ConstPtr& arm_central_msg) { boost::mutex::scoped_lock scoped_lock(lock); arm_central_cmd_ = arm_central_msg->data; } void GazeboRosWheelsPiston::velStateCallback ( const std_msgs::Float32::ConstPtr& vel_state_msg) { boost::mutex::scoped_lock scoped_lock(lock); vel_state_cmd_ = vel_state_msg->data; } void GazeboRosWheelsPiston::QueueThread() { static const double timeout = 0.01; while (alive_ && rosnode_->ok()) { queue_.callAvailable(ros::WallDuration(timeout)); } } void GazeboRosWheelsPiston::moveArmPosCallback( const std_msgs::Bool::ConstPtr& move_arm_msg) { boost::mutex::scoped_lock scoped_lock(lock); move_arm_cmd_ = move_arm_msg->data; } void GazeboRosWheelsPiston::moveArmPosASCallback( const std_msgs::Bool::ConstPtr& move_arm_as_msg) { boost::mutex::scoped_lock scoped_lock(lock); move_arm_as_cmd_ = move_arm_as_msg->data; } void GazeboRosWheelsPiston::movePanArmCallback( const std_msgs::Float32::ConstPtr& move_pan_arm_msg) { boost::mutex::scoped_lock scoped_lock(lock); move_pan_arm_cmd_ = move_pan_arm_msg->data; } void GazeboRosWheelsPiston::moveTiltArmCallback( const std_msgs::Float32::ConstPtr& move_tilt_arm_msg) { boost::mutex::scoped_lock scoped_lock(lock); move_tilt_arm_cmd_ = move_tilt_arm_msg->data; } void GazeboRosWheelsPiston::tfBaseLink(void) { static tf::TransformBroadcaster br; math::Pose tf_arm_link_1_,tf_arm_link_2_, tf_arm_link_3_; tf_base_link_ = electronics_center ->GetWorldCoGPose(); tf_arm_link_1_ = arm_link_1_1_ ->GetRelativePose(); tf_arm_link_2_ = arm_link_2_1_ ->GetRelativePose(); tf_arm_link_3_ = arm_link_3_ ->GetRelativePose(); tf::Transform t_bl; t_bl.setOrigin( tf::Vector3(tf_base_link_.pos.x, tf_base_link_.pos.y, 0) ); t_bl.setRotation(tf::Quaternion(tf_base_link_.rot.x,tf_base_link_.rot.y,tf_base_link_.rot.z,tf_base_link_.rot.w)); tf::Transform t_0; t_0.setOrigin( tf::Vector3(0, 0, 0) ); t_0.setRotation(tf::Quaternion(0,tf_arm_link_1_.rot.y,tf_arm_link_1_.rot.z,1)); tf::Transform t_1; t_1.setOrigin( tf::Vector3(0.21, 0, 0) ); t_1.setRotation(tf::Quaternion(0,0,0,1)); tf::Transform t_2; t_2.setOrigin( tf::Vector3( 0, 0, 0 )); //sen(20)*0.16 = 0.054723 t_2.setRotation(tf::Quaternion(0,(tf_arm_link_2_.rot.y-tf_arm_link_1_.rot.y),0,tf_arm_link_2_.rot.w)); tf::Transform t_3; t_3.setOrigin( tf::Vector3(-0.16,0,0) ); t_3.setRotation(tf::Quaternion(0,0,0,1)); // br.sendTransform(tf::StampedTransform(t_bl, ros::Time::now(),"odom", "siar/base_link")); br.sendTransform(tf::StampedTransform(t_0, ros::Time::now(), "siar/arm", "siar/arm_link_1")); br.sendTransform(tf::StampedTransform(t_1, ros::Time::now(), "siar/arm_link_1", "siar/arm_link_2")); br.sendTransform(tf::StampedTransform(t_2, ros::Time::now(), "siar/arm_link_2", "siar/arm_link_aux")); br.sendTransform(tf::StampedTransform(t_3, ros::Time::now(), "siar/arm_link_aux","siar/arm_link_3")); } void GazeboRosWheelsPiston::publishOdometry(double step_time) { ros::Time current_time = ros::Time::now(); std::string odom_frame = tf::resolve(tf_prefix_, odometry_frame_); std::string base_footprint_frame = tf::resolve(tf_prefix_, robot_base_frame_); // getting data for base_footprint to odom transform math::Pose pose = this->parent->GetWorldPose(); tf::Quaternion qt(pose.rot.x, pose.rot.y, pose.rot.z, pose.rot.w); tf::Vector3 vt(pose.pos.x, pose.pos.y, pose.pos.z); tf::Transform base_footprint_to_odom(qt, vt); if (this->publish_odometry_tf_) { transform_broadcaster_->sendTransform(tf::StampedTransform(base_footprint_to_odom, current_time, odom_frame, base_footprint_frame)); } // publish odom topic odom_.pose.pose.position.x = pose.pos.x; odom_.pose.pose.position.y = pose.pos.y; odom_.pose.pose.orientation.x = pose.rot.x; odom_.pose.pose.orientation.y = pose.rot.y; odom_.pose.pose.orientation.z = pose.rot.z; odom_.pose.pose.orientation.w = pose.rot.w; odom_.pose.covariance[0] = 0.00001; odom_.pose.covariance[7] = 0.00001; odom_.pose.covariance[14] = 1000000000000.0; odom_.pose.covariance[21] = 1000000000000.0; odom_.pose.covariance[28] = 1000000000000.0; odom_.pose.covariance[35] = 0.001; // get velocity in /odom frame math::Vector3 linear; linear = this->parent->GetWorldLinearVel(); odom_.twist.twist.angular.z = this->parent->GetWorldAngularVel().z; // convert velocity to child_frame_id (aka base_footprint) float yaw = pose.rot.GetYaw(); odom_.twist.twist.linear.x = cosf(yaw) * linear.x + sinf(yaw) * linear.y; odom_.twist.twist.linear.y = cosf(yaw) * linear.y - sinf(yaw) * linear.x; odom_.header.stamp = current_time; odom_.header.frame_id = odom_frame; odom_.child_frame_id = base_footprint_frame; if (this->publish_odometry_msg_){ odometry_publisher_.publish(odom_); } } GZ_REGISTER_MODEL_PLUGIN(GazeboRosWheelsPiston) }
#ifndef BOOST_QVM_GEN_VEC_OPERATIONS4_HPP_INCLUDED #define BOOST_QVM_GEN_VEC_OPERATIONS4_HPP_INCLUDED // Copyright 2008-2022 Emil Dotchevski and Reverge Studios, Inc. // 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) // This file was generated by a program. Do not edit manually. #include <boost/qvm/deduce_scalar.hpp> #include <boost/qvm/deduce_vec.hpp> #include <boost/qvm/error.hpp> #include <boost/qvm/gen/vec_assign4.hpp> #include <boost/qvm/math.hpp> #include <boost/qvm/static_assert.hpp> #include <boost/qvm/throw_exception.hpp> namespace boost { namespace qvm { template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, deduce_vec2<A,B,4> >::type operator+( A const & a, B const & b ) { typedef typename deduce_vec2<A,B,4>::type R; BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==4); R r; vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)+vec_traits<B>::template read_element<0>(b); vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)+vec_traits<B>::template read_element<1>(b); vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)+vec_traits<B>::template read_element<2>(b); vec_traits<R>::template write_element<3>(r)=vec_traits<A>::template read_element<3>(a)+vec_traits<B>::template read_element<3>(b); return r; } namespace sfinae { using ::boost::qvm::operator+; } namespace qvm_detail { template <int D> struct plus_vv_defined; template <> struct plus_vv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, deduce_vec2<A,B,4> >::type operator-( A const & a, B const & b ) { typedef typename deduce_vec2<A,B,4>::type R; BOOST_QVM_STATIC_ASSERT(vec_traits<R>::dim==4); R r; vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)-vec_traits<B>::template read_element<0>(b); vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)-vec_traits<B>::template read_element<1>(b); vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)-vec_traits<B>::template read_element<2>(b); vec_traits<R>::template write_element<3>(r)=vec_traits<A>::template read_element<3>(a)-vec_traits<B>::template read_element<3>(b); return r; } namespace sfinae { using ::boost::qvm::operator-; } namespace qvm_detail { template <int D> struct minus_vv_defined; template <> struct minus_vv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, A &>::type operator+=( A & a, B const & b ) { vec_traits<A>::template write_element<0>(a)+=vec_traits<B>::template read_element<0>(b); vec_traits<A>::template write_element<1>(a)+=vec_traits<B>::template read_element<1>(b); vec_traits<A>::template write_element<2>(a)+=vec_traits<B>::template read_element<2>(b); vec_traits<A>::template write_element<3>(a)+=vec_traits<B>::template read_element<3>(b); return a; } namespace sfinae { using ::boost::qvm::operator+=; } namespace qvm_detail { template <int D> struct plus_eq_vv_defined; template <> struct plus_eq_vv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, A &>::type operator-=( A & a, B const & b ) { vec_traits<A>::template write_element<0>(a)-=vec_traits<B>::template read_element<0>(b); vec_traits<A>::template write_element<1>(a)-=vec_traits<B>::template read_element<1>(b); vec_traits<A>::template write_element<2>(a)-=vec_traits<B>::template read_element<2>(b); vec_traits<A>::template write_element<3>(a)-=vec_traits<B>::template read_element<3>(b); return a; } namespace sfinae { using ::boost::qvm::operator-=; } namespace qvm_detail { template <int D> struct minus_eq_vv_defined; template <> struct minus_eq_vv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4 && is_scalar<B>::value, deduce_vec2<A,B,vec_traits<A>::dim> >::type operator*( A const & a, B b ) { typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R; R r; vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)*b; vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)*b; vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)*b; vec_traits<R>::template write_element<3>(r)=vec_traits<A>::template read_element<3>(a)*b; return r; } namespace sfinae { using ::boost::qvm::operator*; } namespace qvm_detail { template <int D> struct mul_vs_defined; template <> struct mul_vs_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< is_scalar<A>::value && vec_traits<B>::dim==4, deduce_vec2<A,B,vec_traits<B>::dim> >::type operator*( A a, B const & b ) { typedef typename deduce_vec2<A,B,vec_traits<B>::dim>::type R; R r; vec_traits<R>::template write_element<0>(r)=a*vec_traits<B>::template read_element<0>(b); vec_traits<R>::template write_element<1>(r)=a*vec_traits<B>::template read_element<1>(b); vec_traits<R>::template write_element<2>(r)=a*vec_traits<B>::template read_element<2>(b); vec_traits<R>::template write_element<3>(r)=a*vec_traits<B>::template read_element<3>(b); return r; } namespace sfinae { using ::boost::qvm::operator*; } namespace qvm_detail { template <int D> struct mul_sv_defined; template <> struct mul_sv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && is_scalar<B>::value, A &>::type operator*=( A & a, B b ) { vec_traits<A>::template write_element<0>(a)*=b; vec_traits<A>::template write_element<1>(a)*=b; vec_traits<A>::template write_element<2>(a)*=b; vec_traits<A>::template write_element<3>(a)*=b; return a; } namespace sfinae { using ::boost::qvm::operator*=; } namespace qvm_detail { template <int D> struct mul_eq_vs_defined; template <> struct mul_eq_vs_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4 && is_scalar<B>::value, deduce_vec2<A,B,vec_traits<A>::dim> >::type operator/( A const & a, B b ) { typedef typename deduce_vec2<A,B,vec_traits<A>::dim>::type R; R r; vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a)/b; vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a)/b; vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a)/b; vec_traits<R>::template write_element<3>(r)=vec_traits<A>::template read_element<3>(a)/b; return r; } namespace sfinae { using ::boost::qvm::operator/; } namespace qvm_detail { template <int D> struct div_vs_defined; template <> struct div_vs_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && is_scalar<B>::value, A &>::type operator/=( A & a, B b ) { vec_traits<A>::template write_element<0>(a)/=b; vec_traits<A>::template write_element<1>(a)/=b; vec_traits<A>::template write_element<2>(a)/=b; vec_traits<A>::template write_element<3>(a)/=b; return a; } namespace sfinae { using ::boost::qvm::operator/=; } namespace qvm_detail { template <int D> struct div_eq_vs_defined; template <> struct div_eq_vs_defined<4> { static bool const value=true; }; } template <class R,class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_vec<A>::value && vec_traits<R>::dim==4 && vec_traits<A>::dim==4, R>::type convert_to( A const & a ) { R r; vec_traits<R>::template write_element<0>(r)=vec_traits<A>::template read_element<0>(a); vec_traits<R>::template write_element<1>(r)=vec_traits<A>::template read_element<1>(a); vec_traits<R>::template write_element<2>(r)=vec_traits<A>::template read_element<2>(a); vec_traits<R>::template write_element<3>(r)=vec_traits<A>::template read_element<3>(a); return r; } namespace sfinae { using ::boost::qvm::convert_to; } namespace qvm_detail { template <int D> struct convert_to_v_defined; template <> struct convert_to_v_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, bool>::type operator==( A const & a, B const & b ) { return vec_traits<A>::template read_element<0>(a)==vec_traits<B>::template read_element<0>(b) && vec_traits<A>::template read_element<1>(a)==vec_traits<B>::template read_element<1>(b) && vec_traits<A>::template read_element<2>(a)==vec_traits<B>::template read_element<2>(b) && vec_traits<A>::template read_element<3>(a)==vec_traits<B>::template read_element<3>(b); } namespace sfinae { using ::boost::qvm::operator==; } namespace qvm_detail { template <int D> struct eq_vv_defined; template <> struct eq_vv_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, bool>::type operator!=( A const & a, B const & b ) { return !(vec_traits<A>::template read_element<0>(a)==vec_traits<B>::template read_element<0>(b)) || !(vec_traits<A>::template read_element<1>(a)==vec_traits<B>::template read_element<1>(b)) || !(vec_traits<A>::template read_element<2>(a)==vec_traits<B>::template read_element<2>(b)) || !(vec_traits<A>::template read_element<3>(a)==vec_traits<B>::template read_element<3>(b)); } namespace sfinae { using ::boost::qvm::operator!=; } namespace qvm_detail { template <int D> struct neq_vv_defined; template <> struct neq_vv_defined<4> { static bool const value=true; }; } template <class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4, deduce_vec<A> >::type operator-( A const & a ) { typedef typename deduce_vec<A>::type R; R r; vec_traits<R>::template write_element<0>(r)=-vec_traits<A>::template read_element<0>(a); vec_traits<R>::template write_element<1>(r)=-vec_traits<A>::template read_element<1>(a); vec_traits<R>::template write_element<2>(r)=-vec_traits<A>::template read_element<2>(a); vec_traits<R>::template write_element<3>(r)=-vec_traits<A>::template read_element<3>(a); return r; } namespace sfinae { using ::boost::qvm::operator-; } namespace qvm_detail { template <int D> struct minus_v_defined; template <> struct minus_v_defined<4> { static bool const value=true; }; } template <class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_vec<A>::value && vec_traits<A>::dim==4, typename vec_traits<A>::scalar_type>::type mag( A const & a ) { typedef typename vec_traits<A>::scalar_type T; T const a0=vec_traits<A>::template read_element<0>(a); T const a1=vec_traits<A>::template read_element<1>(a); T const a2=vec_traits<A>::template read_element<2>(a); T const a3=vec_traits<A>::template read_element<3>(a); T const m2=a0*a0+a1*a1+a2*a2+a3*a3; T const mag=sqrt(m2); return mag; } namespace sfinae { using ::boost::qvm::mag; } namespace qvm_detail { template <int D> struct mag_v_defined; template <> struct mag_v_defined<4> { static bool const value=true; }; } template <class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< is_vec<A>::value && vec_traits<A>::dim==4, typename vec_traits<A>::scalar_type>::type mag_sqr( A const & a ) { typedef typename vec_traits<A>::scalar_type T; T const a0=vec_traits<A>::template read_element<0>(a); T const a1=vec_traits<A>::template read_element<1>(a); T const a2=vec_traits<A>::template read_element<2>(a); T const a3=vec_traits<A>::template read_element<3>(a); T const m2=a0*a0+a1*a1+a2*a2+a3*a3; return m2; } namespace sfinae { using ::boost::qvm::mag_sqr; } namespace qvm_detail { template <int D> struct mag_sqr_v_defined; template <> struct mag_sqr_v_defined<4> { static bool const value=true; }; } template <class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4, deduce_vec<A> >::type normalized( A const & a ) { typedef typename vec_traits<A>::scalar_type T; T const a0=vec_traits<A>::template read_element<0>(a); T const a1=vec_traits<A>::template read_element<1>(a); T const a2=vec_traits<A>::template read_element<2>(a); T const a3=vec_traits<A>::template read_element<3>(a); T const m2=a0*a0+a1*a1+a2*a2+a3*a3; if( m2==scalar_traits<typename vec_traits<A>::scalar_type>::value(0) ) BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error()); T const rm=scalar_traits<T>::value(1)/sqrt(m2); typedef typename deduce_vec<A>::type R; R r; vec_traits<R>::template write_element<0>(r)=a0*rm; vec_traits<R>::template write_element<1>(r)=a1*rm; vec_traits<R>::template write_element<2>(r)=a2*rm; vec_traits<R>::template write_element<3>(r)=a3*rm; return r; } namespace sfinae { using ::boost::qvm::normalized; } template <class A> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename enable_if_c< vec_traits<A>::dim==4, void>::type normalize( A & a ) { typedef typename vec_traits<A>::scalar_type T; T const a0=vec_traits<A>::template read_element<0>(a); T const a1=vec_traits<A>::template read_element<1>(a); T const a2=vec_traits<A>::template read_element<2>(a); T const a3=vec_traits<A>::template read_element<3>(a); T const m2=a0*a0+a1*a1+a2*a2+a3*a3; if( m2==scalar_traits<typename vec_traits<A>::scalar_type>::value(0) ) BOOST_QVM_THROW_EXCEPTION(zero_magnitude_error()); T const rm=scalar_traits<T>::value(1)/sqrt(m2); vec_traits<A>::template write_element<0>(a)*=rm; vec_traits<A>::template write_element<1>(a)*=rm; vec_traits<A>::template write_element<2>(a)*=rm; vec_traits<A>::template write_element<3>(a)*=rm; } namespace sfinae { using ::boost::qvm::normalize; } namespace qvm_detail { template <int D> struct normalize_v_defined; template <> struct normalize_v_defined<4> { static bool const value=true; }; } template <class A,class B> BOOST_QVM_CONSTEXPR BOOST_QVM_INLINE_OPERATIONS typename lazy_enable_if_c< vec_traits<A>::dim==4 && vec_traits<B>::dim==4, deduce_scalar<typename vec_traits<A>::scalar_type,typename vec_traits<B>::scalar_type> >::type dot( A const & a, B const & b ) { typedef typename vec_traits<A>::scalar_type Ta; typedef typename vec_traits<B>::scalar_type Tb; typedef typename deduce_scalar<Ta,Tb>::type Tr; Ta const a0=vec_traits<A>::template read_element<0>(a); Ta const a1=vec_traits<A>::template read_element<1>(a); Ta const a2=vec_traits<A>::template read_element<2>(a); Ta const a3=vec_traits<A>::template read_element<3>(a); Tb const b0=vec_traits<B>::template read_element<0>(b); Tb const b1=vec_traits<B>::template read_element<1>(b); Tb const b2=vec_traits<B>::template read_element<2>(b); Tb const b3=vec_traits<B>::template read_element<3>(b); Tr const dot=a0*b0+a1*b1+a2*b2+a3*b3; return dot; } namespace sfinae { using ::boost::qvm::dot; } namespace qvm_detail { template <int D> struct dot_vv_defined; template <> struct dot_vv_defined<4> { static bool const value=true; }; } } } #endif
#include "framework/framework.h" #include "framework/trace.h" #include "version.h" using namespace OpenApoc; int main(int argc, char *argv[]) { bool enable_trace = false; LogInfo("Starting OpenApoc \"%s\"", OPENAPOC_VERSION); std::vector<UString> cmdline; for (int i = 1; i < argc; i++) { // Special handling of tracing as we want it to be started before the framework // parses the rest of the options if (UString(argv[i]) == "--enable-tracing") { enable_trace = true; continue; } else if (UString(argv[i]) == "--disable-tracing") { enable_trace = false; continue; } cmdline.emplace_back(UString(argv[i])); } if (enable_trace) { Trace::enable(); LogInfo("Tracing enabled"); } Trace::setThreadName("main"); TraceObj obj("main"); Framework *fw = new Framework(UString(argv[0]), cmdline); fw->Run(); delete fw; return 0; }
// Copyright (c) 2017-2020 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blocksignature.h" #include "main.h" #include "zddrchain.h" bool SignBlockWithKey(CBlock& block, const CKey& key) { if (!key.Sign(block.GetHash(), block.vchBlockSig)) return error("%s: failed to sign block hash with key", __func__); return true; } bool SignBlock(CBlock& block, const CKeyStore& keystore) { CKeyID keyID; if (block.IsProofOfWork()) { bool fFoundID = false; for (const CTxOut& txout :block.vtx[0].vout) { if (!txout.GetKeyIDFromUTXO(keyID)) continue; fFoundID = true; break; } if (!fFoundID) return error("%s: failed to find key for PoW", __func__); } else { if (!block.vtx[1].vout[1].GetKeyIDFromUTXO(keyID)) return error("%s: failed to find key for PoS", __func__); } CKey key; if (!keystore.GetKey(keyID, key)) return error("%s: failed to get key from keystore", __func__); return SignBlockWithKey(block, key); } bool CheckBlockSignature(const CBlock& block) { if (block.IsProofOfWork()) return block.vchBlockSig.empty(); if (block.vchBlockSig.empty()) return error("%s: vchBlockSig is empty!", __func__); /** Each block is signed by the private key of the input that is staked. This can be either zDDR or normal UTXO * zDDR: Each zDDR has a keypair associated with it. The serial number is a hash of the public key. * UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx. */ CPubKey pubkey; bool fzDDRStake = block.vtx[1].vin[0].IsZerocoinSpend(); if (fzDDRStake) { libzerocoin::CoinSpend spend = TxInToZerocoinSpend(block.vtx[1].vin[0]); pubkey = spend.getPubKey(); } else { txnouttype whichType; std::vector<valtype> vSolutions; const CTxOut& txout = block.vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) { valtype& vchPubKey = vSolutions[0]; pubkey = CPubKey(vchPubKey); } else if (whichType == TX_COLDSTAKE) { // pick the public key from the P2CS input const CTxIn& txin = block.vtx[1].vin[0]; int start = 1 + (int) *txin.scriptSig.begin(); // skip sig start += 1 + (int) *(txin.scriptSig.begin()+start); // skip flag pubkey = CPubKey(txin.scriptSig.begin()+start+1, txin.scriptSig.end()); } } if (!pubkey.IsValid()) return error("%s: invalid pubkey %s", __func__, HexStr(pubkey)); return pubkey.Verify(block.GetHash(), block.vchBlockSig); }
#ifndef DISK_HPP_ #define DISK_HPP_ #include "TriangleMesh.hpp" #include "Primitive.hpp" namespace Tungsten { class Disk : public Primitive { float _coneAngle; Vec3f _center; float _r; Vec3f _n; float _area; float _invArea; TangentFrame _frame; float _cosApex; Vec3f _coneBase; std::shared_ptr<Bsdf> _bsdf; std::shared_ptr<TriangleMesh> _proxy; void buildProxy(); protected: virtual float powerToRadianceFactor() const override; public: Disk(); Disk(const Vec3f &pos, const Vec3f &n, float r, const std::string &name, std::shared_ptr<Bsdf> bsdf); virtual void fromJson(JsonPtr value, const Scene &scene) override; virtual rapidjson::Value toJson(Allocator &allocator) const override; virtual bool intersect(Ray &ray, IntersectionTemporary &data) const override; virtual bool occluded(const Ray &ray) const override; virtual bool hitBackside(const IntersectionTemporary &data) const override; virtual void intersectionInfo(const IntersectionTemporary &data, IntersectionInfo &info) const override; virtual bool tangentSpace(const IntersectionTemporary &data, const IntersectionInfo &info, Vec3f &T, Vec3f &B) const override; virtual bool isSamplable() const override; virtual void makeSamplable(const TraceableScene &scene, uint32 threadIndex) override; virtual bool samplePosition(PathSampleGenerator &sampler, PositionSample &sample) const override; virtual bool sampleDirection(PathSampleGenerator &sampler, const PositionSample &point, DirectionSample &sample) const override; virtual bool sampleDirect(uint32 threadIndex, const Vec3f &p, PathSampleGenerator &sampler, LightSample &sample) const override; bool invertPosition(WritablePathSampleGenerator &sampler, const PositionSample &point) const; bool invertDirection(WritablePathSampleGenerator &sampler, const PositionSample &/*point*/, const DirectionSample &direction) const; virtual float positionalPdf(const PositionSample &point) const override; virtual float directionalPdf(const PositionSample &point, const DirectionSample &sample) const override; virtual float directPdf(uint32 threadIndex, const IntersectionTemporary &data, const IntersectionInfo &info, const Vec3f &p) const override; virtual Vec3f evalPositionalEmission(const PositionSample &sample) const override; virtual Vec3f evalDirectionalEmission(const PositionSample &point, const DirectionSample &sample) const override; virtual Vec3f evalDirect(const IntersectionTemporary &data, const IntersectionInfo &info) const override; virtual bool invertParametrization(Vec2f uv, Vec3f &pos) const override; virtual bool isDirac() const override; virtual bool isInfinite() const override; virtual float approximateRadiance(uint32 threadIndex, const Vec3f &p) const override; virtual Box3f bounds() const override; virtual const TriangleMesh &asTriangleMesh() override; virtual void prepareForRender() override; virtual int numBsdfs() const override; virtual std::shared_ptr<Bsdf> &bsdf(int index) override; virtual void setBsdf(int index, std::shared_ptr<Bsdf> &bsdf) override; virtual Primitive *clone() override; }; } #endif /* DISK_HPP_ */
// MIT Licensed (see LICENSE.md). #pragma once #ifndef ZILCH_CODE_LOCATION_HPP # define ZILCH_CODE_LOCATION_HPP namespace Zilch { // We can print Zilch messages in many different formats // This is used for printing errors, exceptions, and general code location // information namespace MessageFormat { enum Enum { // This is the standard format we use to print Zilch error messages // We try to be very descriptive about where our errors occur // Style: 'In <origin> at line <line>, character <character> (within function // <function>)' // ' <message>' Zilch, // Style: ' File "<origin>", line <line>, in <function>' // ' <message>' Python, // Msvc errors are useful when editing Zilch inside of Visual Studio, // because you can double click the error and go directly to the file // Style: '<origin>(<line>): <message>' MsvcCpp }; } // A code location provides us with a context of where something occurred class ZeroShared CodeLocation { public: // Default constructor CodeLocation(); // Checks if this location was ever set to a valid value // This is true if the origin is set bool IsValid(); // Get a formatted message that includes this location (may include newlines // depending on the format) String GetFormattedStringWithMessage(MessageFormat::Enum format, StringParam message) const; // Get this location formatted in different styles (does not include newlines) String GetFormattedString(MessageFormat::Enum format) const; // Creates a code location that is strictly at the start of this location CodeLocation GetStartOnlyLocation(); // Creates a code location that is strictly at the end of this location CodeLocation GetEndOnlyLocation(); // This hash matches the hash used in the CodeEntry, and can generally be used // to map back to files size_t GetHash(); // Check if another code location is at the same position and origin (only // uses StartPosition/EndPosition) bool IsSamePositionAndOrigin(const CodeLocation& rhs); // Every file and code string compiled gets a unique id String Code; // Note: Primary is a location that we generally use when displaying errors or // other visualizations For example, in a binary operator the location // Start/End encompasses both the Left/Right operands however the primary // location is the operator itself Primary should always be between start and // end // The line range that the node originated from // Lines start at a value of 1 (a value of 0 is invalid) size_t StartLine; size_t PrimaryLine; size_t EndLine; // The character range that the node originated from (relative to the start of // the line) Characters start at a value of 1 (a value of 0 is invalid) size_t StartCharacter; size_t PrimaryCharacter; size_t EndCharacter; // The zero-based character position from the associated code size_t StartPosition; size_t PrimaryPosition; size_t EndPosition; // The file/script this node originated from String Origin; // This is an optional library that we're from (typically filled out in the // syntaxer phase) String Library; // This is an optional class that we're from (typically filled out in the // syntaxer phase) String Class; // This is an optional function that we're from (typically filled out in the // syntaxer phase) String Function; // Tells us if the location is within C++, which // means that it cannot be debugged or visualized bool IsNative; // When the user provides a code block to the project to be compiled // they have the option of providing user-data. This user-data is the // same data that they passed in mutable const void* CodeUserData; u64 CodeUserDataU64; }; // Every time we add code to the project we do it through this // This is also stored on the library that gets generated out of the project class ZeroShared CodeEntry { public: // Constructor CodeEntry(); String Code; String Origin; void* CodeUserData; // Gets a hash that we can use to uniquely identify this code // This includes the code and its origin // If a file changes names, this will no longer map up to that same file size_t GetHash(); }; } // namespace Zilch // Explicit specializations namespace Zero { // Code locations should be directly memory movable // String would technically just increment a reference and then decrement, so // skip it! WARNING: If this ever becomes non-movable, then be sure to update // UserToken! template <> struct ZeroShared MoveWithoutDestructionOperator<Zilch::CodeLocation> { static inline void MoveWithoutDestruction(Zilch::CodeLocation* dest, Zilch::CodeLocation* source) { memcpy(dest, source, sizeof(*source)); } }; } // namespace Zero #endif
//===-- Hexagon.cpp -------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "InputFiles.h" #include "Symbols.h" #include "Target.h" #include "lld/Common/ErrorHandler.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Object/ELF.h" #include "llvm/Support/Endian.h" using namespace llvm; using namespace llvm::object; using namespace llvm::support::endian; using namespace llvm::ELF; using namespace lld; using namespace lld::elf; namespace { class Hexagon final : public TargetInfo { public: uint32_t calcEFlags() const override; RelExpr getRelExpr(RelType Type, const Symbol &S, const uint8_t *Loc) const override; void relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const override; }; } // namespace // Support V60 only at the moment. uint32_t Hexagon::calcEFlags() const { return 0x60; } static uint32_t applyMask(uint32_t Mask, uint32_t Data) { uint32_t Result = 0; size_t Off = 0; for (size_t Bit = 0; Bit != 32; ++Bit) { uint32_t ValBit = (Data >> Off) & 1; uint32_t MaskBit = (Mask >> Bit) & 1; if (MaskBit) { Result |= (ValBit << Bit); ++Off; } } return Result; } RelExpr Hexagon::getRelExpr(RelType Type, const Symbol &S, const uint8_t *Loc) const { switch (Type) { case R_HEX_B15_PCREL: case R_HEX_B15_PCREL_X: case R_HEX_B22_PCREL: case R_HEX_B22_PCREL_X: case R_HEX_B32_PCREL_X: return R_PC; default: return R_ABS; } } static void or32le(uint8_t *P, int32_t V) { write32le(P, read32le(P) | V); } void Hexagon::relocateOne(uint8_t *Loc, RelType Type, uint64_t Val) const { switch (Type) { case R_HEX_NONE: break; case R_HEX_12_X: or32le(Loc, applyMask(0x000007e0, Val)); break; case R_HEX_32_6_X: or32le(Loc, applyMask(0x0fff3fff, Val >> 6)); break; case R_HEX_B15_PCREL: or32le(Loc, applyMask(0x00df20fe, Val >> 2)); break; case R_HEX_B15_PCREL_X: or32le(Loc, applyMask(0x00df20fe, Val & 0x3f)); break; case R_HEX_B22_PCREL: or32le(Loc, applyMask(0x1ff3ffe, Val >> 2)); break; case R_HEX_B22_PCREL_X: or32le(Loc, applyMask(0x1ff3ffe, Val & 0x3f)); break; case R_HEX_B32_PCREL_X: or32le(Loc, applyMask(0x0fff3fff, Val >> 6)); break; default: error(getErrorLocation(Loc) + "unrecognized reloc " + toString(Type)); break; } } TargetInfo *elf::getHexagonTargetInfo() { static Hexagon Target; return &Target; }
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is licensed under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ #include <vw/BundleAdjustment/ControlNetworkLoader.h> #include <vw/Stereo/StereoModel.h> #include <vw/InterestPoint/Matcher.h> using namespace vw; using namespace vw::ba; #include <boost/filesystem/fstream.hpp> namespace fs = boost::filesystem; struct ContainsEqualIP { ip::InterestPoint& m_compare; ContainsEqualIP( ip::InterestPoint& comp ) : m_compare(comp) {} bool operator()( boost::shared_ptr<IPFeature> in ) { if ( m_compare.x == in->m_ip.x && m_compare.y == in->m_ip.y ) return true; return false; } }; // Utility for checking that the point is BA safe void safe_measurement( ip::InterestPoint& ip ) { if ( ip.scale <= 0 ) ip.scale = 10; } double vw::ba::triangulate_control_point( ControlPoint& cp, std::vector<boost::shared_ptr<camera::CameraModel> > const& camera_models, double min_angle_radians, double forced_triangulation_distance) { Vector3 position_sum; double error = 0, error_sum = 0; size_t count = 0; // 4.1.) Building a listing of triangulation for ( size_t j = 0, k = 1; k < cp.size(); j++, k++ ) { // Make sure camera centers are not equal size_t j_cam_id = cp[j].image_id(); size_t k_cam_id = cp[k].image_id(); if ( norm_2( camera_models[j_cam_id]->camera_center( cp[j].position() ) - camera_models[k_cam_id]->camera_center( cp[k].position() ) ) > 1e-6 ) { try { double angle_tol = stereo::StereoModel::robust_1_minus_cos(min_angle_radians); bool least_squares = false; stereo::StereoModel sm( camera_models[ j_cam_id ].get(), camera_models[ k_cam_id ].get(), least_squares, angle_tol ); Vector3 pt = sm( cp[j].position(), cp[k].position(), error ); // TODO: When forced_triangulation_distance > 0, one can check // if the triangulated point is behind the camera, and if yes, // to replace it with an artificial point in front of the camera. // This will need a good test. if (pt != Vector3() ){ count++; position_sum += pt; error_sum += error; }else if (forced_triangulation_distance <= 0){ vw_out(WarningMessage,"ba") << "\nCould not triangulate point. If too many such errors, " << "perhaps your baseline is too small, " << "or consider decreasing --min-triangulation-angle " << "or using --forced-triangulation-distance.\n"; } } catch ( std::exception const& e) { /* Just let it go */ vw_out(WarningMessage,"ba") << "\nFailure in triangulation: " << e.what(); } } } // 4.2.) Summing, averaging, and storing if ( count == 0) { // vw_out(WarningMessage,"ba") << "\nUnable to triangulate point!\n"; // At the very least we can provide a point that is some // distance out from the camera center and is in the 'general' area. size_t j = cp[0].image_id(); double dist = 10.0; // for backward compatibility if (forced_triangulation_distance > 0) dist = forced_triangulation_distance; try { cp.set_position( camera_models[j]->camera_center(cp[0].position()) + camera_models[j]->pixel_to_vector(cp[0].position())*dist ); } catch ( const camera::PixelToRayErr& ) { cp.set_position( camera_models[j]->camera_center(cp[0].position()) + camera_models[j]->camera_pose(cp[0].position()).rotate(Vector3(0,0,dist)) ); } if (forced_triangulation_distance > 0) return 1; // mark triangulation as successful return 0; } else { error_sum /= double(count); cp.set_position( position_sum / double(count) ); return error_sum; } } bool vw::ba::build_control_network( bool triangulate_control_points, ba::ControlNetwork& cnet, std::vector<boost::shared_ptr<camera::CameraModel> > const& camera_models, std::vector<std::string> const& image_files, std::map< std::pair<int, int>, std::string> const& match_files, size_t min_matches, double min_angle_radians, double forced_triangulation_distance) { // Note that this statement does not clear the network fully. // TODO: Clear all items here. cnet.clear(); // We can't guarantee that image_files is sorted, so we make a // std::map to give ourselves a sorted list and access to a binary search. std::map<std::string,size_t> image_prefix_map; size_t count = 0; ba::CameraRelationNetwork<ba::IPFeature> crn; BOOST_FOREACH( std::string const& file, image_files ) { fs::path file_path(file); image_prefix_map[file_path.replace_extension().string()] = count; crn.add_node( ba::CameraNode<ba::IPFeature>( count, file_path.stem().string() ) ); cnet.add_image_name(file); count++; } // Look for match files starting with given prefix. std::vector<std::string> match_files_vec; std::vector<size_t> index1_vec, index2_vec; // Searching through the directories available to us. typedef std::map<std::string,size_t>::iterator MapIterator; int num_images = image_files.size(); for (int i = 0; i < num_images; i++){ // Loop through all image pairs for (int j = i+1; j < num_images; j++){ std::string image1 = image_files[i]; std::string image2 = image_files[j]; // Find the match file for this pair of images std::pair<int, int> pair_ind(i, j); std::map< std::pair<int, int>, std::string>::const_iterator pair_it = match_files.find(pair_ind); if (pair_it == match_files.end()) continue; // This match file was not passed in, that is ok. std::string match_file = pair_it->second; // std::string prefix1 = fs::path(image1).replace_extension().string(); std::string prefix2 = fs::path(image2).replace_extension().string(); MapIterator it1 = image_prefix_map.find( prefix1 ); MapIterator it2 = image_prefix_map.find( prefix2 ); if ( it1 == image_prefix_map.end() || it2 == image_prefix_map.end() ) continue; // Verify that the match file exists if (!fs::exists(match_file)) { vw_out(WarningMessage) << "Missing match file: " << match_file << std::endl; continue; } match_files_vec.push_back(match_file); index1_vec.push_back(it1->second); index2_vec.push_back(it2->second); } } // Loop through the match files... size_t num_load_rejected = 0, num_loaded = 0; for (size_t file_iter = 0; file_iter < match_files_vec.size(); file_iter++){ std::string match_file = match_files_vec[file_iter]; size_t index1 = index1_vec[file_iter]; size_t index2 = index2_vec[file_iter]; // Actually read in the file as it seems we've found something correct std::vector<ip::InterestPoint> ip1, ip2; vw_out(DebugMessage,"ba") << "Loading: " << match_file << std::endl; ip::read_binary_match_file( match_file, ip1, ip2 ); if ( ip1.size() < min_matches ) { vw_out(DebugMessage,"ba") << "\t" << match_file << " " << ip1.size() << " matches. [rejected]\n"; num_load_rejected += ip1.size(); continue; } vw_out(DebugMessage,"ba") << "\t" << match_file << " " << ip1.size() << " matches.\n"; num_loaded += ip1.size(); // Remove descriptors from interest points and correct scale std::for_each( ip1.begin(), ip1.end(), ip::remove_descriptor ); std::for_each( ip2.begin(), ip2.end(), ip::remove_descriptor ); std::for_each( ip1.begin(), ip1.end(), safe_measurement ); std::for_each( ip2.begin(), ip2.end(), safe_measurement ); typedef boost::shared_ptr< ba::IPFeature > f_ptr; typedef std::list< f_ptr >::iterator f_itr; // Checking to see if features already exist, adding if they // don't, then linking them. vw_out() << "Building the control network for " << match_file <<".\n"; TerminalProgressCallback progress("ba", "Building: "); progress.report_progress(0); double inc_prog = 1.0/double(ip1.size()); for ( size_t k = 0; k < ip1.size(); k++ ) { // Loop through all existing IP // Check if either IP is already in the lists f_itr ipfeature1 = std::find_if( crn[index1].begin(), crn[index1].end(), ContainsEqualIP( ip1[k] ) ); f_itr ipfeature2 = std::find_if( crn[index2].begin(), crn[index2].end(), ContainsEqualIP( ip2[k] ) ); // If the IP are new, add them to the list if ( ipfeature1 == crn[index1].end() ) { crn[index1].relations.push_front( f_ptr( new ba::IPFeature( ip1[k], index1 ) ) ); ipfeature1 = crn[index1].begin(); } if ( ipfeature2 == crn[index2].end() ) { crn[index2].relations.push_front( f_ptr( new ba::IPFeature( ip2[k], index2 ) ) ); ipfeature2 = crn[index2].begin(); } // Doubly linking (*ipfeature1)->connection( *ipfeature2, false ); (*ipfeature2)->connection( *ipfeature1, false ); progress.report_incremental_progress(inc_prog ); } // End loop through ip1 progress.report_finished(); } // End loop through match files if ( num_load_rejected != 0 ) { vw_out(WarningMessage,"ba") << "\tDidn't load " << num_load_rejected << " matches due to inadequacy. Decrease the" << " --min-matches parameter to load smaller " << "sets of matches.\n"; vw_out(WarningMessage,"ba") << "\tLoaded " << num_loaded << " matches.\n"; } // Building control network bool success = crn.write_controlnetwork( cnet ); // Triangulating Positions if (triangulate_control_points){ TerminalProgressCallback progress("ba", "Triangulating: "); progress.report_progress(0); double inc_prog = 1.0/double(cnet.size()); BOOST_FOREACH( ba::ControlPoint& cpoint, cnet ) { progress.report_incremental_progress(inc_prog ); ba::triangulate_control_point( cpoint, camera_models, min_angle_radians, forced_triangulation_distance); } progress.report_finished(); } return success; } void vw::ba::add_ground_control_points(vw::ba::ControlNetwork& cnet, std::vector<std::string> const& gcp_files, cartography::Datum const& datum){ namespace fs = boost::filesystem; std::vector<std::string> const& image_files = cnet.get_image_list(); // Creating a version of image_files that doesn't contain the path typedef std::map<std::string,size_t> LookupType; LookupType image_lookup; for (size_t i = 0; i < image_files.size(); i++ ) { image_lookup[image_files[i]] = i; image_lookup[fs::path(image_files[i]).filename().string()] = i; } std::vector<std::string>::const_iterator gcp_iter = gcp_files.begin(); std::vector<std::string>::const_iterator gcp_end = gcp_files.end(); while ( gcp_iter != gcp_end ) { vw_out() << "Loading GCP file: " << *gcp_iter << std::endl; if ( !fs::exists( *gcp_iter ) ) { vw_throw( ArgumentErr() << "GCP file " << *gcp_iter << " does not exist!" ); } std::ifstream ifile( (*gcp_iter).c_str() ); std::string line; while ( getline(ifile, line, '\n') ){ // Skip empty lines or lines starting with comments if (line.size() == 0) continue; if (line.size() > 0 && line[0] == '#') continue; boost::replace_all(line, ",", " "); // Data to be loaded std::vector<Vector4> measure_locations; std::vector<std::string> measure_cameras; int point_id; Vector3 world_location, world_sigma; std::istringstream is(line); // First elements in the line are the point id, location in // the world, and its sigmas if (!(is >> point_id >> world_location[0] >> world_location[1] >> world_location[2] >> world_sigma[0] >> world_sigma[1] >> world_sigma[2])){ vw_out(WarningMessage) << "Could not parse a ground control point " << "from line: " << line << std::endl; continue; } // Other elements in the line define the position in images while(1){ std::string temp_name; Vector4 temp_loc; if (is >> temp_name >> temp_loc[0] >> temp_loc[1] >> temp_loc[2] >> temp_loc[3]){ if (temp_loc[2] <= 0 || temp_loc[3] <= 0) { vw_throw( ArgumentErr() << "Standard deviations must be positive " << "when loading ground control points." ); } measure_locations.push_back( temp_loc ); measure_cameras.push_back( temp_name ); }else{ break; } } if (world_sigma[0] <= 0 || world_sigma[1] <= 0 || world_sigma[2] <= 0) vw_throw( ArgumentErr() << "Standard deviations must be positive " << "when loading ground control points." ); // Make lat,lon into lon,lat std::swap(world_location[0], world_location[1]); // Building Control Point Vector3 xyz = datum.geodetic_to_cartesian(world_location); vw_out(VerboseDebugMessage,"ba") << "\t\tLocation: " << xyz << std::endl; ControlPoint cpoint(ControlPoint::GroundControlPoint); cpoint.set_position(xyz[0], xyz[1], xyz[2] ); cpoint.set_sigma (world_sigma[0], world_sigma[1], world_sigma[2]); // Adding measures std::vector<Vector4 >::iterator m_iter_loc = measure_locations.begin(); std::vector<std::string>::iterator m_iter_name = measure_cameras.begin(); while ( m_iter_loc != measure_locations.end() ) { LookupType::iterator it = image_lookup.find(*m_iter_name); if ( it != image_lookup.end() ) { vw_out(DebugMessage,"ba") << "\t\tAdded Measure: " << *m_iter_name << " #" << it->second << std::endl; ControlMeasure cm( (*m_iter_loc)[0], (*m_iter_loc)[1], (*m_iter_loc)[2], (*m_iter_loc)[3], it->second ); cpoint.add_measure( cm ); } else { vw_out(WarningMessage,"ba") << "No input image found matching " << *m_iter_name << std::endl; } m_iter_loc++; m_iter_name++; } // Append the GCP if (cpoint.size() > 0) cnet.add_control_point(cpoint); } // End line loop ifile.close(); gcp_iter++; } // End file loop }
// RUN: rm -rf %t // RUN: mkdir %t // RUN: cd %t // RUN: echo '[{"directory":".","command":"clang++ -c %t/test.cpp -o foo -ofoo","file":"%t/test.cpp"}]' | sed -e 's/\\/\//g' > %t/compile_commands.json // RUN: cp "%s" "%t/test.cpp" // RUN: echo '// CHECK: {{qwerty}}' > %t/cclog-check // RUN: clang-check -p "%t" "%t/test.cpp" -analyze -analyzer-output-path=%t/qwerty -extra-arg=-v -extra-arg=-Xclang -extra-arg=-verify 2>&1 | FileCheck %t/cclog-check // RUN: FileCheck %s --input-file=%t/qwerty // CHECK: DOCTYPE plist // CHECK: Division by zero int f() { return 1 / 0; // expected-warning {{Division by zero}} }
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. 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. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #include "BoundingBox.hpp" #include "Point3d.hpp" namespace openstudio{ BoundingBox::BoundingBox() {} void BoundingBox::add(const BoundingBox& other) { this->addPoints(other.corners()); } void BoundingBox::addPoint(const Point3d& point) { if (isEmpty()){ m_minX = point.x(); m_minY = point.y(); m_minZ = point.z(); m_maxX = point.x(); m_maxY = point.y(); m_maxZ = point.z(); }else{ m_minX = std::min(*m_minX, point.x()); m_minY = std::min(*m_minY, point.y()); m_minZ = std::min(*m_minZ, point.z()); m_maxX = std::max(*m_maxX, point.x()); m_maxY = std::max(*m_maxY, point.y()); m_maxZ = std::max(*m_maxZ, point.z()); } } void BoundingBox::addPoints(const std::vector<Point3d>& points) { for (const Point3d& point : points){ addPoint(point); } } bool BoundingBox::intersects(const BoundingBox& other, double tol) { if (isEmpty() || other.isEmpty()){ return false; } bool test = ((*m_minX > other.maxX().get() + tol) || (*m_minY > other.maxY().get() + tol) || (*m_minZ > other.maxZ().get() + tol) || (other.minX().get() > *m_maxX + tol) || (other.minY().get() > *m_maxY + tol) || (other.minZ().get() > *m_maxZ + tol)); return (!test); } bool BoundingBox::isEmpty() const { return !(m_minX); } boost::optional<double> BoundingBox::minX() const { return m_minX; } boost::optional<double> BoundingBox::minY() const { return m_minY; } boost::optional<double> BoundingBox::minZ() const { return m_minZ; } boost::optional<double> BoundingBox::maxX() const { return m_maxX; } boost::optional<double> BoundingBox::maxY() const { return m_maxY; } boost::optional<double> BoundingBox::maxZ() const { return m_maxZ; } std::vector<Point3d> BoundingBox::corners() const { std::vector<Point3d> result; if (isEmpty()){ return result; } result.push_back(Point3d(*m_minX, *m_minY, *m_minZ)); result.push_back(Point3d(*m_maxX, *m_minY, *m_minZ)); result.push_back(Point3d(*m_minX, *m_maxY, *m_minZ)); result.push_back(Point3d(*m_maxX, *m_maxY, *m_minZ)); result.push_back(Point3d(*m_minX, *m_minY, *m_maxZ)); result.push_back(Point3d(*m_maxX, *m_minY, *m_maxZ)); result.push_back(Point3d(*m_minX, *m_maxY, *m_maxZ)); result.push_back(Point3d(*m_maxX, *m_maxY, *m_maxZ)); return result; } }
#include "viewer.h" #include <stdio.h> #include <cmath> #include <vector> #include <iostream> #include <algorithm> #include "GL/glew.h" #include "console.h" using namespace std; using namespace chrono; #define DEFAULT_W 800 #define DEFAULT_H 600 namespace CGL { // HDPI display bool Viewer::HDPI; // framecount & related timeers int Viewer::framecount; time_point<system_clock> Viewer::sys_last; time_point<system_clock> Viewer::sys_curr; // draw toggles bool Viewer::showInfo = true; // window properties GLFWwindow* Viewer::window; size_t Viewer::buffer_w; size_t Viewer::buffer_h; // user space renderer Renderer* Viewer::renderer; // on-screen display OSDText* Viewer::osd_text; int Viewer::line_id_renderer; int Viewer::line_id_framerate; Viewer::Viewer() { } Viewer::~Viewer() { glfwDestroyWindow(window); glfwTerminate(); // free resources delete renderer; delete osd_text; } void Viewer::init() { // initialize glfw glfwSetErrorCallback( err_callback ); if( !glfwInit() ) { out_err("Error: could not initialize GLFW!"); exit( 1 ); } // create window string title = renderer ? "CGL: " + renderer->name() : "CGL"; window = glfwCreateWindow( DEFAULT_W, DEFAULT_H, title.c_str(), NULL, NULL ); if (!window) { out_err("Error: could not create window!"); glfwTerminate(); exit( 1 ); } // set context glfwMakeContextCurrent( window ); glfwSwapInterval(1); // framebuffer event callbacks glfwSetFramebufferSizeCallback( window, resize_callback ); // key event callbacks glfwSetKeyCallback( window, key_callback ); // cursor event callbacks glfwSetCursorPosCallback( window, cursor_callback ); // wheel event callbacks glfwSetScrollCallback(window, scroll_callback); // mouse button callbacks glfwSetInputMode(window, GLFW_STICKY_MOUSE_BUTTONS, 1); glfwSetMouseButtonCallback(window, mouse_button_callback); // initialize glew if (glewInit() != GLEW_OK) { out_err("Error: could not initialize GLEW!"); glfwTerminate(); exit( 1 ); } // enable alpha blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // resize components to current window size, get DPI glfwGetFramebufferSize(window, (int*) &buffer_w, (int*) &buffer_h ); if( buffer_w > DEFAULT_W ) HDPI = true; // initialize renderer if already set if (renderer){ if (HDPI) renderer->use_hdpi_reneder_target(); renderer->init(); } // initialize status OSD osd_text = new OSDText(); if (osd_text->init(HDPI) < 0) { out_err("Error: could not initialize on-screen display!"); exit( 1 ); } // add lines for renderer and fps line_id_renderer = osd_text->add_line(-0.95, 0.90, "Renderer", 18, Color(0.15, 0.5, 0.15)); line_id_framerate = osd_text->add_line(-0.98, -0.96, "Framerate", 14, Color(0.15, 0.5, 0.15)); // resize elements to current size resize_callback(window, buffer_w, buffer_h); } void Viewer::start() { // start timer sys_last = system_clock::now(); // run update loop while( !glfwWindowShouldClose( window ) ) { update(); } } void Viewer::set_renderer(Renderer *renderer) { this->renderer = renderer; } void Viewer::update() { // clear frame glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // run user renderer if (renderer) { renderer->render(); } // draw info if( showInfo ) { drawInfo(); } // swap buffers glfwSwapBuffers(window); // poll events glfwPollEvents(); } void Viewer::drawInfo() { // compute timers - fps is update every second sys_curr = system_clock::now(); double elapsed = ((duration<double>) (sys_curr - sys_last)).count(); if (elapsed >= 1.0f) { // update framecount OSD Color c = framecount < 20 ? Color(1.0, 0.35, 0.35) : Color(0.15, 0.5, 0.15); osd_text->set_color(line_id_framerate, c); string framerate_info = "Framerate: " + to_string(framecount) + " fps"; osd_text->set_text(line_id_framerate, framerate_info); // reset timer and counter framecount = 0; sys_last = sys_curr; } else { // increment framecount framecount++; } // udpate renderer OSD // TODO: This is done on every update and it shouldn't be! // The viewer should only update when the renderer needs to // update the info text. if (renderer) { string renderer_info = renderer->info(); osd_text->set_text(line_id_renderer, renderer_info); } else { string renderer_info = "No input renderer"; osd_text->set_text(line_id_renderer, renderer_info); } // render OSD osd_text->render(); } void Viewer::err_callback( int error, const char* description ) { out_err( "GLFW Error: " << description ); } void Viewer::resize_callback( GLFWwindow* window, int width, int height ) { // get framebuffer size int w, h; glfwGetFramebufferSize(window, &w, &h ); // update buffer size buffer_w = w; buffer_h = h; glViewport( 0, 0, buffer_w, buffer_h ); // resize on-screen display osd_text->resize(buffer_w, buffer_h); // resize render if there is a user space renderer if (renderer) renderer->resize( buffer_w, buffer_h ); } void Viewer::cursor_callback( GLFWwindow* window, double xpos, double ypos ) { // forward pan event to renderer if( HDPI ) { float cursor_x = 2 * xpos; float cursor_y = 2 * ypos; renderer->cursor_event(cursor_x, cursor_y); } else { float cursor_x = xpos; float cursor_y = ypos; renderer->cursor_event(cursor_x, cursor_y); } } void Viewer::scroll_callback( GLFWwindow* window, double xoffset, double yoffset) { renderer->scroll_event(xoffset, yoffset); } void Viewer::mouse_button_callback( GLFWwindow* window, int button, int action, int mods ) { renderer->mouse_event( button, action, mods ); } void Viewer::key_callback( GLFWwindow* window, int key, int scancode, int action, int mods ) { if (action == GLFW_PRESS) { if( key == GLFW_KEY_ESCAPE ) { exit(0); // glfwSetWindowShouldClose( window, true ); } else if( key == GLFW_KEY_GRAVE_ACCENT ){ showInfo = !showInfo; } } renderer->keyboard_event( key, action, mods ); } } // namespace CGL
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <memory> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/lite/toco/graph_transformations/graph_transformations.h" #include "tensorflow/lite/toco/model.h" #include "tensorflow/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { ::tensorflow::Status ResolveFakeQuantArgsFromVars::Run(Model* model, std::size_t op_index, bool* modified) { *modified = false; const auto fakequant_it = model->operators.begin() + op_index; auto* fakequant_base_op = fakequant_it->get(); if (fakequant_base_op->type != OperatorType::kFakeQuant) { return ::tensorflow::Status::OK(); } auto* fakequant_op = static_cast<FakeQuantOperator*>(fakequant_base_op); if (fakequant_op->minmax) { // Already resolved. return ::tensorflow::Status::OK(); } CHECK_EQ(fakequant_op->inputs.size(), 3); // We need to yield until the min and max parameters have been // resolved to constant arrays. for (int i = 1; i <= 2; i++) { if (!IsConstantParameterArray(*model, fakequant_op->inputs[i])) { return ::tensorflow::Status::OK(); } } // Obtain the final min/max values const auto& min_array = model->GetArray(fakequant_op->inputs[1]); const auto& max_array = model->GetArray(fakequant_op->inputs[2]); CHECK_EQ(RequiredBufferSizeForShape(min_array.shape()), 1); CHECK_EQ(RequiredBufferSizeForShape(max_array.shape()), 1); fakequant_op->minmax.reset(new MinMax); MinMax& minmax = *fakequant_op->minmax; minmax.min = min_array.GetBuffer<ArrayDataType::kFloat>().data[0]; minmax.max = max_array.GetBuffer<ArrayDataType::kFloat>().data[0]; // We always want [min, max] to contain 0. if (minmax.min > 0 || minmax.max < 0) { LOG(WARNING) << "For " << LogName(*fakequant_op) << " the MinMax range " << "[" << minmax.min << ", " << minmax.max << "] does not contain 0. " << "Proceeding by tweaking it to contain 0, which will result " "in poor accuracy."; } minmax.min = std::min(minmax.min, 0.); minmax.max = std::max(minmax.max, 0.); // We won't use the input arrays that provided these min and max // values, anymore. Delete them unless they are used by something // else. for (int i = 1; i <= 2; i++) { DeleteArrayIfUnusedOutsideOfOp(fakequant_op->inputs[i], fakequant_op, model); } fakequant_op->inputs.resize(1); *modified = true; return ::tensorflow::Status::OK(); } } // namespace toco
// Copyright Michael Shepanski 2014. // 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 <assert.h> #include <queue> #include <string> #include <sstream> #include <vector> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/utility/identity_type.hpp> #include <libpq/libpq-fs.h> #include <quince/detail/column_type.h> #include <quince/exceptions.h> #include <quince/detail/row.h> #include <quince/detail/util.h> #include <quince_postgresql/database.h> #include <quince_postgresql/detail/dialect_sql.h> #include <quince_postgresql/detail/session.h> using boost::format; using boost::optional; using namespace quince; using std::dynamic_pointer_cast; using std::shared_ptr; using std::string; using std::stringstream; using std::unique_ptr; using std::vector; #define BOOLOID 16 #define BYTEAOID 17 #define INT8OID 20 #define INT2OID 21 #define INT4OID 23 #define TEXTOID 25 #define OIDOID 26 #define FLOAT4OID 700 #define FLOAT8OID 701 #define DATEOID 1082 #define JSONOID 114 #define JSONBOID 3802 #define TIMEOID 1083 #define TIMESTAMPOID 1114 #define VOIDOID 2278 #define TSVECTOROID 3614 #define UNKNOWNOID 705 namespace quince_postgresql { namespace { Oid standard_type_oid(column_type type) { switch (type) { case column_type::boolean: return BOOLOID; case column_type::small_int: return INT2OID; case column_type::integer: return INT4OID; case column_type::big_int: return INT8OID; case column_type::floating_point: return FLOAT4OID; case column_type::double_precision: return FLOAT8OID; case column_type::date_type: return DATEOID; case column_type::json_type: return JSONOID; case column_type::jsonb_type: return JSONBOID; case column_type::time_type: return TIMEOID; case column_type::timestamp: return TIMESTAMPOID; case column_type::string: return TEXTOID; case column_type::byte_vector: return BYTEAOID; case column_type::none: return VOIDOID; default: abort(); } } column_type get_column_type(Oid type_oid) { switch (type_oid) { case BOOLOID: return column_type::boolean; case INT2OID: return column_type::small_int; case INT4OID: return column_type::integer; case INT8OID: return column_type::big_int; case FLOAT4OID: return column_type::floating_point; case FLOAT8OID: return column_type::double_precision; case DATEOID: return column_type::date_type; case JSONOID: return column_type::json_type; case JSONBOID: return column_type::jsonb_type; case TIMEOID: return column_type::time_type; case TIMESTAMPOID: return column_type::timestamp; case TEXTOID: return column_type::string; case BYTEAOID: return column_type::byte_vector; case VOIDOID: return column_type::none; default: throw retrieved_unrecognized_type_exception(type_oid); } } class exec_params { public: explicit exec_params(const vector<cell> &data) : _n_params(data.size()), _types(new Oid[_n_params]), _values(new const char *[_n_params]), _lengths(new int[_n_params]), _formats(new int[_n_params]) { for (size_t i = 0; i < _n_params; i++) { const cell &c = data[i]; if (c.type() == column_type::none) { _types[i] = 0; _values[i] = NULL; _lengths[i] = 0; } else { _types[i] = standard_type_oid(c.type()); _values[i] = static_cast<const char *>(c.data()); _lengths[i] = boost::numeric_cast<int>(c.size()); } _formats[i] = 1; // always binary } } PGresult * exec(PGconn * const conn, const string &sql) const { return PQexecParams( conn, sql.c_str(), boost::numeric_cast<int>(_n_params), _types.get(), _values.get(), _lengths.get(), _formats.get(), 1 ); }; int send(PGconn * const conn, const string &sql) const { return PQsendQueryParams( conn, sql.c_str(), boost::numeric_cast<int>(_n_params), _types.get(), _values.get(), _lengths.get(), _formats.get(), 1 ); } private: const size_t _n_params; std::unique_ptr<Oid[]> _types; std::unique_ptr<BOOST_IDENTITY_TYPE((const char *))[]> _values; std::unique_ptr<int[]> _lengths; const std::unique_ptr<int[]> _formats; }; string new_cursor_name() { static uint64_t count = 0; return "cursor_" + std::to_string(count++); } class query_result { public: explicit query_result(const database &database, PGresult *pg_result) : _database(database), _pg_result(pg_result), _n_rows(boost::numeric_cast<uint32_t>(PQntuples(pg_result))), _n_cols(boost::numeric_cast<uint32_t>(PQnfields(pg_result))), _col_names(new string[_n_cols]), _type_oids(new Oid[_n_cols]), _current_row(0) { for (uint32_t i = 0; i < _n_cols; i++) { const char *chars = PQfname(_pg_result, i); if (chars == NULL) throw malformed_results_exception(); _col_names[i] = chars; _type_oids[i] = PQftype(_pg_result, i); } } ~query_result() { if (_pg_result != NULL) PQclear(_pg_result); } vector<string> metadata() const { vector<string> result; result.reserve(_n_cols); for (uint32_t i = 0; i < _n_cols; i++) { const string &col_name = _col_names[i]; const string type_name = _database.column_type_name(get_column_type(_type_oids[i])); result.push_back((format("\"%1%\" %2%") % col_name % type_name).str()); } return result; } bool bad_no_data() const { return PQresultStatus(_pg_result) != PGRES_COMMAND_OK; } bool bad_data() const { return PQresultStatus(_pg_result) != PGRES_TUPLES_OK; } bool at_end() const { return _current_row == _n_rows; } unique_ptr<row> next() { if (at_end()) return nullptr; unique_ptr<row> result = quince::make_unique<row>(&_database); for (uint32_t i = 0; i < _n_cols; i++) { const optional<column_type> col_type( ! PQgetisnull(_pg_result, _current_row, i), get_column_type(_type_oids[i]) ); const cell cell( col_type, PQfformat(_pg_result, i) == 1, PQgetvalue(_pg_result, _current_row, i), boost::numeric_cast<size_t>(PQgetlength(_pg_result, _current_row, i)) ); result->add_cell(cell, _col_names[i]); } _current_row++; return result; } private: const database &_database; PGresult *const _pg_result; const uint32_t _n_rows; const uint32_t _n_cols; std::unique_ptr<string[]> _col_names; std::unique_ptr<Oid[]> _type_oids; uint32_t _current_row; }; } class session_impl::result_stream_impl : public abstract_result_stream_impl { public: result_stream_impl( const database &database, const string &cursor_name, PGconn *conn, uint32_t fetch_size, const std::function<int(const sql &)> send, const std::function<void(void)> epilogue ) : _database(database), _sql_fetch(database.make_dialect_sql()), _conn(conn), _send(send), _epilogue(epilogue), _current(quince::make_unique<query_result>(_database, fetch())), _exhausted(false) { const_cast<dialect_sql &>(*_sql_fetch).write_fetch(cursor_name, fetch_size); } ~result_stream_impl() { try { close(); } catch (...) {} } void close() { while (!_backlog.empty()) PQclear(take_from_backlog()); _epilogue(); } void absorb() { while (PGresult *r = PQgetResult(_conn)) _backlog.push(r); } unique_ptr<row> next() { unique_ptr<row> result; for (;;) { if (_exhausted) return nullptr; else if (result) return result; else if (_current && !_current->at_end()) result = _current->next(); else if (! _backlog.empty()) _current = quince::make_unique<query_result>(_database, take_from_backlog()); else if (PGresult *gotten = PQgetResult(_conn)) _backlog.push(gotten); else if (PGresult *fetched = fetch()) _backlog.push(fetched); else _exhausted = true; } } private: PGresult * fetch() { _send(*_sql_fetch); while (PGresult * const r = PQgetResult(_conn)) { if (PQntuples(r) == 0) PQclear(r); else return r; } return nullptr; } PGresult * take_from_backlog() { PGresult * const result = _backlog.front(); _backlog.pop(); return result; } const database &_database; unique_ptr<const dialect_sql> _sql_fetch; PGconn * const _conn; const std::function<int(const sql &)> _send; const std::function<void(void)> _epilogue; unique_ptr<query_result> _current; bool _exhausted; std::queue<PGresult *> _backlog; }; string session_impl::spec::connection_string() const { stringstream strm; strm << "host=" << _host << " user=" << _user << " password=" << _password; if (_port) strm << " port=" << *_port; if (_db_name) strm << " dbname=" << *_db_name; return strm.str(); } extern "C" { void ignore_postgresql_notice(void *a_arg, const PGresult *a_res) {} } session_impl::session_impl(const database &database, const session_impl::spec &spec) : _database(database), _conn(connect(spec)) { if (! _conn || PQstatus(_conn) != CONNECTION_OK) throw failed_connection_exception(); if (spec._isolation) { unique_ptr<dialect_sql> cmd = _database.make_dialect_sql(); cmd->write_set_session_characteristics(*spec._isolation); exec(*cmd); } } session_impl::~session_impl() { _asynchronous_stream.reset(); if (_conn) disconnect(_conn); } void session_impl::ignore_notices() { absorb_pending_results(); PQsetNoticeReceiver(_conn, ignore_postgresql_notice, nullptr); } bool session_impl::unchecked_exec(const sql &cmd) { assert(! _asynchronous_stream); return ! query_result(_database, pq_exec(cmd)).bad_no_data(); } unique_ptr<row> session_impl::exec_with_one_output(const sql &cmd) { absorb_pending_results(); return one_output(pq_exec(cmd)); } result_stream session_impl::exec_with_stream_output(const sql &cmd, uint32_t fetch_size) { absorb_pending_results(); const string cursor_name = new_cursor_name(); const unique_ptr<dialect_sql> declare = clone(dynamic_cast<const dialect_sql &>(cmd)); declare->prepend_declare_cursor(cursor_name); check_no_output(pq_exec(*declare)); return new_result_stream(cursor_name, fetch_size); } vector<string> session_impl::exec_with_metadata_output(const sql &cmd) { return metadata(pq_exec(cmd)); } void session_impl::exec(const sql &cmd) { absorb_pending_results(); check_no_output(pq_exec(cmd)); } unique_ptr<row> session_impl::next_output(const result_stream &rs) { assert(rs); shared_ptr<result_stream_impl> rsi = dynamic_pointer_cast<result_stream_impl>(rs); assert(rsi); if (rsi != _asynchronous_stream) { absorb_pending_results(); assert(! _asynchronous_stream); _asynchronous_stream = rsi; } return rsi->next(); } string session_impl::encoding() const { return PQparameterStatus(_conn, "server_encoding"); } void session_impl::throw_last_error() const { const char *const dbms_message = PQerrorMessage(_conn); string message(dbms_message ? dbms_message : ""); const enum { deadlock, broken_connection, other } category = message.find("ERROR: deadlock detected") == 0? deadlock : message.find("ERROR: could not serialize access due to concurrent update") == 0? deadlock : message.find("server closed the connection unexpectedly") == 0? broken_connection : message.find("no connection to the server") == 0? broken_connection : other; message += " (most recent SQL command was `" + _latest_sql + "')"; switch (category) { case deadlock: throw deadlock_exception(message); case broken_connection: _database.discard_connections(); throw broken_connection_exception(message); default: throw dbms_exception(message); } } void session_impl::check_no_output(PGresult *exec_result) { if (query_result(_database, exec_result).bad_no_data()) throw_last_error(); } unique_ptr<row> session_impl::one_output(PGresult *exec_result) { query_result r(_database, exec_result); if (r.bad_data()) throw_last_error(); unique_ptr<row> row = r.next(); if (! r.at_end()) throw multi_row_exception(); return row; } vector<string> session_impl::metadata(PGresult *exec_result) { const query_result r(_database, exec_result); if (r.bad_data()) throw_last_error(); return r.metadata(); } void session_impl::absorb_pending_results() { if (_asynchronous_stream) { _asynchronous_stream->absorb(); _asynchronous_stream.reset(); } else if (PGresult *pg_result = PQgetResult(_conn)) { // unexpected residual results. do PQclear(pg_result); while ((pg_result = PQgetResult(_conn)) != nullptr); } } PGresult * session_impl::pq_exec(const sql &cmd) { return exec_params(cmd.get_input().values()).exec( _conn, _latest_sql = cmd.get_text() ); } int session_impl::pq_send(const sql &cmd) { return exec_params(cmd.get_input().values()).send( _conn, _latest_sql = cmd.get_text() ); } result_stream session_impl::new_result_stream(const string &cursor_name, uint32_t fetch_size) { assert(!_asynchronous_stream); _asynchronous_stream = quince::make_unique<result_stream_impl>( _database, cursor_name, _conn, fetch_size, [this] (const sql &cmd) { return pq_send(cmd); }, [this, cursor_name] { close_cursor(cursor_name); } ); return _asynchronous_stream; } void session_impl::close_cursor(const string &cursor_name) { const unique_ptr<dialect_sql> cmd = _database.make_dialect_sql(); cmd->write_close_cursor(cursor_name); check_no_output(pq_exec(*cmd)); } PGconn * session_impl::connect(const session_impl::spec &spec) { assert(! _disabled); if (! _have_registered_disabler) { // We might get here more than once, because of a race condition. No harm done. // atexit(disable); // Avoid PQfinish() calls after exit(), because (a) there's no benefit and more // importantly (b) they can crash because the libpq might have shut down by then. // _have_registered_disabler = false; } return PQconnectdb(spec.connection_string().c_str()); } void session_impl::disconnect(PGconn *conn) { if (! _disabled) PQfinish(conn); } void session_impl::disable() { _disabled = true; } bool session_impl::_disabled = false; // I can rely on load-time initialization (i.e. before the static init sequence), because bool is a POD. bool session_impl::_have_registered_disabler = false; }
/** * Code adapted from Marek Majkowski's blog post * https://blog.cloudflare.com/every-7-8us-your-computers-memory-has-a-hiccup */ #include <iostream> #include <chrono> #include <vector> #include <memory> #include <immintrin.h> #include <cassert> #ifndef REPETITIONS #define REPETITIONS 512 * 1024 #endif struct Record { uint32_t timestamp; uint32_t duration; }; using Clock = std::chrono::steady_clock; inline static size_t get_time() { return static_cast<size_t>(std::chrono::time_point_cast<std::chrono::nanoseconds>(Clock::now()) .time_since_epoch().count()); } int main() { auto memory = std::unique_ptr<size_t[]>(new size_t[4096]); assert((reinterpret_cast<uintptr_t>(memory.get()) & 15) == 0); auto* src = memory.get(); std::vector<Record> records(REPETITIONS); auto root = get_time(); // use volatile to prevent compiler from optimizing it out volatile size_t dest; for (int i = 0; i < REPETITIONS; i++) { _mm_clflush(src); // clear cache auto start = get_time(); _mm_mfence(); // just to make sure that the access is not reordered dest = *src; _mm_mfence(); auto end = get_time(); records[i].timestamp = static_cast<uint32_t>(start - root); records[i].duration = static_cast<uint32_t>(end - start); } // calculate average access time size_t sum = 0; for (auto value: records) sum += value.duration; size_t avg = sum / records.size(); // calculate durations between long access times (>= 2 * avg) auto last = records[0].timestamp; for (size_t i = 1; i < records.size(); i++) { auto& record = records[i]; if (record.duration > avg * 2) { auto space = record.timestamp - last; std::cerr << space << std::endl; last = record.timestamp; } } return 0; }
// <Snippet1> #using <System.Xml.dll> #using <System.Transactions.dll> #using <System.EnterpriseServices.dll> #using <System.dll> #using <System.Data.dll> using namespace System; using namespace System::Data; using namespace System::Xml; using namespace System::Data::SqlClient; int main() { DataSet^ dsNorthwind = gcnew DataSet; //Create the connection string String^ sConnect; sConnect = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"; //Create a connection object to connect to the northwind db. SqlConnection^ nwconnect = gcnew SqlConnection( sConnect ); //Create a command string to select all the customers in the WA region. String^ sCommand = "Select * from Customers where Region='WA'"; //Create an adapter to load the DataSet. SqlDataAdapter^ myDataAdapter = gcnew SqlDataAdapter( sCommand,nwconnect ); //Fill the DataSet with the selected records. myDataAdapter->Fill( dsNorthwind, "Customers" ); //Load the document with the DataSet. XmlDataDocument^ doc = gcnew XmlDataDocument( dsNorthwind ); //Create an element representing the first customer record. DataRow^ row = doc->DataSet->Tables[ 0 ]->Rows[ 0 ]; XmlElement^ elem = doc->GetElementFromRow( row ); Console::WriteLine( elem->OuterXml ); } // </Snippet1>
#include "../../RStein.AsyncCpp/Schedulers/Scheduler.h" #include "../../RStein.AsyncCpp/Threading/SynchronizationContext.h" #include "../../RStein.AsyncCpp/Threading/SynchronizationContextScope.h" #include "../Mocks/SynchronizationContextMock.h" #include <gtest/gtest.h> namespace RStein::AsyncCpp::SchedulersTest { using UiSynchronizationContext = Mocks::TestSynchronizationContextMock; TEST(Scheduler, FromSynchronizationContextReturnsSchedulerBasedOnSynchronizationContext) { //Assume that this is a special (non-default) synchronization context - UI context, event loop, dedicated service thread etc. UiSynchronizationContext uicontext; Threading::SynchronizationContextScope synchronizationContextScope(uicontext); //UI framework/Specialized service installs special context. Threading::SynchronizationContext::SetSynchronizationContext(&uicontext); auto myCompletionHandler = [] { //UI controls like textbox expects access from the UI thread. //textbox.Text = GetAsyncResult(); }; //And call infrastructure code (e. g. async processor) //asyncProcessor.Run(heavyWorkForBackgroundThread, myCompletionHandler); //Another part of the application, typically infrastructure code (e. g. async processor) captures synchronization context for calling thread and wraps it in scheduler. auto callingThreadScheduler = Schedulers::Scheduler::FromCurrentSynchronizationContext(); auto clientHandler = myCompletionHandler; //Async processor executes async work, possibly in another thread (task, scheduler). //[...time passed...] //Async processor completes work in *another (non-UI/non-special service) thread* and then invokes clientHandler in the UI synchronization context. callingThreadScheduler->EnqueueItem(clientHandler); ASSERT_TRUE(uicontext.WasPostCalled()); } }
/* * Copyright (c) 2018, The bitcoin2network developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of bitcoin2network. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #include "Util.h" #include <cstdio> #include <boost/filesystem.hpp> #include "CryptoNoteConfig.h" #ifdef WIN32 #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #include <shlobj.h> #include <strsafe.h> #else #include <sys/utsname.h> #endif namespace Tools { #ifdef WIN32 std::string get_windows_version_display_string() { typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO); typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); #define BUFSIZE 10000 char pszOS[BUFSIZE] = {0}; OSVERSIONINFOEX osvi; SYSTEM_INFO si; PGNSI pGNSI; PGPI pGPI; BOOL bOsVersionInfoEx; DWORD dwType; ZeroMemory(&si, sizeof(SYSTEM_INFO)); ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi); if(!bOsVersionInfoEx) return pszOS; // Call GetNativeSystemInfo if supported or GetSystemInfo otherwise. pGNSI = (PGNSI) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); if(NULL != pGNSI) pGNSI(&si); else GetSystemInfo(&si); if ( VER_PLATFORM_WIN32_NT==osvi.dwPlatformId && osvi.dwMajorVersion > 4 ) { StringCchCopy(pszOS, BUFSIZE, TEXT("Microsoft ")); // Test for the specific product. if ( osvi.dwMajorVersion == 6 ) { if( osvi.dwMinorVersion == 0 ) { if( osvi.wProductType == VER_NT_WORKSTATION ) StringCchCat(pszOS, BUFSIZE, TEXT("Windows Vista ")); else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 " )); } if ( osvi.dwMinorVersion == 1 ) { if( osvi.wProductType == VER_NT_WORKSTATION ) StringCchCat(pszOS, BUFSIZE, TEXT("Windows 7 ")); else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 R2 " )); } pGPI = (PGPI) GetProcAddress( GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI( osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType); switch( dwType ) { case PRODUCT_ULTIMATE: StringCchCat(pszOS, BUFSIZE, TEXT("Ultimate Edition" )); break; case PRODUCT_PROFESSIONAL: StringCchCat(pszOS, BUFSIZE, TEXT("Professional" )); break; case PRODUCT_HOME_PREMIUM: StringCchCat(pszOS, BUFSIZE, TEXT("Home Premium Edition" )); break; case PRODUCT_HOME_BASIC: StringCchCat(pszOS, BUFSIZE, TEXT("Home Basic Edition" )); break; case PRODUCT_ENTERPRISE: StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" )); break; case PRODUCT_BUSINESS: StringCchCat(pszOS, BUFSIZE, TEXT("Business Edition" )); break; case PRODUCT_STARTER: StringCchCat(pszOS, BUFSIZE, TEXT("Starter Edition" )); break; case PRODUCT_CLUSTER_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Cluster Server Edition" )); break; case PRODUCT_DATACENTER_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition" )); break; case PRODUCT_DATACENTER_SERVER_CORE: StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition (core installation)" )); break; case PRODUCT_ENTERPRISE_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" )); break; case PRODUCT_ENTERPRISE_SERVER_CORE: StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition (core installation)" )); break; case PRODUCT_ENTERPRISE_SERVER_IA64: StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems" )); break; case PRODUCT_SMALLBUSINESS_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server" )); break; case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server Premium Edition" )); break; case PRODUCT_STANDARD_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition" )); break; case PRODUCT_STANDARD_SERVER_CORE: StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition (core installation)" )); break; case PRODUCT_WEB_SERVER: StringCchCat(pszOS, BUFSIZE, TEXT("Web Server Edition" )); break; } } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 ) { if( GetSystemMetrics(SM_SERVERR2) ) StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Server 2003 R2, ")); else if ( osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Storage Server 2003")); else if ( osvi.wSuiteMask & VER_SUITE_WH_SERVER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Home Server")); else if( osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) { StringCchCat(pszOS, BUFSIZE, TEXT( "Windows XP Professional x64 Edition")); } else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2003, ")); // Test for the server type. if ( osvi.wProductType != VER_NT_WORKSTATION ) { if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 ) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Edition for Itanium-based Systems" )); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise Edition for Itanium-based Systems" )); } else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 ) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter x64 Edition" )); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise x64 Edition" )); else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard x64 Edition" )); } else { if ( osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Compute Cluster Edition" )); else if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Edition" )); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise Edition" )); else if ( osvi.wSuiteMask & VER_SUITE_BLADE ) StringCchCat(pszOS, BUFSIZE, TEXT( "Web Edition" )); else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard Edition" )); } } } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 ) { StringCchCat(pszOS, BUFSIZE, TEXT("Windows XP ")); if( osvi.wSuiteMask & VER_SUITE_PERSONAL ) StringCchCat(pszOS, BUFSIZE, TEXT( "Home Edition" )); else StringCchCat(pszOS, BUFSIZE, TEXT( "Professional" )); } if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 ) { StringCchCat(pszOS, BUFSIZE, TEXT("Windows 2000 ")); if ( osvi.wProductType == VER_NT_WORKSTATION ) { StringCchCat(pszOS, BUFSIZE, TEXT( "Professional" )); } else { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Server" )); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) StringCchCat(pszOS, BUFSIZE, TEXT( "Advanced Server" )); else StringCchCat(pszOS, BUFSIZE, TEXT( "Server" )); } } // Include service pack (if any) and build number. if( strlen(osvi.szCSDVersion) > 0 ) { StringCchCat(pszOS, BUFSIZE, TEXT(" ") ); StringCchCat(pszOS, BUFSIZE, osvi.szCSDVersion); } TCHAR buf[80]; StringCchPrintf( buf, 80, TEXT(" (build %d)"), osvi.dwBuildNumber); StringCchCat(pszOS, BUFSIZE, buf); if ( osvi.dwMajorVersion >= 6 ) { if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 ) StringCchCat(pszOS, BUFSIZE, TEXT( ", 64-bit" )); else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL ) StringCchCat(pszOS, BUFSIZE, TEXT(", 32-bit")); } return pszOS; } else { printf( "This sample does not support this version of Windows.\n"); return pszOS; } } #else std::string get_nix_version_display_string() { utsname un; if(uname(&un) < 0) return std::string("*nix: failed to get os version"); return std::string() + un.sysname + " " + un.version + " " + un.release; } #endif std::string get_os_version_string() { #ifdef WIN32 return get_windows_version_display_string(); #else return get_nix_version_display_string(); #endif } #ifdef WIN32 std::string get_special_folder_path(int nfolder, bool iscreate) { namespace fs = boost::filesystem; char psz_path[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, psz_path, nfolder, iscreate)) { return psz_path; } return ""; } #endif std::string getDefaultDataDirectory() { //namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\CRYPTONOTE_NAME // Windows >= Vista: C:\Users\Username\AppData\Roaming\CRYPTONOTE_NAME // Mac: ~/Library/Application Support/CRYPTONOTE_NAME // Unix: ~/.CRYPTONOTE_NAME std::string config_folder; #ifdef WIN32 // Windows config_folder = (get_special_folder_path(CSIDL_APPDATA, true) + "/" + CRYPTONOTE_NAME); #else std::string pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = "/"; else pathRet = pszHome; #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; config_folder = (pathRet + "/" + CRYPTONOTE_NAME); #else // Unix config_folder = (pathRet + "/." + CRYPTONOTE_NAME); #endif #endif return config_folder; } std::string getDefaultCacheFile(const std::string& dataDir) { static const std::string name = "cache_file"; namespace bf = boost::filesystem; bf::path dir = dataDir; if (!bf::exists(dir) ) { throw std::runtime_error("Directory \"" + dir.string() + "\" doesn't exist"); } if (!bf::exists(dir/name)) { throw std::runtime_error("File \"" + boost::filesystem::path(dir/name).string() + "\" doesn't exist"); } return boost::filesystem::path(dir/name).string(); } bool create_directories_if_necessary(const std::string& path) { namespace fs = boost::filesystem; boost::system::error_code ec; fs::path fs_path(path); if (fs::is_directory(fs_path, ec)) { return true; } return fs::create_directories(fs_path, ec); } std::error_code replace_file(const std::string& replacement_name, const std::string& replaced_name) { int code; #if defined(WIN32) // Maximizing chances for success DWORD attributes = ::GetFileAttributes(replaced_name.c_str()); if (INVALID_FILE_ATTRIBUTES != attributes) { ::SetFileAttributes(replaced_name.c_str(), attributes & (~FILE_ATTRIBUTE_READONLY)); } bool ok = 0 != ::MoveFileEx(replacement_name.c_str(), replaced_name.c_str(), MOVEFILE_REPLACE_EXISTING); code = ok ? 0 : static_cast<int>(::GetLastError()); #else bool ok = 0 == std::rename(replacement_name.c_str(), replaced_name.c_str()); code = ok ? 0 : errno; #endif return std::error_code(code, std::system_category()); } bool directoryExists(const std::string& path) { boost::system::error_code ec; return boost::filesystem::is_directory(path, ec); } }
#include <iostream> using namespace std; template <typename T> T maxn(T[], int); int main(int argc, char const *argv[]) { int ints[6] = { 2, 3, 9, 5, 7, 4 }; cout << "Max is : " << maxn(ints, 6) << endl; double ds[4] = { 2.0, 3.0, 9.0, 5.0 }; cout << "Max is : " << maxn(ds, 4) << endl; char const * cs[5] = { "abc", "asjiewe", "quejw", "adkoiweklmqwe", "we" }; cout << "Max is : " << maxn(cs, 5) << endl; } template <typename T> T maxn(T arr[], int n) { T max = arr[0]; for (int i = 1; i < n; i++) { max = arr[i] > max ? arr[i] : max; } return max; } char const * maxn(char const * arr[], int n) { char const * max = arr[0]; int len = strlen(max); for (int i = 1; i < n; i++) { if (strlen(arr[i]) > len) { max = arr[i]; len = strlen(arr[i]); } } return max; }
#include <iostream> #include <cstring> #include <cctype> #include <cassert> #include <map> #include <string> using namespace std; #include "sonnet.h" /* PRE-SUPPLIED HELPER FUNCTIONS START HERE */ /* NOTE: It is much more important to understand the interface to and the "black-box" operation of these functions (in terms of inputs and outputs) than it is to understand the details of their inner working. */ /* get_word(...) retrieves a word from the input string input_line based on its word number. If the word number is valid, the function places an uppercase version of the word in the output parameter output_word, and the function returns true. Otherwise the function returns false. */ bool get_word(const char *input_line, int word_number, char *output_word) { char *output_start = output_word; int words = 0; if (word_number < 1) { *output_word = '\0'; return false; } do { while (*input_line && !isalnum(*input_line)) input_line++; if (*input_line == '\0') break; output_word = output_start; while (*input_line && (isalnum(*input_line) || *input_line=='\'')) { *output_word = toupper(*input_line); output_word++; input_line++; } *output_word = '\0'; if (++words == word_number) return true; } while (*input_line); *output_start = '\0'; return false; } /* char rhyming_letter(const char *ending) generates the rhyme scheme letter (starting with 'a') that corresponds to a given line ending (specified as the parameter). The function remembers its state between calls using an internal lookup table, such that subsequents calls with different endings will generate new letters. The state can be reset (e.g. to start issuing rhyme scheme letters for a new poem) by calling rhyming_letter(RESET). */ char rhyming_letter(const char *ending) { // the next rhyming letter to be issued (persists between calls) static char next = 'a'; // the table which maps endings to letters (persists between calls) static map<string, char> lookup; // providing a way to reset the table between poems if (ending == RESET) { lookup.clear(); next = 'a'; return '\0'; } string end(ending); // if the ending doesn't exist, add it, and issue a new letter if (lookup.count(end) == 0) { lookup[end]=next; assert(next <= 'z'); return next++; } // otherwise return the letter corresponding to the existing ending return lookup[end]; } /* START WRITING YOUR FUNCTION BODIES HERE */
// Copyright (c) 2009 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 "base/process_util.h" #include <ctype.h> #include <dirent.h> #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include "base/file_util.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/sys_info.h" #include "base/thread_restrictions.h" namespace { enum ParsingState { KEY_NAME, KEY_VALUE }; // Reads /proc/<pid>/stat and populates |proc_stats| with the values split by // spaces. Returns true if successful. bool GetProcStats(pid_t pid, std::vector<std::string>* proc_stats) { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath stat_file("/proc"); stat_file = stat_file.Append(base::IntToString(pid)); stat_file = stat_file.Append("stat"); std::string mem_stats; if (!file_util::ReadFileToString(stat_file, &mem_stats)) return false; base::SplitString(mem_stats, ' ', proc_stats); return true; } // Reads /proc/<pid>/cmdline and populates |proc_cmd_line_args| with the command // line arguments. Returns true if successful. // Note: /proc/<pid>/cmdline contains command line arguments separated by single // null characters. We tokenize it into a vector of strings using '\0' as a // delimiter. bool GetProcCmdline(pid_t pid, std::vector<std::string>* proc_cmd_line_args) { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath cmd_line_file("/proc"); cmd_line_file = cmd_line_file.Append(base::IntToString(pid)); cmd_line_file = cmd_line_file.Append("cmdline"); std::string cmd_line; if (!file_util::ReadFileToString(cmd_line_file, &cmd_line)) return false; std::string delimiters; delimiters.push_back('\0'); Tokenize(cmd_line, delimiters, proc_cmd_line_args); return true; } } // namespace namespace base { ProcessId GetParentProcessId(ProcessHandle process) { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath stat_file("/proc"); stat_file = stat_file.Append(base::IntToString(process)); stat_file = stat_file.Append("status"); std::string status; if (!file_util::ReadFileToString(stat_file, &status)) return -1; StringTokenizer tokenizer(status, ":\n"); ParsingState state = KEY_NAME; std::string last_key_name; while (tokenizer.GetNext()) { switch (state) { case KEY_NAME: last_key_name = tokenizer.token(); state = KEY_VALUE; break; case KEY_VALUE: DCHECK(!last_key_name.empty()); if (last_key_name == "PPid") { int ppid; base::StringToInt(tokenizer.token(), &ppid); return ppid; } state = KEY_NAME; break; } } NOTREACHED(); return -1; } FilePath GetProcessExecutablePath(ProcessHandle process) { FilePath stat_file("/proc"); stat_file = stat_file.Append(base::IntToString(process)); stat_file = stat_file.Append("exe"); FilePath exe_name; if (!file_util::ReadSymbolicLink(stat_file, &exe_name)) { // No such process. Happens frequently in e.g. TerminateAllChromeProcesses return FilePath(); } return exe_name; } ProcessIterator::ProcessIterator(const ProcessFilter* filter) : filter_(filter) { procfs_dir_ = opendir("/proc"); } ProcessIterator::~ProcessIterator() { if (procfs_dir_) { closedir(procfs_dir_); procfs_dir_ = NULL; } } bool ProcessIterator::CheckForNextProcess() { // TODO(port): skip processes owned by different UID dirent* slot = 0; const char* openparen; const char* closeparen; std::vector<std::string> cmd_line_args; // Arbitrarily guess that there will never be more than 200 non-process // files in /proc. Hardy has 53. int skipped = 0; const int kSkipLimit = 200; while (skipped < kSkipLimit) { slot = readdir(procfs_dir_); // all done looking through /proc? if (!slot) return false; // If not a process, keep looking for one. bool notprocess = false; int i; for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) { if (!isdigit(slot->d_name[i])) { notprocess = true; break; } } if (i == NAME_MAX || notprocess) { skipped++; continue; } // Read the process's command line. std::string pid_string(slot->d_name); int pid; if (StringToInt(pid_string, &pid) && !GetProcCmdline(pid, &cmd_line_args)) return false; // Read the process's status. char buf[NAME_MAX + 12]; sprintf(buf, "/proc/%s/stat", slot->d_name); FILE *fp = fopen(buf, "r"); if (!fp) return false; const char* result = fgets(buf, sizeof(buf), fp); fclose(fp); if (!result) return false; // Parse the status. It is formatted like this: // %d (%s) %c %d %d ... // pid (name) runstate ppid gid // To avoid being fooled by names containing a closing paren, scan // backwards. openparen = strchr(buf, '('); closeparen = strrchr(buf, ')'); if (!openparen || !closeparen) return false; char runstate = closeparen[2]; // Is the process in 'Zombie' state, i.e. dead but waiting to be reaped? // Allowed values: D R S T Z if (runstate != 'Z') break; // Nope, it's a zombie; somebody isn't cleaning up after their children. // (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.) // There could be a lot of zombies, can't really decrement i here. } if (skipped >= kSkipLimit) { NOTREACHED(); return false; } // This seems fragile. entry_.pid_ = atoi(slot->d_name); entry_.ppid_ = atoi(closeparen + 3); entry_.gid_ = atoi(strchr(closeparen + 4, ' ')); entry_.cmd_line_args_.assign(cmd_line_args.begin(), cmd_line_args.end()); // TODO(port): read pid's commandline's $0, like killall does. Using the // short name between openparen and closeparen won't work for long names! int len = closeparen - openparen - 1; entry_.exe_file_.assign(openparen + 1, len); return true; } bool NamedProcessIterator::IncludeEntry() { // TODO(port): make this also work for non-ASCII filenames if (WideToASCII(executable_name_) != entry().exe_file()) return false; return ProcessIterator::IncludeEntry(); } ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process), last_time_(0), last_system_time_(0), last_cpu_(0) { processor_count_ = base::SysInfo::NumberOfProcessors(); } // static ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) { return new ProcessMetrics(process); } // On linux, we return vsize. size_t ProcessMetrics::GetPagefileUsage() const { std::vector<std::string> proc_stats; if (!GetProcStats(process_, &proc_stats)) LOG(WARNING) << "Failed to get process stats."; const size_t kVmSize = 22; if (proc_stats.size() > kVmSize) { int vm_size; base::StringToInt(proc_stats[kVmSize], &vm_size); return static_cast<size_t>(vm_size); } return 0; } // On linux, we return the high water mark of vsize. size_t ProcessMetrics::GetPeakPagefileUsage() const { std::vector<std::string> proc_stats; if (!GetProcStats(process_, &proc_stats)) LOG(WARNING) << "Failed to get process stats."; const size_t kVmPeak = 21; if (proc_stats.size() > kVmPeak) { int vm_peak; if (base::StringToInt(proc_stats[kVmPeak], &vm_peak)) return vm_peak; } return 0; } // On linux, we return RSS. size_t ProcessMetrics::GetWorkingSetSize() const { std::vector<std::string> proc_stats; if (!GetProcStats(process_, &proc_stats)) LOG(WARNING) << "Failed to get process stats."; const size_t kVmRss = 23; if (proc_stats.size() > kVmRss) { int num_pages; if (base::StringToInt(proc_stats[kVmRss], &num_pages)) return static_cast<size_t>(num_pages) * getpagesize(); } return 0; } // On linux, we return the high water mark of RSS. size_t ProcessMetrics::GetPeakWorkingSetSize() const { std::vector<std::string> proc_stats; if (!GetProcStats(process_, &proc_stats)) LOG(WARNING) << "Failed to get process stats."; const size_t kVmHwm = 23; if (proc_stats.size() > kVmHwm) { int num_pages; base::StringToInt(proc_stats[kVmHwm], &num_pages); return static_cast<size_t>(num_pages) * getpagesize(); } return 0; } bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes, size_t* shared_bytes) { WorkingSetKBytes ws_usage; if (!GetWorkingSetKBytes(&ws_usage)) return false; if (private_bytes) *private_bytes = ws_usage.priv << 10; if (shared_bytes) *shared_bytes = ws_usage.shared * 1024; return true; } // Private and Shared working set sizes are obtained from /proc/<pid>/smaps. // When that's not available, use the values from /proc<pid>/statm as a // close approximation. // See http://www.pixelbeat.org/scripts/ps_mem.py bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; FilePath proc_dir = FilePath("/proc").Append(base::IntToString(process_)); std::string smaps; int private_kb = 0; int pss_kb = 0; bool have_pss = false; bool ret; { FilePath smaps_file = proc_dir.Append("smaps"); // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; ret = file_util::ReadFileToString(smaps_file, &smaps); } if (ret && smaps.length() > 0) { const std::string private_prefix = "Private_"; const std::string pss_prefix = "Pss"; StringTokenizer tokenizer(smaps, ":\n"); StringPiece last_key_name; ParsingState state = KEY_NAME; while (tokenizer.GetNext()) { switch (state) { case KEY_NAME: last_key_name = tokenizer.token_piece(); state = KEY_VALUE; break; case KEY_VALUE: if (last_key_name.empty()) { NOTREACHED(); return false; } if (last_key_name.starts_with(private_prefix)) { int cur; base::StringToInt(tokenizer.token(), &cur); private_kb += cur; } else if (last_key_name.starts_with(pss_prefix)) { have_pss = true; int cur; base::StringToInt(tokenizer.token(), &cur); pss_kb += cur; } state = KEY_NAME; break; } } } else { // Try statm if smaps is empty because of the SUID sandbox. // First we need to get the page size though. int page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; if (page_size_kb <= 0) return false; std::string statm; { FilePath statm_file = proc_dir.Append("statm"); // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; ret = file_util::ReadFileToString(statm_file, &statm); } if (!ret || statm.length() == 0) return false; std::vector<std::string> statm_vec; base::SplitString(statm, ' ', &statm_vec); if (statm_vec.size() != 7) return false; // Not the format we expect. int statm1, statm2; base::StringToInt(statm_vec[1], &statm1); base::StringToInt(statm_vec[2], &statm2); private_kb = (statm1 - statm2) * page_size_kb; } ws_usage->priv = private_kb; // Sharable is not calculated, as it does not provide interesting data. ws_usage->shareable = 0; ws_usage->shared = 0; if (have_pss) ws_usage->shared = pss_kb; return true; } // To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING // in your kernel configuration. bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; std::string proc_io_contents; FilePath io_file("/proc"); io_file = io_file.Append(base::IntToString(process_)); io_file = io_file.Append("io"); if (!file_util::ReadFileToString(io_file, &proc_io_contents)) return false; (*io_counters).OtherOperationCount = 0; (*io_counters).OtherTransferCount = 0; StringTokenizer tokenizer(proc_io_contents, ": \n"); ParsingState state = KEY_NAME; std::string last_key_name; while (tokenizer.GetNext()) { switch (state) { case KEY_NAME: last_key_name = tokenizer.token(); state = KEY_VALUE; break; case KEY_VALUE: DCHECK(!last_key_name.empty()); if (last_key_name == "syscr") { base::StringToInt64(tokenizer.token(), reinterpret_cast<int64*>(&(*io_counters).ReadOperationCount)); } else if (last_key_name == "syscw") { base::StringToInt64(tokenizer.token(), reinterpret_cast<int64*>(&(*io_counters).WriteOperationCount)); } else if (last_key_name == "rchar") { base::StringToInt64(tokenizer.token(), reinterpret_cast<int64*>(&(*io_counters).ReadTransferCount)); } else if (last_key_name == "wchar") { base::StringToInt64(tokenizer.token(), reinterpret_cast<int64*>(&(*io_counters).WriteTransferCount)); } state = KEY_NAME; break; } } return true; } // Exposed for testing. int ParseProcStatCPU(const std::string& input) { // /proc/<pid>/stat contains the process name in parens. In case the // process name itself contains parens, skip past them. std::string::size_type rparen = input.rfind(')'); if (rparen == std::string::npos) return -1; // From here, we expect a bunch of space-separated fields, where the // 0-indexed 11th and 12th are utime and stime. On two different machines // I found 42 and 39 fields, so let's just expect the ones we need. std::vector<std::string> fields; base::SplitString(input.substr(rparen + 2), ' ', &fields); if (fields.size() < 13) return -1; // Output not in the format we expect. int fields11, fields12; base::StringToInt(fields[11], &fields11); base::StringToInt(fields[12], &fields12); return fields11 + fields12; } // Get the total CPU of a single process. Return value is number of jiffies // on success or -1 on error. static int GetProcessCPU(pid_t pid) { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; // Use /proc/<pid>/task to find all threads and parse their /stat file. FilePath path = FilePath(StringPrintf("/proc/%d/task/", pid)); DIR* dir = opendir(path.value().c_str()); if (!dir) { PLOG(ERROR) << "opendir(" << path.value() << ")"; return -1; } int total_cpu = 0; while (struct dirent* ent = readdir(dir)) { if (ent->d_name[0] == '.') continue; FilePath stat_path = path.AppendASCII(ent->d_name).AppendASCII("stat"); std::string stat; if (file_util::ReadFileToString(stat_path, &stat)) { int cpu = ParseProcStatCPU(stat); if (cpu > 0) total_cpu += cpu; } } closedir(dir); return total_cpu; } double ProcessMetrics::GetCPUUsage() { // This queries the /proc-specific scaling factor which is // conceptually the system hertz. To dump this value on another // system, try // od -t dL /proc/self/auxv // and look for the number after 17 in the output; mine is // 0000040 17 100 3 134512692 // which means the answer is 100. // It may be the case that this value is always 100. static const int kHertz = sysconf(_SC_CLK_TCK); struct timeval now; int retval = gettimeofday(&now, NULL); if (retval) return 0; int64 time = TimeValToMicroseconds(now); if (last_time_ == 0) { // First call, just set the last values. last_time_ = time; last_cpu_ = GetProcessCPU(process_); return 0; } int64 time_delta = time - last_time_; DCHECK_NE(time_delta, 0); if (time_delta == 0) return 0; int cpu = GetProcessCPU(process_); // We have the number of jiffies in the time period. Convert to percentage. // Note this means we will go *over* 100 in the case where multiple threads // are together adding to more than one CPU's worth. int percentage = 100 * (cpu - last_cpu_) / (kHertz * TimeDelta::FromMicroseconds(time_delta).InSecondsF()); last_time_ = time; last_cpu_ = cpu; return percentage; } namespace { // The format of /proc/meminfo is: // // MemTotal: 8235324 kB // MemFree: 1628304 kB // Buffers: 429596 kB // Cached: 4728232 kB // ... const size_t kMemTotalIndex = 1; const size_t kMemFreeIndex = 4; const size_t kMemBuffersIndex = 7; const size_t kMemCacheIndex = 10; } // namespace size_t GetSystemCommitCharge() { // Synchronously reading files in /proc is safe. base::ThreadRestrictions::ScopedAllowIO allow_io; // Used memory is: total - free - buffers - caches FilePath meminfo_file("/proc/meminfo"); std::string meminfo_data; if (!file_util::ReadFileToString(meminfo_file, &meminfo_data)) { LOG(WARNING) << "Failed to open /proc/meminfo."; return 0; } std::vector<std::string> meminfo_fields; SplitStringAlongWhitespace(meminfo_data, &meminfo_fields); if (meminfo_fields.size() < kMemCacheIndex) { LOG(WARNING) << "Failed to parse /proc/meminfo. Only found " << meminfo_fields.size() << " fields."; return 0; } DCHECK_EQ(meminfo_fields[kMemTotalIndex-1], "MemTotal:"); DCHECK_EQ(meminfo_fields[kMemFreeIndex-1], "MemFree:"); DCHECK_EQ(meminfo_fields[kMemBuffersIndex-1], "Buffers:"); DCHECK_EQ(meminfo_fields[kMemCacheIndex-1], "Cached:"); int mem_total, mem_free, mem_buffers, mem_cache; base::StringToInt(meminfo_fields[kMemTotalIndex], &mem_total); base::StringToInt(meminfo_fields[kMemFreeIndex], &mem_free); base::StringToInt(meminfo_fields[kMemBuffersIndex], &mem_buffers); base::StringToInt(meminfo_fields[kMemCacheIndex], &mem_cache); return mem_total - mem_free - mem_buffers - mem_cache; } namespace { void OnNoMemorySize(size_t size) { if (size != 0) LOG(FATAL) << "Out of memory, size = " << size; LOG(FATAL) << "Out of memory."; } void OnNoMemory() { OnNoMemorySize(0); } } // namespace extern "C" { #if !defined(USE_TCMALLOC) extern "C" { void* __libc_malloc(size_t size); void* __libc_realloc(void* ptr, size_t size); void* __libc_calloc(size_t nmemb, size_t size); void* __libc_valloc(size_t size); void* __libc_pvalloc(size_t size); void* __libc_memalign(size_t alignment, size_t size); } // extern "C" // Overriding the system memory allocation functions: // // For security reasons, we want malloc failures to be fatal. Too much code // doesn't check for a NULL return value from malloc and unconditionally uses // the resulting pointer. If the first offset that they try to access is // attacker controlled, then the attacker can direct the code to access any // part of memory. // // Thus, we define all the standard malloc functions here and mark them as // visibility 'default'. This means that they replace the malloc functions for // all Chromium code and also for all code in shared libraries. There are tests // for this in process_util_unittest.cc. // // If we are using tcmalloc, then the problem is moot since tcmalloc handles // this for us. Thus this code is in a !defined(USE_TCMALLOC) block. // // We call the real libc functions in this code by using __libc_malloc etc. // Previously we tried using dlsym(RTLD_NEXT, ...) but that failed depending on // the link order. Since ld.so needs calloc during symbol resolution, it // defines its own versions of several of these functions in dl-minimal.c. // Depending on the runtime library order, dlsym ended up giving us those // functions and bad things happened. See crbug.com/31809 // // This means that any code which calls __libc_* gets the raw libc versions of // these functions. #define DIE_ON_OOM_1(function_name) \ void* function_name(size_t) __attribute__ ((visibility("default"))); \ \ void* function_name(size_t size) { \ void* ret = __libc_##function_name(size); \ if (ret == NULL && size != 0) \ OnNoMemorySize(size); \ return ret; \ } #define DIE_ON_OOM_2(function_name, arg1_type) \ void* function_name(arg1_type, size_t) \ __attribute__ ((visibility("default"))); \ \ void* function_name(arg1_type arg1, size_t size) { \ void* ret = __libc_##function_name(arg1, size); \ if (ret == NULL && size != 0) \ OnNoMemorySize(size); \ return ret; \ } DIE_ON_OOM_1(malloc) DIE_ON_OOM_1(valloc) DIE_ON_OOM_1(pvalloc) DIE_ON_OOM_2(calloc, size_t) DIE_ON_OOM_2(realloc, void*) DIE_ON_OOM_2(memalign, size_t) // posix_memalign has a unique signature and doesn't have a __libc_ variant. int posix_memalign(void** ptr, size_t alignment, size_t size) __attribute__ ((visibility("default"))); int posix_memalign(void** ptr, size_t alignment, size_t size) { // This will use the safe version of memalign, above. *ptr = memalign(alignment, size); return 0; } #endif // !defined(USE_TCMALLOC) } // extern C void EnableTerminationOnOutOfMemory() { // Set the new-out of memory handler. std::set_new_handler(&OnNoMemory); // If we're using glibc's allocator, the above functions will override // malloc and friends and make them die on out of memory. } bool AdjustOOMScore(ProcessId process, int score) { if (score < 0 || score > 15) return false; FilePath oom_adj("/proc"); oom_adj = oom_adj.Append(base::Int64ToString(process)); oom_adj = oom_adj.AppendASCII("oom_adj"); if (!file_util::PathExists(oom_adj)) return false; std::string score_str = base::IntToString(score); return (static_cast<int>(score_str.length()) == file_util::WriteFile(oom_adj, score_str.c_str(), score_str.length())); } } // namespace base
/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * (C) 2001 Dirk Mueller (mueller@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2010 Apple Inc. All rights reserved. * (C) 2006 Alexey Proskuryakov (ap@nypop.com) * Copyright (C) 2007 Samuel Weinig (sam@webkit.org) * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "core/html/HTMLButtonElement.h" #include "bindings/core/v8/V8DOMActivityLogger.h" #include "core/HTMLNames.h" #include "core/dom/Attribute.h" #include "core/events/KeyboardEvent.h" #include "core/html/FormDataList.h" #include "core/html/HTMLFormElement.h" #include "core/layout/LayoutButton.h" #include "wtf/StdLibExtras.h" namespace blink { using namespace HTMLNames; inline HTMLButtonElement::HTMLButtonElement(Document& document, HTMLFormElement* form) : HTMLFormControlElement(buttonTag, document, form) , m_type(SUBMIT) , m_isActivatedSubmit(false) { } PassRefPtrWillBeRawPtr<HTMLButtonElement> HTMLButtonElement::create(Document& document, HTMLFormElement* form) { return adoptRefWillBeNoop(new HTMLButtonElement(document, form)); } void HTMLButtonElement::setType(const AtomicString& type) { setAttribute(typeAttr, type); } LayoutObject* HTMLButtonElement::createLayoutObject(const ComputedStyle&) { return new LayoutButton(this); } const AtomicString& HTMLButtonElement::formControlType() const { switch (m_type) { case SUBMIT: { DEFINE_STATIC_LOCAL(const AtomicString, submit, ("submit", AtomicString::ConstructFromLiteral)); return submit; } case BUTTON: { DEFINE_STATIC_LOCAL(const AtomicString, button, ("button", AtomicString::ConstructFromLiteral)); return button; } case RESET: { DEFINE_STATIC_LOCAL(const AtomicString, reset, ("reset", AtomicString::ConstructFromLiteral)); return reset; } } ASSERT_NOT_REACHED(); return emptyAtom; } bool HTMLButtonElement::isPresentationAttribute(const QualifiedName& name) const { if (name == alignAttr) { // Don't map 'align' attribute. This matches what Firefox and IE do, but not Opera. // See http://bugs.webkit.org/show_bug.cgi?id=12071 return false; } return HTMLFormControlElement::isPresentationAttribute(name); } void HTMLButtonElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == typeAttr) { if (equalIgnoringCase(value, "reset")) m_type = RESET; else if (equalIgnoringCase(value, "button")) m_type = BUTTON; else m_type = SUBMIT; setNeedsWillValidateCheck(); } else HTMLFormControlElement::parseAttribute(name, value); } void HTMLButtonElement::defaultEventHandler(Event* event) { if (event->type() == EventTypeNames::DOMActivate && !isDisabledFormControl()) { if (form() && m_type == SUBMIT) { m_isActivatedSubmit = true; form()->prepareForSubmission(event); event->setDefaultHandled(); m_isActivatedSubmit = false; // Do this in case submission was canceled. } if (form() && m_type == RESET) { form()->reset(); event->setDefaultHandled(); } } if (event->isKeyboardEvent()) { if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { setActive(true); // No setDefaultHandled() - IE dispatches a keypress in this case. return; } if (event->type() == EventTypeNames::keypress) { switch (toKeyboardEvent(event)->charCode()) { case '\r': dispatchSimulatedClick(event); event->setDefaultHandled(); return; case ' ': // Prevent scrolling down the page. event->setDefaultHandled(); return; } } if (event->type() == EventTypeNames::keyup && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { if (active()) dispatchSimulatedClick(event); event->setDefaultHandled(); return; } } HTMLFormControlElement::defaultEventHandler(event); } bool HTMLButtonElement::willRespondToMouseClickEvents() { if (!isDisabledFormControl() && form() && (m_type == SUBMIT || m_type == RESET)) return true; return HTMLFormControlElement::willRespondToMouseClickEvents(); } bool HTMLButtonElement::canBeSuccessfulSubmitButton() const { return m_type == SUBMIT; } bool HTMLButtonElement::isActivatedSubmit() const { return m_isActivatedSubmit; } void HTMLButtonElement::setActivatedSubmit(bool flag) { m_isActivatedSubmit = flag; } bool HTMLButtonElement::appendFormData(FormDataList& formData, bool) { if (m_type != SUBMIT || name().isEmpty() || !m_isActivatedSubmit) return false; formData.appendData(name(), value()); return true; } void HTMLButtonElement::accessKeyAction(bool sendMouseEvents) { focus(); dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents); } bool HTMLButtonElement::isURLAttribute(const Attribute& attribute) const { return attribute.name() == formactionAttr || HTMLFormControlElement::isURLAttribute(attribute); } const AtomicString& HTMLButtonElement::value() const { return getAttribute(valueAttr); } bool HTMLButtonElement::recalcWillValidate() const { return m_type == SUBMIT && HTMLFormControlElement::recalcWillValidate(); } bool HTMLButtonElement::isInteractiveContent() const { return true; } bool HTMLButtonElement::supportsAutofocus() const { return true; } Node::InsertionNotificationRequest HTMLButtonElement::insertedInto(ContainerNode* insertionPoint) { if (insertionPoint->inDocument()) { V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld(); if (activityLogger) { Vector<String> argv; argv.append("button"); argv.append(fastGetAttribute(typeAttr)); argv.append(fastGetAttribute(formmethodAttr)); argv.append(fastGetAttribute(formactionAttr)); activityLogger->logEvent("blinkAddElement", argv.size(), argv.data()); } } return HTMLFormControlElement::insertedInto(insertionPoint); } void HTMLButtonElement::attributeWillChange(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue) { if (name == formactionAttr && inDocument()) { V8DOMActivityLogger* activityLogger = V8DOMActivityLogger::currentActivityLoggerIfIsolatedWorld(); if (activityLogger) { Vector<String> argv; argv.append("button"); argv.append(formactionAttr.toString()); argv.append(oldValue); argv.append(newValue); activityLogger->logEvent("blinkSetAttribute", argv.size(), argv.data()); } } HTMLFormControlElement::attributeWillChange(name, oldValue, newValue); } } // namespace
//////////////////////////////////////////////////////////////////////////////// // // // Name: SigParam.cxx // // // // Creator: Andrew Hard // // Email: ahard@cern.ch <-- Please use for reporting issues! // // Date: 01/11/2016 // // // // This class implements the resonance modeling for the ATLAS Hgamma group. // // // // General notes: // // // // - Function names can be: // // * "DoubleCB" for double-sided Crystal Ball // // * "CBGA" for Crystal Ball + Gaussian // // * "GAx3" for 3 Gaussians // // * "BifurGA" for bifurcated Gaussian // // * "Landau" // // * "LAx2" // // * "CBLA" // // * "CBPlusVoigt" // // * "Voigt" // // * "DoubleCBLA" // // * "GALA" // // * "BifurGALA" // // * "LandauMod" // // // // - Category indices should start at zero. // // // //////////////////////////////////////////////////////////////////////////////// #include "SigParam.h" /** ----------------------------------------------------------------------------- Constructor for the SigParam class. @param signalType - The type of signal (ggH, VBF, WH, ZH, ttH, bbH, etc). @param directory - The directory for input and output files. */ SigParam::SigParam(TString signalType, TString directory) { std::cout << "\nSigParam::Initializing..." << std::endl; // Assign output directory: setSignalType(signalType); setDirectory(directory); // Create RooWorkspace and RooCategory to store all signal models: m_ws = new RooWorkspace("signalWS"); m_cat.clear(); // Import mass and weight variables, then make pointers: m_ws->factory("wt[1.0]"); m_ws->factory("mResonance[10,10000]"); m_ws->factory("expr::mRegularized('(@0-100.0)/100.0',{mResonance})"); m_verbose = false; m_nCategories = 0; // Define the data sets at each mass in each category for resonance fit: m_massCatePairs.clear(); m_cateNames.clear(); // Lists of mass resolution and mass scale systematics: m_listMRS = ""; m_listMSS = ""; // Set the default initial values and ranges for fit parameters: m_paramState.clear(); m_varParameterization.clear(); // Some basic fit options: useCommonCBGAMean(false); setMassWindowSize(0.1); // Used by default setMassWindowFixed(false, 105,140); // Not used unless called by user // Fit result information: m_currChi2 = 0.0; m_currNLL = 0.0; m_currExtendVal = 0.0; m_generatedDataNorm = 0.0; // Set the plot formatting: doBinnedFit(false, 1); setLogYAxis(false); setPlotATLASLabel("Simulation Internal"); setPlotFormat(".eps"); setPlotLuminosity("1.0 fb^{-1}"); setPlotXAxisTitle("Mass [GeV]"); setRatioPlot(true, 0.0, 2.0); // Funny stuff to save the function name in the workspace for loading later: m_currFunction = "DoubleCB"; RooRealVar nameVar("functionName", m_currFunction, 0); m_ws->import(nameVar); // Default values for the parameterization functions and parameters are set // below. These will be overwritten by any calls to setVarParameterizat() or // setParamState() by the user after initializing the SigParam class. //--------------------------------------------------------------------------// // Default parameterization functions for variables: // Common parameters: setVarParameterization("muCBNom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("sigmaCBNom", "@0+@1*obs"); // Crystal Ball + Gaussian: setVarParameterization("alphaCB", "@0+@1*obs"); setVarParameterization("muGANom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("sigmaGANom", "@0+@1*obs"); // Double-sided Crystal Ball: setVarParameterization("alphaCBLo", "@0+@1/(obs+@2)"); setVarParameterization("alphaCBHi", "@0+@1/(obs+@2)"); // Triple Gaussian: setVarParameterization("muGA1Nom", "@0+@1*obs+mRes"); setVarParameterization("muGA2Nom", "@0+@1*obs+mRes"); setVarParameterization("muGA3Nom", "@0+@1*obs+mRes"); setVarParameterization("sigmaGA1Nom", "@0+@1*obs"); setVarParameterization("sigmaGA2Nom", "@0+@1*obs"); setVarParameterization("sigmaGA3Nom", "@0+@1*obs"); // Bifurcated Gaussian: setVarParameterization("sigmaGALowNom", "@0+@1*obs"); setVarParameterization("sigmaGAHiNom", "@0+@1*obs"); // Landau: setVarParameterization("muLANom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("sigmaLANom", "@0+@1*obs"); // Double Landau: setVarParameterization("muLA1Nom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("muLA2Nom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("sigmaLA1Nom", "@0+@1*obs"); setVarParameterization("sigmaLA2Nom", "@0+@1*obs"); // Voigt: setVarParameterization("muVoigtNom", "@0+@1*obs+@2*obs*obs+mRes"); setVarParameterization("widthVoigtNom", "@0+@1*obs"); setVarParameterization("sigmaVoigtNom", "@0+@1*obs"); // Modified Landau: setVarParameterization("alphaLA", "@0+@1*obs"); //--------------------------------------------------------------------------// // Default parameter values below are for parameterized fit over mResonance. // Common parameters: setParamState("a_muCBNom", "[-0.0,-2.0,2.0]"); setParamState("b_muCBNom", "[-0.1,-0.5,0.5]"); setParamState("c_muCBNom", "[-0.02,-0.5,0.5]"); setParamState("a_sigmaCBNom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaCBNom", "[3.90,0.01,10.0]"); // Crystal Ball + Gaussian: setParamState("a_alphaCB", "[2.2,0.0,4.0]"); setParamState("b_alphaCB", "[0.0,-0.1,0.1]"); setParamState("nCB", "[10.0]"); setParamState("a_muGANom", "[-0.0,-2.0,2.0]"); setParamState("b_muGANom", "[-0.1,-0.5,0.5]"); setParamState("c_muGANom", "[-0.02,-0.5,0.5]"); setParamState("a_sigmaGANom", "[5.0,-1.0,20.0]"); setParamState("b_sigmaGANom", "[1.8,0.1,4.0]"); setParamState("fracCB", "[0.9,0.01,0.99]"); // Double-sided Crystal Ball: setParamState("a_alphaCBLo", "[2.42,1.0,4.0]"); setParamState("b_alphaCBLo", "[-483,-1000,0]"); setParamState("c_alphaCBLo", "[380,100,500]"); setParamState("nCBLo", "[9.0,0.1,20.0]"); setParamState("a_alphaCBHi", "[2.2,0.0,4.0]"); setParamState("b_alphaCBHi", "[0.0,-0.5,0.5]"); setParamState("c_alphaCBHi", "[0.0,-2.0,1.0]"); setParamState("nCBHi", "[5.0,0.1,10.0]"); // Triple Gaussian: setParamState("a_muGA1Nom", "[-0.01,-2.0,2.0]"); setParamState("b_muGA1Nom", "[-0.1,-0.5,0.5]"); setParamState("a_muGA2Nom", "[0.01,-2.0,2.0]"); setParamState("b_muGA2Nom", "[-0.1,-0.5,0.5]"); setParamState("a_muGA3Nom", "[0.0,-2.0,2.0]"); setParamState("b_muGA3Nom", "[-0.1,-0.5,0.5]"); setParamState("a_sigmaGA1Nom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaGA1Nom", "[3.90,0.01,10.0]"); setParamState("a_sigmaGA2Nom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaGA2Nom", "[3.90,0.01,10.0]"); setParamState("a_sigmaGA3Nom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaGA3Nom", "[3.90,0.01,10.0]"); setParamState("fracGA1", "[0.32,0.01,0.99]"); setParamState("fracGA2", "[0.33,0.01,0.99]"); //Bifurcated Gaussian: setParamState("a_sigmaGALowNom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaGALowNom", "[3.90,0.01,10.0]"); setParamState("a_sigmaGAHiNom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaGAHiNom", "[3.90,0.01,10.0]"); // Landau: setParamState("a_muLANom", "[-0.0,-2.0,2.0]"); setParamState("b_muLANom", "[-0.1,-0.5,0.5]"); setParamState("c_muLANom", "[-0.02,-0.5,0.5]"); setParamState("a_sigmaLANom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaLANom", "[3.90,0.01,10.0]"); // Double Landau: setParamState("a_muLA1Nom", "[-0.01,-2.0,2.0]"); setParamState("b_muLA1Nom", "[-0.11,-0.5,0.5]"); setParamState("c_muLA1Nom", "[-0.021,-0.5,0.5]"); setParamState("a_muLA2Nom", "[-0.0,-2.0,2.0]"); setParamState("b_muLA2Nom", "[-0.1,-0.5,0.5]"); setParamState("c_muLA2Nom", "[-0.02,-0.5,0.5]"); setParamState("a_sigmaLA1Nom", "[0.01,-10.0,10.0]"); setParamState("b_sigmaLA1Nom", "[3.91,0.01,10.0]"); setParamState("a_sigmaLA2Nom", "[0.0,-10.0,10.0]"); setParamState("b_sigmaLA2Nom", "[3.90,0.01,10.0]"); setParamState("fracLA1", "[0.32,0.01,0.99]"); // Voigt: setParamState("a_muVoigtNom", "[-0.0,-2.0,2.0]"); setParamState("b_muVoigtNom", "[-0.1,-0.5,0.5]"); setParamState("c_muVoigtNom", "[-0.02,-0.5,0.5]"); setParamState("a_widthVoigtNom", "[5.0,-1.0,20.0]"); setParamState("b_widthVoigtNom", "[1.8,0.1,4.0]"); setParamState("a_sigmaVoigtNom", "[5.0,-1.0,20.0]"); setParamState("b_sigmaVoigtNom", "[1.8,0.1,4.0]"); // Modified Landau: setParamState("a_alphaLA", "[0.0,-1.0,1.0]"); setParamState("b_alphaLA", "[0.0,-1.0,1.0]"); // Other: setParamState("fracGA", "[0.5,0.01,0.99]"); //--------------------------------------------------------------------------// // Parameter values below are for fits to individual mass points: // Some parameters such as nCB and frac are listed above to avoid duplication. // Common parameters: setParamState("muCBNom", "[125,0.1,10000]"); setParamState("sigmaCBNom", "[1.7,0.01,200.0]"); setParamState("alphaCB", "[1.5,0.1,3.0]"); setParamState("muGANom", "[125,0.1,10000]"); setParamState("sigmaGANom", "[10.0,0.01,80.0]"); // Double-sided Crystal Ball PDF: setParamState("alphaCBLo", "[1.5,0.1,2.5]"); setParamState("alphaCBHi", "[2.2,0.1,3.0]"); // Triple Gaussian PDF: setParamState("muGA1Nom", "[125,0.0,10000]"); setParamState("muGA2Nom", "[125,0.0,10000]"); setParamState("muGA3Nom", "[125,0.0,10000]"); setParamState("sigmaGA1Nom", "[2.0,0.01,200.0]"); setParamState("sigmaGA2Nom", "[4.0,0.01,200.0]"); setParamState("sigmaGA3Nom", "[6.0,0.01,200.0]"); // Bifurcated Gaussian PDF: setParamState("sigmaGALowNom", "[3.0,0.01,200.0]"); setParamState("sigmaGAHiNom", "[1.0,0.01,200.0]"); // Landau PDF: setParamState("muLANom", "[125,0.0,10000]"); setParamState("sigmaLANom", "[2.0,0.01,200.0]"); // Double Landau PDF: setParamState("muLA1Nom", "[125,0.0,10000]"); setParamState("muLA2Nom", "[126,0.0,10000]"); setParamState("sigmaLA1Nom", "[2.1,0.01,200.0]"); setParamState("sigmaLA2Nom", "[2.0,0.01,200.0]"); // Voigt PDF: setParamState("muVoigtNom", "[125,0.0,10000]"); setParamState("widthVoigtNom", "[10.0,0.01,80.0]"); setParamState("sigmaVoigtNom", "[10.0,0.01,80.0]"); // Modified Landau: setParamState("alphaLA", "[0.0,-1.0,1.0]"); std::cout << "SigParam: Successfully initialized!" << std::endl; } /** ----------------------------------------------------------------------------- Adds the data from a RooDataSet object to the dataset for parameterization. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The event category index (starting at 0). @param dataSet - The RooDataSet object to import. @param observableName - The name of the observable. */ void SigParam::addDataSet(double resonanceMass, int cateIndex, RooDataSet* dataSet, TString observableName) { // Loop over events stored in the input dataset: for (int i_d = 0; i_d < dataSet->numEntries(); i_d++) { // Get the RooRealVars and values in the current event: const RooArgSet *currArgs = (RooArgSet*)dataSet->get(i_d); double massValue = -999.0; double weightValue = -999.0; // Iterate through the RooArgSet, find mass and weight variables: TIterator *iterArgs = currArgs->createIterator(); RooRealVar* currArg; while ((currArg = (RooRealVar*)iterArgs->Next())) { if (TString(currArg->GetName()).EqualTo(observableName)) { massValue = currArg->getVal(); } } weightValue = dataSet->weight(); // Then add the mass and weight values to the dataset: if (massValue > -990 && weightValue > -990) { addMassPoint(resonanceMass, cateIndex, massValue, weightValue); } // Exit if the variable names were incorrect: else { std::cout << "SigParam: No match for observable or weight." << std::endl; exit(0); } } } /** ----------------------------------------------------------------------------- Adds the data from a Root TTree object or an MxAOD to the dataset for signal parameterization. Note: the input @param resonanceMass - The truth mass of the resonance. @param cateIndex - The event category index (starting at 0). @param dataTree - The TTree or MxAOD object to import. @param massBranchName - The name of the branch storing mass values. @param weightBranchName - The name of the branch storing event weights. */ void SigParam::addDataTree(double resonanceMass, int cateIndex, TTree* dataTree, TString massBranchName, TString weightBranchName) { // Get the mass and weight branches. double massValue; double weightValue; dataTree->SetBranchAddress(massBranchName, &massValue); dataTree->SetBranchAddress(weightBranchName, &weightValue); // Loop over the TTree. for (Long64_t i_t = 0; i_t < dataTree->GetEntries(); i_t++) { // Add current event values to the dataset used for parameterization. addMassPoint(resonanceMass, cateIndex, massValue, weightValue); } } /** ----------------------------------------------------------------------------- Adds a mass point to the dataset for fitting the signal diphoton resonance. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The event category index (starting at 0). @param diphotonMass - The reconstructed diphoton invariant mass. @param eventWeight - The weight of the event. */ void SigParam::addMassPoint(double resonanceMass, int cateIndex, double diphotonMass, double eventWeight) { TString currKey = getKey(resonanceMass, cateIndex); // Create new dataset if the corresponding one doesn't yet exist. if (!dataExists(resonanceMass, cateIndex)) { // Create mass observable for this category: if (!m_ws->var(Form("m_yy_%s",currKey.Data()))) { m_ws->factory(Form("m_yy_%s[10,10000]",currKey.Data())); } RooDataSet* newData = new RooDataSet(Form("data_%s",currKey.Data()), Form("data_%s",currKey.Data()), RooArgSet(*m_ws->var(Form("m_yy_%s",currKey.Data())), *m_ws->var("wt")), RooFit::WeightVar(*m_ws->var("wt"))); m_ws->import(*newData); // Check to see that RooCategory exists: if (m_cat.count(cateIndex) == 0) { m_cat[cateIndex] = new RooCategory(Form("signalCates%d", cateIndex), Form("signalCates%d", cateIndex)); } // Each dataset also corresponds to a unique category in the fit: m_cat[cateIndex]->defineType(currKey); // Keep track of all resonance mass - category pairs for fitting. std::pair<double,int> currPair; //currPair.first = resonanceMass currPair.first = massIntToDouble(massDoubleToInt(resonanceMass)); currPair.second = cateIndex; m_massCatePairs.push_back(currPair); } // Set the observable and weight values and then fill dataset: m_ws->var(Form("m_yy_%s",currKey.Data()))->setVal(diphotonMass); m_ws->var("wt")->setVal(eventWeight); RooDataSet* currData =(RooDataSet*)m_ws->data(Form("data_%s",currKey.Data())); currData->add(RooArgSet(*m_ws->var(Form("m_yy_%s",currKey.Data())), *m_ws->var("wt")), eventWeight); // Also update the number of categories: if (cateIndex >= m_nCategories) { m_nCategories = cateIndex + 1; } } /** ----------------------------------------------------------------------------- Add a single mass resolution systematic uncertainty to the signal shape. Note: the constraint terms must be defined separately. @param nameMResSys - The name of the systematic nuisance parameter. */ void SigParam::addMResSystematic(TString nameMResSys) { // Name of nuisance parameter: TString atlasExpMRS = Form("atlas_expected_%s",nameMResSys.Data()); // Check to see if the nuisance parameter is already in the workspace: if (!(bool)m_ws->obj(atlasExpMRS)) { m_ws->factory(Form("%s[1]",atlasExpMRS.Data())); } // Add to the list storing signal resolution nuisance parameters: if (!m_listMRS.Contains(nameMResSys)) { m_listMRS.Append(Form(",%s",atlasExpMRS.Data())); } } /** ----------------------------------------------------------------------------- Add several mass resolution systematic uncertainties to the signal shape. Note: the constraint terms must be defined separately. @param namesMResSys - A list of the names of systematic nuisance parameters. */ void SigParam::addMResSystematics(std::vector<TString> namesMResSys) { for (std::vector<TString>::iterator sysIter = namesMResSys.begin(); sysIter != namesMResSys.end(); sysIter++) { SigParam::addMResSystematic(*sysIter); } } /** ----------------------------------------------------------------------------- Add a single mass scale systematic uncertainty to the signal shape. Note: the constraint terms must be defined separately. @param nameMScaleSys - The name of the systematic nuisance parameter. */ void SigParam::addMScaleSystematic(TString nameMScaleSys) { // Name of nuisance parameter: TString atlasExpMSS = Form("atlas_expected_%s", nameMScaleSys.Data()); // Check to see if the nuisance parameter is already in the workspace: if (!(bool)m_ws->obj(atlasExpMSS)) { m_ws->factory(Form("%s[1]",atlasExpMSS.Data())); } // Add to the list storing signal mass scale nuisance parameters: if (!m_listMSS.Contains(nameMScaleSys)) { m_listMSS.Append(Form(",%s",atlasExpMSS.Data())); } } /** ----------------------------------------------------------------------------- Add several mass scale systematic uncertainties to the signal shape. Note: the constraint terms must be defined separately. @param namesMScaleSys - List of the names of systematic nuisance parameters. */ void SigParam::addMScaleSystematics(std::vector<TString> namesMScaleSys) { for (std::vector<TString>::iterator sysIter = namesMScaleSys.begin(); sysIter != namesMScaleSys.end(); sysIter++) { SigParam::addMScaleSystematic(*sysIter); } } /** ----------------------------------------------------------------------------- Adds a signal PDF from this class to a pre-existing workspace. @param workspace - The pre-existing workspace. @param cateIndex - The index of the category of the desired PDF. @return - True iff the PDF and yield parameter were imported. */ bool SigParam::addSigToWS(RooWorkspace *&workspace, int cateIndex) { std::cout << "SigParam: Adding parameterized " << m_signalType << " signal in category " << cateIndex << " to pre-existing workspace." << std::endl; bool goodStatus = true; // Add the signal model to the workspace: RooAbsPdf* currSignal = m_ws->pdf(Form("sigPdf_%sc%d",m_signalType.Data(),cateIndex)); if (currSignal && !workspace->pdf(currSignal->GetName())) { workspace->import(*currSignal); } else { std::cout << "SigParam: Signal doesn't exist or is duplicate!" << std::endl; return false; } // Then explicitly add the parameters to the workspace: RooArgSet *currSet = currSignal->getVariables(); TIterator *iterParam = currSet->createIterator(); RooRealVar* currParam = NULL; while ((currParam = (RooRealVar*)iterParam->Next())) { workspace->import(*currParam); } // Import the yield formula and associated parameters: workspace->import(*m_ws->var(Form("yieldVar_a_%sc%d", m_signalType.Data(), cateIndex))); workspace->import(*m_ws->var(Form("yieldVar_b_%sc%d", m_signalType.Data(), cateIndex))); workspace->import(*m_ws->var(Form("yieldVar_c_%sc%d", m_signalType.Data(), cateIndex))); workspace->import(*m_ws->var(Form("yieldVar_d_%sc%d", m_signalType.Data(), cateIndex))); TString yieldName = Form("sigYield_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->function(yieldName)) { if (!workspace->function(yieldName)) { workspace->import(*m_ws->function(yieldName)); } else { std::cout << "SigParam: yield parameter " << yieldName << " already found in workspace." << std::endl; } } else { std::cout << "SigParam: Error! Yield param was not created by this program." << std::endl; goodStatus = false; } std::cout << "SigParam:: Finished adding parameterized signal." << std::endl; return goodStatus; } /** ----------------------------------------------------------------------------- Adds a signal PDF from this class to a pre-existing workspace. @param workspace - The pre-existing workspace. @param resonanceMass - The mass of the resonance. @param cateIndex - The index of the category of the desired PDF. @return - True iff the PDF and yield parameter were imported. */ bool SigParam::addSigToWS(RooWorkspace *&workspace, double resonanceMass, int cateIndex) { std::cout << "SigParam: Adding individual " << m_signalType << " signal in category " << cateIndex << " with mass " << resonanceMass << " to pre-existing workspace." << std::endl; bool goodStatus = true; TString currKey = getKey(resonanceMass, cateIndex); // Add the signal model to the workspace, if not already contained: RooAbsPdf* currSignal = m_ws->pdf(Form("sigPdf_%s%s",m_signalType.Data(), currKey.Data())); if (currSignal && !workspace->pdf(currSignal->GetName())) { workspace->import(*currSignal); } else { std::cout << "SigParam: Signal doesn't exist or is duplicate!" << std::endl; return false; } // Then explicitly add the parameters to the workspace: RooArgSet *currSet = currSignal->getVariables(); TIterator *iterParam = currSet->createIterator(); RooRealVar* currParam = NULL; while ((currParam = (RooRealVar*)iterParam->Next())) { if (!workspace->var(currParam->GetName())) { workspace->import(*currParam); } else { std::cout << "SigParam: parameter " << currParam->GetName() << " already found in workspace." << std::endl; } } // add yield factor to workspace: TString yieldName = Form("sigYield_%s%s",m_signalType.Data(), currKey.Data()); if (m_ws->var(yieldName)) { if (!workspace->var(yieldName)) { workspace->import((*m_ws->var(yieldName))); } else { std::cout << "SigParam: yield parameter " << yieldName << " already found in workspace." << std::endl; } } else { std::cout << "SigParam: Error! Yield param was not created by this program." << std::endl; goodStatus = false; } std::cout << "SigParam:: Finished adding individual signal." << std::endl; return goodStatus; } /** ----------------------------------------------------------------------------- Adds a parameter to the workspace for the fit. @param varName - The name of the shape variable of interest. @param cateIndex - The event category index (starting at 0). */ void SigParam::addVariable(TString varName, int cateIndex) { if (m_verbose) { std::cout << "SigParam: addVariable(" << varName << ", " << cateIndex << ")" << std::endl; } std::vector<TString> currParams = listParamsForVar(varName); // Loop over the parameterization variables corresponding to varName. for (int i_p = 0; i_p < (int)currParams.size(); i_p++) { TString valAndRange = getParamState(currParams[i_p]); TString fullName = Form("%s_%sc%d", (currParams[i_p]).Data(), m_signalType.Data(), cateIndex); // Check to see whether the variable has already been added before creating: if (!m_ws->var(fullName)) { m_ws->factory(Form("%s%s", fullName.Data(), valAndRange.Data())); } } } /** ----------------------------------------------------------------------------- Creates a single or combined binned dataset. @param unbinnedName - The name of the unbinned data in the workspace. @param resonanceMass - The mass value. @param cateIndex - The index of the category. */ void SigParam::binTheData(TString unbinnedName, double resonanceMass, int cateIndex) { // Create a single binned dataset: if (!unbinnedName.Contains(Form("data_c%d",cateIndex))) { TString currBinnedName = unbinnedName; currBinnedName.ReplaceAll("data","dataBinned"); binSingleDataSet(unbinnedName,currBinnedName, resonanceMass, cateIndex); } // Create the combined binned dataset: else { RooArgSet *args = new RooArgSet(); // Create a dataset map to store the RooDataSet objects: std::map<std::string,RooDataSet*> currDataMap; currDataMap.clear(); // Create a list of the corresponding unbinned datasets, and loop over it: std::vector<double> currMassPoints = massPointsForCategory(cateIndex); for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { TString currKey = getKey(currMassPoints[i_m], cateIndex); // Bin each one, add to map TString currUnbinnedName = Form("data_%s", currKey.Data()); TString currBinnedName = Form("dataBinned_%s", currKey.Data()); binSingleDataSet(currUnbinnedName, currBinnedName, currMassPoints[i_m], cateIndex); currDataMap[((std::string)currKey)] = (RooDataSet*)m_ws->data(currBinnedName); args->add(*m_ws->var(Form("m_yy_%s",currKey.Data()))); } args->add(*(m_ws->var("wt"))); RooDataSet *dataBinned =new RooDataSet(Form("dataBinned_c%d", cateIndex), Form("dataBinned_c%d", cateIndex), *args, RooFit::Index(*m_cat[cateIndex]), RooFit::Import(currDataMap), RooFit::WeightVar(*m_ws->var("wt"))); m_ws->import(*dataBinned); } } /** ----------------------------------------------------------------------------- Create a binned dataset from an unbinned dataset. @param unbinnedName - The name of the unbinned data in the workspace. @param binnedName - The name of the binned data to create. @param resonanceMass - The mass value. @param cateIndex - The index of the category. */ void SigParam::binSingleDataSet(TString unbinnedName, TString binnedName, double resonanceMass, int cateIndex) { if (m_verbose) { std::cout << "SigParam: Rebin sample " << unbinnedName << ", category " << cateIndex << " for mass " << resonanceMass << std::endl; } RooDataSet *unbinnedData = (RooDataSet*)m_ws->data(unbinnedName); RooRealVar *myyCurr = m_ws->var(Form("m_yy_%s", (getKey(resonanceMass, cateIndex)).Data())); // Create a histogram to automatically bin the points: //int nBins = (int)(m_nBinsPerGeV*(myyCurr->getMax() - myyCurr->getMin())); int nBins = (int)((myyCurr->getMax()-myyCurr->getMin())/(double)m_geVPerBin); TH1 *hist = unbinnedData ->createHistogram(Form("hist_%s",unbinnedName.Data()), *myyCurr, RooFit::Binning(nBins, myyCurr->getMin(), myyCurr->getMax())); // Create a dataset to fill with binned entries: RooDataSet* binnedData = new RooDataSet(binnedName, binnedName, RooArgSet(*myyCurr, *m_ws->var("wt")), RooFit::WeightVar(*m_ws->var("wt"))); for (int i_b = 1; i_b <= hist->GetNbinsX(); i_b++) { myyCurr->setVal(hist->GetXaxis()->GetBinCenter(i_b)); m_ws->var("wt")->setVal(hist->GetBinContent(i_b)); binnedData->add(RooArgSet(*myyCurr, *m_ws->var("wt")), hist->GetBinContent(i_b)); } // Import binned dataset to the workspace: m_ws->import(*binnedData); } /** ----------------------------------------------------------------------------- Calculate the width of the shape containing 68.2% of the events. @param resonanceMass - The mass value. @param cateIndex - The index of the category. @param mean - The peak value of the PDF. */ double SigParam::calculateStdDev(double resonanceMass, int cateIndex) { // The precision should be 0.001%: double precision = 0.00001; TString currKey = getKey(resonanceMass, cateIndex); // Load the mass variable and range: RooRealVar *observable = m_ws->var(Form("m_yy_%s", currKey.Data())); double minOrigin = observable->getMin(); double maxOrigin = observable->getMax(); // Use the parameterized PDF if it exists, otherwise the individual PDF: RooAbsPdf *currPdf = NULL; if ((m_ws->pdf(Form("sigPdf_%sc%d",m_signalType.Data(),cateIndex)))) { (*m_ws->var("mResonance")).setVal(resonanceMass); currPdf = (m_ws->pdf(Form("sigPdf_%sc%d",m_signalType.Data(),cateIndex))); } else if((m_ws->pdf(Form("sigPdf_%s%s",m_signalType.Data(),currKey.Data())))){ currPdf = (m_ws->pdf(Form("sigPdf_%s%s",m_signalType.Data(),currKey.Data()))); } // Get the maximum possible signal width, and also the mean: double mean = getMeanOrStdDev("Mean", resonanceMass, cateIndex); double stdDev = TMath::Min(fabs(mean-minOrigin), fabs(maxOrigin-mean)); // Calculate the initial integral using the full mass range: if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } observable->setRange("rangeFull", minOrigin, maxOrigin); RooAbsReal* intTot = (RooAbsReal*)currPdf ->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range("rangeFull")); double integralValTotal = intTot->getVal(); // Initial values for the integral and step size: double integralVal = 1.0; double stepSize = stdDev; int nIterations = 0; double target = 0.682; int maxIterations = 30; // Iteratively find the STDDEV: while ((fabs(integralVal - target)/target) > precision && nIterations <= maxIterations) { // Decrease the step size by half each time: nIterations++; stepSize = 0.5 * stepSize; // STDDEV too large: decrease the width: if (integralVal > target) stdDev = stdDev - stepSize; // STDDEV too small: increase the width: else stdDev = stdDev + stepSize; // Then calculate the fractional integral value: if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } observable->setRange(Form("range%f",stdDev), mean-stdDev, mean+stdDev); RooAbsReal* intCurr = (RooAbsReal*)currPdf ->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range(Form("range%f",stdDev))); integralVal = intCurr->getVal() / integralValTotal; } if (m_verbose) { std::cout << "SigParam: The STDDEV of the resonance is " << stdDev << " after " << nIterations << " iterations." << std::endl; } observable->setMin(minOrigin); observable->setMax(maxOrigin); return stdDev; } /** ----------------------------------------------------------------------------- Create a TF1 function object based on the results of a parameterized fit. @param varName - The name of the fit variable that has been parameterized. @param cateIndex - The index of the category. @param xMin - The minimum value of the function. @param xMax - The maximum value of the function. @return - A TF1 function with the fitted parameter values. */ TF1 *SigParam::createTF1FromParameterization(TString varName, int cateIndex, double xMin, double xMax) { // Modify the formatting of the function as defined for RooFit: TString currFuncFormat = getVarParameterization(varName); currFuncFormat = currFuncFormat.ReplaceAll("obs", "((x-100.0)/100.0)"); currFuncFormat = currFuncFormat.ReplaceAll("mRes", "x"); for (int i_p = 0; i_p < getNParamsForVar(varName); i_p++) { currFuncFormat = currFuncFormat.ReplaceAll(Form("@%d",i_p), Form("[%d]",i_p)); } // For variables that are not parameterized: if (currFuncFormat.EqualTo("")) currFuncFormat = "[0]"; // Instantiate a new TF1 based on the function format above. TF1 *currFunc = new TF1(Form("fit_%s",varName.Data()), currFuncFormat, xMin, xMax); // Then set the parameter values: std::vector<TString> paramList = listParamsForVar(varName); for (int i_p = 0; i_p < (int)paramList.size(); i_p++) { currFunc->SetParameter(i_p, getParameterValue(paramList[i_p], cateIndex)); } // And return the TF1: return currFunc; } /** ----------------------------------------------------------------------------- Check if the dataset being requested has been instantiated (exists in map). @param massIndex - The index of the signal mass. @param cateIndex - The index of the category. @return - True iff the dataset has been defined. */ bool SigParam::dataExists(double resonanceMass, int cateIndex) { if (m_ws->data(Form("data_%s",(getKey(resonanceMass,cateIndex)).Data()))) { return true; } else return false; } /** ----------------------------------------------------------------------------- This method generates and fits toy MC generated from a dataset, and returns the profiled Higgs mass and normalization as well as the truth values. @param resonanceMass - The floating value of the signal mass. @param cateIndex - The index of the category. @param dataType - "asimov", "mctoy", "pdftoy". @param seed - The random seed for pseudo-data generation (not for Asimov). @return - A vector: [0] = the truth resonance mass, [1] = the profiled resonance mass, [2] = truth data normalization, [3] = profiled normalization. */ std::vector<double> SigParam::doBiasTest(double resonanceMass, int cateIndex, TString dataType, int seed) { // First generate the desired data: generateData(resonanceMass, cateIndex, dataType, seed); // Free the parameters before fitting: TString currKey = getKey(resonanceMass, cateIndex); TString pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) { setParamsConstant(m_ws->pdf(pdfName), true); setResMassConstant(false, resonanceMass); } else { //pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); std::cout << "SigParam: ERROR! doBiasTest() method currently only configured for parameterized shape, where mResonance can be free for the fit." << std::endl; exit(0); } // Then fit that dataset: RooFitResult* currFitResult = fitResult(resonanceMass, cateIndex, dataType, "ExtendedParameterized"); // Return the fit bias information: std::vector<double> biasResult; biasResult.clear(); // Bad fits have null pointer to status, nonzero value, or infinite/nan NLL if (currFitResult && currFitResult->status() == 0 && std::isfinite(m_currNLL)) { biasResult.push_back(resonanceMass); biasResult.push_back(m_ws->var("mResonance")->getVal()); biasResult.push_back(generatedDataNorm()); biasResult.push_back(extendedTerm()); } return biasResult; } /** ----------------------------------------------------------------------------- Option to do a binned fit. Sets the private variable m_binned. @param binned - True iff the fit should be binned. @param geVPerBin - The number of bins per GeV for the binned data. */ void SigParam::doBinnedFit(bool binned, double geVPerBin) { m_binned = binned; m_geVPerBin = geVPerBin; if (m_verbose) { std::cout << "SigParam: Binned bool = " << m_binned << std::endl; } } /** ----------------------------------------------------------------------------- Check if two doubles are equal. @param massValue1 - The first mass value to compare. @param massValue2 - The second mass value to compare. @return - True iff the masses are equal within 0.001 GeV. */ bool SigParam::equalMasses(double massValue1, double massValue2) { return (fabs(massValue1 - massValue2) <= 0.001);// mass precision in GeV } /** ----------------------------------------------------------------------------- Retrieve the extended term value (normalization) from the most recent fit. @return - The value of the extended term from the last fit. */ double SigParam::extendedTerm() { return m_currExtendVal; } /** ----------------------------------------------------------------------------- Perform a single or simultaneous fit. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category. @param dataType - The type of data being fitted. "" for nominal signal MC, "asimov", "mctoy", or "pdftoy" for generated data types. @param option - Fit options (e.g. "Extended", "Parameterized"). @return - The RooFitResult, which gives fit status. */ RooFitResult* SigParam::fitResult(double resonanceMass, int cateIndex, TString dataType, TString option) { if (m_verbose) { std::cout << "SigParam: Preparing to fit resonance" << std::endl; } // Clock the fit: clock_t time; time = clock(); // Define the PDF and dataset names: TString currKey = getKey(resonanceMass,cateIndex); TString sigName = ""; if (resonanceMass < 0.0) { sigName = Form("sigPdfTmp_%sc%d", m_signalType.Data(), cateIndex); } else if (option.Contains("Parameterized")) { sigName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); } else { sigName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); } // The default dataset (for "" dataType): TString dataName = (resonanceMass < 0.0) ? Form("data_c%d",cateIndex) : Form("data_%s",currKey.Data()); // Change the dataset name if the fit is binned: if (m_binned) { TString binnedDataName = dataName; binnedDataName.ReplaceAll("data", "dataBinned"); // Also check that binned data have been created, otherwise create: if (m_ws->data(dataName) && !m_ws->data(binnedDataName)) { binTheData(dataName, resonanceMass, cateIndex); } dataName = binnedDataName; } // The section below modifies the PDF and dataset names for fitting generated // data such as asimov data or toy data: if (dataType.Contains("asimov") || dataType.Contains("mctoy") || dataType.Contains("pdftoy")) { // Must specify a mass value for fitting generated datasets: if (resonanceMass < 0.0) { std::cout << "SigParam: ERROR! Must specify a mass to fit for generated data. Use the same mass that was used to generate Asimov or toy MC data." << std::endl; exit(0); } // Try to choose a parameterized PDF, then use individual if that fails: sigName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (!m_ws->pdf(sigName)) { sigName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); } dataName = Form("data_%s_%s", dataType.Data(), currKey.Data()); } // Now create pointers to chosen signal and data ahead of fitting! RooDataSet *currData = (RooDataSet*)m_ws->data(dataName); RooAbsPdf *currSignal = m_ws->pdf(sigName); // In case an extended fit is requested: RooExtendPdf *currExtend = NULL; RooRealVar *currNorm = NULL; if (option.Contains("Extended")) { currNorm = new RooRealVar("currNorm", "currNorm", 100.0, 0.0, 1000000.0); currExtend = new RooExtendPdf("extendedPdf", "extendedPdf", *currSignal, *currNorm); } // Make sure inputs are defined, else exit: if (!currSignal) { std::cout << "SigParam: ERROR! Signal for fit not defined: " << sigName << std::endl; exit(0); } if (!currData) { std::cout << "SigParam: ERROR! Data for fit not defined: " << dataName << std::endl; exit(0); } int fitPrintLevel = m_verbose ? 0 : -1; RooFitResult *result = NULL; // Individual fit: apply the mass range requirement. if (resonanceMass > 0 && !option.Contains("Parameterized")) { double fitMin = m_ws->var(Form("m_yy_%s",currKey.Data()))->getMin(); double fitMax = m_ws->var(Form("m_yy_%s",currKey.Data()))->getMax(); if (option.Contains("Extended")) { result = currExtend->fitTo(*currData, RooFit::PrintLevel(fitPrintLevel), RooFit::SumW2Error(kTRUE), RooFit::Save(true), RooFit::Range(fitMin,fitMax)); m_currExtendVal = currNorm->getVal(); } else { result = currSignal->fitTo(*currData, RooFit::PrintLevel(fitPrintLevel), RooFit::SumW2Error(kTRUE), RooFit::Save(true), RooFit::Range(fitMin,fitMax)); } } // Parameterized fit: no explicit mass range requirement. else { if (option.Contains("Extended")) { result = currExtend->fitTo(*currData, RooFit::PrintLevel(fitPrintLevel), RooFit::SumW2Error(kTRUE), RooFit::Save(true)); m_currExtendVal = currNorm->getVal(); } else { result = currSignal->fitTo(*currData, RooFit::PrintLevel(fitPrintLevel), RooFit::SumW2Error(kTRUE), RooFit::Save(true)); } } m_currNLL = result->minNll(); return result; // Fix the fit parameters: SigParam::setParamsConstant(currSignal, true); // Clock the fit: time = clock() - time; if (m_verbose) { std::cout << "SigParam: Fit procedure concluded." << std::endl; printf("\tFit required %d clock cycles (%f seconds).\n\n", (int)time, ((float)time/CLOCKS_PER_SEC)); } return result; } /** ----------------------------------------------------------------------------- Perform a simultaneous fit across multiple masses. @param cateIndex - The index of the category. @param dataType - The type of data being fitted. "" for nominal signal MC, "asimov", "mctoy", or "pdftoy" for generated data types. @param option - Fit options (e.g. "Extended"). @return - The RooFitResult, which gives fit status. */ RooFitResult* SigParam::fitResult(int cateIndex, TString dataType, TString option) { return SigParam::fitResult(-999.9, cateIndex, dataType, option); } /** ----------------------------------------------------------------------------- Check whether the given function has been implemented in this class. @param function - The name of the function to test for definition. @return - True iff. the function has been defined. */ bool SigParam::functionIsDefined(TString function) { if (function.Contains("DoubleCB") || function.Contains("CBGA") || function.Contains("GAx3") || function.Contains("BifurGA") || function.Contains("Landau") || function.Contains("Voigt") || function.Contains("LAx2") || function.Contains("CBLA") || function.Contains("DoubleCBLA") || function.Contains("GALA") || function.Contains("BifurGALA") || function.Contains("LandauMod")){ return true; } else { std::cout << "SigParam: ERROR! " << function << " is undefined. Please use" << " one of the following: DoubleCB, CBGA, GAx3, BifurGA, Landau," << " LAx2, CBLA, Voigt, CBPlusVoigt, DoubleCBLA, " << "GALA, BifurGALA, LandauMod" << std::endl; return false; } } /** ----------------------------------------------------------------------------- This method generates and fits either Asimov data, toy data from the input MC, or toy data from the fitted PDF. @param resonanceMass - The floating value of the signal mass. @param cateIndex - The index of the category. @param type - "asimov", "mctoy", "pdftoy". @param seed - The random seed for pseudo-data generation (not for Asimov). @return - True iff. generation works and fit converges. */ bool SigParam::generateAndFitData(double resonanceMass, int cateIndex, TString dataType, int seed) { // First generate the desired data: generateData(resonanceMass, cateIndex, dataType, seed); // Free the parameters before fitting: TString currKey = getKey(resonanceMass, cateIndex); TString pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) setResMassConstant(false, resonanceMass); else pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); setParamsConstant(m_ws->pdf(pdfName), false); // Then fit that dataset: RooFitResult* result = fitResult(resonanceMass, cateIndex, dataType, "ExtendedParameterized"); // Return the fit status: // Bad fits have null pointer to status, nonzero value, or infinite/nan NLL return (result && result->status() == 0 && std::isfinite(m_currNLL)); } /** ----------------------------------------------------------------------------- This method generates either Asimov data, toy data from the input MC, or toy data from the fitted PDF. @param resonanceMass - The floating value of the signal mass. @param cateIndex - The index of the category. @param type - "asimov", "mctoy", "pdftoy". @param seed - The random seed for pseudo-data generation (not for Asimov). @return - A pointer to the new RooAbsData set. */ RooDataSet* SigParam::generateData(double resonanceMass, int cateIndex, TString dataType, int seed) { if (m_verbose) { std::cout << "SigParam: Creating Asimov data mRes=" << resonanceMass << ", cate=" << cateIndex << ", type=" << dataType << std::endl; } // The dataset to be generated and returned: RooDataSet *generatedData = NULL; // Get the name of the dataset: TString currKey = getKey(resonanceMass, cateIndex); TString dataName = Form("data_%s", currKey.Data()); // Use simultaneous model if it exists, otherwise use individual model: TString obsName; TString pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) { // Need to set the resonance mass to the correct value: setResMassConstant(true, resonanceMass); // Also use the generic m_yy observable: obsName = "m_yy"; } // Individual model must be used: else { pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); obsName = Form("m_yy_%s", currKey.Data()); } // Get the yield at this mass and category for generation: double nEventsToGenerate = getYieldInCategory(resonanceMass, cateIndex); //--------------------// // If Asimov data are requested: if (dataType.EqualTo("asimov")) { // Generate the Asimov data using the RooStats method: m_ws->factory(Form("SUM::sigPdfAsimov(nSigAsimov[%f]*%s)", nEventsToGenerate, pdfName.Data())); generatedData = (RooDataSet*)RooStats::AsymptoticCalculator:: GenerateAsimovData(*m_ws->pdf("sigPdfAsimov"), RooArgSet(*m_ws->var(obsName))); //GenerateAsimovData(*m_ws->pdf(pdfName), RooArgSet(*m_ws->var(obsName))); // Then add ghost events: double min = m_ws->var(obsName)->getMin(); double max = m_ws->var(obsName)->getMax(); double ghostWt = 0.0000001; for (double massVal = min; massVal <=max; massVal += fabs((max-min)/10.0)) { m_ws->var(obsName)->setVal(massVal); generatedData->add(RooArgSet(*m_ws->var(obsName)), ghostWt); } } //--------------------// // If toy data from the fitted PDF are requested: else if(dataType.EqualTo("pdftoy")) { RooRandom::randomGenerator()->SetSeed(seed); generatedData = (RooDataSet*)m_ws->pdf(pdfName) ->generate(*m_ws->var(obsName),nEventsToGenerate,RooFit::Extended(true)); } //--------------------// // If toy data from the input dataset are requested: else if (dataType.EqualTo("mctoy")) { // Check that the underlying dataset exists! if (!m_ws->data(dataName)) { std::cout << "SigParam: ERROR! dataset required but missing: " << dataName << std::endl; exit(0); } // Instantiate the dataset to be returned: generatedData = new RooDataSet(Form("data_mctoy_%s",currKey.Data()), Form("data_mctoy_%s",currKey.Data()), RooArgSet(*m_ws->var(obsName),*m_ws->var("wt")), RooFit::WeightVar(*m_ws->var("wt"))); // Turn original dataset into histogram: double min = m_ws->var(obsName)->getMin(); double max = m_ws->var(obsName)->getMax(); //int bins = (int)(m_nBinsPerGeV * (max - min)); int bins = (int)((max - min)/(double)m_geVPerBin); TString originObsName = Form("m_yy_%s", currKey.Data()); TH1F *dataHist = (TH1F*)m_ws->data(dataName) ->createHistogram("histTmp", *m_ws->var(originObsName), RooFit::Binning(bins,min,max)); // Randomly generate poisson normalization: RooRandom::randomGenerator()->SetSeed(seed); TRandom *random = new TRandom(); random->SetSeed(seed); int integerEventsToGenerate = random->Poisson(nEventsToGenerate); for (int i_r = 0; i_r < integerEventsToGenerate; i_r++) { // Generate random events from input data histogram: double currVal = dataHist->GetRandom(); double currWt = 1.0; // Then add to new RooDataSet: m_ws->var(obsName)->setVal(currVal); m_ws->var("wt")->setVal(currWt); generatedData ->add(RooArgSet(*m_ws->var(obsName), *m_ws->var("wt")), currWt); } // Then add ghost events: double ghostWt = 0.0000001; for (double massVal = min; massVal <=max; massVal += fabs((max-min)/10.0)) { m_ws->var(obsName)->setVal(massVal); m_ws->var("wt")->setVal(ghostWt); generatedData ->add(RooArgSet(*m_ws->var(obsName), *m_ws->var("wt")), ghostWt); } delete dataHist; } //--------------------// // Option not recognized: else { std::cout << "SigParam: ERROR! GenerateData doesn't recognize type " << dataType << std::endl; exit(0); } if (m_verbose) { std::cout << "SigParam: generated data has " << generatedData->sumEntries() << " entries (weighted)" << std::endl; } // Rename the dataset: generatedData->SetNameTitle(Form("data_%s_%s", dataType.Data(), currKey.Data()), Form("data_%s_%s", dataType.Data(), currKey.Data())); // Save norm. so that it is retrievable via generatedDataNormalization(): m_generatedDataNorm = generatedData->sumEntries(); // Import and return new dataset: m_ws->import(*generatedData); return generatedData; } /** ----------------------------------------------------------------------------- Get the weighted normalization of the dataset that was just generated. @return - The weighted sum of entries or the number of entries. */ double SigParam::generatedDataNorm() { return m_generatedDataNorm; } /** ----------------------------------------------------------------------------- Retrieve a key string for the given mass and category index. @param resonanceMass - The floating value of the signal mass. @param cateIndex - The index of the category. @return - A key string specific to the mass and category. */ TString SigParam::getKey(double resonanceMass, int cateIndex) { TString key = Form("m%d_c%d", massDoubleToInt(resonanceMass), cateIndex); return key; } /** ----------------------------------------------------------------------------- Get the mean value of the fit shape. If multiple functions are used, the weighted mean is returned, where the weight is determined by the relative normalization of each component. Note: the StdDev is calculated via integration, and is not simply the resolution parameter for a given PDF. @param value - "Mean" or "StdDev". @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category for the PDF. @return - The weighted mean (mu) of the signal shape. */ double SigParam::getMeanOrStdDev(TString value, double resonanceMass, int cateIndex) { if (value.EqualTo("StdDev")) { return calculateStdDev(resonanceMass, cateIndex); } else if (value.EqualTo("Mean")) { std::vector<double> valList; valList.clear(); std::vector<double> fracList; fracList.clear(); std::vector<TString> currVars = variablesForFunction(m_currFunction); for (int i_v = 0; i_v < (int)currVars.size(); i_v++) { if (currVars[i_v].Contains("mu") && value.EqualTo("Mean")) { valList.push_back(getParameterValue(currVars[i_v], resonanceMass, cateIndex)); } else if (currVars[i_v].Contains("frac")) { fracList.push_back(getParameterValue(currVars[i_v], resonanceMass, cateIndex)); } } // Then loop over the muList, and create a weighted sum of the mean values, // with the weight given by the "frac" variables: double result = 0.0; double priorFracs = 0.0; if (m_currFunction.Contains("BifurGA")) fracList.push_back(0.5); for (int i_m = 0; i_m < (int)valList.size(); i_m++) { if (i_m < (int)valList.size()-1) { result += (valList[i_m] * fracList[i_m]); priorFracs += fracList[i_m]; } else { result += (valList[i_m] * (1.0-priorFracs)); } } return result; } else { std::cout << "SigParam: ERROR! value " << value << " undefined." << std::endl; exit(0); } } /** ----------------------------------------------------------------------------- Get the mean value of the data used to fit the PDFs. @param value - "Mean" or "StdDev". @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category for the PDF. @return - The weighted mean (mu) of the input data. */ double SigParam::getMeanOrStdDevInData(TString value, double resonanceMass, int cateIndex) { TString currKey = getKey(resonanceMass, cateIndex); if (value.Contains("Mean")) { return m_ws->data(Form("data_%s",currKey.Data())) ->mean(*m_ws->var(Form("m_yy_%s",currKey.Data()))); } else if (value.Contains("StdDev")) { return m_ws->data(Form("data_%s",currKey.Data())) ->sigma(*m_ws->var(Form("m_yy_%s",currKey.Data()))); } else { std::cout << "SigParam: ERROR! value " << value << " undefined." << std::endl; exit(0); } } /** ----------------------------------------------------------------------------- Get the number of categories contained in the datasets for fitting. Note: it is possible that there are different numbers of categories defined for different mass points. This is up to the user to sort out. @return - The total number of categories for the parameterization. */ int SigParam::getNCategories() { return m_nCategories; } /** ----------------------------------------------------------------------------- Get the number of parameters used to parameterize the given variable. @param varName - The name of the fit variable that has been parameterized. @return - The number of parameters. */ int SigParam::getNParamsForVar(TString varName) { TString currFunction = getVarParameterization(varName); if (currFunction.EqualTo("")) return 0; // TString CountChar method requires a bug report for ROOT. //else return currFunction.CountChar("@"); else { int counter = 0; for (Ssiz_t i_c = 0; i_c < currFunction.Length(); i_c++) { if (TString(currFunction[i_c]).EqualTo("@")) counter++; } return counter; } } /** ----------------------------------------------------------------------------- Get the value of the fit error for a particular parameter of the signal PDF. @param paramName - The name of the shape parameter of interest. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category. @return - The value of the specified signal parameter. */ double SigParam::getParameterError(TString paramName, double resonanceMass, int cateIndex) { if (paramName.Contains("nCB") || paramName.Contains("frac")){ return SigParam::getParameterError(paramName, cateIndex); } else { TString varName = Form("%s_%s%s", paramName.Data(), m_signalType.Data(), (getKey(resonanceMass,cateIndex)).Data()); if (!m_ws->var(varName)) { std::cout << "SigParam: requested parameter not found: " << paramName << std::endl; exit(0); } else return m_ws->var(varName)->getError(); } } /** ----------------------------------------------------------------------------- Get the value of the fit error for a particular parameter of the signal PDF. @param paramName - The name of the shape parameter of interest. @param cateIndex - The index of the category. @return - The value of the specified signal parameter. */ double SigParam::getParameterError(TString paramName, int cateIndex) { TString varName = Form("%s_%sc%d", paramName.Data(), m_signalType.Data(), cateIndex); if (!m_ws->var(varName)) { std::cout << "SigParam: requested parameter not found: " << paramName << std::endl; exit(0); } else return m_ws->var(varName)->getError(); } /** ----------------------------------------------------------------------------- Get the value of a particular parameter of the signal PDF. @param paramName - The name of the shape parameter of interest. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category. @return - The value of the specified signal parameter. */ double SigParam::getParameterValue(TString paramName, double resonanceMass, int cateIndex) { if (paramName.Contains("nCB") || paramName.Contains("frac")) { return SigParam::getParameterValue(paramName, cateIndex); } else { TString varName = Form("%s_%s%s", paramName.Data(), m_signalType.Data(), (getKey(resonanceMass,cateIndex)).Data()); if (!m_ws->var(varName)) { std::cout << "SigParam: requested parameter not found: param = " << paramName << ", mass = " << resonanceMass << ", cate = " << cateIndex << std::endl; exit(0); } else return m_ws->var(varName)->getVal(); } } /** ----------------------------------------------------------------------------- Get the value of a particular parameter of the signal PDF. @param paramName - The name of the shape parameter of interest. @param cateIndex - The index of the category. @return - The value of the specified signal parameter. */ double SigParam::getParameterValue(TString paramName, int cateIndex) { TString varName = Form("%s_%sc%d", paramName.Data(), m_signalType.Data(), cateIndex); if (!m_ws->var(varName)) { std::cout << "SigParam: requested parameter not found: param = " << paramName << ", cate = " << cateIndex << std::endl; exit(0); } else return m_ws->var(varName)->getVal(); } /** ----------------------------------------------------------------------------- Get the parameterized value of a particular parameter of the signal PDF. This method only works for parameterized fits. @param paramName - The name of the shape parameter of interest. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category. @return - The value of the specified signal parameter. */ double SigParam::getParameterizedValue(TString paramName, double resonanceMass, int cateIndex) { if (m_verbose) { std::cout << "getParameterizedValue(" << paramName << ", " << resonanceMass << ", " << cateIndex << ")" << std::endl; } m_ws->var("mResonance")->setVal(resonanceMass); TString funcName = Form("%s_%sc%d", paramName.Data(), m_signalType.Data(), cateIndex); funcName.ReplaceAll("Nom",""); if (m_ws->function(funcName)) return m_ws->function(funcName)->getVal(); else { std::cout << "SigParam: ERROR! Unrecognized parameterization variable " << funcName << ". Returning nominal variable value instead." << std::endl; return getParameterValue(paramName, resonanceMass, cateIndex); } } /** ----------------------------------------------------------------------------- Get the initial value [a] and range [b,c] of a parameter: "[a,b,c]" @param paramName - The name of the parameter of interest. @return - The initial value and range of the parameter. */ TString SigParam::getParamState(TString paramName) { return m_paramState[paramName]; } /** ----------------------------------------------------------------------------- Retrieves the resonance parameterized as a function of mResonance. @param cateIndex - The index of the category for the PDF. @return - A pointer to the signal PDF. */ RooAbsPdf* SigParam::getResonance(int cateIndex) { std::cout << "SigParam: Get parameterized shape in category = " << cateIndex << std::endl; TString pdfName = Form("sigPdf_%sc%d",m_signalType.Data(), cateIndex); RooAbsPdf* pdf = m_ws->pdf(pdfName); std::cout << "SigParam: Returning parameterized pdf " << pdfName << std::endl; return pdf; } /** ----------------------------------------------------------------------------- Get the resonance shape for a single category and mass. @param resonanceMass - The truth mass of the resonance @param cateIndex - The index of the category for which we want the PDF. @return - A pointer to the signal PDF. */ RooAbsPdf* SigParam::getSingleResonance(double resonanceMass, int cateIndex) { std::cout << "SigParam: Get parameterized shape in category = " << cateIndex << " and mass = " << resonanceMass << std::endl; TString pdfName = Form("sigPdf_%s%s",m_signalType.Data(), (getKey(resonanceMass,cateIndex)).Data()); RooAbsPdf* pdf = m_ws->pdf(pdfName); std::cout << "SigParam: Returning parameterized pdf " << pdfName << std::endl; return pdf; } /** ----------------------------------------------------------------------------- Get the value of a test statistic from the most recent fit in the specified category. Chi2 is only available for binned fits, whereas NLL is available for any fit. The fits are all done by minimizing -log(L). @param statistic - The name of the test statistic "Chi2" or "NLL". @param cateIndex - The index of the category that was fit. @return - The value of the test statistic. */ double SigParam::getTestStat(TString statistic, int cateIndex) { if (statistic.EqualTo("Chi2") && !m_binned) { std::cout << "SigParam: Error! Chi^2 can only be calculated for binned fit." << std::endl; exit(0); } return m_testStats[Form("%s_c%d", statistic.Data(), cateIndex)]; } /** ----------------------------------------------------------------------------- Get the value of a test statistic from the most recent fit in the specified category and resonance mass. Chi2 is only available for binned fits, whereas NLL is available for any fit. The fits are all done by minimizing -log(L). @param statistic - The name of the test statistic "Chi2" or "NLL". @param resonanceMass - The truth mass of the resonance that was fit. @param cateIndex - The index of the category that was fit. @return - The value of the test statistic. */ double SigParam::getTestStat(TString statistic, double resonanceMass, int cateIndex) { if (statistic.EqualTo("Chi2") && !m_binned) { std::cout << "SigParam: Error! Chi^2 can only be calculated for binned fit." << std::endl; exit(0); } TString currKey = getKey(resonanceMass,cateIndex); return m_testStats[Form("%s_%s", statistic.Data(), currKey.Data())]; } /** ----------------------------------------------------------------------------- Get the value of a test statistic from the most recent fit. Chi2 is only available for binned fits, whereas NLL is available for any fit. The fits are all done by minimizing -log(L). @param statistic - The name of the test statistic "Chi2" or "NLL". @return - The value of the test statistic from the single most recent fit. */ double SigParam::getTestStatLatest(TString statistic) { if (statistic.EqualTo("Chi2") && !m_binned) { std::cout << "SigParam: Error! Chi^2 can only be calculated for binned fit." << std::endl; exit(0); } else if (statistic.EqualTo("Chi2")) { if (m_verbose) { std::cout << "SigParam: Most recent fit gives " << statistic << " = " << m_currChi2 << std::endl; } return m_currChi2; } else { if (m_verbose) { std::cout << "SigParam: Most recent fit gives " << statistic << " = " << m_currNLL << std::endl; } return m_currNLL; } } /** ----------------------------------------------------------------------------- Get a list of parameters associated with the PDF in the given category. @param resonanceMass - The truth mass of the resonance @param cateIndex - The index of the category for which we want the PDF. @return - A vector of parameter names. */ std::vector<TString> SigParam::getVariableNames(double resonanceMass, int cateIndex) { std::cout << "SigParam: Get PDF variables in category = " << cateIndex << " and mass = " << resonanceMass << std::endl; std::vector<TString> result; result.clear(); TString currKey = getKey(resonanceMass, cateIndex); TString pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); RooArgSet* currSet = (*m_ws->pdf(pdfName)).getVariables(); TIterator *iterArg = currSet->createIterator(); RooRealVar *currArg = NULL; while ((currArg = (RooRealVar*)iterArg->Next())) { TString currArgName = currArg->GetName(); currArgName = currArgName.ReplaceAll(currKey, ""); currArgName = currArgName.ReplaceAll(Form("_%s",m_signalType.Data()), ""); currArgName = currArgName.ReplaceAll(Form("c%d",cateIndex), ""); if (!currArgName.Contains("m_yy")) result.push_back(currArgName); } return result; } /** ----------------------------------------------------------------------------- Retrieve the functional form of the parameterization in the resonance mass of the given fit variable. @param varName - The name of the fit variable that has been parameterized. @return - A string with the functional form of the parameterization. */ TString SigParam::getVarParameterization(TString varName) { std::map<TString,TString>::iterator varIter; for (varIter = m_varParameterization.begin(); varIter != m_varParameterization.end(); varIter++) { if (varName.EqualTo(varIter->first)) { return varIter->second; } } if (m_verbose) { std::cout << "SigParam: WARNING No defined parameterization for " << varName << std::endl; } return ""; } /** ----------------------------------------------------------------------------- Get the workspace that stores the SigParam class data. @return - A pointer to the workspace storing all datasets and PDFs. */ RooWorkspace* SigParam::getWorkspace() { return m_ws; } /** ----------------------------------------------------------------------------- Get the error on the signal yield for a particular mass in a particular category. NOTE: THIS FAILS IF DATASET NOT DEFINED. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category for which we want the PDF. @return - The signal yield for the specified mass in the given category. */ double SigParam::getYieldErrorInCategory(double resonanceMass, int cateIndex) { if (m_verbose) { std::cout << "SigParam: Get error on yield in category = " << cateIndex << " at mass = " << resonanceMass << std::endl; } TString currKey = getKey(resonanceMass,cateIndex); // Then try to get individual yield: if(m_ws->var(Form("sigYield_%s%s",m_signalType.Data(),currKey.Data()))) { if (m_verbose) std::cout << "SigParam: point yield" << std::endl; return m_ws->var(Form("sigYield_%s%s",m_signalType.Data(), currKey.Data()))->getError(); } // Then try to get directly from dataset normalization: else if ((m_ws->data(Form("data_%s",currKey.Data())))) { if (m_verbose) std::cout << "SigParam: data yield" << std::endl; return normalizationError(m_ws->data(Form("data_%s",currKey.Data()))); } // Or return error message: else { std::cout << "SigParam: requested yield error not found. NOTE: You cannot " << "access the interpolated yield error at the current time." << std::endl; exit(0); } } /** ----------------------------------------------------------------------------- Get the signal yield error for a particular resonance mass in all categories. @param resonanceMass - The truth mass of the resonance. @return - The signal yield in all categories for the specified mass. */ double SigParam::getYieldErrorTotal(double resonanceMass) { std::cout << "SigParam: Get error on total yield at mass = " << resonanceMass << std::endl; // Loop through names of datasets, add components: double sum = 0.0; for (int i_c = 0; i_c < getNCategories(); i_c++) { sum += getYieldErrorInCategory(resonanceMass, i_c); } return sum; } /** ----------------------------------------------------------------------------- Get the signal yield for a particular mass in a particular category. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category for which we want the PDF. @return - The signal yield for the specified mass in the given category. */ double SigParam::getYieldInCategory(double resonanceMass, int cateIndex) { if (m_verbose) { std::cout << "SigParam: Get yield in category = " << cateIndex << " at mass = " << resonanceMass << std::endl; } TString currKey = getKey(resonanceMass,cateIndex); // First check if parameterized yield is available: if (m_ws->function(Form("sigYield_%sc%d", m_signalType.Data(), cateIndex))) { if (m_verbose) std::cout << "SigParam: parameterized yield" << std::endl; m_ws->var("mResonance")->setVal(resonanceMass); return m_ws->function(Form("sigYield_%sc%d", m_signalType.Data(), cateIndex))->getVal(); } // Then try to get individual yield: else if(m_ws->var(Form("sigYield_%s%s",m_signalType.Data(),currKey.Data()))) { if (m_verbose) std::cout << "SigParam: point yield" << std::endl; return m_ws->var(Form("sigYield_%s%s",m_signalType.Data(), currKey.Data()))->getVal(); } // Then try to get directly from dataset normalization: else if ((m_ws->data(Form("data_%s",currKey.Data())))) { if (m_verbose) std::cout << "SigParam: data yield" << std::endl; return m_ws->data(Form("data_%s",currKey.Data()))->sumEntries(); } // Or return error message: else { std::cout << "SigParam: requested yield not found." << std::endl; exit(0); } } /** ----------------------------------------------------------------------------- Get the signal yield for a signal at a specified mass in a specified category inside a specified range of the observable. @param resonanceMass - The truth mass of the resonance. @param cateIndex - The index of the category for which we want the PDF. @param obsMin - The minimum of the observable range. @param obsMax - The maximum of the observable range. @return - The signal yield in the window [obsMin,obsMax]. */ double SigParam::getYieldInWindow(double resonanceMass, int cateIndex, double obsMin, double obsMax) { TString pdfName = ""; TString obsName = ""; // Look for parameterized model: pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) { setResMassConstant(true, resonanceMass); obsName = Form("m_yy"); } // If no parameterized model exists, get single point model: else { TString currKey = getKey(resonanceMass, cateIndex); pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); obsName = Form("m_yy_%s", currKey.Data()); } // Then check that both data and PDF exist: if (!m_ws->pdf(pdfName)) { std::cout << "SigParam: PDF for yield undefined." << std::endl; exit(0); } // Get the total integral of the PDF: double obsMinOrigin = m_ws->var(obsName)->getMin(); double obsMaxOrigin = m_ws->var(obsName)->getMax(); m_ws->var(obsName)->setRange("rangeTotal", obsMinOrigin, obsMaxOrigin); RooAbsReal* integralTotal = (RooAbsReal*)m_ws->pdf(pdfName) ->createIntegral(RooArgSet(*m_ws->var(obsName)), RooFit::NormSet(*m_ws->var(obsName)), RooFit::Range("rangeTotal")); double integralTotalVal = integralTotal->getVal(); // Get the integral of the PDF in the window: m_ws->var(obsName)->setRange("rangeWindow", obsMin, obsMax); RooAbsReal* integralWindow = (RooAbsReal*)m_ws->pdf(pdfName) ->createIntegral(RooArgSet(*m_ws->var(obsName)), RooFit::NormSet(*m_ws->var(obsName)), RooFit::Range("rangeWindow")); double integralWindowVal = integralWindow->getVal(); // Then reset observable range: m_ws->var(obsName)->setRange(obsMinOrigin, obsMaxOrigin); // Caculate and return yield: double yield = getYieldInCategory(resonanceMass, cateIndex); double fractionInWindow = integralWindowVal / integralTotalVal; double yieldInWindow = fractionInWindow * yield; return yieldInWindow; } /** ----------------------------------------------------------------------------- Get the signal yield for a particular resonance mass in all categories. @param resonanceMass - The truth mass of the resonance. @return - The signal yield in all categories for the specified mass. */ double SigParam::getYieldTotal(double resonanceMass) { std::cout << "SigParam: Get total yield at mass = " << resonanceMass << std::endl; // Loop through names of datasets, add components: double sum = 0.0; for (int i_c = 0; i_c < getNCategories(); i_c++) { sum += getYieldInCategory(resonanceMass, i_c); } return sum; } /** ----------------------------------------------------------------------------- Get the total inclusive signal yield for a signal at a specified mass in the specified observable window. @param resonanceMass - The truth mass of the resonance. @param obsMin - The minimum of the observable range. @param obsMax - The maximum of the observable range. */ double SigParam::getYieldTotalInWindow(double resonanceMass, double obsMin, double obsMax) { // Loop through names of datasets, add components: double sum = 0.0; for (int i_c = 0; i_c < getNCategories(); i_c++) { sum += getYieldInWindow(resonanceMass, i_c, obsMin, obsMax); } return sum; } /** ----------------------------------------------------------------------------- Get a list of parameters required to parameterize the given variable as a function of the resonance mass. @param varName - The name of the fit variable that has been parameterized. @return - A list of parameters corresponding to the variable. */ std::vector<TString> SigParam::listParamsForVar(TString varName) { std::vector<TString> result; result.clear(); TString prefix[10] = {"a_","b_","c_","d_","e_","f_","g_","h_","i_","j_"}; int varOrder = getNParamsForVar(varName); if (varOrder == 0) { result.push_back(varName); } else { for (int i_p = 0; i_p < varOrder; i_p++) { if (i_p == 10) { std::cout << "SigParam: Error! listParamsForVar() supports < 10 var." << std::endl; exit(0); } result.push_back(Form("%s%s", (prefix[i_p]).Data(), varName.Data())); } } return result; } /** ----------------------------------------------------------------------------- Load the signal parameterization from file. @param directory - Name of the directory housing the input workspace. @return - True iff the file is successfully loaded. */ bool SigParam::loadParameterization(TString directory, TString signalType){ std::cout << "SigParam: Load parameterization from " << directory << " for signal type " << signalType << std::endl; setDirectory(directory); bool parameterizationExists = false; TFile inputFile(Form("%s/res_%sworkspace.root", m_directory.Data(), m_signalType.Data())); if (inputFile.IsOpen()) { m_ws = (RooWorkspace*)inputFile.Get("signalWS"); if (m_ws) { parameterizationExists = true; setSignalType(signalType); m_currFunction = m_ws->var("functionName")->GetTitle(); std::cout << "SigParam: Successfully loaded from file!" << std::endl; } } if (!parameterizationExists) { std::cout << "SigParam: ERROR loading from file." << std::endl; exit(0); } return parameterizationExists; } /** ----------------------------------------------------------------------------- Parameterize the resonance shape in all categories. @param function - The functional form of the resonance. @return - True iff. all fits converge. */ bool SigParam::makeAllParameterizations(TString function) { std::cout << "SigParam: Engage full signal parameterization!" << std::endl; if (!functionIsDefined(function)) { std::cout << "SigParam: Error! Improper function " << function << std::endl; return false; } bool result = true; // Define models in each category independently: for (int i_c = 0; i_c < m_nCategories; i_c++) { if (!makeCategoryParameterization(i_c, function)) result = false; } std::cout << "SigParam: Completed full signal parameterization" << std::endl; return result; } /** ----------------------------------------------------------------------------- Parameterize the resonance shape as a function of mass for a single category. @param cateIndex - The index of the category to fit. @param function - The functional form of the resonance. @return - True iff. all fits converge. */ bool SigParam::makeCategoryParameterization(int cateIndex, TString function) { if (m_verbose) { std::cout << "SigParam: parameterizing category " << cateIndex << std::endl; } if (!functionIsDefined(function)) { std::cout << "SigParam: Error! Improper function " << function << std::endl; return false; } // Create a list of mass points in this category. std::vector<double> currMassPoints = massPointsForCategory(cateIndex); // Create a simultaneous PDF just for this category: RooSimultaneous *currSim = new RooSimultaneous(Form("sigPdfTmp_%sc%d",m_signalType.Data(),cateIndex), Form("sigPdfTmp_%sc%d",m_signalType.Data(),cateIndex), *m_cat[cateIndex]); // If no mass points, cannot fit signal, silly! if (currMassPoints.size() == 0) { std::cout << "SigParam: No masspoints for cate. " << cateIndex << std::endl; return false; } // If only one mass point, no need for parameterization: else if (currMassPoints.size() == 1) { std::cout << "SigParam: 1 mass point -> no parameterization." << std::endl; return makeSingleResonance(currMassPoints[0], cateIndex, function); } // If more than 1 mass points, parameterize variables: // Define the RooFormulaVars which control mH parameterization: // Loop over mass points, define resonance model in each: for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { TString currKey = getKey(currMassPoints[i_m],cateIndex); double mRegVal = regularizedMass(currMassPoints[i_m]); double mResVal = currMassPoints[i_m]; parameterizeFunction(function, mRegVal, mResVal, cateIndex, false); // Create, individual resonance shapes, add to simultaneous PDF: resonanceCreator(currMassPoints[i_m], cateIndex, function); currSim->addPdf(*m_ws->pdf(Form("sigPdf_%s%s",m_signalType.Data(), currKey.Data())), currKey); } // Import simultaneous PDF into workspace: m_ws->import(*currSim); // Set to store all mass observables and weight variable: RooArgSet *args = new RooArgSet(); // Get the RooDataSets and observables in loop over categories: std::map<std::string,RooDataSet*> currDataMap; currDataMap.clear(); for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { // maybe add if statement here... TString currKey = getKey(currMassPoints[i_m], cateIndex); // Then add to the map: currDataMap[((std::string)currKey)] = (RooDataSet*)m_ws->data(Form("data_%s",currKey.Data())); // Reduce the dataset to within (rounded) fraction of the mean if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } if (m_fixWindow) { m_ws->var(Form("m_yy_%s",currKey.Data())) ->setRange(m_windowMin, m_windowMax); } else { m_ws->var(Form("m_yy_%s",currKey.Data())) ->setRange(round((1.0-m_windowFraction) * currMassPoints[i_m]), round((1.0+m_windowFraction) * currMassPoints[i_m])); } // Add the current observable to the set: args->add(*m_ws->var(Form("m_yy_%s",currKey.Data()))); } // Add weight variable to arg set: args->add(*(m_ws->var("wt"))); // Create the combined dataset to be profiled: RooDataSet *obsData = new RooDataSet(Form("data_c%d",cateIndex), Form("data_c%d",cateIndex), *args, RooFit::Index(*m_cat[cateIndex]), RooFit::Import(currDataMap), RooFit::WeightVar(*m_ws->var("wt"))); m_ws->import(*obsData); // Then fit simultaneous PDF to combined dataset: RooFitResult *result = fitResult(cateIndex); // Save the test statistics: m_testStats[Form("NLL_c%d", cateIndex)] = getTestStatLatest("NLL"); if (m_binned) { m_testStats[Form("Chi2_c%d", cateIndex)] = getTestStatLatest("Chi2"); } // Then construct parametric resonance (function of mResonance): m_ws->factory("m_yy[10,10000]"); parameterizeFunction(function, -999, -999, cateIndex, true); // Create the parameterized resonance shape (function of mResonance): resonanceCreator(-999, cateIndex, Form("%s_Parameterized",function.Data())); // Get the yield parameterization: makeYieldParameterization(cateIndex); // Return the fit status: // Bad fits have null pointer to status, nonzero value, or infinite/nan NLL return (result && result->status() == 0 && std::isfinite(m_currNLL)); } /** ----------------------------------------------------------------------------- Create the resonance for a single mass point and category. @param resonanceMass - The truth mass of the resonance @param cateIndex - The index of the category to fit. @param function - The functional form of the resonance. @return - True iff. all fits converge. */ bool SigParam::makeSingleResonance(double resonanceMass, int cateIndex, TString function) { if (m_verbose) { std::cout << "SigParam: individual fit in category " << cateIndex << " and at mass " << resonanceMass << std::endl; } if (!functionIsDefined(function)) { std::cout << "SigParam: Error! Improper function " << function << std::endl; return false; } // Before calling resonanceCreator, need to define dependent variables. TString currKey = getKey(resonanceMass, cateIndex); // Get a list of variables for the current PDF and add them to the workspace: std::vector<TString> currVars = variablesForFunction(function); for (int i_v = 0; i_v < (int)currVars.size(); i_v++) { TString varSuffix = ""; if (currVars[i_v].Contains("nCB") || currVars[i_v].Contains("frac")) { varSuffix = Form("%sc%d", m_signalType.Data(), cateIndex); } else { varSuffix = Form("%s%s", m_signalType.Data(), currKey.Data()); } TString initialValAndRange = getParamState(currVars[i_v]); m_ws->factory(Form("%s_%s%s", currVars[i_v].Data(), varSuffix.Data(), initialValAndRange.Data())); // If it is a mean value, set to the resonance mass initially: if ((currVars[i_v].Contains("muCB") || currVars[i_v].Contains("muGA") || currVars[i_v].Contains("muVoigt") || currVars[i_v].Contains("muLA")) && !(m_ws->var(Form("%s_%s", currVars[i_v].Data(), varSuffix.Data())) ->isConstant())) { if (m_verbose) std::cout << "Setting mean." << std::endl; m_ws->var(Form("%s_%s", currVars[i_v].Data(), varSuffix.Data())) ->setVal(resonanceMass); m_ws->var(Form("%s_%s", currVars[i_v].Data(), varSuffix.Data())) ->setRange(0.9*resonanceMass,1.1*resonanceMass); } } // Create the single resonance PDF: resonanceCreator(resonanceMass, cateIndex, function); // Reduce the dataset to within (rounded) +/-5 sigma of the mean TString dataName = Form("data_%s",currKey.Data()); if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } if (m_fixWindow) { m_ws->var(Form("m_yy_%s",currKey.Data())) ->setRange(m_windowMin, m_windowMax); } else { m_ws->var(Form("m_yy_%s",currKey.Data())) ->setRange(round((1.0-m_windowFraction) * resonanceMass), round((1.0+m_windowFraction) * resonanceMass)); } // Then fit single PDF to single dataset: RooFitResult *result = fitResult(resonanceMass, cateIndex); // Save the test statistics: m_testStats[Form("NLL_%s", currKey.Data())] = getTestStatLatest("NLL"); if (m_binned) { m_testStats[Form("Chi2_%s", currKey.Data())] = getTestStatLatest("Chi2"); } // Return the fit status. // Bad fits have null pointer to status, nonzero value, or infinite/nan NLL return (result && result->status() == 0 && std::isfinite(m_currNLL)); } /** ----------------------------------------------------------------------------- Parameterizes the signal yields in a category as a function of mH. @param cateIndex - The index of the category to fit. */ void SigParam::makeYieldParameterization(int cateIndex) { std::cout << "SigParam: Parameterizing the signal yield." << std::endl; // Create arrays to store fit data: int nResPoints = 0; double mResValues[100] = {0.0}; double yieldValues[100] = {0.0}; double mResErrors[100] = {0.0}; double yieldErrors[100] = {0.0}; // Retrieve dataset yield for each mass point that was imported: std::vector<double> currMassPoints = massPointsForCategory(cateIndex); for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { TString dataName = Form("data_%s",(getKey(currMassPoints[i_m],cateIndex)).Data()); if ((m_ws->data(dataName))) { mResValues[nResPoints] = regularizedMass(currMassPoints[i_m]); yieldValues[nResPoints] = (*m_ws->data(dataName)).sumEntries(); yieldErrors[nResPoints] = normalizationError(m_ws->data(dataName)); nResPoints++; } } // Use TF1 and TGraph to fit the yield: m_yieldFunc[cateIndex] = new TF1("yieldFunc", "pol3", 0.0, 0.5); m_yieldGraph[cateIndex] = new TGraphErrors(nResPoints, mResValues, yieldValues, mResErrors, yieldErrors); m_yieldGraph[cateIndex]->Fit(m_yieldFunc[cateIndex]); // Create the yield parameters: m_ws->factory(Form("yieldVar_a_%sc%d[%f]", m_signalType.Data(), cateIndex, m_yieldFunc[cateIndex]->GetParameter(0))); m_ws->factory(Form("yieldVar_b_%sc%d[%f]", m_signalType.Data(), cateIndex, m_yieldFunc[cateIndex]->GetParameter(1))); m_ws->factory(Form("yieldVar_c_%sc%d[%f]", m_signalType.Data(), cateIndex, m_yieldFunc[cateIndex]->GetParameter(2))); m_ws->factory(Form("yieldVar_d_%sc%d[%f]", m_signalType.Data(), cateIndex, m_yieldFunc[cateIndex]->GetParameter(3))); // Then create a yield RooFormulaVar. m_ws->factory(Form("expr::sigYield_%sc%d('@0+@1*@4+@2*@4*@4+@3*@4*@4*@4',{yieldVar_a_%sc%d,yieldVar_b_%sc%d,yieldVar_c_%sc%d,yieldVar_d_%sc%d,mRegularized})", m_signalType.Data(), cateIndex, m_signalType.Data(), cateIndex, m_signalType.Data(), cateIndex, m_signalType.Data(), cateIndex, m_signalType.Data(), cateIndex)); } /** ----------------------------------------------------------------------------- Convert the resonance mass integer to a floating value. @param massInteger - An integer value representing the mass. @return - The floating value of the mass in GeV. */ double SigParam::massIntToDouble(int massInteger) { return ((double)massInteger) / 1000.0; } /** ----------------------------------------------------------------------------- Convert the resonance mass value to an integer representation. @param resonanceMass - The value of the resonance mass. @return - The integer representation of the mass. */ int SigParam::massDoubleToInt(double resonanceMass) { resonanceMass = round(resonanceMass); return (int)(resonanceMass * 1000); } /** ----------------------------------------------------------------------------- Get a list of mass points corresponding to a single category. @param cateIndex - The index of the category. @return - A vector of mass values. */ std::vector<double> SigParam::massPointsForCategory(int cateIndex) { // Create a list of mass points in this category. std::vector<double> currMassPoints; currMassPoints.clear(); for (int i_p = 0; i_p < (int)m_massCatePairs.size(); i_p++) { if ((m_massCatePairs[i_p]).second == cateIndex) { currMassPoints.push_back((m_massCatePairs[i_p]).first); } } std::sort(currMassPoints.begin(), currMassPoints.end()); return currMassPoints; } /** ----------------------------------------------------------------------------- Import a list of names for the fit categories. Otherwise, categories will simply be numbered. Sets the value of private variable m_cateNames. @param cateNames - A vector of category names. */ void SigParam::nameTheCategories(std::vector<TString> cateNames) { if ((int)cateNames.size() != m_nCategories && m_verbose) { std::cout << "SigParam: WARNING! Number of defined categories different from number of category names provided." << std::endl; } m_cateNames = cateNames; } /** ----------------------------------------------------------------------------- Get the normalization error for a weighted dataset. @param dataSet - The dataset for which we want the total normalization error. @return - The sumw2 normalization error for the dataset. */ double SigParam::normalizationError(RooAbsData *dataSet) { double normError = 0.0; // Loop over events stored in the input dataset: for (int i_d = 0; i_d < dataSet->numEntries(); i_d++) { dataSet->get(i_d); normError += dataSet->weightSquared(); } return sqrt(normError); } /** ----------------------------------------------------------------------------- Parameterize the specified function. @param function - The functional form of the resonance. @param mRegularized - The regularized mass. @param mResonance - The resonance mass. @param cateIndex - The event category index (starting at 0). @param parameterized - True iff for floating mResonance. */ void SigParam::parameterizeFunction(TString function, double mRegularized, double mResonance, int cateIndex, bool parameterized) { std::vector<TString> currVariables = variablesForFunction(function); for (int i_v = 0; i_v < (int)currVariables.size(); i_v++) { parameterizeVar(currVariables[i_v], mRegularized, mResonance, cateIndex, parameterized); } } /** ----------------------------------------------------------------------------- Parameterize the specified variable. @param varName - The name of the shape variable of interest. @param mRegularized - The regularized mass. @param mResonance - The resonance mass. @param cateIndex - The event category index (starting at 0). @param parameterized - True iff for floating mResonance. */ void SigParam::parameterizeVar(TString varName, double mRegularized, double mResonance, int cateIndex, bool parameterized) { if (m_verbose) { std::cout << "SigParam: parameterizeVar(" << varName << ", " << cateIndex << ")" << std::endl; } // Make sure all parameterization variables have been added: addVariable(varName, cateIndex); TString currKey = getKey(mResonance, cateIndex); // Then create a string of the parameters from the vector of parameters: TString paramString = ""; std::vector<TString> paramList = listParamsForVar(varName); for (int i_p = 0; i_p < (int)paramList.size(); i_p++) { paramString += Form("%s_%sc%d",(paramList[i_p]).Data(),m_signalType.Data(),cateIndex); if (i_p < (int)paramList.size()-1) paramString += ","; } // Get the functional form of the variable: TString functionForm = getVarParameterization(varName); if (!functionForm.EqualTo("")) { if (parameterized) { int nParams = (int)paramList.size(); functionForm = functionForm.ReplaceAll("obs", Form("@%d",nParams)); functionForm = functionForm.ReplaceAll("mRes", Form("@%d",nParams+1)); paramString += ",mRegularized,mResonance"; m_ws->factory(Form("expr::%s_%sc%d('%s',{%s})", varName.Data(), m_signalType.Data(), cateIndex, functionForm.Data(), paramString.Data())); } else { functionForm = functionForm.ReplaceAll("obs", Form("%f", mRegularized)); functionForm = functionForm.ReplaceAll("mRes", Form("%f", mResonance)); m_ws->factory(Form("expr::%s_%s%s('%s',{%s})", varName.Data(), m_signalType.Data(),currKey.Data(),functionForm.Data(), paramString.Data())); } } } /** ----------------------------------------------------------------------------- Create a RooDataSet with a new RooRealVar. @param data - The RooAbsData set for comparison. @param observable - The mass observable for data and pdf. */ RooDataSet* SigParam::plotData(RooAbsData *data, RooRealVar *observable) { // Clone the dataset: TString cloneName = data->GetName(); RooDataSet *dataClone = (RooDataSet*)data->Clone(Form("%s_copy",cloneName.Data())); dataClone->changeObservableName(observable->GetName(), "m_yy"); m_ws->import(*dataClone); return dataClone; } /** ----------------------------------------------------------------------------- Create a ratio plot (or subtraction plot, for the moment...) @param data - The RooAbsData set for comparison. @param pdf - The PDF for comparison. @param observable - The mass observable for data and pdf. @param xBins - The number of bins for the observable. @param chi2Prob - The chi^2 probability of the fit at this point. @return - A TGraphErrors to plot. */ TGraphErrors* SigParam::plotSubtraction(RooAbsData *data, RooAbsPdf *pdf, RooRealVar *observable, double xBins, double &chi2Prob) { double minOrigin = observable->getMin(); double maxOrigin = observable->getMax(); //double nEvents = data->sumEntries(); double nEvents = data->sumEntries(Form("%s>%f&&%s<%f", observable->GetName(), minOrigin, observable->GetName(), maxOrigin)); TH1F *originHist = (TH1F*)data->createHistogram("dataSub", *observable, RooFit::Binning(xBins,minOrigin,maxOrigin)); TGraphErrors *result = new TGraphErrors(); double increment = (maxOrigin - minOrigin) / ((double)xBins); RooAbsReal* intTot = (RooAbsReal*)pdf->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range("fullRange")); double valTot = intTot->getVal(); int pointIndex = 0; for (double i_m = minOrigin; i_m < maxOrigin; i_m += increment) { if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } observable->setRange(Form("range%2.2f",i_m), i_m, (i_m+increment)); RooAbsReal* intCurr = (RooAbsReal*)pdf->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range(Form("range%2.2f",i_m))); double valCurr = intCurr->getVal(); double currMass = i_m + (0.5*increment); double currPdfWeight = nEvents * (valCurr / valTot); TString varName = observable->GetName(); double currDataWeight = data->sumEntries(Form("%s>%f&&%s<%f",varName.Data(), i_m,varName.Data(), (i_m+increment))); double currWeight = currDataWeight - currPdfWeight; result->SetPoint(pointIndex, currMass, currWeight); double currError = originHist->GetBinError(pointIndex+1); result->SetPointError(pointIndex, 0.0, currError); pointIndex++; } observable->setMin(minOrigin); observable->setMax(maxOrigin); delete originHist; return result; } /** ----------------------------------------------------------------------------- Create a ratio plot (or subtraction plot, for the moment...) @param data - The RooAbsData set for comparison. @param pdf - The PDF for comparison. @param observable - The mass observable for data and pdf. @param xBins - The number of bins for the observable. @param chi2Val - The chi^2 probability of the fit at this point only. @return - A TGraphErrors to plot. */ TGraphErrors* SigParam::plotDivision(RooAbsData *data, RooAbsPdf *pdf, RooRealVar *observable, double xBins, double &chi2Prob) { // Store the original variable range: double minOrigin = observable->getMin(); double maxOrigin = observable->getMax(); //double nEvents = data->sumEntries(); double nEvents = data->sumEntries(Form("%s>%f&&%s<%f", observable->GetName(), minOrigin, observable->GetName(), maxOrigin)); TH1F *originHist = (TH1F*)data->createHistogram("dataSub", *observable, RooFit::Binning(xBins,minOrigin,maxOrigin)); TGraphErrors *result = new TGraphErrors(); double increment = ((maxOrigin - minOrigin) / ((double)xBins)); observable->setRange("fullRange", minOrigin, maxOrigin); RooAbsReal* intTot = (RooAbsReal*)pdf->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range("fullRange")); double valTot = intTot->getVal(); int pointIndex = 0; int pointIndexNonZero = 0; for (double i_m = minOrigin; i_m < maxOrigin; i_m += increment) { if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } observable->setRange(Form("range%2.2f",i_m), i_m, (i_m+increment)); RooAbsReal* intCurr = (RooAbsReal*)pdf->createIntegral(RooArgSet(*observable), RooFit::NormSet(*observable), RooFit::Range(Form("range%2.2f",i_m))); double valCurr = intCurr->getVal(); double currMass = i_m + (0.5*increment); double currPdfWeight = nEvents * (valCurr / valTot); TString varName = observable->GetName(); double currDataWeight = data->sumEntries(Form("%s>%f&&%s<%f",varName.Data(), i_m,varName.Data(), (i_m+increment))); double currWeight = currDataWeight / currPdfWeight; result->SetPoint(pointIndex, currMass, currWeight); double currError = originHist->GetBinError(pointIndex+1) / currPdfWeight; result->SetPointError(pointIndex, 0.0, currError); pointIndex++; double currChi2 = (((currDataWeight-currPdfWeight) * (currDataWeight-currPdfWeight)) / ((originHist->GetBinError(pointIndex+1)) * (originHist->GetBinError(pointIndex+1)))); if (std::isfinite(currChi2)) { chi2Prob += currChi2; pointIndexNonZero++; } } // Return to the original variable range, store the chi^2 value: observable->setMin(minOrigin); observable->setMax(maxOrigin); chi2Prob = TMath::Prob(chi2Prob, pointIndexNonZero); delete originHist; return result; } /** ----------------------------------------------------------------------------- Plot a resonance PDF for all masses defined for one category. Note: this method requires a simultaneous fit to run first, so that the m_yy object can be created in the workspace. @param cateIndex - The index of the category. */ void SigParam::plotCategoryResonances(int cateIndex) { if (m_verbose) { std::cout << "SigParam: Plot resonances in cate. " << cateIndex << std::endl; } // Create a canvas with two pads (one main plot, one subtraction plot) TCanvas *can = new TCanvas("can", "can", 800, 800); can->cd(); TPad *pad1 = new TPad( "pad1", "pad1", 0.00, 0.33, 1.00, 1.00 ); TPad *pad2 = new TPad( "pad2", "pad2", 0.00, 0.00, 1.00, 0.33 ); pad1->SetBottomMargin(0.00001); pad1->SetBorderMode(0); pad2->SetTopMargin(0.00001); pad2->SetBottomMargin(0.4); pad2->SetBorderMode(0); can->cd(); pad1->Draw(); pad2->Draw(); // Get a list of the resonance masses: std::vector<double> currMassPoints = massPointsForCategory(cateIndex); // Also get the range of the plot: int xMin = 0; int xMax = 0; for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { RooRealVar *currObs = m_ws ->var(Form("m_yy_%s",(getKey(currMassPoints[i_m],cateIndex).Data()))); if (i_m == 0) { xMin = currObs->getMin(); xMax = currObs->getMax(); } else if (currObs->getMin() < xMin) xMin = currObs->getMin(); else if (currObs->getMax() > xMax) xMax = currObs->getMax(); } int xBins = (int)((xMax - xMin)/(double)m_geVPerBin); // Set this new limited range for the RooRealVar observable: if (!m_verbose) { RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING); } m_ws->var("m_yy")->setRange(xMin, xMax); // Create a RooPlot for the fit and data: RooPlot* frame = m_ws->var("m_yy")->frame(RooFit::Bins(xBins), RooFit::Range(xMin, xMax)); frame->SetYTitle(Form("Events/%d GeV", m_geVPerBin)); frame->SetXTitle(m_xAxisTitle); TH1F *medianHist = NULL; // Loop over mass points, drawing data and PDF for each: for (int i_m = 0; i_m < (int)currMassPoints.size(); i_m++) { pad1->cd(); RooAbsData *currData = NULL; RooAbsPdf *currPdf = NULL; RooRealVar *currObs = NULL; TString currKey = getKey(currMassPoints[i_m], cateIndex); // Plot the data: if ((m_ws->data(Form("data_%s",currKey.Data())))) { currData = (m_ws->data(Form("data_%s",currKey.Data()))); currObs = m_ws->var(Form("m_yy_%s",currKey.Data())); currData = plotData(currData, currObs); currData->plotOn(frame); } else { std::cout << "SigParam: data for plotting undefined." << std::endl; return; } // Then plot the parameterized signal PDF: if ((m_ws->pdf(Form("sigPdf_%sc%d",m_signalType.Data(),cateIndex)))) { (*m_ws->var("mResonance")).setVal(currMassPoints[i_m]); currPdf = (m_ws->pdf(Form("sigPdf_%sc%d",m_signalType.Data(),cateIndex))); currPdf->plotOn(frame, RooFit::LineColor(4)); } else { std::cout << "SigParam: ERROR! Parameterized shape not defined!" << std::endl; exit(0); } // Then draw the frame: if (i_m == 0) { frame->Draw(); // Print ATLAS text on the plot: TLatex l; l.SetNDC(); l.SetTextColor(kBlack); l.SetTextFont(72); l.SetTextSize(0.05); l.DrawLatex(0.55, 0.88, "ATLAS"); l.SetTextFont(42); l.SetTextSize(0.05); l.DrawLatex(0.67, 0.88, m_atlasLabel); //l.SetTextSize(0.04); l.DrawLatex(0.55, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); //l.DrawLatex(0.55, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); if ((int)m_cateNames.size() == m_nCategories) { l.DrawLatex(0.55, 0.76, m_cateNames[cateIndex]); } else { l.DrawLatex(0.55, 0.76, Form("category %d", cateIndex)); } } else frame->Draw("SAME"); // Switch to sub-plot: pad2->cd(); if (i_m == 0) { medianHist = new TH1F("median", "median", xBins, xMin, xMax); for (int i_b = 1; i_b <= xBins; i_b++) medianHist->SetBinContent(i_b,1.0); medianHist->SetLineColor(kRed); medianHist->SetLineWidth(2); medianHist->GetXaxis()->SetTitle(m_xAxisTitle); if (m_doRatioPlot) { medianHist->GetYaxis()->SetTitle("MC / Fit"); } else medianHist->GetYaxis()->SetTitle("MC - Fit"); medianHist->GetXaxis()->SetTitleOffset(0.95); medianHist->GetYaxis()->SetTitleOffset(0.7); medianHist->GetXaxis()->SetTitleSize(0.1); medianHist->GetYaxis()->SetTitleSize(0.1); medianHist->GetXaxis()->SetLabelSize(0.1); medianHist->GetYaxis()->SetLabelSize(0.1); medianHist->GetYaxis()->SetRangeUser(-0.2, 2.2); medianHist->GetYaxis()->SetNdivisions(5); medianHist->Draw(); TLine *line = new TLine(); line->SetLineStyle(1); line->SetLineWidth(2); line->SetLineColor(kRed); if (m_doRatioPlot) { line->SetLineWidth(1); line->SetLineStyle(2); line->DrawLine(xMin,((1.0+m_ratioMin)/2.0),xMax,((1.0+m_ratioMin)/2.0)); line->DrawLine(xMin,((1.0+m_ratioMax)/2.0),xMax,((1.0+m_ratioMax)/2.0)); } else line->DrawLine(xMin, 0.0, xMax, 0.0); } double currChi2Prob = 0.0; TGraphErrors* subData = (m_doRatioPlot) ? plotDivision(currData, currPdf, m_ws->var("m_yy"), xBins, currChi2Prob) : plotSubtraction(currData, currPdf, m_ws->var("m_yy"), xBins,currChi2Prob); subData->Draw("EPSAME"); } // Print the canvas: can->Print(Form("%s/plot_paramResonance_c%d%s", m_directory.Data(), cateIndex, m_fileFormat.Data())); delete can; delete medianHist; } /** ----------------------------------------------------------------------------- Plot a resonance PDF for one value of the resonance mass in one category. @param resonanceMass - The resonance mass value in GeV. @param cateIndex - The index of the category. @param dataType - "asimov", "mctoy", "pdftoy". */ void SigParam::plotSingleResonance(double resonanceMass, int cateIndex, TString dataType) { if (m_verbose) { std::cout << "SigParam: Plotting resonance at mass " << resonanceMass << " in category " << cateIndex << " with dataset " << dataType << std::endl; } // Create canvas and sub-pads: TCanvas *can = new TCanvas("can","can",800,800); can->cd(); TPad *pad1 = new TPad( "pad1", "pad1", 0.00, 0.33, 1.00, 1.00 ); TPad *pad2 = new TPad( "pad2", "pad2", 0.00, 0.00, 1.00, 0.33 ); pad1->SetBottomMargin(0.00001); pad1->SetBorderMode(0); pad2->SetTopMargin(0.00001); pad2->SetBottomMargin(0.4); pad2->SetBorderMode(0); can->cd(); pad1->Draw(); pad2->Draw(); pad1->cd(); // Settings determining the PDF, data, and observable to plot: TString currKey = getKey(resonanceMass,cateIndex); TString pdfName = ""; TString dataName = ""; TString obsName = ""; bool parameterized = false; // For fits to Asimov, MC toy, or PDF toy data: if (dataType.Contains("asimov") || dataType.Contains("mctoy") || dataType.Contains("pdftoy")) { dataName = Form("data_%s_%s", dataType.Data(), currKey.Data()); // Loop for parameterized model and then single mass point model: pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) { setResMassConstant(true, resonanceMass); obsName = "m_yy"; parameterized = true; } else { pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); obsName = Form("m_yy_%s", currKey.Data()); } } // Else for nominal fits: else { dataName = Form("data_%s", currKey.Data()); obsName = Form("m_yy_%s", currKey.Data()); // Look for parameterized model and then single mass point model: pdfName = Form("sigPdf_%sc%d", m_signalType.Data(), cateIndex); if (m_ws->pdf(pdfName)) { setResMassConstant(true, resonanceMass); // Clone the dataset with a different observable: plotData(m_ws->data(dataName), m_ws->var(obsName)); dataName = Form("%s_copy", dataName.Data()); parameterized = true; } else pdfName = Form("sigPdf_%s%s", m_signalType.Data(), currKey.Data()); } // Then check that both data and PDF exist: if (!m_ws->data(dataName) || !m_ws->pdf(pdfName)) { std::cout << "SigParam: data or PDF for plotting undefined." << std::endl; exit(0); } // Load the appropriate observable and define the plot binning: double rMin = m_ws->var(obsName)->getMin(); double rMax = m_ws->var(obsName)->getMax(); int rBins = (int)((rMax - rMin)/(double)m_geVPerBin); // Create the RooPlot object using the observable, and set axis titles: RooPlot *frame = m_ws->var(obsName)->frame(RooFit::Bins(rBins),RooFit::Range(rMin,rMax)); frame->SetYTitle(Form("Events/%d GeV", m_geVPerBin)); frame->SetXTitle(m_xAxisTitle); // Then add the data and PDF to the RooPlot: m_ws->data(dataName)->plotOn(frame); m_ws->pdf(pdfName)->plotOn(frame, RooFit::LineColor(2)); // Draw the RooPlot: frame->Draw(); // Special y-axis ranges for log-scale plots: if (m_useLogYAxis) { gPad->SetLogy(); frame->GetYaxis() ->SetRangeUser(0.00001 *(*m_ws->data(dataName)).sumEntries(), (*m_ws->data(dataName)).sumEntries()); } TLatex l; l.SetNDC(); l.SetTextColor(kBlack); l.SetTextFont(72); l.SetTextSize(0.05); l.DrawLatex(0.20, 0.88, "ATLAS"); l.SetTextFont(42); l.SetTextSize(0.05); l.DrawLatex(0.32, 0.88, m_atlasLabel); //l.SetTextSize(0.04); l.DrawLatex(0.2, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); //l.DrawLatex(0.2, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); if ((int)m_cateNames.size() == m_nCategories && m_nCategories > 0) { l.DrawLatex(0.2, 0.76, m_cateNames[cateIndex]); } else { l.DrawLatex(0.2, 0.76, Form("category %d", cateIndex)); } double yVal = 0.88; TLatex varText; varText.SetNDC(); varText.SetTextColor(1); varText.SetTextSize(0.04); std::vector<TString> currVars = variablesForFunction(m_currFunction); for (int i_v = 0; i_v < (int)currVars.size()+1; i_v++) { TString currName = ""; double currVal = 0.0; if (i_v < (int) currVars.size()) { currName = currVars[i_v]; if (parameterized) { currVal = getParameterizedValue(currName, resonanceMass, cateIndex); } else currVal = getParameterValue(currName, resonanceMass, cateIndex); currName.ReplaceAll("frac", "fraction_{"); currName.ReplaceAll("Nom",""); currName.ReplaceAll("nCB","n_{CB"); currName.ReplaceAll("width","w_{"); currName.ReplaceAll("sigma","#sigma_{"); currName.ReplaceAll("alpha","#alpha_{"); currName.ReplaceAll("mu", "#mu_{"); currName += "}"; } else { currName = "Yield"; currVal = getYieldInCategory(resonanceMass, cateIndex); } varText.DrawLatex(0.7, yVal, Form("%s\t = %2.2f",currName.Data(),currVal)); yVal -= 0.06; } // Move to second pad for ratio or subtraction plot: pad2->cd(); TH1F *medianHist = new TH1F("median", "median", rBins, rMin, rMax); medianHist->SetLineColor(kRed); medianHist->SetLineWidth(2); medianHist->GetXaxis()->SetTitle(m_xAxisTitle); if (m_doRatioPlot) { for (int i_b = 1; i_b <= rBins; i_b++) medianHist->SetBinContent(i_b,1.0); medianHist->GetYaxis()->SetTitle("MC / Fit"); medianHist->GetYaxis()->SetRangeUser(-0.2,2.2); } else { for (int i_b = 1; i_b <= rBins; i_b++) medianHist->SetBinContent(i_b,0.0); medianHist->GetYaxis()->SetTitle("MC - Fit"); } medianHist->GetYaxis()->SetNdivisions(5); medianHist->GetXaxis()->SetTitleOffset(0.95); medianHist->GetYaxis()->SetTitleOffset(0.7); medianHist->GetXaxis()->SetTitleSize(0.1); medianHist->GetYaxis()->SetTitleSize(0.1); medianHist->GetXaxis()->SetLabelSize(0.1); medianHist->GetYaxis()->SetLabelSize(0.1); medianHist->Draw(); double currChi2Prob = 0.0; TGraphErrors* subData = (m_doRatioPlot) ? plotDivision(m_ws->data(dataName), m_ws->pdf(pdfName), m_ws->var(obsName), rBins, currChi2Prob) : plotSubtraction(m_ws->data(dataName), m_ws->pdf(pdfName), m_ws->var(obsName), rBins, currChi2Prob); subData->GetXaxis()->SetTitle(m_xAxisTitle); // Draw lines showing ratio of 1.0 +/-0.5 TLine *line = new TLine(); line->SetLineStyle(1); line->SetLineWidth(2); line->SetLineColor(kRed); if (m_doRatioPlot) { line->SetLineWidth(1); line->SetLineStyle(2); line->DrawLine(rMin,((1.0+m_ratioMin)/2.0),rMax,((1.0+m_ratioMin)/2.0)); line->DrawLine(rMin,((1.0+m_ratioMax)/2.0),rMax,((1.0+m_ratioMax)/2.0)); } else line->DrawLine(rMin, 0.0, rMax, 0.0); subData->Draw("EPSAME"); TLatex chiText; chiText.SetNDC(); chiText.SetTextColor(1); chiText.SetTextSize(0.1); //chiText.DrawLatex(0.7, 0.9, Form("p_{#chi} = %2.2f", currChi2Prob)); can->Print(Form("%s/plot%s_singleRes_m%2.2f_c%d%s", m_directory.Data(), dataType.Data(), resonanceMass, cateIndex, m_fileFormat.Data())); delete can; delete medianHist; } /** ----------------------------------------------------------------------------- Graph the signal yields as function of resonance mass in the given category. @param cateIndex - The index of the category for yield plotting. */ void SigParam::plotYields(int cateIndex) { std::cout << "SigParam: Plotting yields in category " << cateIndex << std::endl; TCanvas *can = new TCanvas("can","can",800,800); can->cd(); TPad *pad1 = new TPad("pad1", "pad1", 0.00, 0.33, 1.00, 1.00); TPad *pad2 = new TPad("pad2", "pad2", 0.00, 0.00, 1.00, 0.33); pad1->SetBottomMargin(0.00001); pad1->SetBorderMode(0); pad2->SetTopMargin(0.00001); pad2->SetBottomMargin(0.4); pad2->SetBorderMode(0); can->cd(); pad1->Draw(); pad2->Draw(); pad1->cd(); m_yieldFunc[cateIndex]->SetLineColor(kBlue); m_yieldGraph[cateIndex]->GetYaxis()->SetTitle("Signal yield"); m_yieldGraph[cateIndex]->Draw("AEP"); m_yieldFunc[cateIndex]->Draw("LSAME"); TString formattedSignal = m_signalType.Data(); formattedSignal.ReplaceAll("_",""); // Print ATLAS text on the plot: TLatex l; l.SetNDC(); l.SetTextColor(kBlack); l.SetTextFont(72); l.SetTextSize(0.05); l.DrawLatex(0.55, 0.88, "ATLAS"); l.SetTextFont(42); l.SetTextSize(0.05); l.DrawLatex(0.67,0.88, m_atlasLabel); //l.SetTextSize(0.04); l.DrawLatex(0.55, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); //l.DrawLatex(0.55, 0.82, Form("#sqrt{s} = 13 TeV: #scale[0.7]{#int}Ldt = %s", m_lumiLabel.Data())); if ((int)m_cateNames.size() == m_nCategories) { l.DrawLatex(0.55, 0.76, m_cateNames[cateIndex]); } else { l.DrawLatex(0.55, 0.76, Form("Category %d", cateIndex)); } pad2->cd(); TGraphErrors *gRatio = new TGraphErrors(); gRatio->SetNameTitle(Form("ratio_c%d",cateIndex),Form("ratio_c%d",cateIndex)); for (int i_p = 0; i_p < m_yieldGraph[cateIndex]->GetN(); i_p++) { double currX = 0.0; double currY = 0.0; m_yieldGraph[cateIndex]->GetPoint(i_p, currX, currY); double errorX = m_yieldGraph[cateIndex]->GetErrorX(i_p); double errorY = m_yieldGraph[cateIndex]->GetErrorY(i_p); gRatio->SetPoint(i_p, currX, (currY/m_yieldFunc[cateIndex]->Eval(currX))); gRatio->SetPointError(i_p, (errorX / m_yieldFunc[cateIndex]->Eval(currX)), (errorY / m_yieldFunc[cateIndex]->Eval(currX))); } gRatio->GetXaxis()->SetTitle("(Mass-100)/100 [GeV]"); gRatio->GetYaxis()->SetTitle("MC / Fit"); gRatio->GetXaxis()->SetTitleOffset(0.95); gRatio->GetYaxis()->SetTitleOffset(0.7); gRatio->GetXaxis()->SetTitleSize(0.1); gRatio->GetYaxis()->SetTitleSize(0.1); gRatio->GetXaxis()->SetLabelSize(0.1); gRatio->GetYaxis()->SetLabelSize(0.1); gRatio->GetYaxis()->SetNdivisions(4); gRatio->GetXaxis() ->SetRangeUser(m_yieldGraph[cateIndex]->GetXaxis()->GetXmin(), m_yieldGraph[cateIndex]->GetXaxis()->GetXmin()); gRatio->Draw("AEP"); TLine *line = new TLine(); line->SetLineStyle(1); line->SetLineWidth(1); line->SetLineColor(kBlue); line->DrawLine(gRatio->GetXaxis()->GetXmin(), 1, gRatio->GetXaxis()->GetXmax(), 1); can->Print(Form("%s/plot_paramYield_%sc%d%s", m_directory.Data(), m_signalType.Data(), cateIndex, m_fileFormat.Data())); delete can; } /** ----------------------------------------------------------------------------- Prints the mean and standard deviation for the signal in each category. NOTE: The standard deviation is the actual interval around the peak containing 68.2% of the signal events, and not the shape width parameter. @param resonanceMass - The value of the resonance mass for which the parameter values should be printed. */ void SigParam::printResTable(double resonanceMass) { TString tableLocation = Form("%s/latexTable.txt", m_directory.Data()); std::ofstream latexTable(tableLocation); latexTable << "\\begin{table}[!htb]" << std::endl; latexTable << "\\caption{Mean and resolution for the PDF in each category.}" << std::endl; latexTable << "\\label{tab:fitMeanAndRes}" << std::endl; latexTable << "\\centering" << std::endl; latexTable << "\\begin{tabular}{lcc}" << std::endl; latexTable << "\\hline" << std::endl; latexTable << "Category & Mean [GeV] & Resolution [GeV] \\\\" << std::endl; latexTable << "\\hline" << std::endl; latexTable << "\\hline" << std::endl; // loop over categories, print mean and resoultion for each. for (int i_c = 0; i_c < m_nCategories; i_c++) { double currMean = getMeanOrStdDev("Mean", resonanceMass, i_c); double currSigma = getMeanOrStdDev("StdDev", resonanceMass, i_c); if ((int)m_cateNames.size() == m_nCategories) { latexTable << m_cateNames[i_c] << " & " << currMean << " & " << currSigma << " \\\\" << std::endl; } else { latexTable << "category " << i_c << " & " << currMean << " & " << currSigma << " \\\\" << std::endl; } } latexTable << "\\hline" << std::endl; latexTable << "\\end{tabular}" << std::endl; latexTable << "\\end{table}" << std::endl; latexTable.close(); std::cout << "SigParam: Printed LaTex table: " << tableLocation << std::endl; } /** ----------------------------------------------------------------------------- Create a regularized mass variable that helps minimizers converge. @param resonanceMass - The mass value in GeV. @return - The regularized mass mR = (m-100)/100; */ double SigParam::regularizedMass(double resonanceMass) { return ((resonanceMass - 100.0) / 100.0); } /** ----------------------------------------------------------------------------- Create the resonance shape corresponding to a single mass point in a single analysis category. The signal will be stored in the class workspace. @param resonanceMass - the truth mass of the resonance. @param cateIndex - the index of the category to fit. @param function - the functional form of the resonance. */ void SigParam::resonanceCreator(double resonanceMass, int cateIndex, TString function) { if (m_verbose) { std::cout << "SigParam: Adding resonance to workspace" << "\tresonanceMass: " << resonanceMass << "\tcategory: " << cateIndex << std::endl; } m_currFunction = function; m_ws->var("functionName")->SetTitle(m_currFunction); // Check that the dataset has been defined and is not empty. if (!dataExists(resonanceMass, cateIndex) && !function.Contains("Parameterized")) { std::cout << "SigParam: Cannot fit resonance, no dataset." << std::endl; exit(0); } TString currKey = getKey(resonanceMass, cateIndex); TString suffix = (function.Contains("Parameterized")) ? Form("%sc%d", m_signalType.Data(), cateIndex) : Form("%s%s", m_signalType.Data(), currKey.Data()); TString obsName = (function.Contains("Parameterized")) ? "m_yy" : Form("m_yy_%s",currKey.Data()); // Define the Double Crystal Ball + Landau shape: if (function.Contains("DoubleCBLA")) { // Double-CB component: m_ws->factory(Form("HggTwoSidedCBPdf::pdfDCB_%s(%s, prod::muCB_%s(muCBNom_%s%s), prod::sigmaCB_%s(sigmaCBNom_%s%s), alphaCBLo_%s, nCBLo_%sc%d, alphaCBHi_%s, nCBHi_%sc%d)", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), m_signalType.Data(), cateIndex)); // Landau component: m_ws->factory(Form("RooLandau::pdfLA_%s(%s, prod::muLA_%s(muLANom_%s%s), prod::sigmaLA_%s(sigmaLANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Double Crystal Ball + Landau: m_ws->factory(Form("SUM::sigPdf_%s(fracCB_%sc%d*pdfDCB_%s,pdfLA_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Define the Bifurcated Gaussian + Landau shape: else if (function.Contains("BifurGALA")) { // Bifurcated Gaussian component: m_ws->factory(Form("RooBifurGauss::pdfBGA_%s(%s, prod::muGA_%s(muGANom_%s%s), prod::sigmaGALow_%s(sigmaGALowNom_%s%s), prod::sigmaGAHi_%s(sigmaGAHiNom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Landau component: m_ws->factory(Form("RooLandau::pdfLA_%s(%s, prod::muLA_%s(muLANom_%s%s), prod::sigmaLA_%s(sigmaLANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Gaussian + Landau: m_ws->factory(Form("SUM::sigPdf_%s(fracGA_%sc%d*pdfBGA_%s,pdfLA_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Define the Gaussian + Landau shape: else if (function.Contains("GALA")) { // Gaussian component: m_ws->factory(Form("RooGaussian::pdfGA_%s(%s, prod::muGA_%s(muGANom_%s%s), prod::sigmaGA_%s(sigmaGANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Landau component: m_ws->factory(Form("RooLandau::pdfLA_%s(%s, prod::muLA_%s(muLANom_%s%s), prod::sigmaLA_%s(sigmaLANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Gaussian + Landau: m_ws->factory(Form("SUM::sigPdf_%s(fracGA_%sc%d*pdfGA_%s,pdfLA_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Define the Modified Landau shape: else if (function.Contains("LandauMod")) { m_ws->factory(Form("RooLandau::sigPdf_%s(%s, prod::muLA_%s(muLANom_%s%s), sum::sigmaLA_%s(prod::a_sigmaLA_%s(sigmaLANom_%s%s),prod::b_sigmaLA_%s(alphaLA_%s,%s)))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), suffix.Data(), obsName.Data())); } // Define the Crystal Ball + Gaussian shape: else if (function.Contains("CBGA")) { // Cystal Ball component: m_ws->factory(Form("RooCBShape::pdfCB_%s(%s, prod::muCB_%s(muCBNom_%s%s), prod::sigmaCB_%s(sigmaCBNom_%s%s), alphaCB_%s, nCB_%sc%d)", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), m_signalType.Data(), cateIndex)); // Gaussian component: if (m_sameCBGAMean) { m_ws->factory(Form("RooGaussian::pdfGA_%s(%s, prod::muGA_%s(muCBNom_%s%s), prod::sigmaGA_%s(sigmaGANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); } else { m_ws->factory(Form("RooGaussian::pdfGA_%s(%s, prod::muGA_%s(muGANom_%s%s), prod::sigmaGA_%s(sigmaGANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); } // Crystal Ball + Gaussian: m_ws->factory(Form("SUM::sigPdf_%s(fracCB_%sc%d*pdfCB_%s,pdfGA_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Define double-sided Crystal Ball shape: else if (function.Contains("DoubleCB")) { m_ws->factory(Form("HggTwoSidedCBPdf::sigPdf_%s(%s, prod::muCB_%s(muCBNom_%s%s), prod::sigmaCB_%s(sigmaCBNom_%s%s), alphaCBLo_%s, nCBLo_%sc%d, alphaCBHi_%s, nCBHi_%sc%d)", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), m_signalType.Data(), cateIndex)); } else if (function.Contains("GAx3")) { m_ws->factory(Form("RooGaussian::pdfGA1_%s(%s, prod::muGA1_%s(muGA1Nom_%s%s), prod::sigmaGA1_%s(sigmaGA1Nom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); m_ws->factory(Form("RooGaussian::pdfGA2_%s(%s, prod::muGA2_%s(muGA2Nom_%s%s), prod::sigmaGA2_%s(sigmaGA2Nom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); m_ws->factory(Form("RooGaussian::pdfGA3_%s(%s, prod::muGA3_%s(muGA3Nom_%s%s), prod::sigmaGA3_%s(sigmaGA3Nom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); m_ws->factory(Form("SUM::sigPdf_%s(fracGA1_%sc%d*pdfGA1_%s,fracGA2_%sc%d*pdfGA2_%s,pdfGA3_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Bifurcated Gaussian shape: else if (function.Contains("BifurGA")) { m_ws->factory(Form("RooBifurGauss::sigPdf_%s(%s, prod::muGA_%s(muGANom_%s%s), prod::sigmaGALow_%s(sigmaGALowNom_%s%s), prod::sigmaGAHi_%s(sigmaGAHiNom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); } // Landau shape: else if (function.Contains("Landau")) { m_ws->factory(Form("RooLandau::sigPdf_%s(%s, prod::muLA_%s(muLANom_%s%s), prod::sigmaLA_%s(sigmaLANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); } // Double Landau shape: else if (function.Contains("LAx2")) { // Landau #1: m_ws->factory(Form("RooLandau::pdfLA1_%s(%s, prod::muLA1_%s(muLA1Nom_%s%s), prod::sigmaLA1_%s(sigmaLA1Nom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Landau #2: m_ws->factory(Form("RooLandau::pdfLA2_%s(%s, prod::muLA2_%s(muLA2Nom_%s%s), prod::sigmaLA2_%s(sigmaLA2Nom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Add the two Landaus: m_ws->factory(Form("SUM::sigPdf_%s(fracLA1_%sc%d*pdfLA1_%s,pdfLA2_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Crystal Ball + Landau: else if (function.Contains("CBLA")) { // Cystal Ball component: m_ws->factory(Form("RooCBShape::pdfCB_%s(%s, prod::muCB_%s(muCBNom_%s%s), prod::sigmaCB_%s(sigmaCBNom_%s%s), alphaCB_%s, nCB_%sc%d)", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), m_signalType.Data(), cateIndex)); // Landau component: m_ws->factory(Form("RooLandau::pdfLA_%s(%s, prod::muLA_%s(muLANom_%s%s), prod::sigmaLA_%s(sigmaLANom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Add the Crystal Ball and Landau: m_ws->factory(Form("SUM::sigPdf_%s(fracCB_%sc%d*pdfCB_%s,pdfLA_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } // Crystal-ball plus Voigt: else if (function.Contains("CBPlusVoigt")) { // Cystal Ball component: m_ws->factory(Form("RooCBShape::pdfCB_%s(%s, prod::muCB_%s(muCBNom_%s%s), prod::sigmaCB_%s(sigmaCBNom_%s%s), alphaCB_%s, nCB_%sc%d)", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), m_signalType.Data(), cateIndex)); // Voigtian component: m_ws->factory(Form("RooVoigtian::pdfVoigt_%s(%s, prod::muVoigt_%s(muVoigtNom_%s%s), prod::widthVoigt_%s(widthVoigtNom_%s%s), prod::sigmaVoigt_%s(sigmaVoigtNom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); // Crystal Ball + Voigtian: m_ws->factory(Form("SUM::sigPdf_%s(fracCB_%sc%d*pdfCB_%s,pdfVoigt_%s)", suffix.Data(), m_signalType.Data(), cateIndex, suffix.Data(), suffix.Data())); } else if (function.Contains("Voigt")) { m_ws->factory(Form("RooVoigtian::sigPdf_%s(%s, prod::muVoigt_%s(muVoigtNom_%s%s), prod::widthVoigt_%s(widthVoigtNom_%s%s), prod::sigmaVoigt_%s(sigmaVoigtNom_%s%s))", suffix.Data(), obsName.Data(), suffix.Data(), suffix.Data(), m_listMSS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data(), suffix.Data(), suffix.Data(), m_listMRS.Data())); } // Define the yield: if (!function.Contains("Parameterized")) { double yieldValue = (*m_ws->data(Form("data_%s",currKey.Data()))).sumEntries(); double yieldError = normalizationError(m_ws->data(Form("data_%s",currKey.Data()))); m_ws->factory(Form("sigYield_%s%s[%f]", m_signalType.Data(), currKey.Data(), yieldValue)); m_ws->var(Form("sigYield_%s%s", m_signalType.Data(), currKey.Data())) ->setError(yieldError); } if (m_verbose) { std::cout << "SigParam: Resonance successfully added." << std::endl; } } /** ----------------------------------------------------------------------------- Save parameterization workspace, list of parameter values, and signal yields. */ void SigParam::saveAll() { saveParameterization(); saveParameterList(); saveYieldList(); } /** ----------------------------------------------------------------------------- Save the workspace containing the parameterization data to file. */ void SigParam::saveParameterization() { TString workspaceName = Form("%s/res_%sworkspace.root", m_directory.Data(), m_signalType.Data()); m_ws->addClassDeclImportDir(Form("%s/../HGamTools/", gSystem->Getenv("ROOTCOREBIN"))); m_ws->importClassCode();// Import the PDF classes (HggTwoSidedCBPdf, etc.) m_ws->writeToFile(workspaceName); if (m_verbose) { std::cout << "SigParam: Saved workspace to " << workspaceName << std::endl; } } /** ----------------------------------------------------------------------------- Save a list of parameter names and values. */ void SigParam::saveParameterList() { TString paramListName = Form("%s/resonance_paramList.txt",m_directory.Data()); std::ofstream outFile(paramListName); RooArgSet args = m_ws->allVars(); TIterator *iterArgs = args.createIterator(); RooRealVar *currIter = NULL; while ((currIter = (RooRealVar*)iterArgs->Next())) { outFile << currIter->GetName() << " " << currIter->getVal() << std::endl; } outFile.close(); if (m_verbose) { std::cout << "SigParam: Saved param list to " << paramListName << std::endl; } } /** ----------------------------------------------------------------------------- Save a list of signal yields in all categories and at all mass points. */ void SigParam::saveYieldList() { TString yieldListName = Form("%s/resonance_yieldList.txt",m_directory.Data()); std::ofstream outFile(yieldListName); // Loop over datasets: for (int i_d = 0; i_d < (int)m_massCatePairs.size(); i_d++) { double currMass = (m_massCatePairs[i_d]).first; int currCate = (m_massCatePairs[i_d]).second; outFile << currMass << " " << currCate << " " << getYieldInCategory(currMass, currCate) << std::endl; } outFile.close(); if (m_verbose) { std::cout << "SigParam: saved yield list to " << yieldListName << std::endl; } } /** ----------------------------------------------------------------------------- Set the output directory for files. @param directory - The new input/output directory for files. */ void SigParam::setDirectory(TString directory) { TString simpSigName = m_signalType; simpSigName.Remove(simpSigName.Length()-1); if (directory.EqualTo("")) { if (simpSigName.EqualTo("")) m_directory = ""; else m_directory = simpSigName; } else { if (simpSigName.EqualTo("")) m_directory = directory; else m_directory = Form("%s/%s", directory.Data(), simpSigName.Data()); } // Create the output directory if it doesn't exist: system(Form("mkdir -vp %s", m_directory.Data())); if (m_verbose) { std::cout << "SigParam: I/O directory set to " << directory << std::endl; } } /** ----------------------------------------------------------------------------- Use a logarithmic Y axis for the plots. @param useLogYAxis - True iff plots should have log axis. */ void SigParam::setLogYAxis(bool useLogYAxis) { m_useLogYAxis = useLogYAxis; } /** ----------------------------------------------------------------------------- Set the size of the mass window for fitting and plotting. Specify the minimum and maximum of the window. @param fixWindow - True iff you want to use a fixed mass window for all fits. @param windowMin - The minimum mass of the fit window. @param windowMax - The maximum mass of the fit window. */ void SigParam::setMassWindowFixed(bool fixWindow, double windowMin, double windowMax) { m_fixWindow = fixWindow; m_windowMin = windowMin; m_windowMax = windowMax; } /** ----------------------------------------------------------------------------- Set the size of the mass window for fitting and plotting. Specify a fraction so that the window will be [(1-frac)*mass, (1+frac)*mass]. @param fraction - The fractional size of the mass window for fits and plots. */ void SigParam::setMassWindowSize(double fraction) { m_windowFraction = fraction; } /** ----------------------------------------------------------------------------- Make the parameters of a PDF free or fixed. @param pdf - The PDF containing the parameters to be freed/fixed. @param isConstant - True iff setting the parameters constant. */ void SigParam::setParamsConstant(RooAbsPdf* pdf, bool isConstant) { RooArgSet *currArgs = pdf->getVariables(); TIterator *iterArgs = currArgs->createIterator(); RooRealVar* currIter = NULL; while ((currIter = (RooRealVar*)iterArgs->Next())) { currIter->setConstant(isConstant); } } /** ----------------------------------------------------------------------------- Set the initial value and range for a fit parameter. @param paramName - The name of the shape parameter of interest. @param valueAndRange - A string with the initial value and range: "[a,b,c]". */ void SigParam::setParamState(TString paramName, TString valueAndRange) { m_paramState[paramName] = valueAndRange; } /** ----------------------------------------------------------------------------- Set the ATLAS label to be applied to the plots. @param atlasLabel - The plot label to be applied next to ATLAS. For example, "Internal", or "Simulation Internal", or "Simulation Preliminary"... */ void SigParam::setPlotATLASLabel(TString atlasLabel) { m_atlasLabel = atlasLabel; } /** ----------------------------------------------------------------------------- Set the format for plots. Examples are ".eps", ".pdf", ".png", etc. Standard ROOT file extensions. */ void SigParam::setPlotFormat(TString fileFormat) { m_fileFormat = fileFormat; } /** ----------------------------------------------------------------------------- Set the luminosity magnitude and units to be drawn in plots @param lumiLabel - The luminosity label to appear in plots. For example, "1.0 fb^{-1}" for 1fb-1 of data. Use LaTex formatting. */ void SigParam::setPlotLuminosity(TString lumiLabel) { m_lumiLabel = lumiLabel; } /** ----------------------------------------------------------------------------- Set the x-axis title (name of the observable over which the fit is performed. @param xAxisTitle - The title of the x-axis (observable name and unit). */ void SigParam::setPlotXAxisTitle(TString xAxisTitle) { m_xAxisTitle = xAxisTitle; } /** ----------------------------------------------------------------------------- Set the sub-plot option to a ratio plot instead of a subtraction plot. @param doRatioPlot - True iff you want to do a ratio plot. @param ratioMin - The minimum ratio plot y-axis range. @param ratioMax - The maximum ratio plot y-axis range. */ void SigParam::setRatioPlot(bool doRatioPlot, double ratioMin, double ratioMax){ m_doRatioPlot = doRatioPlot; m_ratioMin = ratioMin; m_ratioMax = ratioMax; } /** ----------------------------------------------------------------------------- @param setConstant - True iff the mass value should be constant in the model. @param resonanceMass - The constant resonance mass value. */ void SigParam::setResMassConstant(bool setConstant, double resonanceMass) { // Either set the resonance mass fixed or floating in the workspace: m_ws->var("mResonance")->setConstant(setConstant); m_ws->var("mResonance")->setVal(resonanceMass); if (m_verbose) { std::cout << "SigParam: setResMassConstant(" << setConstant << ", " << resonanceMass << ")" << std::endl; } } /** ----------------------------------------------------------------------------- @param setConstant - True iff the mass value should be constant in the model. */ void SigParam::setResMassConstant(bool setConstant) { setResMassConstant(setConstant, m_ws->var("mResonance")->getVal()); } /** ----------------------------------------------------------------------------- Set the signal type to avoid collisions when using many production modes. @param signalType - The type of signal. */ void SigParam::setSignalType(TString signalType) { if (signalType == "") m_signalType = ""; else m_signalType = Form("%s_", signalType.Data()); if (m_verbose) { std::cout << "SigParam: Signal type set to " << signalType << std::endl; } } /** ----------------------------------------------------------------------------- Define the functional form of the parameterization in the resonance mass of the given fit variable. @param varName - The name of the fit variable that has been parameterized. @param function - The functional form for parameterizing the given variable. The parameters should be listed as @0, @1, @2, while the observable mass should be written as "obs" and the truth mass of the resonance should be "mRes". Examples are shown in the class initialization. */ void SigParam::setVarParameterization(TString varName, TString function) { m_varParameterization[varName] = function; if (m_verbose) { std::cout << "SigParam: Setting " << varName << " parameterization to " << function << std::endl; } } /** ----------------------------------------------------------------------------- Tell the program whether or not to use the same value for the Crystal Ball and Gaussian means. @param sameCBGAMean - True iff the same mean value should be used. */ void SigParam::useCommonCBGAMean(bool sameCBGAMean) { m_sameCBGAMean = sameCBGAMean; if (m_verbose) { std::cout << "SigParam: Use common mean for CB and GA = " << sameCBGAMean << std::endl; } } /** ----------------------------------------------------------------------------- Get the variables associated with the given resonance PDF. @param function - The functional form of the resonance. @return - A list of the variables for the PDF. */ std::vector<TString> SigParam::variablesForFunction(TString function) { // Check that the function is defined before retrieving variables: if (!functionIsDefined(function)) { std::cout << "SigParam: Undefined resonance PDF " << function << std::endl; exit(0); } std::vector<TString> result; result.clear(); // Double Crystal Ball-plus Landau specific parameters: if (function.Contains("DoubleCBLA")) { result.push_back("muCBNom"); result.push_back("sigmaCBNom"); result.push_back("alphaCBLo"); result.push_back("alphaCBHi"); result.push_back("nCBLo"); result.push_back("nCBHi"); result.push_back("fracCB"); result.push_back("muLANom"); result.push_back("sigmaLANom"); } // Bifurcated Gaussian plus Landau specific parameters: else if (function.Contains("BifurGALA")) { result.push_back("muGANom"); result.push_back("sigmaGALowNom"); result.push_back("sigmaGAHiNom"); result.push_back("fracGA"); result.push_back("muLANom"); result.push_back("sigmaLANom"); } // Gaussian plus Landau-specific parameters: else if (function.Contains("GALA")) { result.push_back("muGANom"); result.push_back("sigmaGANom"); result.push_back("fracGA"); result.push_back("muLANom"); result.push_back("sigmaLANom"); } // Modified Landau parameters: else if (function.Contains("LandauMod")) { result.push_back("muLANom"); result.push_back("sigmaLANom"); result.push_back("alphaLA"); } // Crystal Ball + Gaussian-specific parameters: else if (function.Contains("CBGA")) { result.push_back("muCBNom"); result.push_back("sigmaCBNom"); result.push_back("alphaCB"); result.push_back("nCB"); result.push_back("fracCB"); if (!m_sameCBGAMean) result.push_back("muGANom"); result.push_back("sigmaGANom"); } // Double Crystal Ball-specific parameters: else if (function.Contains("DoubleCB")) { result.push_back("muCBNom"); result.push_back("sigmaCBNom"); result.push_back("alphaCBLo"); result.push_back("alphaCBHi"); result.push_back("nCBLo"); result.push_back("nCBHi"); } // Triple Gaussian-specific parameters: else if (function.Contains("GAx3")) { result.push_back("muGA1Nom"); result.push_back("muGA2Nom"); result.push_back("muGA3Nom"); result.push_back("sigmaGA1Nom"); result.push_back("sigmaGA2Nom"); result.push_back("sigmaGA3Nom"); result.push_back("fracGA1"); result.push_back("fracGA2"); } // Bifurcated Gaussian-specific parameters: else if (function.Contains("BifurGA")) { result.push_back("muGANom"); result.push_back("sigmaGALowNom"); result.push_back("sigmaGAHiNom"); } // Landau-specific parameters: else if (function.Contains("Landau")) { result.push_back("muLANom"); result.push_back("sigmaLANom"); } // Double Landau-specific parameters: else if (function.Contains("LAx2")) { result.push_back("muLA1Nom"); result.push_back("muLA2Nom"); result.push_back("sigmaLA1Nom"); result.push_back("sigmaLA2Nom"); result.push_back("fracLA1"); } // Crystal Ball + Landau-specific parameters: else if (function.Contains("CBLA")) { result.push_back("muCBNom"); result.push_back("sigmaCBNom"); result.push_back("alphaCB"); result.push_back("nCB"); result.push_back("fracCB"); result.push_back("muLANom"); result.push_back("sigmaLANom"); } // Crystal-Ball plus Voigtian specific parameters: else if (function.Contains("CBPlusVoigt")) { result.push_back("muCBNom"); result.push_back("sigmaCBNom"); result.push_back("alphaCB"); result.push_back("nCB"); result.push_back("fracCB"); result.push_back("muVoigtNom"); result.push_back("widthVoigtNom"); result.push_back("sigmaVoigtNom"); } // Voigtian specific parameters: else if (function.Contains("Voigt")) { result.push_back("muVoigtNom"); result.push_back("widthVoigtNom"); result.push_back("sigmaVoigtNom"); } else { std::cout << "SigParam: Undefined resonance PDF " << function << std::endl; exit(0); } return result; } /** ----------------------------------------------------------------------------- Sets the std::cout print level. @param beVerbose - True iff you want a lot of spammy text. */ void SigParam::verbosity(bool beVerbose) { m_verbose = beVerbose; if (m_verbose) { std::cout << "SigParam: m_verbosity = " << m_verbose << std::endl; } }
/* * Copyright (c) 2004-present, Facebook, 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 "fboss/lib/usb/PCA9548MuxedBus.h" namespace facebook { namespace fboss { void MuxChannel::select() { mux->select(channel); } void QsfpMux::clear(bool force) { // factor in selected channel auto selected = mux_.selected(); if (!selected && force) { // nothing is selected, but clear was called with // force=true. Let's clear everything in this case. selected = 0b11111111; } else if (!selected) { return; } for (uint8_t channel = 0; selected; selected >>= 1, ++channel) { if (selected % 2 == 1) { pca9548_helpers::clearLayer(children(channel)); } } mux_.unselectAll(); } void QsfpMux::registerChildMux( CP2112Intf* dev, uint8_t channel, uint8_t address) { children_[channel].push_back( std::make_unique<QsfpMux>(dev, address, this, channel)); } namespace pca9548_helpers { void clearLayer(MuxLayer& layer, bool force) { for (auto& mux : layer) { mux->clear(force); } } void selectPath(Path::iterator begin, Path::iterator end) { for (auto it = begin; it != end; ++it) { (*it)->select(); } } } // namespace pca9548_helpers } // namespace fboss } // namespace facebook
/* * Copyright (C) 2013 The Libphonenumber Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "phonenumbers/short_metadata.h" namespace i18n { namespace phonenumbers { namespace { static const unsigned char data[] = { 0x0A, 0x6D, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x43, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0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0x14, 0x12, 0x0B, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x45, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x1A, 0x12, 0x13, 0x31, 0x31, 0x32, 0x7C, 0x34, 0x34, 0x35, 0x5B, 0x31, 0x36, 0x5D, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0F, 0x12, 0x05, 0x34, 0x34, 0x35, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x34, 0x35, 0x30, 0x48, 0x04, 0x0A, 0xA8, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x13, 0x12, 0x0A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x39, 0x29, 0x32, 0x03, 0x31, 0x30, 0x32, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x46, 0xDA, 0x01, 0x13, 0x12, 0x0A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x39, 0x29, 0x32, 0x03, 0x31, 0x30, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x17, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x39, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x30, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x80, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x47, 0xDA, 0x01, 0x11, 0x12, 0x0A, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x37, 0x36, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0x6B, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x49, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0x87, 0x02, 0x0A, 0x15, 0x12, 0x0B, 0x5B, 0x31, 0x35, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x30, 0x12, 0x25, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x5B, 0x30, 0x31, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x33, 0x5B, 0x31, 0x35, 0x5D, 0x7C, 0x34, 0x31, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x06, 0x2A, 0x11, 0x12, 0x06, 0x35, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x05, 0x35, 0x30, 0x30, 0x30, 0x30, 0x48, 0x05, 0x4A, 0x02, 0x41, 0x4C, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x32, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x55, 0x12, 0x4E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x36, 0x35, 0x5C, 0x64, 0x7C, 0x38, 0x39, 0x5B, 0x31, 0x32, 0x5D, 0x29, 0x7C, 0x35, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x34, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x32, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x32, 0x33, 0x32, 0x03, 0x31, 0x32, 0x33, 0x48, 0x03, 0x8A, 0x02, 0x15, 0x12, 0x0A, 0x31, 0x33, 0x31, 0x7C, 0x35, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x03, 0x31, 0x33, 0x31, 0x48, 0x03, 0x48, 0x05, 0x0A, 0xA4, 0x01, 0x0A, 0x14, 0x12, 0x0C, 0x5B, 0x31, 0x34, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x10, 0x12, 0x07, 0x31, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x4D, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x1D, 0x12, 0x16, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x38, 0x5B, 0x31, 0x2D, 0x37, 0x5D, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x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0x32, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x31, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x2D, 0x39, 0x5D, 0x3F, 0x29, 0x32, 0x03, 0x31, 0x31, 0x31, 0x48, 0x02, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x52, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x30, 0x5B, 0x30, 0x31, 0x37, 0x5D, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x38, 0x12, 0x31, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x33, 0x35, 0x2D, 0x37, 0x5D, 0x7C, 0x31, 0x5B, 0x30, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x32, 0x5B, 0x31, 0x35, 0x5D, 0x7C, 0x39, 0x29, 0x7C, 0x33, 0x33, 0x37, 0x32, 0x7C, 0x38, 0x39, 0x33, 0x33, 0x38, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x32, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x38, 0x39, 0x33, 0x33, 0x38, 0x32, 0x05, 0x38, 0x39, 0x33, 0x33, 0x38, 0x48, 0x05, 0x8A, 0x02, 0x16, 0x12, 0x0A, 0x33, 0x33, 0x37, 0x32, 0x7C, 0x38, 0x39, 0x33, 0x33, 0x38, 0x32, 0x04, 0x33, 0x33, 0x37, 0x32, 0x48, 0x04, 0x48, 0x05, 0x0A, 0x89, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x34, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x53, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x10, 0x12, 0x09, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x0A, 0xC9, 0x01, 0x0A, 0x15, 0x12, 0x0F, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x06, 0x22, 0x24, 0x12, 0x18, 0x31, 0x31, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x54, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x7C, 0x33, 0x33, 0x7C, 0x34, 0x34, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x32, 0x12, 0x2B, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x29, 0x7C, 0x32, 0x32, 0x7C, 0x33, 0x33, 0x7C, 0x34, 0x34, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xD9, 0x02, 0x0A, 0x1B, 0x12, 0x0D, 0x5B, 0x30, 0x2D, 0x32, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x37, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x48, 0x07, 0x48, 0x08, 0x22, 0x20, 0x12, 0x13, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x38, 0x38, 0x38, 0x35, 0x7C, 0x35, 0x35, 0x35, 0x29, 0x7C, 0x37, 0x33, 0x33, 0x32, 0x03, 0x37, 0x33, 0x33, 0x48, 0x03, 0x48, 0x04, 0x48, 0x07, 0x2A, 0x27, 0x12, 0x17, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x28, 0x3F, 0x3A, 0x33, 0x34, 0x7C, 0x34, 0x35, 0x36, 0x29, 0x7C, 0x39, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x29, 0x32, 0x06, 0x31, 0x39, 0x31, 0x31, 0x32, 0x33, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x4A, 0x02, 0x41, 0x55, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x6D, 0x12, 0x66, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x32, 0x7C, 0x39, 0x5B, 0x34, 0x36, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x33, 0x5D, 0x5C, 0x64, 0x7C, 0x34, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x7C, 0x35, 0x5C, 0x64, 0x7B, 0x33, 0x2C, 0x34, 0x7D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x5B, 0x30, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x29, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x39, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x36, 0x7D, 0x29, 0x7C, 0x32, 0x32, 0x35, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x33, 0x33, 0x7C, 0x36, 0x37, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x26, 0x12, 0x19, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x32, 0x34, 0x37, 0x33, 0x33, 0x29, 0x7C, 0x32, 0x32, 0x35, 0x7C, 0x37, 0x36, 0x37, 0x32, 0x03, 0x32, 0x32, 0x35, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0xFA, 0x01, 0x1B, 0x12, 0x0F, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x38, 0x38, 0x38, 0x35, 0x7C, 0x35, 0x35, 0x35, 0x29, 0x32, 0x04, 0x31, 0x35, 0x35, 0x35, 0x48, 0x04, 0x48, 0x07, 0x8A, 0x02, 0x19, 0x12, 0x09, 0x31, 0x39, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x36, 0x7D, 0x32, 0x06, 0x31, 0x39, 0x31, 0x31, 0x32, 0x33, 0x48, 0x06, 0x48, 0x07, 0x48, 0x08, 0x0A, 0x80, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0E, 0x12, 0x07, 0x31, 0x30, 0x30, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x30, 0x30, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x57, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x30, 0x30, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x30, 0x30, 0xEA, 0x01, 0x15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0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xBF, 0x01, 0x0A, 0x12, 0x12, 0x0C, 0x5B, 0x31, 0x34, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x41, 0x5A, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x22, 0x12, 0x1B, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x38, 0x30, 0x29, 0x30, 0x32, 0x03, 0x31, 0x30, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x17, 0x12, 0x0D, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x38, 0x30, 0x29, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x17, 0x12, 0x0D, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x38, 0x30, 0x29, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x0A, 0xE6, 0x01, 0x0A, 0x12, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x14, 0x12, 0x08, 0x31, 0x31, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x41, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x32, 0x5B, 0x32, 0x2D, 0x34, 0x5D, 0x32, 0x03, 0x31, 0x32, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x6B, 0x12, 0x64, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x32, 0x7D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x37, 0x5D, 0x7C, 0x5B, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x32, 0x36, 0x5D, 0x7C, 0x5B, 0x37, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x32, 0x7D, 0x29, 0x7C, 0x5B, 0x33,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0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xBF, 0x02, 0x0A, 0x15, 0x12, 0x0D, 0x5B, 0x31, 0x35, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x0C, 0x12, 0x03, 0x31, 0x30, 0x36, 0x32, 0x03, 0x31, 0x30, 0x36, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x44, 0xDA, 0x01, 0x1B, 0x12, 0x12, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x9E, 0x01, 0x12, 0x96, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x33, 0x39, 0x5D, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x5B, 0x31, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x36, 0x28, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x2D, 0x32, 0x39, 0x5D, 0x29, 0x7C, 0x31, 0x5B, 0x31, 0x36, 0x2D, 0x39, 0x5D, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x34, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x2D, 0x35, 0x5D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x5C, 0x64, 0x3F, 0x7C, 0x33, 0x5C, 0x64, 0x7C, 0x36, 0x5B, 0x33, 0x2D, 0x36, 0x5D, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x35, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x38, 0x36, 0x7C, 0x35, 0x30, 0x31, 0x32, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x35, 0x39, 0x34, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x31, 0x30, 0x33, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x27, 0x12, 0x1B, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x5B, 0x31, 0x33, 0x5D, 0x29, 0x7C, 0x37, 0x38, 0x36, 0x7C, 0x35, 0x30, 0x31, 0x32, 0x7C, 0x39, 0x35, 0x39, 0x34, 0x32, 0x04, 0x39, 0x35, 0x39, 0x34, 0x48, 0x03, 0x48, 0x04, 0x8A, 0x02, 0x0E, 0x12, 0x04, 0x39, 0x35, 0x39, 0x34, 0x32, 0x04, 0x39, 0x35, 0x39, 0x34, 0x48, 0x04, 0x0A, 0xC2, 0x03, 0x0A, 0x22, 0x12, 0x1A, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x22, 0x3C, 0x12, 0x35, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x32, 0x35, 0x2D, 0x38, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x38, 0x31, 0x33, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x03, 0x31, 0x30, 0x30, 0x2A, 0x3D, 0x12, 0x33, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x33, 0x5D, 0x34, 0x7C, 0x31, 0x5C, 0x64, 0x29, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x5D, 0x5C, 0x64, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x7C, 0x31, 0x5C, 0x64, 0x29, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x04, 0x31, 0x32, 0x30, 0x34, 0x48, 0x04, 0x4A, 0x02, 0x42, 0x45, 0xDA, 0x01, 0x16, 0x12, 0x0D, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x30, 0x30, 0x48, 0x03, 0xEA, 0x01, 0xCD, 0x01, 0x12, 0xC5, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x38, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x37, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x37, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 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0x7D, 0x7C, 0x5B, 0x31, 0x39, 0x5D, 0x39, 0x39, 0x32, 0x03, 0x31, 0x39, 0x39, 0x2A, 0x16, 0x12, 0x0B, 0x39, 0x5B, 0x31, 0x34, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x39, 0x31, 0x30, 0x30, 0x30, 0x48, 0x05, 0x4A, 0x02, 0x42, 0x48, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x5B, 0x31, 0x39, 0x5D, 0x39, 0x39, 0x32, 0x03, 0x31, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x5B, 0x12, 0x54, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x36, 0x37, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x35, 0x38, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x5C, 0x64, 0x7C, 0x31, 0x32, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x31, 0x7C, 0x38, 0x5B, 0x31, 0x38, 0x5D, 0x7C, 0x39, 0x5B, 0x31, 0x36, 0x39, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x34, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x34, 0x38, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x22, 0x12, 0x17, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x36, 0x37, 0x5D, 0x5C, 0x64, 0x7C, 0x38, 0x38, 0x30, 0x7C, 0x39, 0x38, 0x35, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x30, 0x36, 0x30, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x1A, 0x12, 0x0F, 0x28, 0x3F, 0x3A, 0x38, 0x38, 0x30, 0x7C, 0x39, 0x38, 0x35, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x38, 0x38, 0x30, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xD5, 0x01, 0x0A, 0x13, 0x12, 0x0D, 0x5B, 0x31, 0x36, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x14, 0x12, 0x0B, 0x31, 0x31, 0x5B, 0x32, 0x33, 0x37, 0x5D, 0x7C, 0x36, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x49, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x32, 0x33, 0x37, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x3D, 0x12, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5C, 0x64, 0x7C, 0x35, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x32, 0x35, 0x36, 0x5D, 0x29, 0x7C, 0x36, 0x31, 0x31, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x7C, 0x37, 0x37, 0x7C, 0x39, 0x37, 0x39, 0x29, 0x7C, 0x38, 0x5B, 0x32, 0x38, 0x5D, 0x38, 0x7C, 0x39, 0x30, 0x30, 0x32, 0x03, 0x31, 0x31, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x1F, 0x12, 0x16, 0x36, 0x31, 0x31, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x38, 0x38, 0x38, 0x7C, 0x39, 0x30, 0x30, 0x32, 0x03, 0x36, 0x31, 0x31, 0x48, 0x03, 0x8A, 0x02, 0x13, 0x12, 0x0A, 0x28, 0x3F, 0x3A, 0x37, 0x31, 0x7C, 0x39, 0x30, 0x29, 0x30, 0x32, 0x03, 0x37, 0x31, 0x30, 0x48, 0x03, 0x0A, 0xAA, 0x01, 0x0A, 0x11, 0x12, 0x0B, 0x5B, 0x31, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x18, 0x12, 0x11, 0x31, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x7C, 0x37, 0x5B, 0x33, 0x2D, 0x35, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x31, 0x37, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x4A, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x37, 0x48, 0x03, 0xEA, 0x01, 0x27, 0x12, 0x20, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x36, 0x30, 0x29, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x35, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x31,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xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x4D, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x37, 0x36, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0x78, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x31, 0x33, 0x35, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x31, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x4E, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x31, 0x33, 0x35, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x31, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x31, 0x33, 0x35, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0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 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x51, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x37, 0x36, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0xE3, 0x04, 0x0A, 0x19, 0x12, 0x0F, 0x5B, 0x31, 0x32, 0x34, 0x2D, 0x36, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x25, 0x12, 0x1A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x35, 0x37, 0x7C, 0x38, 0x32, 0x38, 0x29, 0x32, 0x03, 0x31, 0x38, 0x31, 0x48, 0x03, 0x48, 0x04, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x52, 0xDA, 0x01, 0x1E, 0x12, 0x15, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x32, 0x38, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x39, 0x30, 0x48, 0x03, 0xEA, 0x01, 0xD2, 0x02, 0x12, 0xCA, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x2D, 0x35, 0x37, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x7C, 0x33, 0x5B, 0x31, 0x32, 0x34, 0x2D, 0x39, 0x5D, 0x7C, 0x34, 0x5B, 0x31, 0x2D, 0x33, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x35, 0x5B, 0x31, 0x2D, 0x34, 0x36, 0x38, 0x5D, 0x7C, 0x36, 0x5B, 0x31, 0x33, 0x39, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x34, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x31, 0x36, 0x38, 0x5D, 0x29, 0x7C, 0x35, 0x5B, 0x30, 0x2D, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x7C, 0x31, 0x5B, 0x30, 0x2D, 0x33, 0x35, 0x2D, 0x38, 0x5D, 0x3F, 0x7C, 0x32, 0x5B, 0x30, 0x31, 0x34, 0x35, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x33, 0x37, 0x5D, 0x3F, 0x7C, 0x34, 0x5B, 0x33, 0x37, 0x2D, 0x39, 0x5D, 0x3F, 0x7C, 0x35, 0x5B, 0x30, 0x2D, 0x33, 0x35, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x31, 0x36, 0x5D, 0x3F, 0x7C, 0x37, 0x5B, 0x31, 0x33, 0x37, 0x5D, 0x3F, 0x7C, 0x38, 0x5B, 0x35, 0x2D, 0x38, 0x5D, 0x7C, 0x39, 0x5B, 0x31, 0x33, 0x35, 0x39, 0x5D, 0x29, 0x29, 0x7C, 0x31, 0x5B, 0x32, 0x35, 0x2D, 0x38, 0x5D, 0x7C, 0x32, 0x5B, 0x33, 0x35, 0x37, 0x38, 0x39, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x34, 0x35, 0x36, 0x38, 0x5D, 0x7C, 0x33, 0x5B, 0x31, 0x32, 0x5D, 0x29, 0x7C, 0x34, 0x5B, 0x31, 0x32, 0x35, 0x36, 0x38, 0x5D, 0x7C, 0x35, 0x5C, 0x64, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x38, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x2D, 0x34, 0x37, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x37, 0x28, 0x3F, 0x3A, 0x33, 0x33, 0x30, 0x7C, 0x38, 0x37, 0x38, 0x29, 0x7C, 0x38, 0x35, 0x39, 0x35, 0x39, 0x3F, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x30, 0x34, 0x3F, 0x7C, 0x31, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x35, 0x37, 0x7C, 0x38, 0x32, 0x38, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x35, 0x35, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x31, 0x30, 0x30, 0x30, 0x30, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x36, 0x38, 0xF2, 0x01, 0x16, 0x12, 0x09, 0x31, 0x30, 0x32, 0x7C, 0x32, 0x37, 0x33, 0x33, 0x30, 0x32, 0x05, 0x32, 0x37, 0x33, 0x33, 0x30, 0x48, 0x03, 0x48, 0x05, 0xFA, 0x01, 0x33, 0x12, 0x24, 0x31, 0x35, 0x31, 0x7C, 0x32, 0x37, 0x38, 0x37, 0x38, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x30, 0x34, 0x3F, 0x7C, 0x31, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x35, 0x37, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x35, 0x35, 0x32, 0x05, 0x32, 0x37, 0x38, 0x37, 0x38, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x47, 0x12, 0x38, 0x32, 0x28, 0x3F, 0x3A, 0x37, 0x28, 0x3F, 0x3A, 0x33, 0x33, 0x30, 0x7C, 0x38, 0x37, 0x38, 0x29, 0x7C, 0x38, 0x35, 0x39, 0x35, 0x39, 0x3F, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x32, 0x38, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x31, 0x30, 0x30, 0x30, 0x30, 0x29, 0x32, 0x05, 0x32, 0x37, 0x38, 0x37, 0x38, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x0A, 0x73, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 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FF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x0A, 0x9F, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x10, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x37, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x42, 0x57, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x37, 0x48, 0x03, 0xEA, 0x01, 0x14, 0x12, 0x0D, 0x31, 0x33, 0x31, 0x32, 0x33, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x37, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x31, 0x33, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x31, 0x33, 0x31, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x31, 0x33, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0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, 0x31, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x41, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x4B, 0x12, 0x42, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x29, 0x7C, 0x5B, 0x32, 0x35, 0x2D, 0x39, 0x5D, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x7C, 0x30, 0x30, 0x30, 0x30, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x31, 0x31, 0x29, 0x7C, 0x34, 0x31, 0x31, 0x32, 0x05, 0x31, 0x32, 0x33, 0x34, 0x35, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x09, 0x5B, 0x32, 0x33, 0x35, 0x36, 0x37, 0x5D, 0x31, 0x31, 0x32, 0x03, 0x36, 0x31, 0x31, 0x48, 0x03, 0x8A, 0x02, 0x34, 0x12, 0x25, 0x5B, 0x31, 0x32, 0x35, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x7C, 0x30, 0x30, 0x30, 0x30, 0x5C,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, 0x38, 0x38, 0x29, 0x32, 0x03, 0x31, 0x31, 0x33, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x44, 0xDA, 0x01, 0x1A, 0x12, 0x11, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x34, 0x38, 0x5D, 0x7C, 0x37, 0x37, 0x7C, 0x38, 0x38, 0x29, 0x32, 0x03, 0x31, 0x31, 0x33, 0x48, 0x03, 0xEA, 0x01, 0x21, 0x12, 0x1A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x34, 0x38, 0x5D, 0x7C, 0x32, 0x33, 0x7C, 0x37, 0x37, 0x7C, 0x38, 0x38, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x31, 0x33, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x95, 0x01, 0x0A, 0x0E, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x16, 0x12, 0x0F, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x7C, 0x32, 0x32, 0x5C, 0x64, 0x29, 0x32, 0x03, 0x31, 0x31, 0x37, 0x2A, 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, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xF7, 0x02, 0x0A, 0x16, 0x12, 0x0C, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x2E, 0x12, 0x21, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x37, 0x38, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x34, 0x5B, 0x34, 0x37, 0x5D, 0x29, 0x7C, 0x35, 0x32, 0x30, 0x30, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x2A, 0x29, 0x12, 0x1C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x35, 0x38, 0x39, 0x5D, 0x29, 0x5C, 0x64, 0x7C, 0x35, 0x34, 0x33, 0x7C, 0x38, 0x33, 0x31, 0x31, 0x31, 0x32, 0x03, 0x35, 0x34, 0x33, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x43, 0x48, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x37, 0x38, 0x5D, 0x7C, 0x34, 0x34, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x7C, 0x12, 0x75, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x37, 0x38, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x37, 0x38, 0x5D, 0x7C, 0x34, 0x35, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x33, 0x2D, 0x35, 0x37, 0x5D, 0x7C, 0x31, 0x5B, 0x34, 0x35, 0x5D, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x5B, 0x31, 0x2D, 0x34, 0x36, 0x5D, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x5B, 0x31, 0x38, 0x39, 0x5D, 0x7C, 0x35, 0x30, 0x7C, 0x37, 0x7C, 0x38, 0x5B, 0x30, 0x38, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x2E, 0x12, 0x23, 0x31, 0x28, 0x3F, 0x3A, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x33, 0x35, 0x5D, 0x7C, 0x31, 0x5C, 0x64, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x5B, 0x31, 0x2D, 0x34, 0x36, 0x5D, 0x29, 0x29, 0x32, 0x03, 0x31, 0x34, 0x30, 0x48, 0x03, 0x48, 0x04, 0xFA, 0x01, 0x17, 0x12, 0x0C, 0x35, 0x28, 0x3F, 0x3A, 0x32, 0x30, 0x5C, 0x64, 0x7C, 0x33, 0x35, 0x29, 0x32, 0x03, 0x35, 0x33, 0x35, 0x48, 0x03, 0x48, 0x04, 0x8A, 0x02, 0x19, 0x12, 0x0C, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x32, 0x03, 0x32, 0x30, 0x30, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x0A, 0xAC, 0x01, 0x0A, 0x11, 0x12, 0x0B, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x5B, 0x37, 0x38, 0x5D, 0x30, 0x29, 0x32, 0x03, 0x31, 0x31, 0x30, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x49, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x5B, 0x37, 0x38, 0x5D, 0x30, 0x29, 0x32, 0x03, 0x31, 0x31, 0x30, 0x48, 0x03, 0xEA, 0x01, 0x1C, 0x12, 0x15, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x5B, 0x37, 0x38, 0x5D, 0x30, 0x29, 0x7C, 0x34, 0x34, 0x34, 0x33, 0x32, 0x03, 0x31, 0x31, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0F, 0x12, 0x05, 0x34, 0x34, 0x34, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x34, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x0F, 0x12, 0x05, 0x34, 0x34, 0x34, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x34, 0x34, 0x30, 0x48, 0x04, 0x0A, 0x78, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x36, 0x38, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x36, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x4B, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x36, 0x38, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x36, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x36, 0x38, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x36, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x8C, 0x06, 0x0A, 0x14, 0x12, 0x0C, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x13, 0x12, 0x09, 0x31, 0x32, 0x31, 0x33, 0x7C, 0x34, 0x33, 0x34, 0x32, 0x32, 0x04, 0x34, 0x33, 0x34, 0x32, 0x48, 0x04, 0x2A, 0x9F, 0x02, 0x12, 0x92, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x30, 0x7C, 0x32, 0x31, 0x31, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x33, 0x7C, 0x5B, 0x33, 0x34, 0x38, 0x5D, 0x30, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x5D, 0x29, 0x7C, 0x34, 0x31, 0x37, 0x7C, 0x35, 0x36, 0x30, 0x7C, 0x38, 0x31, 0x38, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x39, 0x7C, 0x38, 0x30, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x32, 0x32, 0x7C, 0x32, 0x32, 0x5B, 0x34, 0x37, 0x5D, 0x7C, 0x33, 0x32, 0x33, 0x7C, 0x37, 0x37, 0x37, 0x7C, 0x38, 0x38, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x35, 0x31, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x31, 0x33, 0x32, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x7C, 0x37, 0x37, 0x7C, 0x39, 0x30, 0x29, 0x7C, 0x36, 0x36, 0x35, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x32, 0x7C, 0x32, 0x34, 0x33, 0x7C, 0x33, 0x36, 0x35, 0x36, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x35, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x35, 0x35, 0x34, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x34, 0x7C, 0x34, 0x31, 0x35, 0x34, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x36, 0x36, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x39, 0x39, 0x35, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x30, 0x30, 0x7C, 0x31, 0x33, 0x31, 0x7C, 0x32, 0x32, 0x32, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x36, 0x36, 0x29, 0x7C, 0x35, 0x30, 0x30, 0x7C, 0x36, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x38, 0x37, 0x38, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x31, 0x7C, 0x31, 0x31, 0x5B, 0x32, 0x38, 0x5D, 0x7C, 0x34, 0x38, 0x32, 0x7C, 0x38, 0x38, 0x39, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x31, 0x7C, 0x5B, 0x31, 0x32, 0x5D, 0x30, 0x30, 0x7C, 0x33, 0x33, 0x30, 0x29, 0x32, 0x04, 0x32, 0x32, 0x32, 0x34, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x43, 0x4C, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x33, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x33, 0x33, 0x48, 0x03, 0xEA, 0x01, 0xD3, 0x02, 0x12, 0xCB, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x3F, 0x30, 0x7C, 0x32, 0x31, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x36, 0x37, 0x39, 0x5D, 0x7C, 0x31, 0x33, 0x3F, 0x7C, 0x5B, 0x33, 0x34, 0x38, 0x5D, 0x30, 0x3F, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x5D, 0x3F, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x32, 0x2D, 0x36, 0x5D, 0x7C, 0x31, 0x37, 0x7C, 0x5B, 0x33, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x35, 0x36, 0x30, 0x7C, 0x38, 0x31, 0x38, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x39, 0x7C, 0x38, 0x30, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x7C, 0x31, 0x32, 0x32, 0x29, 0x7C, 0x32, 0x32, 0x5B, 0x34, 0x37, 0x5D, 0x7C, 0x33, 0x32, 0x33, 0x7C, 0x37, 0x37, 0x37, 0x7C, 0x38, 0x38, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x35, 0x31, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x31, 0x33, 0x32, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x7C, 0x33, 0x37, 0x7C, 0x37, 0x37, 0x7C, 0x39, 0x30, 0x29, 0x7C, 0x36, 0x36, 0x35, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x32, 0x7C, 0x32, 0x34, 0x33, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x34, 0x32, 0x7C, 0x36, 0x35, 0x36, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x35, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x35, 0x35, 0x34, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x34, 0x7C, 0x34, 0x31, 0x35, 0x34, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x36, 0x36, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x39, 0x39, 0x35, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x30, 0x30, 0x7C, 0x31, 0x33, 0x31, 0x7C, 0x32, 0x32, 0x32, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x36, 0x36, 0x29, 0x7C, 0x35, 0x30, 0x30, 0x7C, 0x36, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x38, 0x37, 0x38, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x31, 0x7C, 0x31, 0x31, 0x5B, 0x32, 0x38, 0x5D, 0x7C, 0x34, 0x38, 0x32, 0x7C, 0x38, 0x38, 0x39, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x31, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x30, 0x30, 0x29, 0x7C, 0x32, 0x30, 0x30, 0x7C, 0x33, 0x33, 0x30, 0x29, 0x32, 0x03, 0x31, 0x33, 0x39, 0xF2, 0x01, 0x13, 0x12, 0x09, 0x32, 0x30, 0x30, 0x31, 0x7C, 0x33, 0x33, 0x33, 0x37, 0x32, 0x04, 0x33, 0x33, 0x33, 0x37, 0x48, 0x04, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x26, 0x12, 0x1A, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x32, 0x34, 0x35, 0x36, 0x5D, 0x5C, 0x64, 0x3F, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x04, 0x35, 0x35, 0x37, 0x37, 0x48, 0x04, 0x48, 0x05, 0x0A, 0xAC, 0x01, 0x0A, 0x13, 0x12, 0x0B, 0x5B, 0x31, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x33, 0x7D, 0x48, 0x02, 0x48, 0x03, 0x48, 0x04, 0x22, 0x19, 0x12, 0x0F, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x37, 0x5D, 0x7C, 0x5B, 0x33, 0x37, 0x5D, 0x29, 0x32, 0x02, 0x31, 0x33, 0x48, 0x02, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x4D, 0xDA, 0x01, 0x19, 0x12, 0x0F, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x37, 0x5D, 0x7C, 0x5B, 0x33, 0x37, 0x5D, 0x29, 0x32, 0x02, 0x31, 0x33, 0x48, 0x02, 0x48, 0x03, 0xEA, 0x01, 0x1A, 0x12, 0x14, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x37, 0x5D, 0x7C, 0x5B, 0x33, 0x37, 0x5D, 0x29, 0x7C, 0x38, 0x37, 0x31, 0x31, 0x32, 0x02, 0x31, 0x33, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0F, 0x12, 0x05, 0x38, 0x37, 0x31, 0x5C, 0x64, 0x32, 0x04, 0x38, 0x37, 0x31, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x0F, 0x12, 0x05, 0x38, 0x37, 0x31, 0x5C, 0x64, 0x32, 0x04, 0x38, 0x37, 0x31, 0x30, 0x48, 0x04, 0x0A, 0xBC, 0x01, 0x0A, 0x1C, 0x12, 0x14, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x48, 0x06, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xF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FF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x4F, 0xDA, 0x01, 0x1C, 0x12, 0x13, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x39, 0x5D, 0x7C, 0x32, 0x33, 0x7C, 0x33, 0x32, 0x7C, 0x35, 0x36, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x45, 0x12, 0x3E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x31, 0x5B, 0x32, 0x35, 0x36, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x33, 0x35, 0x37, 0x5D, 0x7C, 0x33, 0x5B, 0x32, 0x37, 0x5D, 0x7C, 0x34, 0x5B, 0x34, 0x36, 0x37, 0x5D, 0x7C, 0x35, 0x5B, 0x33, 0x36, 0x5D, 0x7C, 0x36, 0x5B, 0x34, 0x35, 0x5D, 0x7C, 0x39, 0x35, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x35, 0x34, 0x33, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x16, 0x12, 0x0B, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x35, 0x34, 0x33, 0x32, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x8A, 0x02, 0x16, 0x12, 0x0B, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x35, 0x34, 0x33, 0x32, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x0A, 0xDB, 0x02, 0x0A, 0x13, 0x12, 0x0D, 0x5B, 0x31, 0x33, 0x35, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x52, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0xD0, 0x01, 0x12, 0xC7, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x35, 0x7C, 0x32, 0x5B, 0x32, 0x2D, 0x34, 0x36, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x2D, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x32, 0x7C, 0x33, 0x37, 0x7C, 0x5B, 0x34, 0x36, 0x5D, 0x36, 0x7C, 0x37, 0x5B, 0x35, 0x37, 0x5D, 0x7C, 0x38, 0x5B, 0x37, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x2D, 0x33, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x7C, 0x33, 0x34, 0x7C, 0x35, 0x35, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x31, 0x7C, 0x33, 0x33, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x5B, 0x34, 0x2D, 0x36, 0x5D, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x35, 0x7C, 0x35, 0x5B, 0x31, 0x35, 0x5D, 0x29, 0x7C, 0x36, 0x39, 0x33, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x5B, 0x37, 0x38, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x37, 0x29, 0x7C, 0x39, 0x37, 0x35, 0x29, 0x7C, 0x33, 0x38, 0x35, 0x35, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x7C, 0x34, 0x39, 0x29, 0x7C, 0x35, 0x31, 0x30, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x04, 0x31, 0x30, 0x32, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x22, 0x12, 0x18, 0x33, 0x38, 0x35, 0x35, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x7C, 0x34, 0x39, 0x29, 0x7C, 0x35, 0x31, 0x30, 0x29, 0x32, 0x04, 0x33, 0x38, 0x35, 0x35, 0x48, 0x04, 0x0A, 0x96, 0x01, 0x0A, 0x15, 0x12, 0x0F, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x06, 0x22, 0x0B,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0x33, 0x30, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x33, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x32, 0x03, 0x31, 0x33, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x80, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x57, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x37, 0x36, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0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FF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x43, 0x59, 0xDA, 0x01, 0x13, 0x12, 0x0A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x22, 0x12, 0x1B, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x29, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xE9, 0x01, 0x0A, 0x12, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x35, 0x12, 0x2A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x29, 0x7C, 0x35, 0x5B, 0x30, 0x35, 0x36, 0x38, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48,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0x5C, 0x64, 0x5C, 0x64, 0x3F, 0x48, 0x02, 0x48, 0x03, 0x22, 0x0D, 0x12, 0x05, 0x31, 0x5B, 0x34, 0x37, 0x5D, 0x32, 0x02, 0x31, 0x34, 0x48, 0x02, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x44, 0x5A, 0xDA, 0x01, 0x0D, 0x12, 0x05, 0x31, 0x5B, 0x34, 0x37, 0x5D, 0x32, 0x02, 0x31, 0x34, 0x48, 0x02, 0xEA, 0x01, 0x0F, 0x12, 0x09, 0x31, 0x5B, 0x34, 0x37, 0x5D, 0x7C, 0x37, 0x33, 0x30, 0x32, 0x02, 0x31, 0x34, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0C, 0x12, 0x03, 0x37, 0x33, 0x30, 0x32, 0x03, 0x37, 0x33, 0x30, 0x48, 0x03, 0x8A, 0x02, 0x0C, 0x12, 0x03, 0x37, 0x33, 0x30, 0x32, 0x03, 0x37, 0x33, 0x30, 0x48, 0x03, 0x0A, 0x8C, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x45, 0x43, 0xDA, 0x01, 0x18, 0x12, 0x11, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x18, 0x12, 0x11, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xF6, 0x0A, 0x0A, 0x12, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x97, 0x01, 0x12, 0x8F, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x35, 0x7C, 0x32, 0x38, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x34, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x31, 0x7C, 0x35, 0x5C, 0x64, 0x3F, 0x29, 0x7C, 0x36, 0x36, 0x30, 0x29, 0x7C, 0x34, 0x39, 0x32, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x33, 0x5D, 0x7C, 0x34, 0x31, 0x30, 0x7C, 0x35, 0x30, 0x31, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x32, 0x7C, 0x33, 0x33, 0x33, 0x7C, 0x36, 0x34, 0x34, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x32, 0x7C, 0x31, 0x32, 0x37, 0x7C, 0x38, 0x39, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x7C, 0x38, 0x5B, 0x35, 0x37, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x33, 0x34, 0x5D, 0x7C, 0x31, 0x34, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x30, 0x2A, 0xFC, 0x05, 0x12, 0xEE, 0x05, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x5B, 0x31, 0x32, 0x34, 0x35, 0x38, 0x5D, 0x5C, 0x64, 0x3F, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x36, 0x2D, 0x38, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x31, 0x5B, 0x30, 0x2D, 0x33, 0x36, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x36, 0x5B, 0x30, 0x36, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x35, 0x5B, 0x32, 0x35, 0x5D, 0x29, 0x7C, 0x5B, 0x33, 0x36, 0x37, 0x5D, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x34, 0x5D, 0x7C, 0x5B, 0x31, 0x32, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x34, 0x5B, 0x32, 0x34, 0x5D, 0x7C, 0x35, 0x34, 0x29, 0x7C, 0x35, 0x35, 0x5B, 0x31, 0x32, 0x34, 0x35, 0x37, 0x5D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x31, 0x5B, 0x31, 0x33, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x33, 0x5B, 0x33, 0x35, 0x36, 0x5D, 0x29, 0x7C, 0x31, 0x5B, 0x31, 0x33, 0x34, 0x37, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x33, 0x34, 0x37, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x32, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x7C, 0x38, 0x38, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x33, 0x35, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x34, 0x5B, 0x33, 0x34, 0x5D, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x31, 0x33, 0x34, 0x5D, 0x7C, 0x35, 0x5B, 0x30, 0x33, 0x35, 0x5D, 0x29, 0x7C, 0x36, 0x36, 0x36, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x34, 0x5C, 0x64, 0x3F, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x33, 0x35, 0x38, 0x5D, 0x7C, 0x31, 0x5B, 0x30, 0x32, 0x34, 0x5D, 0x7C, 0x35, 0x30, 0x7C, 0x37, 0x5C, 0x64, 0x3F, 0x29, 0x7C, 0x39, 0x30, 0x30, 0x29, 0x7C, 0x35, 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3F, 0x3A, 0x31, 0x5B, 0x31, 0x32, 0x37, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x32, 0x36, 0x38, 0x5D, 0x7C, 0x39, 0x5B, 0x32, 0x36, 0x39, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x5C, 0x64, 0x3F, 0x7C, 0x36, 0x39, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x36, 0x39, 0x5D, 0x29, 0x7C, 0x31, 0x5B, 0x31, 0x2D, 0x33, 0x36, 0x38, 0x39, 0x5D, 0x7C, 0x32, 0x31, 0x29, 0x29, 0x32, 0x03, 0x31, 0x32, 0x33, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x45, 0x45, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x30, 0x32, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x30, 0x48, 0x03, 0xEA, 0x01, 0xF6, 0x01, 0x12, 0xEE, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x35, 0x37, 0x39, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x5B, 0x31, 0x2D, 0x38, 0x5D, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x35, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x3F, 0x7C, 0x5B, 0x33, 0x36, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x36, 0x5D, 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0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x99, 0x01, 0x12, 0x8B, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x7C, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x30, 0x33, 0x35, 0x5D, 0x7C, 0x35, 0x5B, 0x31, 0x2D, 0x35, 0x39, 0x5D, 0x7C, 0x36, 0x5B, 0x32, 0x33, 0x36, 0x37, 0x39, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x32, 0x38, 0x5D, 0x7C, 0x38, 0x39, 0x29, 0x5C, 0x64, 0x29, 0x5C, 0x64, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x34, 0x34, 0x7C, 0x39, 0x30, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x3F, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x30, 0x32, 0x34, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x7C, 0x35, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x39, 0x5D, 0x7C, 0x36, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x37, 0x5B, 0x31, 0x32, 0x38, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x38, 0x39, 0x5D, 0x29, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x32, 0x36, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x0A, 0xAC, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x33, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x45, 0x47, 0xDA, 0x01, 0x16, 0x12, 0x0D, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x38, 0x30, 0x29, 0x32, 0x03, 0x31, 0x32, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x24, 0x12, 0x1D, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x5B, 0x36, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x38, 0x30, 0x29, 0x7C, 0x33, 0x34, 0x34, 0x30, 0x30, 0x32, 0x03, 0x31, 0x32, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x33, 0x34, 0x34, 0x30, 0x30, 0x32, 0x05, 0x33, 0x34, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x33, 0x34, 0x34, 0x30, 0x30, 0x32, 0x05, 0x33, 0x34, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x87, 0x01, 0x0A, 0x0C, 0x12, 0x06, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x3F, 0x48, 0x02, 0x48, 0x03, 0x22, 0x12, 0x12, 0x0C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x35, 0x39, 0x5D, 0x7C, 0x37, 0x37, 0x29, 0x32, 0x02, 0x31, 0x35, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF,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, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x30, 0x36, 0x7C, 0x39, 0x31, 0x37, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x39, 0x7C, 0x39, 0x31, 0x34, 0x29, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x33, 0xEA, 0x01, 0x45, 0x12, 0x3E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x2D, 0x36, 0x5D, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x34, 0x34, 0x32, 0x32, 0x7C, 0x37, 0x37, 0x39, 0x39, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x30, 0x36, 0x7C, 0x39, 0x31, 0x37, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x39, 0x7C, 0x39, 0x31, 0x34, 0x29, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x34, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xDA, 0x04, 0x0A, 0x18, 0x12, 0x0E, 0x5B, 0x30, 0x2D, 0x33, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x49, 0x12, 0x3C, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x36, 0x7C, 0x36, 0x5B, 0x35, 0x37, 0x5D, 0x7C, 0x38, 0x5B, 0x35, 0x38, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x36, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x5B, 0x33, 0x2D, 0x37, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x30, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x03, 0x30, 0x31, 0x36, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x2A, 0x68, 0x12, 0x61, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x7C, 0x5B, 0x37, 0x39, 0x5D, 0x39, 0x5B, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x7C, 0x32, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x33, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7C, 0x38, 0x30, 0x29, 0x7C, 0x33, 0x5B, 0x33, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x39, 0x30, 0x28, 0x3F, 0x3A, 0x35, 0x5C, 0x64, 0x7C, 0x37, 0x29, 0x32, 0x03, 0x31, 0x32, 0x30, 0x4A, 0x02, 0x45, 0x53, 0xDA, 0x01, 0x13, 0x12, 0x0A, 0x30, 0x38, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x31, 0x31, 0x32, 0x32, 0x03, 0x30, 0x38, 0x35, 0x48, 0x03, 0xEA, 0x01, 0xCC, 0x01, 0x12, 0xC4, 0x01, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x2D, 0x32, 0x36, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x32, 0x35, 0x37, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x35, 0x38, 0x5D, 0x7C, 0x39, 0x5B, 0x31, 0x32, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x33, 0x2D, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x33, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x34, 0x7D, 0x7C, 0x5B, 0x33, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x5C, 0x64, 0x7C, 0x33, 0x5B, 0x33, 0x35, 0x37, 0x5D, 0x7C, 0x5B, 0x37, 0x39, 0x5D, 0x39, 0x5B, 0x35, 0x37, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x33, 0x34, 0x5D, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x33, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7C, 0x38, 0x30, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x39, 0x30, 0x28, 0x3F, 0x3A, 0x35, 0x5B, 0x31, 0x32, 0x34, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x37, 0x29, 0x7C, 0x32, 0x32, 0x5C, 0x64, 0x5C, 0x64, 0x3F, 0x32, 0x03, 0x30, 0x31, 0x30, 0xF2, 0x01, 0x2A, 0x12, 0x1F, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x36, 0x5D, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x7C, 0x38, 0x30, 0x7C, 0x39, 0x5B, 0x31, 0x32, 0x5D, 0x29, 0x7C, 0x32, 0x31, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x03, 0x30, 0x31, 0x30, 0x48, 0x03, 0x48, 0x06, 0xFA, 0x01, 0x2A, 0x12, 0x23, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x5C, 0x64, 0x7C, 0x33, 0x5B, 0x33, 0x34, 0x5D, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x32, 0x32, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x32, 0x30, 0x8A, 0x02, 0x44, 0x12, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x5C, 0x64, 0x7C, 0x33, 0x5B, 0x33, 0x35, 0x37, 0x5D, 0x7C, 0x5B, 0x37, 0x39, 0x5D, 0x39, 0x5B, 0x35, 0x37, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x33, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7C, 0x38, 0x30, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x32, 0x32, 0x30, 0x30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 0x22, 0x12, 0x12, 0x06, 0x31, 0x31, 0x36, 0x31, 0x31, 0x31, 0x32, 0x06, 0x31, 0x31, 0x36, 0x31, 0x31, 0x31, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x46, 0x49, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x1F, 0x12, 0x18, 0x31, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x37, 0x35, 0x5B, 0x31, 0x32, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xD6, 0x01, 0x0A, 0x22, 0x12, 0x1A, 0x5B, 0x30, 0x2D, 0x35, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x02, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0F, 0x12, 0x06, 0x39, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x46, 0x4A, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x39, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x4A, 0x12, 0x44, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x33, 0x34, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x5B, 0x32, 0x35, 0x5D, 0x39, 0x29, 0x7C, 0x32, 0x5B, 0x32, 0x38, 0x39, 0x5D, 0x7C, 0x33, 0x30, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x39, 0x31, 0x5B, 0x31, 0x33, 0x37, 0x5D, 0x7C, 0x5B, 0x34, 0x35, 0x5D, 0x34, 0x7C, 0x37, 0x35, 0x32, 0x02, 0x32, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x75, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0A, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x2A, 0x0B, 0x48, 0xFF,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 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x82, 0x04, 0x0A, 0x18, 0x12, 0x0C, 0x5B, 0x31, 0x2D, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x35, 0x7D, 0x48, 0x02, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x58, 0x12, 0x48, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x7C, 0x31, 0x33, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x34, 0x35, 0x39, 0x5D, 0x7C, 0x5B, 0x36, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x39, 0x5B, 0x31, 0x36, 0x37, 0x5D, 0x29, 0x7C, 0x32, 0x32, 0x34, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x33, 0x37, 0x30, 0x30, 0x29, 0x7C, 0x37, 0x34, 0x30, 0x32, 0x04, 0x33, 0x30, 0x31, 0x30, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x2A, 0x1B, 0x12, 0x10, 0x33, 0x36, 0x36, 0x36, 0x35, 0x7C, 0x5B, 0x34, 0x2D, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x05, 0x34, 0x32, 0x30, 0x30, 0x30, 0x48, 0x05, 0x4A, 0x02, 0x46, 0x52, 0xDA, 0x01, 0x18, 0x12, 0x0D, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x02, 0x48, 0x03, 0xEA, 0x01, 0x95, 0x01, 0x12, 0x8C, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x34, 0x35, 0x39, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x39, 0x5B, 0x31, 0x36, 0x37, 0x5D, 0x7C, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x32, 0x30, 0x29, 0x7C, 0x32, 0x34, 0x29, 0x7C, 0x33, 0x5C, 0x64, 0x7B, 0x33, 0x2C, 0x34, 0x7D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x33, 0x34, 0x7C, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x32, 0x32, 0x7C, 0x34, 0x30, 0x7C, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x29, 0x7C, 0x5B, 0x34, 0x35, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x04, 0x31, 0x30, 0x31, 0x30, 0xF2, 0x01, 0x50, 0x12, 0x44, 0x31, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x7C, 0x32, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x33, 0x34, 0x7C, 0x36, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x32, 0x30, 0x32, 0x30, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x36, 0x34, 0x36, 0x7C, 0x39, 0x5B, 0x30, 0x37, 0x5D, 0x30, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x33, 0x34, 0x29, 0x7C, 0x37, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x32, 0x04, 0x31, 0x30, 0x32, 0x33, 0x48, 0x03, 0x48, 0x04, 0xFA, 0x01, 0x41, 0x12, 0x2F, 0x31, 0x31, 0x38, 0x37, 0x37, 0x37, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x32, 0x30, 0x29, 0x7C, 0x32, 0x34, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x33, 0x34, 0x29, 0x7C, 0x37, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x38, 0x37, 0x37, 0x37, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x8A, 0x02, 0x1F, 0x12, 0x12, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x34, 0x7C, 0x5B, 0x33, 0x2D, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x29, 0x32, 0x05, 0x33, 0x33, 0x37, 0x30, 0x30, 0x48, 0x03, 0x48, 0x05, 0x0A, 0xA0, 0x01, 0x0A, 0x13, 0x12, 0x0D, 0x31, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x02, 0x48, 0x04, 0x22, 0x19, 0x12, 0x13, 0x31, 0x28, 0x3F, 0x3A, 0x28, 0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0x30, 0x30, 0x30, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x32, 0x30, 0x32, 0x7C, 0x34, 0x38, 0x29, 0x7C, 0x34, 0x34, 0x34, 0x34, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x42, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x98, 0x02, 0x12, 0x90, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x35, 0x30, 0x29, 0x7C, 0x33, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x37, 0x5C, 0x64, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7C, 0x37, 0x31, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x5B, 0x35, 0x36, 0x5D, 0x30, 0x29, 0x7C, 0x38, 0x30, 0x30, 0x5C, 0x64, 0x7C, 0x39, 0x5B, 0x31, 0x35, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x29, 0x3F, 0x7C, 0x31, 0x33, 0x30, 0x30, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x31, 0x31, 0x7C, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x33, 0x33, 0x36, 0x7C, 0x34, 0x35, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x7C, 0x38, 0x29, 0x29, 0x7C, 0x33, 0x5B, 0x31, 0x33, 0x5D, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x33, 0x35, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x34, 0x34, 0x5B, 0x34, 0x35, 0x5D, 0x7C, 0x35, 0x5C, 0x64, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x35, 0x30, 0x7C, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x39, 0x7C, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x39, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x7C, 0x39, 0x39, 0x29, 0x32, 0x03, 0x31, 0x35, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x46, 0x12, 0x38, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x30, 0x7C, 0x35, 0x37, 0x31, 0x7C, 0x37, 0x5B, 0x35, 0x36, 0x5D, 0x30, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x29, 0x3F, 0x7C, 0x31, 0x33, 0x30, 0x30, 0x7C, 0x33, 0x33, 0x33, 0x36, 0x7C, 0x34, 0x38, 0x29, 0x7C, 0x34, 0x34, 0x34, 0x34, 0x7C, 0x39, 0x30, 0x31, 0x32, 0x04, 0x31, 0x35, 0x37, 0x31, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x32, 0x12, 0x25, 0x31, 0x32, 0x35, 0x30, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x30, 0x32, 0x7C, 0x31, 0x33, 0x30, 0x30, 0x29, 0x7C, 0x37, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x32, 0x30, 0x32, 0x30, 0x32, 0x48, 0x04, 0x48, 0x05, 0x0A, 0x6B, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x44, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0xC1, 0x01, 0x0A, 0x19, 0x12, 0x13, 0x5B, 0x30, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x45, 0xDA, 0x01, 0x25, 0x12, 0x1C, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x32, 0x7C, 0x33, 0x33, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x32, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x29, 0x12, 0x22, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x32, 0x7C, 0x33, 0x33, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x32, 0x32, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x0A, 0x70, 0x0A, 0x07, 0x12, 0x03, 0x31, 0x5C, 0x64, 0x48, 0x02, 0x22, 0x0C, 0x12, 0x06, 0x31, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x35, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x46, 0xDA, 0x01, 0x0C, 0x12, 0x06, 0x31, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x35, 0xEA, 0x01, 0x0C, 0x12, 0x06, 0x31, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x35, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xBB, 0x01, 0x0A, 0x15, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 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xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x48, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x39, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x24, 0x12, 0x1D, 0x31, 0x39, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x28, 0x3F, 0x3A, 0x35, 0x34, 0x7C, 0x38, 0x33, 0x29, 0x30, 0x30, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x1D, 0x12, 0x11, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x28, 0x3F, 0x3A, 0x35, 0x34, 0x7C, 0x38, 0x33, 0x29, 0x30, 0x30, 0x32, 0x04, 0x35, 0x34, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x1D, 0x12, 0x11, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x28, 0x3F, 0x3A, 0x35, 0x34, 0x7C, 0x38, 0x33, 0x29, 0x30, 0x30, 0x32, 0x04, 0x35, 0x34, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x0A, 0xF4, 0x02, 0x0A, 0x16, 0x12, 0x0C, 0x5B, 0x31, 0x35, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x4A, 0x12, 0x3D, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x32, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x37, 0x5C, 0x64, 0x29, 0x7C, 0x35, 0x5B, 0x31, 0x35, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x39, 0x5D, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x38, 0x30, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x30, 0x30, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x2A, 0x15, 0x12, 0x0B, 0x38, 0x5B, 0x31, 0x2D, 0x36, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x04, 0x38, 0x31, 0x30, 0x30, 0x48, 0x04, 0x4A, 0x02, 0x47, 0x49, 0xDA, 0x01, 0x16, 0x12, 0x0D, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x30, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x7E, 0x12, 0x77, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x37, 0x5B, 0x30, 0x31, 0x34, 0x5D, 0x29, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x39, 0x5D, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x38, 0x5B, 0x30, 0x2D, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x34, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x7C, 0x38, 0x5B, 0x31, 0x2D, 0x35, 0x38, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0x15, 0x12, 0x0A, 0x31, 0x35, 0x30, 0x7C, 0x38, 0x37, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x35, 0x30, 0x48, 0x03, 0x48, 0x04, 0xFA, 0x01, 0x32, 0x12, 0x27, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x32, 0x33, 0x7C, 0x35, 0x31, 0x7C, 0x39, 0x5B, 0x32, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x38, 0x38, 0x29, 0x32, 0x03, 0x31, 0x32, 0x33, 0x48, 0x03, 0x48, 0x05, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x6C, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0A, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 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33, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x30, 0x48, 0x03, 0xEA, 0x01, 0x23, 0x12, 0x1C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x7C, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x5B, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x29, 0x5C, 0x64, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x31, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x6D, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x55, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0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48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x47, 0x59, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x39, 0x31, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x54, 0x12, 0x4D, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x7C, 0x38, 0x30, 0x29, 0x31, 0x7C, 0x34, 0x34, 0x34, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x5B, 0x36, 0x37, 0x5D, 0x37, 0x7C, 0x39, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x37, 0x38, 0x5D, 0x7C, 0x5B, 0x32, 0x2D, 0x34, 0x37, 0x5D, 0x29, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x34, 0x34, 0x33, 0x7C, 0x35, 0x5B, 0x35, 0x36, 0x38, 0x5D, 0x29, 0x7C, 0x39, 0x31, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x32, 0x03, 0x30, 0x30, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0F, 0x12, 0x05, 0x31, 0x34, 0x34, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x34, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x0F, 0x12, 0x05, 0x31, 0x34, 0x34, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x34, 0x34, 0x30, 0x48, 0x04, 0x0A, 0xBE, 0x03, 0x0A, 0x17, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x36, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x48, 0x07, 0x22, 0x13, 0x12, 0x0A, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x32, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x48, 0x4B, 0xDA, 0x01, 0x13, 0x12, 0x0A, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x32, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0xA2, 0x02, 0x12, 0x9A, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x33, 0x36, 0x5D, 0x5C, 0x64, 0x7C, 0x32, 0x5B, 0x31, 0x34, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x30, 0x2C, 0x33, 0x7D, 0x7C, 0x38, 0x5B, 0x31, 0x33, 0x38, 0x5D, 0x29, 0x7C, 0x31, 0x32, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x33, 0x5D, 0x5C, 0x64, 0x7B, 0x30, 0x2C, 0x34, 0x7D, 0x7C, 0x28, 0x3F, 0x3A, 0x35, 0x38, 0x7C, 0x38, 0x5B, 0x31, 0x33, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x30, 0x2C, 0x33, 0x7D, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x30, 0x2C, 0x34, 0x7D, 0x7C, 0x32, 0x31, 0x39, 0x5C, 0x64, 0x7B, 0x30, 0x2C, 0x32, 0x7D, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x36, 0x30, 0x5C, 0x64, 0x29, 0x5C, 0x64, 0x7C, 0x38, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x5B, 0x32, 0x2D, 0x38, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x7C, 0x32, 0x29, 0x32, 0x7C, 0x33, 0x7C, 0x38, 0x5B, 0x31, 0x32, 0x38, 0x5D, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x30, 0x2D, 0x36, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x31, 0x2D, 0x33, 0x38, 0x39, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x32, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x39, 0x33, 0x29, 0x29, 0x5C, 0x64, 0x7C, 0x38, 0x29, 0x5C, 0x64, 0x7C, 0x35, 0x30, 0x5B, 0x31, 0x33, 0x38, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x38, 0x36, 0x29, 0x7C, 0x38, 0x29, 0x29, 0x29, 0x7C, 0x39, 0x39, 0x5B, 0x32, 0x39, 0x5D, 0x7C, 0x31, 0x30, 0x5B, 0x30, 0x31, 0x33, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x23, 0x12, 0x16, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x38, 0x5C, 0x64, 0x7C, 0x39, 0x29, 0x7C, 0x38, 0x35, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x32, 0x03, 0x31, 0x30, 0x39, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x0C, 0x12, 0x03, 0x39, 0x39, 0x32, 0x32, 0x03, 0x39, 0x39, 0x32, 0x48, 0x03, 0x0A, 0x93, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0C, 0x12, 0x03, 0x31, 0x39, 0x39, 0x32, 0x03, 0x31, 0x39, 0x39, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x48, 0x4E, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x39, 0x39, 0x32, 0x03, 0x31, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x10, 0x12, 0x09, 0x31, 0x39, 0x39, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xF8, 0x01, 0x0A, 0x17, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x35, 0x7D, 0x48, 0x02, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x1F, 0x12, 0x11, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x33, 0x39, 0x37, 0x37, 0x29, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x05, 0x48, 0x06, 0x2A, 0x13, 0x12, 0x08, 0x31, 0x31, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x05, 0x31, 0x31, 0x38, 0x31, 0x32, 0x48, 0x05, 0x4A, 0x02, 0x48, 0x52, 0xDA, 0x01, 0x1F, 0x12, 0x14, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x32, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x39, 0x5B, 0x33, 0x34, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x02, 0x48, 0x03, 0xEA, 0x01, 0x4C, 0x12, 0x45, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x33, 0x39, 0x37, 0x37, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x38, 0x37, 0x29, 0x29, 0x7C, 0x39, 0x5B, 0x33, 0x34, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x31, 0x33, 0x39, 0x37, 0x37, 0x32, 0x05, 0x31, 0x33, 0x39, 0x37, 0x37, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x31, 0x33, 0x39, 0x37, 0x37, 0x32, 0x05, 0x31, 0x33, 0x39, 0x37, 0x37, 0x48, 0x05, 0x0A, 0x9C, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x34, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x34, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x48, 0x54, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x34, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x34, 0x48, 0x03, 0xEA, 0x01, 0x13, 0x12, 0x0C, 0x31, 0x31, 0x5B, 0x34, 0x38, 0x5D, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x03, 0x31, 0x31, 0x34, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xBF, 0x01, 0x0A, 0x15, 0x12, 0x0F, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x06, 0x22, 0x21, 0x12, 0x15, 0x31, 0x31, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x48, 0x55, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x34, 0x35, 0x37, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x2D, 0x12, 0x26, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x34, 0x35, 0x37, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2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, 0x34, 0x30, 0x30, 0x7C, 0x38, 0x39, 0x38, 0x38, 0x37, 0x32, 0x05, 0x37, 0x31, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x37, 0x31, 0x34, 0x30, 0x30, 0x32, 0x05, 0x37, 0x31, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xFD, 0x01, 0x0A, 0x16, 0x12, 0x0C, 0x5B, 0x31, 0x35, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x14, 0x12, 0x08, 0x31, 0x31, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x15, 0x12, 0x0A, 0x35, 0x5B, 0x33, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x35, 0x33, 0x30, 0x31, 0x32, 0x48, 0x05, 0x4A, 0x02, 0x49, 0x45, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x4B, 0x12, 0x44, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x39, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x33, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x12, 0x12, 0x07, 0x35, 0x31, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x35, 0x31, 0x30, 0x31, 0x32, 0x48, 0x05, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x35, 0x31, 0x32, 0x31, 0x30, 0x32, 0x05, 0x35, 0x31, 0x32, 0x31, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x28, 0x12, 0x1D, 0x31, 0x31, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x33, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x31, 0x32, 0x31, 0x30, 0x29, 0x32, 0x05, 0x35, 0x31, 0x32, 0x31, 0x30, 0x48, 0x05, 0x0A, 0xB8, 0x01, 0x0A, 0x10, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x49, 0x4C, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x32, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x37, 0x12, 0x2F, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x32, 0x5D, 0x7C, 0x34, 0x30, 0x30, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x32, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x32, 0x04, 0x31, 0x34, 0x35, 0x35, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x31, 0x30, 0x34, 0x30, 0x30, 0x32, 0x05, 0x31, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x31, 0x30, 0x34, 0x30, 0x30, 0x32, 0x05, 0x31, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xB1, 0x01, 0x0A, 0x1D, 0x12, 0x15, 0x5B, 0x31, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x48, 0x06, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x49, 0x4D, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x2A, 0x12, 0x23, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x3F, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x36, 0x34, 0x34, 0x34, 0x7C, 0x39, 0x38, 0x38, 0x37, 0x29, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x35, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x19, 0x12, 0x0E, 0x38, 0x28, 0x3F, 0x3A, 0x36, 0x34, 0x34, 0x34, 0x7C, 0x39, 0x38, 0x38, 0x37, 0x29, 0x32, 0x05, 0x38, 0x36, 0x34, 0x34, 0x34, 0x48, 0x05, 0x0A, 0xF6, 0x0A, 0x0A, 0x1E, 0x12, 0x0E, 0x5B, 0x31, 0x32, 0x35, 0x37, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x38, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x48, 0x07, 0x48, 0x08, 0x48, 0x09, 0x22, 0x22, 0x12, 0x10, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x7C, 0x37, 0x37, 0x37, 0x7C, 0x38, 0x30, 0x30, 0x32, 0x06, 0x31, 0x30, 0x35, 0x30, 0x31, 0x30, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x2A, 0x28, 0x12, 0x19, 0x31, 0x31, 0x5B, 0x36, 0x37, 0x5D, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x35, 0x36, 0x31, 0x36, 0x31, 0x35, 0x36, 0x31, 0x32, 0x07, 0x31, 0x31, 0x36, 0x30, 0x35, 0x33, 0x30, 0x48, 0x07, 0x48, 0x08, 0x4A, 0x02, 0x49, 0x4E, 0xDA, 0x01, 0x23, 0x12, 0x18, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x32, 0x38, 0x5D, 0x7C, 0x31, 0x32, 0x7C, 0x32, 0x39, 0x38, 0x29, 0x7C, 0x32, 0x36, 0x31, 0x31, 0x32, 0x03, 0x31, 0x30, 0x38, 0x48, 0x03, 0x48, 0x04, 0xEA, 0x01, 0xDC, 0x07, 0x12, 0xD4, 0x07, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x32, 0x34, 0x38, 0x5D, 0x7C, 0x33, 0x5B, 0x33, 0x39, 0x5D, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x30, 0x7C, 0x36, 0x7C, 0x5B, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x36, 0x5B, 0x33, 0x34, 0x36, 0x38, 0x5D, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x33, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x32, 0x30, 0x3F, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x38, 0x30, 0x29, 0x7C, 0x39, 0x5B, 0x30, 0x31, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x5B, 0x32, 0x38, 0x39, 0x5D, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x39, 0x38, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C,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, 0x5B, 0x34, 0x2D, 0x36, 0x39, 0x5D, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x3F, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x39, 0x29, 0x29, 0x7C, 0x39, 0x39, 0x29, 0x5C, 0x64, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x35, 0x35, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x34, 0x5C, 0x64, 0x3F, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x29, 0x7C, 0x37, 0x37, 0x7C, 0x38, 0x38, 0x7C, 0x39, 0x30, 0x5C, 0x64, 0x3F, 0x29, 0x5C, 0x64, 0x29, 0x7C, 0x37, 0x37, 0x37, 0x7C, 0x38, 0x30, 0x30, 0x32, 0x03, 0x31, 0x30, 0x38, 0xF2, 0x01, 0x2E, 0x12, 0x1F, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x33, 0x34, 0x5D, 0x5C, 0x64, 0x29, 0x7C, 0x37, 0x35, 0x37, 0x35, 0x35, 0x35, 0x29, 0x32, 0x07, 0x35, 0x37, 0x35, 0x37, 0x35, 0x35, 0x35, 0x48, 0x05, 0x48, 0x07, 0xFA, 0x01, 0x72, 0x12, 0x5D, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x36, 0x37, 0x5D, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x31, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x35, 0x33, 0x33, 0x30, 0x7C, 0x37, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x30, 0x39, 0x29, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x30, 0x30, 0x7C, 0x36, 0x31, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x35, 0x36, 0x31, 0x29, 0x29, 0x32, 0x05, 0x35, 0x33, 0x30, 0x30, 0x30, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x48, 0x07, 0x48, 0x08, 0x8A, 0x02, 0x55, 0x12, 0x42, 0x31, 0x28, 0x3F, 0x3A, 0x33, 0x39, 0x7C, 0x39, 0x30, 0x5B, 0x30, 0x31, 0x39, 0x5D, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x33, 0x34, 0x5D, 0x5C, 0x64, 0x29, 0x7C, 0x36, 0x31, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x35, 0x36, 0x31, 0x29, 0x7C, 0x37, 0x35, 0x37, 0x35, 0x35, 0x35, 0x29, 0x32, 0x05, 0x35, 0x31, 0x34, 0x33, 0x31, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x07, 0x48, 0x08, 0x0A, 0xC6, 0x01, 0x0A, 0x15, 0x12, 0x0D, 0x5B, 0x31, 0x34, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x49, 0x51, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x34, 0x5D, 0x7C, 0x31, 0x35, 0x7C, 0x32, 0x32, 0x29, 0x32, 0x03, 0x31, 0x32, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x28, 0x12, 0x20, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x34, 0x5D, 0x7C, 0x31, 0x35, 0x7C, 0x32, 0x32, 0x29, 0x7C, 0x34, 0x34, 0x33, 0x32, 0x7C, 0x37, 0x31, 0x31, 0x31, 0x37, 0x7C, 0x39, 0x39, 0x38, 0x38, 0x32, 0x04, 0x34, 0x34, 0x33, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x1B, 0x12, 0x0F, 0x34, 0x34, 0x33, 0x32, 0x7C, 0x37, 0x31, 0x31, 0x31, 0x37, 0x7C, 0x39, 0x39, 0x38, 0x38, 0x32, 0x04, 0x34, 0x34, 0x33, 0x32, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x1B, 0x12, 0x0F, 0x34, 0x34, 0x33, 0x32, 0x7C, 0x37, 0x31, 0x31, 0x31, 0x37, 0x7C, 0x39, 0x39, 0x38, 0x38, 0x32, 0x04, 0x34, 0x34, 0x33, 0x32, 0x48, 0x04, 0x48, 0x05, 0x0A, 0xE7, 0x03, 0x0A, 0x17, 0x12, 0x0D, 0x5B, 0x30, 0x2D, 0x32, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x11, 0x12, 0x08, 0x31, 0x5B, 0x31, 0x32, 0x39, 0x5D, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x32, 0x33, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x49, 0x52, 0xDA, 0x01, 0x1B, 0x12, 0x12, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x32, 0x35, 0x5D, 0x7C, 0x32, 0x35, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0xAA, 0x02, 0x12, 0xA2, 0x02, 0x30, 0x39, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x32, 0x5B, 0x31, 0x36, 0x2D, 0x38, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x38, 0x7C, 0x5B, 0x31, 0x34, 0x5D, 0x35, 0x7C, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x36, 0x36, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x7C, 0x38, 0x30, 0x29, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x36, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x38, 0x36, 0x7C, 0x39, 0x5B, 0x31, 0x39, 0x5D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x2D, 0x36, 0x38, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x2D, 0x35, 0x39, 0x5D, 0x7C, 0x33, 0x5B, 0x33, 0x34, 0x36, 0x2D, 0x38, 0x5D, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x34, 0x37, 0x5D, 0x7C, 0x5B, 0x32, 0x38, 0x39, 0x5D, 0x30, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x31, 0x5B, 0x30, 0x32, 0x34, 0x37, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x2D, 0x33, 0x5D, 0x7C, 0x33, 0x39, 0x7C, 0x5B, 0x34, 0x39, 0x5D, 0x30, 0x7C, 0x36, 0x35, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x36, 0x5D, 0x36, 0x7C, 0x5B, 0x32, 0x37, 0x5D, 0x7C, 0x39, 0x30, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x30, 0x33, 0x7C, 0x31, 0x5B, 0x31, 0x38, 0x5D, 0x7C, 0x32, 0x32, 0x7C, 0x33, 0x5B, 0x33, 0x37, 0x5D, 0x7C, 0x34, 0x5B, 0x32, 0x38, 0x5D, 0x7C, 0x38, 0x38, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x39, 0x5B, 0x30, 0x2D, 0x35, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x33, 0x38, 0x5D, 0x7C, 0x31, 0x5B, 0x30, 0x37, 0x39, 0x5D, 0x7C, 0x32, 0x36, 0x7C, 0x39, 0x5B, 0x36, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x39, 0x30, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x39, 0x30, 0x7C, 0x30, 0x30, 0x30, 0x39, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x1F, 0x12, 0x12, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x36, 0x7C, 0x31, 0x5B, 0x35, 0x38, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x05, 0x30, 0x39, 0x36, 0x31, 0x32, 0x48, 0x04, 0x48, 0x05, 0xFA, 0x01, 0x24, 0x12, 0x18, 0x31, 0x5B, 0x35, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x39, 0x39, 0x28, 0x3F, 0x3A, 0x39, 0x30, 0x7C, 0x30, 0x30, 0x30, 0x39, 0x29, 0x32, 0x04, 0x39, 0x39, 0x39, 0x30, 0x48, 0x04, 0x48, 0x06, 0x8A, 0x02, 0x12, 0x12, 0x06, 0x39, 0x39, 0x30, 0x30, 0x30, 0x39, 0x32, 0x06, 0x39, 0x39, 0x30, 0x30, 0x30, 0x39, 0x48, 0x06, 0x0A, 0x80, 0x02, 0x0A, 0x1E, 0x12, 0x16, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x22, 0x17, 0x12, 0x0C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x37, 0x31, 0x5C, 0x64, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x04, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x49, 0x53, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x68, 0x12, 0x61, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x38, 0x5D, 0x7C, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x36, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x5B, 0x31, 0x34, 0x35, 0x5D, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x34, 0x36, 0x5D, 0x29, 0x7C, 0x35, 0x35, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x37, 0x7C, 0x37, 0x5B, 0x30, 0x37, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x30, 0x7C, 0x31, 0x5B, 0x31, 0x36, 0x2D, 0x39, 0x5D, 0x7C, 0x38, 0x38, 0x29, 0x7C, 0x39, 0x30, 0x30, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x08, 0x31, 0x34, 0x5B, 0x30, 0x34, 0x5D, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x34, 0x30, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x16, 0x12, 0x0C, 0x31, 0x28, 0x3F, 0x3A, 0x34, 0x31, 0x7C, 0x39, 0x30, 0x29, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x34, 0x31, 0x30, 0x48, 0x04, 0x0A, 0xE8, 0x03, 0x0A, 0x17, 0x12, 0x0B, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x36, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x48, 0x07, 0x22, 0x25, 0x12, 0x1A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x33, 0x35, 0x38, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x38, 0x37, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x06, 0x2A, 0x39, 0x12, 0x2B, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x34, 0x37, 0x38, 0x5D, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x7C, 0x5B, 0x35, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x29, 0x7C, 0x35, 0x35, 0x29, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x32, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x48, 0x07, 0x4A, 0x02, 0x49, 0x54, 0xDA, 0x01, 0x11, 0x12, 0x08, 0x31, 0x31, 0x5B, 0x32, 0x33, 0x35, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0xEB, 0x01, 0x12, 0xE3, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x2D, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x29, 0x7C, 0x32, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x33, 0x5B, 0x33, 0x39, 0x5D, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x38, 0x32, 0x7C, 0x39, 0x5C, 0x64, 0x7B, 0x31, 0x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5D, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x19, 0x12, 0x12, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x32, 0x39, 0x5D, 0x7C, 0x37, 0x36, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x8A, 0x02, 0x0A, 0x12, 0x03, 0x31, 0x37, 0x36, 0x32, 0x03, 0x31, 0x37, 0x36, 0x0A, 0xE1, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x1B, 0x12, 0x12, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x31, 0x32, 0x37, 0x5D, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4A, 0x4F, 0xDA, 0x01, 0x1B, 0x12, 0x12, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x31, 0x32, 0x37, 0x5D, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x32, 0x12, 0x2B, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x7C, 0x31, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x2D, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x30, 0x33, 0x7C, 0x31, 0x31, 0x7C, 0x38, 0x37, 0x38, 0x38, 0x29, 0x32, 0x03, 0x31, 0x30, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x19, 0x12, 0x0E, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x7C, 0x38, 0x37, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x39, 0x30, 0x39, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x19, 0x12, 0x0E, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x7C, 0x38, 0x37, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x39, 0x30, 0x39, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x75, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0D, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x30, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x30, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4A, 0x50, 0xDA, 0x01, 0x0D, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x30, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x30, 0xEA, 0x01, 0x0D, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x30, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xAA, 0x05, 0x0A, 0x14, 0x12, 0x0C, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x34, 0x12, 0x2C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x7C, 0x39, 0x5C, 0x64, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x7C, 0x32, 0x5B, 0x31, 0x32, 0x37, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x7C, 0x36, 0x5B, 0x36, 0x37, 0x5D, 0x29, 0x29, 0x29, 0x32, 0x04, 0x31, 0x35, 0x30, 0x31, 0x2A, 0x13, 0x12, 0x08, 0x39, 0x30, 0x39, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x05, 0x39, 0x30, 0x39, 0x31, 0x32, 0x48, 0x05, 0x4A, 0x02, 0x4B, 0x45, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x31, 0x32, 0x7C, 0x31, 0x31, 0x34, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x9F, 0x02, 0x12, 0x97, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x37, 0x2D, 0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 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x37, 0x5D, 0x5C, 0x64, 0x7C, 0x39, 0x39, 0x29, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x28, 0x3F, 0x3A, 0x36, 0x5B, 0x32, 0x33, 0x35, 0x37, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x32, 0x39, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x39, 0x38, 0x38, 0x7C, 0x5B, 0x30, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x39, 0x30, 0x39, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x05, 0x39, 0x30, 0x39, 0x31, 0x32, 0x8A, 0x02, 0x50, 0x12, 0x48, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x30, 0x30, 0x7C, 0x34, 0x5B, 0x31, 0x34, 0x5D, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x7C, 0x35, 0x35, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x7C, 0x36, 0x5B, 0x36, 0x37, 0x5D, 0x29, 0x29, 0x7C, 0x36, 0x5B, 0x30, 0x33, 0x35, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x39, 0x38, 0x38, 0x7C, 0x39, 0x30, 0x39, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x32, 0x04, 0x38, 0x39, 0x38, 0x38, 0x0A, 0x8A, 0x01, 0x0A, 0x11, 0x12, 0x0B, 0x5B, 0x31, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4B, 0x47, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x30, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x32, 0x03, 0x31, 0x30, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x13, 0x12, 0x0C, 0x31, 0x30, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x32, 0x03, 0x31, 0x30, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0E, 0x12, 0x04, 0x34, 0x30, 0x34, 0x30, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x0E, 0x12, 0x04, 0x34, 0x30, 0x34, 0x30, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x0A, 0x9F, 0x01, 0x0A, 0x19, 0x12, 0x13, 0x5B, 0x31, 0x34, 0x36, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4B, 0x48, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x31, 0x5B, 0x37, 0x38, 0x39, 0x5D, 0x7C, 0x36, 0x36, 0x36, 0x32, 0x03, 0x31, 0x31, 0x37, 0x48, 0x03, 0xEA, 0x01, 0x18, 0x12, 0x11, 0x31, 0x31, 0x5B, 0x37, 0x38, 0x39, 0x5D, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x36, 0x36, 0x36, 0x32, 0x03, 0x31, 0x31, 0x37, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x34, 0x48, 0x05, 0x0A, 0xB2, 0x01, 0x0A, 0x12, 0x12, 0x0C, 0x5B, 0x31, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4B, 0x49, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x39, 0x5B, 0x32, 0x2D, 0x35, 0x5D, 0x7C, 0x39, 0x39, 0x5B, 0x32, 0x33, 0x34, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x36, 0x12, 0x2F, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x2D, 0x38, 0x5D, 0x7C, 0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 0xFF, 0x01, 0x4A, 0x02, 0x4B, 0x50, 0xDA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x31, 0x39, 0x29, 0x7C, 0x38, 0x31, 0x39, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x31, 0x39, 0x29, 0x7C, 0x38, 0x31, 0x39, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x8E, 0x02, 0x0A, 0x10, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x1F, 0x12, 0x14, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x7C, 0x32, 0x38, 0x7C, 0x33, 0x33, 0x30, 0x7C, 0x38, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x38, 0x48, 0x03, 0x48, 0x04, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4B, 0x52, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x32, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x65, 0x12, 0x5E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x31, 0x31, 0x34, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x34, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x31, 0x31, 0x34, 0x29, 0x7C, 0x32, 0x5B, 0x30, 0x31, 0x33, 0x38, 0x39, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x33, 0x5B, 0x30, 0x33, 0x39, 0x5D, 0x7C, 0x34, 0x35, 0x7C, 0x36, 0x36, 0x7C, 0x38, 0x38, 0x7C, 0x39, 0x5B, 0x31, 0x38, 0x5D, 0x29, 0x7C, 0x5B, 0x36, 0x37, 0x39, 0x5D, 0x31, 0x31, 0x34, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x34, 0x7C, 0x32, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x31, 0x12, 0x26, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x31, 0x31, 0x34, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x34, 0x7C, 0x34, 0x29, 0x7C, 0x5B, 0x36, 0x2D, 0x39, 0x5D, 0x31, 0x31, 0x34, 0x29, 0x32, 0x03, 0x31, 0x30, 0x30, 0x48, 0x03, 0x48, 0x05, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x91, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x31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, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x17, 0x12, 0x0A, 0x33, 0x30, 0x34, 0x30, 0x30, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x32, 0x05, 0x33, 0x30, 0x34, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x17, 0x12, 0x0A, 0x33, 0x30, 0x34, 0x30, 0x30, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x32, 0x05, 0x33, 0x30, 0x34, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x0A, 0x75, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4C, 0x41, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x39, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x30, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x39, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x99, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D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0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xBE, 0x01, 0x0A, 0x13, 0x12, 0x0D, 0x5B, 0x33, 0x34, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x10, 0x12, 0x07, 0x33, 0x35, 0x35, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x33, 0x35, 0x35, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4C, 0x52, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x33, 0x35, 0x35, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x33, 0x35, 0x35, 0x48, 0x03, 0xEA, 0x01, 0x20, 0x12, 0x19, 0x33, 0x35, 0x35, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x30, 0x7C, 0x39, 0x33, 0x33, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x33, 0x35, 0x35, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x1E, 0x12, 0x14, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x7C, 0x39, 0x33, 0x29, 0x29, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x1E, 0x12, 0x14, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x34, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x34, 0x30, 0x7C, 0x39, 0x33, 0x29, 0x29, 0x5C, 0x64, 0x32, 0x04, 0x34, 0x30, 0x34, 0x30, 0x48, 0x04, 0x0A, 0x78, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x32, 0x35, 0x37, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4C, 0x53, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x32, 0x35, 0x37, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x32, 0x35, 0x37, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xE0, 0x01, 0x0A, 0x1F, 0x12, 0x17, 0x5B, 0x30, 0x31, 0x5D, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x02, 0x48, 0x03, 0x48, 0x06, 0x22, 0x14, 0x12, 0x08, 0x31, 0x31, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x0B, 0x48, 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, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x25, 0x12, 0x19, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x32, 0x02, 0x30, 0x31, 0x48, 0x02, 0x48, 0x03, 0x48, 0x06, 0x2A, 0x18, 0x12, 0x0C, 0x31, 0x31, 0x38, 0x30, 0x7C, 0x38, 0x32, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x31, 0x38, 0x30, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x4C, 0x56, 0xDA, 0x01, 0x18, 0x12, 0x0E, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x31, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x32, 0x02, 0x30, 0x31, 0x48, 0x02, 0x48, 0x03, 0xEA, 0x01, 0x48, 0x12, 0x42, 0x30, 0x5B, 0x31, 0x2D, 0x34, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x35, 0x7C, 0x36, 0x35, 0x29, 0x35, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x38, 0x32, 0x31, 0x5B, 0x35, 0x37, 0x5D, 0x34, 0x32, 0x02, 0x30, 0x31, 0xF2, 0x01, 0x0E, 0x12, 0x04, 0x31, 0x31, 0x38, 0x31, 0x32, 0x04, 0x31, 0x31, 0x38, 0x31, 0x48, 0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0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4D, 0x4B, 0xDA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x32, 0x33, 0x34, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x39, 0x5B, 0x32, 0x33, 0x34, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xDD, 0x03, 0x0A, 0x18, 0x12, 0x0E, 0x5B, 0x31, 0x33, 0x36, 0x2D, 0x38, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x34, 0x7D, 0x48, 0x02, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x33, 0x12, 0x26, 0x33, 0x35, 0x32, 0x30, 0x30, 0x7C, 0x36, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x37, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x32, 0x7C, 0x34, 0x34, 0x29, 0x7C, 0x38, 0x30, 0x30, 0x30, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x05, 0x33, 0x35, 0x32, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0x2A, 0x41, 0x12, 0x34, 0x31, 0x32, 0x32, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x35, 0x32, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x34, 0x2D, 0x36, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x35, 0x37, 0x34, 0x29, 0x7C, 0x38, 0x30, 0x30, 0x32, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x05, 0x33, 0x35, 0x32, 0x31, 0x31, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x4D, 0x4C, 0xDA, 0x01, 0x0E, 0x12, 0x06, 0x31, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x37, 0x48, 0x02, 0xEA, 0x01, 0x99, 0x01, 0x12, 0x90, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x5B, 0x30, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x36, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x31, 0x33, 0x5D, 0x29, 0x7C, 0x5B, 0x35, 0x37, 0x38, 0x5D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x33, 0x35, 0x7C, 0x35, 0x37, 0x29, 0x7C, 0x32, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x36, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x39, 0x5D, 0x7C, 0x35, 0x39, 0x7C, 0x37, 0x37, 0x7C, 0x38, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x34, 0x34, 0x7C, 0x35, 0x35, 0x29, 0x7C, 0x38, 0x30, 0x30, 0x5B, 0x30, 0x31, 0x32, 0x5D, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x04, 0x31, 0x32, 0x31, 0x30, 0xF2, 0x01, 0x27, 0x12, 0x1B, 0x33, 0x37, 0x28, 0x3F, 0x3A, 0x34, 0x33, 0x33, 0x7C, 0x35, 0x37, 0x35, 0x29, 0x7C, 0x37, 0x34, 0x30, 0x30, 0x7C, 0x38, 0x30, 0x30, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x04, 0x37, 0x34, 0x30, 0x30, 0x48, 0x04, 0x48, 0x05, 0xFA, 0x01, 0x2B, 0x12, 0x20, 0x33, 0x28, 0x3F, 0x3A, 0x35, 0x30, 0x33, 0x35, 0x7C, 0x5B, 0x36, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x7C, 0x38, 0x30, 0x30, 0x5B, 0x30, 0x31, 0x32, 0x5D, 0x5B, 0x31, 0x32, 0x5D, 0x32, 0x05, 0x33, 0x35, 0x30, 0x33, 0x35, 0x48, 0x05, 0x8A, 0x02, 0x3E, 0x12, 0x31, 0x33, 0x28, 0x3F, 0x3A, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x32, 0x34, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x29, 0x7C, 0x35, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x29, 0x7C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0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x5B, 0x34, 0x35, 0x5D, 0x31, 0x32, 0x03, 0x31, 0x34, 0x31, 0x48, 0x03, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xAC, 0x01, 0x0A, 0x19, 0x12, 0x13, 0x5B, 0x31, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x14, 0x12, 0x0B, 0x31, 0x39, 0x39, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x39, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4D, 0x57, 0xDA, 0x01, 0x14, 0x12, 0x0B, 0x31, 0x39, 0x39, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x18, 0x12, 0x11, 0x31, 0x39, 0x39, 0x7C, 0x38, 0x30, 0x34, 0x30, 0x30, 0x7C, 0x39, 0x39, 0x5B, 0x37, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x31, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x38, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x38, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x38, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x38, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xD3, 0x01, 0x0A, 0x15, 0x12, 0x0D, 0x5B, 0x30, 0x35, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x16, 0x12, 0x0A, 0x35, 0x33, 0x30, 0x35, 0x33, 0x7C, 0x37, 0x37, 0x36, 0x36, 0x32, 0x04, 0x37, 0x37, 0x36, 0x36, 0x48, 0x04, 0x48, 0x05, 0x4A, 0x02, 0x4D, 0x58, 0xDA, 0x01, 0x1C, 0x12, 0x13, 0x30, 0x28, 0x3F, 0x3A, 0x36, 0x5B, 0x30, 0x35, 0x36, 0x38, 0x5D, 0x7C, 0x38, 0x30, 0x29, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x30, 0x36, 0x36, 0x48, 0x03, 0xEA, 0x01, 0x47, 0x12, 0x40, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x34, 0x39, 0x5D, 0x30, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x31, 0x35, 0x36, 0x38, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x35, 0x33, 0x30, 0x35, 0x33, 0x7C, 0x37, 0x37, 0x36, 0x36, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0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0x36, 0x32, 0x38, 0x7C, 0x39, 0x39, 0x5B, 0x31, 0x2D, 0x34, 0x36, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x10, 0x12, 0x05, 0x36, 0x36, 0x36, 0x32, 0x38, 0x32, 0x05, 0x36, 0x36, 0x36, 0x32, 0x38, 0x48, 0x05, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x1E, 0x12, 0x13, 0x33, 0x5B, 0x32, 0x33, 0x36, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x36, 0x36, 0x36, 0x32, 0x38, 0x32, 0x05, 0x33, 0x36, 0x30, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xA7, 0x01, 0x0A, 0x0E, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x37, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x37, 0x38, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x37, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4D, 0x5A, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x37, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x37, 0x38, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x37, 0x48, 0x03, 0xEA, 0x01, 0x22, 0x12, 0x1B, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x35, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x31, 0x5B, 0x37, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x37, 0x38, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x37, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x99, 0x01, 0x0A, 0x13, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x10, 0x12, 0x05, 0x31, 0x30, 0x31, 0x31, 0x31, 0x32, 0x05, 0x31, 0x30, 0x31, 0x31, 0x31, 0x48, 0x05, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4E, 0x41, 0xDA, 0x01, 0x10, 0x12, 0x05, 0x31, 0x30, 0x31, 0x31, 0x31, 0x32, 0x05, 0x31, 0x30, 0x31, 0x31, 0x31, 0x48, 0x05, 0xEA, 0x01, 0x21, 0x12, 0x1A, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x7C, 0x39, 0x33, 0x29, 0x31, 0x31, 0x31, 0x7C, 0x28, 0x3F, 0x3A, 0x31, 0x5C, 0x64, 0x7C, 0x39, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x39, 0x30, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 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, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x33, 0x34, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x33, 0x5D, 0x7C, 0x34, 0x30, 0x7C, 0x35, 0x35, 0x3F, 0x7C, 0x36, 0x30, 0x7C, 0x37, 0x7C, 0x38, 0x29, 0x7C, 0x32, 0x32, 0x32, 0x7C, 0x33, 0x33, 0x33, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x37, 0x32, 0x33, 0x31, 0x34, 0x31, 0x7C, 0x38, 0x38, 0x38, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x40, 0x12, 0x37, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x33, 0x34, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x33, 0x5D, 0x7C, 0x34, 0x30, 0x7C, 0x35, 0x35, 0x7C, 0x36, 0x30, 0x29, 0x7C, 0x32, 0x32, 0x32, 0x7C, 0x33, 0x33, 0x33, 0x7C, 0x35, 0x35, 0x35, 0x7C, 0x38, 0x38, 0x38, 0x32, 0x03, 0x31, 0x30, 0x30, 0x48, 0x03, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x81, 0x01, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 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, 0x01, 0x10, 0x12, 0x09, 0x31, 0x39, 0x39, 0x7C, 0x34, 0x30, 0x37, 0x30, 0x30, 0x32, 0x03, 0x31, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x34, 0x30, 0x37, 0x30, 0x30, 0x32, 0x05, 0x34, 0x30, 0x37, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x30, 0x37, 0x30, 0x30, 0x32, 0x05, 0x34, 0x30, 0x37, 0x30, 0x30, 0x48, 0x05, 0x0A, 0xD1, 0x01, 0x0A, 0x14, 0x12, 0x0E, 0x5B, 0x31, 0x32, 0x34, 0x36, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x1D, 0x12, 0x16, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x38, 0x5D, 0x29, 0x7C, 0x37, 0x33, 0x37, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x31, 0x35, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4E, 0x49, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x38, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x35, 0x48, 0x03, 0xEA, 0x01, 0x42, 0x12, 0x3B, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x5B, 0x32, 0x39, 0x5D, 0x30, 0x30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, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x6E, 0x12, 0x67, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x34, 0x5D, 0x7C, 0x33, 0x5B, 0x33, 0x34, 0x5D, 0x7C, 0x34, 0x34, 0x29, 0x7C, 0x33, 0x5B, 0x30, 0x33, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x34, 0x30, 0x30, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x31, 0x5B, 0x30, 0x2D, 0x37, 0x39, 0x5D, 0x29, 0x29, 0x7C, 0x5B, 0x33, 0x34, 0x5D, 0x30, 0x30, 0x30, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0F, 0x12, 0x05, 0x31, 0x32, 0x30, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x32, 0x30, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x12, 0x12, 0x08, 0x5B, 0x33, 0x34, 0x5D, 0x30, 0x30, 0x5C, 0x64, 0x32, 0x04, 0x33, 0x30, 0x30, 0x30, 0x48, 0x04, 0x0A, 0xD2, 0x01, 0x0A, 0x1E, 0x12, 0x16, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x04, 0x48, 0x06, 0x22, 0x1C, 0x12, 0x10, 0x31, 0x31, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x32, 0x06, 0x31, 0x31, 0x36, 0x31, 0x31, 0x37, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4E, 0x4F, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x43, 0x12, 0x3C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x33, 0x39, 0x5D, 0x7C, 0x36, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x32, 0x5B, 0x30, 0x34, 0x38, 0x5D, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x5B, 0x35, 0x39, 0x5D, 0x29, 0x7C, 0x37, 0x5B, 0x35, 0x37, 0x5D, 0x7C, 0x39, 0x30, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x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 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0A, 0x12, 0x03, 0x30, 0x31, 0x30, 0x32, 0x03, 0x30, 0x31, 0x30, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xF1, 0x01, 0x0A, 0x0D, 0x12, 0x07, 0x5C, 0x64, 0x7B, 0x33, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0C, 0x12, 0x03, 0x30, 0x31, 0x38, 0x32, 0x03, 0x30, 0x31, 0x38, 0x48, 0x03, 0x4A, 0x02, 0x4E, 0x5A, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x4A, 0x12, 0x43, 0x30, 0x31, 0x38, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x34, 0x7C, 0x33, 0x37, 0x31, 0x7C, 0x37, 0x5B, 0x30, 0x33, 0x5D, 0x37, 0x7C, 0x39, 0x34, 0x34, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x36, 0x31, 0x7C, 0x32, 0x36, 0x5B, 0x30, 0x2D, 0x33, 0x5D, 0x7C, 0x37, 0x34, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x48, 0x12, 0x40, 0x30, 0x31, 0x38, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x33, 0x34, 0x7C, 0x33, 0x37, 0x31, 0x7C, 0x37, 0x5B, 0x30, 0x33, 0x5D, 0x37, 0x7C, 0x39, 0x34, 0x34, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x36, 0x31, 0x7C, 0x32, 0x36, 0x5B, 0x30, 0x2D, 0x33, 0x5D, 0x7C, 0x37, 0x34, 0x32, 0x29, 0x32, 0x04, 0x34, 0x30, 0x39, 0x38, 0x0A, 0x75, 0x0A, 0x0A, 0x12, 0x06, 0x39, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x48, 0x04, 0x22, 0x0D, 0x12, 0x05, 0x39, 0x39, 0x39, 0x5C, 0x64, 0x32, 0x04, 0x39, 0x39, 0x39, 0x30, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x4F, 0x4D, 0xDA, 0x01, 0x0D, 0x12, 0x05, 0x39, 0x39, 0x39, 0x5C, 0x64, 0x32, 0x04, 0x39, 0x39, 0x39, 0x30, 0xEA, 0x01, 0x0C, 0x12, 0x04, 0x39, 0x39, 0x39, 0x39, 0x32, 0x04, 0x39, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF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x5C, 0x64, 0x7B, 0x33, 0x7D, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x50, 0x54, 0xDA, 0x01, 0x0F, 0x12, 0x06, 0x31, 0x31, 0x5B, 0x32, 0x35, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x20, 0x12, 0x19, 0x31, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x35, 0x37, 0x38, 0x5D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x6C, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x50, 0x57, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x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5D, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x32, 0x30, 0x30, 0x48, 0x04, 0x48, 0x06, 0x4A, 0x02, 0x52, 0x4F, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x54, 0x12, 0x4D, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x30, 0x7C, 0x39, 0x33, 0x32, 0x29, 0x29, 0x7C, 0x5B, 0x32, 0x34, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x32, 0x31, 0x7C, 0x33, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x35, 0x5B, 0x31, 0x37, 0x38, 0x5D, 0x29, 0x29, 0x7C, 0x38, 0x5B, 0x34, 0x38, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x1D, 0x12, 0x13, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x34, 0x5D, 0x7C, 0x38, 0x5B, 0x34, 0x38, 0x5D, 0x29, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x32, 0x30, 0x30, 0x48, 0x04, 0x0A, 0x97, 0x01, 0x0A, 0x17, 0x12, 0x0B, 0x5B,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0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x91, 0x02, 0x0A, 0x15, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x1C, 0x12, 0x0E, 0x31, 0x31, 0x36, 0x31, 0x31, 0x31, 0x7C, 0x39, 0x33, 0x37, 0x7C, 0x39, 0x39, 0x38, 0x32, 0x06, 0x31, 0x31, 0x36, 0x31, 0x31, 0x31, 0x48, 0x03, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x41, 0xDA, 0x01, 0x1A, 0x12, 0x11, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x39, 0x5B, 0x37, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x68, 0x12, 0x61, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x32, 0x7C, 0x36, 0x31, 0x31, 0x31, 0x29, 0x7C, 0x34, 0x31, 0x30, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x39, 0x7C, 0x32, 0x32, 0x7C, 0x39, 0x31, 0x29, 0x29, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x32, 0x34, 0x2D, 0x37, 0x39, 0x5D, 0x7C, 0x31, 0x31, 0x7C, 0x33, 0x5B, 0x33, 0x37, 0x39, 0x5D, 0x7C, 0x34, 0x30, 0x7C, 0x36, 0x36, 0x7C, 0x38, 0x5B, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x33, 0x37, 0xF2, 0x01, 0x0E, 0x12, 0x04, 0x31, 0x34, 0x31, 0x30, 0x32, 0x04, 0x31, 0x34, 0x31, 0x30, 0x48, 0x04, 0xFA, 0x01, 0x21, 0x12, 0x16, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x30, 0x7C, 0x34, 0x31, 0x30, 0x29, 0x7C, 0x39, 0x30, 0x5B, 0x32, 0x34, 0x36, 0x37, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x30, 0x32, 0x48, 0x03, 0x48, 0x04, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xD1, 0x01, 0x0A, 0x0F, 0x12, 0x0B, 0x5B, 0x31, 0x32, 0x37, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0A, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x42, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0xEA, 0x01, 0x69, 0x12,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FF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x44, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x39, 0x39, 0x39, 0x32, 0x03, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xAE, 0x03, 0x0A, 0x19, 0x12, 0x0F, 0x5B, 0x31, 0x2D, 0x33, 0x37, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x14, 0x12, 0x08, 0x31, 0x31, 0x36, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x1F, 0x12, 0x11, 0x31, 0x31, 0x38, 0x31, 0x31, 0x5B, 0x38, 0x39, 0x5D, 0x7C, 0x37, 0x32, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x06, 0x31, 0x31, 0x38, 0x31, 0x31, 0x38, 0x48, 0x05, 0x48, 0x06, 0x4A, 0x02, 0x53, 0x45, 0xDA, 0x01, 0x14, 0x12, 0x09, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x30, 0x30, 0x30, 0x30, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x05, 0xEA, 0x01, 0xD9, 0x01, 0x12, 0xCF, 0x01, 0x31, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x35, 0x5D, 0x7C, 0x33, 0x31, 0x33, 0x7C, 0x34, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x5B, 0x30, 0x36, 0x5D, 0x7C, 0x31, 0x31, 0x5B, 0x31, 0x37, 0x5D, 0x7C, 0x31, 0x32, 0x33, 0x29, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x38, 0x5D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x31, 0x5B, 0x30, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x36, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x30, 0x32, 0x33, 0x35, 0x38, 0x5D, 0x7C, 0x33, 0x33, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x30, 0x7C, 0x36, 0x5B, 0x31, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x33, 0x32, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x37, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x32, 0x32, 0x7C, 0x38, 0x38, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x31, 0x5B, 0x30, 0x31, 0x33, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x35, 0x31, 0x30, 0x29, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x05, 0x31, 0x31, 0x33, 0x31, 0x33, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x3F, 0x12, 0x36, 0x32, 0x28, 0x3F, 0x3A, 0x32, 0x5B, 0x30, 0x32, 0x33, 0x35, 0x38, 0x5D, 0x7C, 0x33, 0x33, 0x7C, 0x34, 0x5B, 0x30, 0x31, 0x5D, 0x7C, 0x35, 0x30, 0x7C, 0x36, 0x5B, 0x31, 0x2D, 0x34, 0x5D, 0x29, 0x7C, 0x33, 0x32, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x32, 0x32, 0x7C, 0x38, 0x38, 0x29, 0x7C, 0x39, 0x31, 0x32, 0x32, 0x03, 0x32, 0x32, 0x32, 0x48, 0x03, 0x8A, 0x02, 0x11, 0x12, 0x06, 0x37, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x05, 0x37, 0x32, 0x31, 0x32, 0x33, 0x48, 0x05, 0x0A, 0xC8, 0x01, 0x0A, 0x14, 0x12, 0x0C, 0x5B, 0x31, 0x37, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x10, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x33, 0x35, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x33, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x47, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x39, 0x39, 0x5B, 0x33, 0x35, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x33, 0x48, 0x03, 0xEA, 0x01, 0x48, 0x12, 0x41, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x33, 0x36, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x5B, 0x35, 0x37, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x29, 0x29, 0x7C, 0x37, 0x37, 0x32, 0x32, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x30, 0x32, 0x2D, 0x39, 0x5D, 0x32, 0x03, 0x39, 0x39, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x37, 0x37, 0x32, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x37, 0x37, 0x32, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x96, 0x01, 0x0A, 0x11, 0x12, 0x0B, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x13, 0x12, 0x0A, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x39, 0x39, 0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, 0x36, 0x30, 0x34, 0x30, 0x30, 0x32, 0x05, 0x36, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x36, 0x30, 0x34, 0x30, 0x30, 0x32, 0x05, 0x36, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x75, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x4D, 0xDA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x33, 0x35, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x33, 0xEA, 0x01, 0x0E, 0x12, 0x07, 0x31, 0x31, 0x5B, 0x33, 0x35, 0x38, 0x5D, 0x32, 0x03, 0x31, 0x31, 0x33, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x91, 0x02, 0x0A, 0x17, 0x12, 0x0B, 0x5B, 0x31, 0x32, 0x5D, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x35, 0x7D, 0x48, 0x02, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x2A, 0x12, 0x1C, 0x31, 0x28, 0x3F, 0x3A, 0x35, 0x31, 0x35, 0x7C, 0x5B, 0x37, 0x38, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x31, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x02, 0x31, 0x37, 0x48, 0x02, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x2A, 0x23, 0x12, 0x16, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x32, 0x34, 0x36, 0x5D, 0x7C, 0x5B, 0x34, 0x36, 0x38, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x32, 0x34, 0x30, 0x30, 0x30, 0x48, 0x05, 0x48, 0x06, 0x4A, 0x02, 0x53, 0x4E, 0xDA, 0x01, 0x0D, 0x12, 0x05, 0x31, 0x5B, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x37, 0x48, 0x02, 0xEA, 0x01, 0x43, 0x12, 0x3D, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x36, 0x39, 0x5D, 0x7C, 0x28, 0x3F, 0x3A, 0x5B, 0x32, 0x34, 0x36, 0x5D, 0x5C, 0x64, 0x7C, 0x35, 0x31, 0x29, 0x5C, 0x64, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x36, 0x5D, 0x7C, 0x5B, 0x31, 0x32, 0x34, 0x36, 0x38, 0x5D, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x31, 0x5B, 0x32, 0x37, 0x38, 0x5D, 0x32, 0x02, 0x31, 0x32, 0xF2, 0x01, 0x1B, 0x12, 0x0E, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x7C, 0x32, 0x29, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x32, 0x05, 0x32, 0x32, 0x30, 0x30, 0x30, 0x48, 0x05, 0x48,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0x0A, 0x0E, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x35, 0x32, 0x03, 0x31, 0x31, 0x35, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x52, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x35, 0x32, 0x03, 0x31, 0x31, 0x35, 0x48, 0x03, 0xEA, 0x01, 0x0F, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x6C, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0A, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x54, 0xDA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0xEA, 0x01, 0x0A, 0x12, 0x03, 0x31, 0x31, 0x32, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x93, 0x01, 0x0A, 0x18, 0x12, 0x12, 0x5B, 0x34, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0C, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x53, 0x56, 0xDA, 0x01, 0x0C, 0x12, 0x03, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x10, 0x12, 0x09, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x30, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x30, 0x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FF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xE0, 0x05, 0x0A, 0x0E, 0x12, 0x08, 0x31, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x33, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x22, 0x5F, 0x12, 0x58, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x7C, 0x32, 0x5B, 0x30, 0x33, 0x5D, 0x7C, 0x33, 0x5B, 0x33, 0x34, 0x37, 0x39, 0x5D, 0x7C, 0x35, 0x35, 0x7C, 0x37, 0x5B, 0x36, 0x37, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x34, 0x36, 0x5D, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x35, 0x35, 0x7C, 0x37, 0x38, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x34, 0x34, 0x7C, 0x36, 0x5B, 0x37, 0x39, 0x5D, 0x7C, 0x38, 0x38, 0x7C, 0x39, 0x5B, 0x31, 0x36, 0x5D, 0x29, 0x7C, 0x38, 0x38, 0x5C, 0x64, 0x7C, 0x39, 0x5B, 0x31, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x39, 0x31, 0x2A, 0x25, 0x12, 0x1B, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x33, 0x7C, 0x32, 0x5B, 0x32, 0x33, 0x5D, 0x5C, 0x64, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x39, 0x7C, 0x35, 0x36, 0x29, 0x29, 0x32, 0x04, 0x31, 0x31, 0x31, 0x33, 0x48, 0x04, 0x4A, 0x02, 0x54, 0x48, 0xDA, 0x01, 0x15, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x36, 0x36, 0x39, 0x7C, 0x39, 0x5B, 0x31, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x39, 0x31, 0xEA, 0x01, 0xBA, 0x02, 0x12, 0xB2, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x32, 0x5D, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x33, 0x5D, 0x7C, 0x31, 0x5B, 0x31, 0x2D, 0x33, 0x35, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x33, 0x35, 0x38, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x33, 0x2D, 0x37, 0x39, 0x5D, 0x7C, 0x34, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x38, 0x39, 0x5D, 0x7C, 0x35, 0x5B, 0x30, 0x34, 0x2D, 0x39, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x34, 0x2D, 0x37, 0x39, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x33, 0x2D, 0x39, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x32, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x32, 0x2D, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x32, 0x32, 0x7C, 0x33, 0x5B, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x7C, 0x32, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x31, 0x33, 0x5D, 0x7C, 0x35, 0x5B, 0x35, 0x36, 0x5D, 0x7C, 0x36, 0x5B, 0x34, 0x35, 0x5D, 0x7C, 0x37, 0x33, 0x29, 0x7C, 0x34, 0x37, 0x37, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x34, 0x5B, 0x30, 0x2D, 0x33, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x35, 0x5B, 0x31, 0x2D, 0x38, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x31, 0x36, 0x37, 0x39, 0x5D, 0x7C, 0x37, 0x5B, 0x31, 0x32, 0x35, 0x36, 0x38, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x2D, 0x32, 0x34, 0x35, 0x38, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x31, 0x33, 0x35, 0x38, 0x39, 0x5D, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x32, 0x39, 0x5D, 0x7C, 0x32, 0x5B, 0x30, 0x33, 0x5D, 0x7C, 0x34, 0x5B, 0x33, 0x2D, 0x36, 0x5D, 0x7C, 0x36, 0x5B, 0x31, 0x2D, 0x39, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x32, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x35, 0x38, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x31, 0x34, 0x2D, 0x39, 0x5D, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x31, 0x39, 0x7C, 0x37, 0x5B, 0x32, 0x37, 0x5D, 0x7C, 0x39, 0x30, 0x29, 0x7C, 0x38, 0x38, 0x38, 0x7C, 0x39, 0x5B, 0x31, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x31, 0x30, 0x30, 0xF2, 0x01, 0xCA, 0x01, 0x12, 0xBF, 0x01, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x33, 0x7C, 0x31, 0x5B, 0x31, 0x35, 0x5D, 0x7C, 0x32, 0x5B, 0x35, 0x38, 0x5D, 0x7C, 0x33, 0x5B, 0x30, 0x35, 0x36, 0x5D, 0x7C, 0x34, 0x5B, 0x30, 0x32, 0x2D, 0x34, 0x39, 0x5D, 0x7C, 0x35, 0x5B, 0x30, 0x34, 0x36, 0x2D, 0x39, 0x5D, 0x7C, 0x5B, 0x36, 0x38, 0x5D, 0x5C, 0x64, 0x7C, 0x37, 0x5B, 0x30, 0x33, 0x2D, 0x35, 0x38, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x35, 0x37, 0x39, 0x5D, 0x29, 0x7C, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x31, 0x2D, 0x33, 0x35, 0x5D, 0x7C, 0x37, 0x5B, 0x31, 0x37, 0x5D, 0x29, 0x5C, 0x64, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x30, 0x2D, 0x38, 0x5D, 0x7C, 0x34, 0x5B, 0x30, 0x2D, 0x33, 0x37, 0x38, 0x5D, 0x7C, 0x35, 0x5B, 0x31, 0x2D, 0x34, 0x37, 0x38, 0x5D, 0x7C, 0x5B, 0x36, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x7C, 0x37, 0x5B, 0x31, 0x35, 0x36, 0x5D, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x5C, 0x64, 0x7C, 0x32, 0x30, 0x7C, 0x34, 0x5B, 0x33, 0x35, 0x36, 0x5D, 0x7C, 0x36, 0x5B, 0x31, 0x2D, 0x36, 0x38, 0x5D, 0x7C, 0x37, 0x5B, 0x30, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x7C, 0x38, 0x5B, 0x30, 0x31, 0x35, 0x5D, 0x7C, 0x39, 0x5B, 0x30, 0x34, 0x35, 0x37, 0x2D, 0x39, 0x5D, 0x29, 0x29, 0x32, 0x04, 0x31, 0x31, 0x30, 0x33, 0x48, 0x04, 0xFA, 0x01, 0x0F, 0x12, 0x05, 0x31, 0x31, 0x34, 0x5C, 0x64, 0x32, 0x04, 0x31, 0x31, 0x34, 0x30, 0x48, 0x04, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0x83, 0x01, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C,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x01, 0x4A, 0x02, 0x54, 0x52, 0xDA, 0x01, 0x16, 0x12, 0x0D, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x30, 0x32, 0x5D, 0x7C, 0x35, 0x35, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0xC0, 0x03, 0x12, 0xB8, 0x03, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x33, 0x39, 0x5D, 0x7C, 0x38, 0x31, 0x31, 0x29, 0x7C, 0x32, 0x5B, 0x31, 0x32, 0x36, 0x5D, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x32, 0x36, 0x5D, 0x7C, 0x33, 0x37, 0x3F, 0x7C, 0x5B, 0x35, 0x38, 0x5D, 0x36, 0x7C, 0x36, 0x35, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x31, 0x34, 0x5D, 0x7C, 0x37, 0x31, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x33, 0x35, 0x2D, 0x39, 0x5D, 0x7C, 0x30, 0x37, 0x7C, 0x37, 0x38, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x36, 0x7C, 0x5B, 0x31, 0x33, 0x38, 0x39, 0x5D, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x37, 0x39, 0x5D, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7C, 0x36, 0x33, 0x7C, 0x39, 0x35, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x37, 0x7C, 0x32, 0x36, 0x38, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x7C, 0x32, 0x33, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x37, 0x5B, 0x32, 0x36, 0x5D, 0x7C, 0x38, 0x32, 0x29, 0x7C, 0x36, 0x5B, 0x31, 0x34, 0x5D, 0x34, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x7C, 0x38, 0x39, 0x29, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x35, 0x7C, 0x37, 0x32, 0x29, 0x7C, 0x33, 0x35, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x33, 0x30, 0x7C, 0x36, 0x34, 0x29, 0x7C, 0x35, 0x30, 0x32, 0x7C, 0x36, 0x37, 0x34, 0x7C, 0x37, 0x34, 0x37, 0x7C, 0x38, 0x35, 0x31, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x39, 0x5D, 0x7C, 0x36, 0x30, 0x29, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x7C, 0x33, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x5B, 0x34, 0x37, 0x5D, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x31, 0x29, 0x7C, 0x34, 0x33, 0x39, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x34, 0x33, 0x7C, 0x35, 0x35, 0x29, 0x7C, 0x37, 0x31, 0x37, 0x7C, 0x38, 0x33, 0x32, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x35, 0x7C, 0x32, 0x39, 0x30, 0x7C, 0x5B, 0x34, 0x2D, 0x36, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x37, 0x37, 0x32, 0x7C, 0x38, 0x33, 0x33, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x36, 0x5D, 0x31, 0x7C, 0x39, 0x32, 0x29, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x32, 0x33, 0x36, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x33, 0x39, 0x7C, 0x38, 0x5B, 0x35, 0x39, 0x5D, 0x29, 0x7C, 0x37, 0x36, 0x39, 0x29, 0x7C, 0x37, 0x38, 0x39, 0x30, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x36, 0x38, 0x38, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x38, 0x7C, 0x36, 0x35, 0x29, 0x7C, 0x38, 0x35, 0x5B, 0x30, 0x36, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x35, 0x39, 0x7C, 0x32, 0x39, 0x30, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x13, 0x12, 0x09, 0x32, 0x38, 0x35, 0x30, 0x7C, 0x35, 0x34, 0x32, 0x30, 0x32, 0x04, 0x35, 0x34, 0x32, 0x30, 0x48, 0x04, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x8B, 0x03, 0x12, 0xFE, 0x02, 0x31, 0x28, 0x3F, 0x3A, 0x33, 0x28, 0x3F, 0x3A, 0x33, 0x37, 0x7C, 0x5B, 0x35, 0x38, 0x5D, 0x36, 0x7C, 0x36, 0x35, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x34, 0x7C, 0x37, 0x31, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x7C, 0x37, 0x38, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x32, 0x5D, 0x36, 0x7C, 0x39, 0x39, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x33, 0x7C, 0x36, 0x33, 0x7C, 0x39, 0x35, 0x29, 0x29, 0x7C, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x37, 0x7C, 0x32, 0x36, 0x38, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x37, 0x7C, 0x32, 0x33, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x37, 0x5B, 0x32, 0x36, 0x5D, 0x7C, 0x38, 0x32, 0x29, 0x7C, 0x36, 0x5B, 0x31, 0x34, 0x5D, 0x34, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x33, 0x30, 0x7C, 0x38, 0x39, 0x29, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x35, 0x7C, 0x37, 0x32, 0x29, 0x7C, 0x33, 0x35, 0x33, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x7C, 0x33, 0x30, 0x7C, 0x36, 0x34, 0x29, 0x7C, 0x35, 0x30, 0x32, 0x7C, 0x36, 0x37, 0x34, 0x7C, 0x37, 0x34, 0x37, 0x7C, 0x38, 0x35, 0x31, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x5B, 0x32, 0x39, 0x5D, 0x7C, 0x36, 0x30, 0x29, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x32, 0x35, 0x7C, 0x33, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x5B, 0x34, 0x37, 0x5D, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x31, 0x33, 0x5D, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x31, 0x29, 0x7C, 0x34, 0x33, 0x39, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x34, 0x33, 0x7C, 0x35, 0x35, 0x29, 0x7C, 0x37, 0x31, 0x37, 0x7C, 0x38, 0x33, 0x32, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x34, 0x35, 0x7C, 0x32, 0x39, 0x30, 0x7C, 0x5B, 0x34, 0x2D, 0x36, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x7C, 0x37, 0x37, 0x32, 0x7C, 0x38, 0x33, 0x33, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x5B, 0x30, 0x36, 0x5D, 0x31, 0x7C, 0x39, 0x32, 0x29, 0x29, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x32, 0x33, 0x36, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x32, 0x7C, 0x33, 0x39, 0x7C, 0x38, 0x5B, 0x35, 0x39, 0x5D, 0x29, 0x7C, 0x37, 0x36, 0x39, 0x29, 0x7C, 0x37, 0x38, 0x39, 0x30, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x36, 0x38, 0x38, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x38, 0x7C, 0x36, 0x35, 0x29, 0x7C, 0x38, 0x35, 0x5B, 0x30, 0x36, 0x5D, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x35, 0x39, 0x7C, 0x32, 0x39, 0x30, 0x29, 0x32, 0x04, 0x35, 0x34, 0x32, 0x30, 0x48, 0x03, 0x48, 0x04, 0x0A, 0x73, 0x0A, 0x09, 0x12, 0x05, 0x39, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0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0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x54, 0x5A, 0xDA, 0x01, 0x13, 0x12, 0x0A, 0x31, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x17, 0x12, 0x10, 0x31, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x34, 0x36, 0x34, 0x30, 0x30, 0x7C, 0x39, 0x39, 0x39, 0x32, 0x03, 0x31, 0x31, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x12, 0x12, 0x07, 0x34, 0x36, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x36, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x12, 0x12, 0x07, 0x34, 0x36, 0x34, 0x5C, 0x64, 0x5C, 0x64, 0x32, 0x05, 0x34, 0x36, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x9D, 0x02, 0x0A, 0x16, 0x12, 0x0C, 0x5B, 0x31, 0x38, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x35, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x48, 0x06, 0x22, 0x21, 0x12, 0x15, 0x31, 0x31, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x32, 0x06, 0x31, 0x31, 0x36, 0x30, 0x30, 0x30, 0x48, 0x06, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x55, 0x41, 0xDA, 0x01, 0x17, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x2D, 0x33, 0x5D, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0xEA, 0x01, 0x73, 0x12, 0x6C, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x5B, 0x31, 0x2D, 0x34, 0x39, 0x5D, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x30, 0x7C, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x32, 0x33, 0x29, 0x29, 0x7C, 0x38, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x32, 0x7D, 0x29, 0x7C, 0x5B, 0x32, 0x37, 0x38, 0x5D, 0x5C, 0x64, 0x7C, 0x34, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x31, 0x7C, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x36, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x30, 0x30, 0x5C, 0x64, 0x7B, 0x31, 0x2C, 0x32, 0x7D, 0x32, 0x03, 0x31, 0x31, 0x32, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x22, 0x12, 0x15, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x38, 0x7C, 0x5B, 0x38, 0x39, 0x5D, 0x30, 0x30, 0x29, 0x5C, 0x64, 0x7B,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01, 0x32, 0x28, 0x3F, 0x3A, 0x34, 0x32, 0x38, 0x30, 0x7C, 0x35, 0x32, 0x30, 0x39, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x34, 0x34, 0x39, 0x7C, 0x36, 0x36, 0x33, 0x29, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x33, 0x34, 0x30, 0x7C, 0x33, 0x37, 0x38, 0x36, 0x7C, 0x35, 0x35, 0x36, 0x34, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x31, 0x33, 0x35, 0x7C, 0x32, 0x35, 0x34, 0x29, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x33, 0x36, 0x36, 0x7C, 0x34, 0x36, 0x33, 0x29, 0x7C, 0x33, 0x33, 0x35, 0x35, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x31, 0x35, 0x37, 0x7C, 0x33, 0x32, 0x37, 0x29, 0x7C, 0x37, 0x35, 0x35, 0x33, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x32, 0x32, 0x31, 0x7C, 0x32, 0x37, 0x37, 0x29, 0x29, 0x7C, 0x35, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x34, 0x34, 0x7C, 0x34, 0x38, 0x39, 0x32, 0x7C, 0x35, 0x39, 0x32, 0x38, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x31, 0x38, 0x37, 0x7C, 0x33, 0x34, 0x32, 0x29, 0x29, 0x7C, 0x36, 0x39, 0x33, 0x38, 0x38, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x38, 0x7C, 0x30, 0x38, 0x37, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x32, 0x38, 0x38, 0x7C, 0x39, 0x30, 0x39, 0x29, 0x7C, 0x36, 0x34, 0x32, 0x36, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x36, 0x32, 0x33, 0x34, 0x7C, 0x39, 0x36, 0x31, 0x36, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x35, 0x32, 0x39, 0x37, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x34, 0x30, 0x7C, 0x38, 0x33, 0x35, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x32, 0x39, 0x34, 0x7C, 0x36, 0x38, 0x38, 0x29, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x36, 0x38, 0x39, 0x7C, 0x37, 0x39, 0x36, 0x29, 0x29, 0x32, 0x05, 0x32, 0x34, 0x32, 0x38, 0x30, 0x48, 0x05, 0x4A, 0x02, 0x55, 0x53, 0xDA, 0x01, 0x10, 0x12, 0x07, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x31, 0x31, 0x32, 0x03, 0x39, 0x31, 0x31, 0x48, 0x03, 0xEA, 0x01, 0x40, 0x12, 0x39, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x32, 0x7C, 0x35, 0x5B, 0x31, 0x2D, 0x34, 0x37, 0x5D, 0x7C, 0x5B, 0x36, 0x38, 0x5D, 0x5C, 0x64, 0x7C, 0x37, 0x5B, 0x30, 0x2D, 0x35, 0x37, 0x5D, 0x7C, 0x39, 0x38, 0x29, 0x29, 0x7C, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x5C, 0x64, 0x7B, 0x33, 0x2C, 0x35, 0x7D, 0x29, 0x32, 0x03, 0x39, 0x31, 0x31, 0xF2, 0x01, 0x9E, 0x01, 0x12, 0x90, 0x01, 0x32, 0x28, 0x3F, 0x3A, 0x33, 0x33, 0x33, 0x33, 0x7C, 0x34, 0x32, 0x32, 0x34, 0x32, 0x7C, 0x35, 0x36, 0x34, 0x34, 0x37, 0x7C, 0x36, 0x36, 0x38, 0x38, 0x7C, 0x37, 0x35, 0x36, 0x32, 0x32, 0x7C, 0x39, 0x30, 0x30, 0x32, 0x29, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x31, 0x30, 0x31, 0x30, 0x7C, 0x32, 0x36, 0x36, 0x35, 0x7C, 0x37, 0x34, 0x30, 0x34, 0x29, 0x7C, 0x34, 0x30, 0x34, 0x30, 0x34, 0x7C, 0x35, 0x36, 0x30, 0x35, 0x36, 0x30, 0x7C, 0x36, 0x28, 0x3F, 0x3A, 0x30, 0x30, 0x36, 0x30, 0x7C, 0x32, 0x32, 0x36, 0x33, 0x39, 0x7C, 0x35, 0x32, 0x34, 0x36, 0x7C, 0x37, 0x36, 0x32, 0x32, 0x29, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x30, 0x31, 0x7C, 0x33, 0x38, 0x32, 0x32, 0x7C, 0x34, 0x36, 0x36, 0x36, 0x29, 0x7C, 0x38, 0x28, 0x3F, 0x3A, 0x33, 0x38, 0x32, 0x35, 0x35, 0x7C, 0x34, 0x38, 0x31, 0x36, 0x7C, 0x37, 0x32, 0x32, 0x36, 0x35, 0x29, 0x7C, 0x39, 0x39, 0x30, 0x39, 0x39, 0x32, 0x05, 0x37, 0x33, 0x38, 0x32, 0x32, 0x48, 0x05, 0x48, 0x06, 0xFA, 0x01, 0x28, 0x12, 0x19, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x33, 0x7D, 0x7C, 0x33, 0x33, 0x36, 0x36, 0x39, 0x7C, 0x5B, 0x32, 0x33, 0x35, 0x36, 0x5D, 0x31, 0x31, 0x32, 0x05, 0x33, 0x33, 0x36, 0x36, 0x39, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x8A, 0x02, 0x19, 0x12, 0x0C, 0x5B, 0x32, 0x2D, 0x39, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x2C, 0x35, 0x7D, 0x32, 0x05, 0x32, 0x30, 0x35, 0x36, 0x36, 0x48, 0x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 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x29, 0x3F, 0x48, 0x02, 0x48, 0x03, 0x48, 0x05, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x55, 0x5A, 0xDA, 0x01, 0x1E, 0x12, 0x14, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x35, 0x30, 0x29, 0x32, 0x02, 0x30, 0x31, 0x48, 0x02, 0x48, 0x03, 0xEA, 0x01, 0x20, 0x12, 0x1A, 0x30, 0x28, 0x3F, 0x3A, 0x30, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x5B, 0x31, 0x32, 0x33, 0x5D, 0x7C, 0x35, 0x30, 0x29, 0x7C, 0x34, 0x35, 0x34, 0x30, 0x30, 0x32, 0x02, 0x30, 0x31, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x10, 0x12, 0x05, 0x34, 0x35, 0x34, 0x30, 0x30, 0x32, 0x05, 0x34, 0x35, 0x34, 0x30, 0x30, 0x48, 0x05, 0x8A, 0x02, 0x10, 0x12, 0x05, 0x34, 0x35, 0x34, 0x30, 0x30, 0x32, 0x05, 0x34, 0x35, 0x34, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x7B, 0x0A, 0x09, 0x12, 0x05, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0F, 0x12, 0x08, 0x31, 0x31, 0x5B, 0x32, 0x33, 0x35, 0x38, 0x5D, 0x32, 0x03,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xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xB4, 0x02, 0x0A, 0x14, 0x12, 0x0C, 0x5B, 0x31, 0x33, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x32, 0x2C, 0x34, 0x7D, 0x48, 0x03, 0x48, 0x04, 0x48, 0x05, 0x22, 0x19, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x05, 0x2A, 0x18, 0x12, 0x0D, 0x34, 0x31, 0x28, 0x3F, 0x3A, 0x33, 0x34, 0x38, 0x7C, 0x38, 0x35, 0x31, 0x29, 0x32, 0x05, 0x34, 0x31, 0x33, 0x34, 0x38, 0x48, 0x05, 0x4A, 0x02, 0x5A, 0x41, 0xDA, 0x01, 0x19, 0x12, 0x0E, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x31, 0x5C, 0x64, 0x5C, 0x64, 0x7C, 0x31, 0x32, 0x29, 0x32, 0x03, 0x31, 0x31, 0x32, 0x48, 0x03, 0x48, 0x05, 0xEA, 0x01, 0x50, 0x12, 0x49, 0x31, 0x28, 0x3F, 0x3A, 0x30, 0x28, 0x3F, 0x3A, 0x31, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x7C, 0x37, 0x37, 0x29, 0x7C, 0x32, 0x30, 0x7C, 0x37, 0x29, 0x7C, 0x31, 0x5B, 0x31, 0x32, 0x5D, 0x7C, 0x37, 0x37, 0x28, 0x3F, 0x3A, 0x33, 0x5B, 0x32, 0x33, 0x37, 0x5D, 0x7C, 0x5B, 0x34, 0x35, 0x5D, 0x37, 0x7C, 0x36, 0x5B, 0x32, 0x37, 0x39, 0x5D, 0x7C, 0x39, 0x5B, 0x32, 0x36, 0x5D, 0x29, 0x29, 0x7C, 0x5B, 0x33, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x03, 0x31, 0x30, 0x37, 0xF2, 0x01, 0x4D, 0x12, 0x42, 0x33, 0x28, 0x3F, 0x3A, 0x30, 0x37, 0x38, 0x5B, 0x32, 0x33, 0x5D, 0x7C, 0x37, 0x28, 0x3F, 0x3A, 0x30, 0x36, 0x34, 0x7C, 0x35, 0x36, 0x37, 0x29, 0x7C, 0x38, 0x31, 0x32, 0x36, 0x29, 0x7C, 0x34, 0x28, 0x3F, 0x3A, 0x32, 0x36, 0x39, 0x39, 0x7C, 0x33, 0x28, 0x3F, 0x3A, 0x36, 0x39, 0x39, 0x7C, 0x39, 0x34, 0x5B, 0x31, 0x36, 0x5D, 0x29, 0x7C, 0x37, 0x37, 0x35, 0x31, 0x7C, 0x38, 0x38, 0x33, 0x37, 0x29, 0x32, 0x05, 0x33, 0x30, 0x37, 0x38, 0x32, 0x48, 0x05, 0xFA, 0x01, 0x0C, 0x12, 0x03, 0x31, 0x31, 0x31, 0x32, 0x03, 0x31, 0x31, 0x31, 0x48, 0x03, 0x8A, 0x02, 0x14, 0x12, 0x09, 0x5B, 0x33, 0x34, 0x5D, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x05, 0x33, 0x30, 0x30, 0x30, 0x30, 0x48, 0x05, 0x0A, 0x88, 0x01, 0x0A, 0x0C, 0x12, 0x08, 0x5B, 0x31, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x48, 0x03, 0x22, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x2A, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x4A, 0x02, 0x5A, 0x4D, 0xDA, 0x01, 0x16, 0x12, 0x0F, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x31, 0x33, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x39, 0x39, 0xEA, 0x01, 0x16, 0x12, 0x0F, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x31, 0x33, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x0A, 0xDF, 0x01, 0x0A, 0x19, 0x12, 0x13, 0x5B, 0x31, 0x33, 0x39, 0x5D, 0x5C, 0x64, 0x5C, 0x64, 0x28, 0x3F, 0x3A, 0x5C, 0x64, 0x7B, 0x32, 0x7D, 0x29, 0x3F, 0x48, 0x03, 0x48, 0x05, 0x22, 0x17, 0x12, 0x0E, 0x39, 0x28, 0x3F, 0x3A, 0x35, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x7C, 0x36, 0x31, 0x29, 0x32, 0x03, 0x39, 0x36, 0x31, 0x48, 0x03, 0x2A, 0x11, 0x12, 0x06, 0x33, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x32, 0x05, 0x33, 0x30, 0x31, 0x32, 0x33, 0x48, 0x05, 0x4A, 0x02, 0x5A, 0x57, 0xDA, 0x01, 0x19, 0x12, 0x10, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x32, 0x7C, 0x39, 0x39, 0x5B, 0x33, 0x2D, 0x35, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x39, 0x39, 0x48, 0x03, 0xEA, 0x01, 0x32, 0x12, 0x2B, 0x31, 0x31, 0x5B, 0x32, 0x34, 0x36, 0x39, 0x5D, 0x7C, 0x33, 0x5C, 0x64, 0x7B, 0x34, 0x7D, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x35, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x32, 0x35, 0x5D, 0x7C, 0x39, 0x5B, 0x33, 0x2D, 0x35, 0x39, 0x5D, 0x29, 0x32, 0x03, 0x39, 0x39, 0x39, 0xF2, 0x01, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xFA, 0x01, 0x24, 0x12, 0x1B, 0x28, 0x3F, 0x3A, 0x31, 0x31, 0x34, 0x7C, 0x39, 0x28, 0x3F, 0x3A, 0x35, 0x5B, 0x30, 0x32, 0x33, 0x5D, 0x7C, 0x36, 0x5B, 0x30, 0x2D, 0x32, 0x35, 0x5D, 0x29, 0x29, 0x32, 0x03, 0x31, 0x31, 0x34, 0x48, 0x03, 0x8A, 0x02, 0x0B, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; } // namespace int short_metadata_size() { return sizeof(data) / sizeof(data[0]); } const void* short_metadata_get() { return data; } } // namespace phonenumbers } // namespace i18n
#include <bts/blockchain/packet_record.hpp> #include <bts/blockchain/chain_interface.hpp> namespace bts { namespace blockchain { // Using next_available_claim_index() >= claim_statuses.size() claim that the packet is out uint32_t packet_record::next_available_claim_index() const { uint32_t index = 0; for ( uint32_t i = 0; i < claim_statuses.size(); i ++ ) { if ( claim_statuses[i].account_id == -1) { return index; } else { index ++; } } return index; } bool packet_record::is_unclaimed_empty() const { return next_available_claim_index() >= claim_statuses.size(); } asset packet_record::left_packet_amount() const { asset left_amount(0, amount.asset_id); for ( uint32_t i = 0; i < claim_statuses.size(); i ++ ) { if ( claim_statuses[i].account_id == -1) { left_amount += claim_statuses[i].amount; } else { // pass, already be claimed; } } return left_amount; } void packet_record::sanity_check( const chain_interface& db )const { try { FC_ASSERT( from_account_id == 0 || db.lookup<account_record>( abs( from_account_id ) ).valid() ); FC_ASSERT( amount.amount > 0 ); FC_ASSERT( amount.asset_id == 0 || db.lookup<asset_record>( amount.asset_id ).valid() ); for ( auto status : claim_statuses ) { FC_ASSERT( status.amount.asset_id == amount.asset_id ); } } FC_CAPTURE_AND_RETHROW( (*this) ) } opacket_record packet_record::lookup( const chain_interface& db, const packet_id_type& id ) { try { return db.packet_lookup_by_index( id ); } FC_CAPTURE_AND_RETHROW( (id) ) } void packet_record::store( chain_interface& db, const packet_id_type& id, const packet_record& record ) { try { db.packet_insert_into_index_map( id, record ); } FC_CAPTURE_AND_RETHROW( (id)(record) ) } void packet_record::remove( chain_interface& db, const packet_id_type& id ) { try { const opacket_record prev_record = db.lookup<packet_record>( id ); if( prev_record.valid() ) db.packet_erase_from_index_map( id ); } FC_CAPTURE_AND_RETHROW( (id) ) } } } // bts::blockchain
/**************************************************************************** ** Meta object code from reading C++ file 'infowidget.h' ** ** Created: Tue May 5 10:34:44 2009 ** by: The Qt Meta Object Compiler version 61 (Qt 4.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "infowidget.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'infowidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 61 #error "This file was generated using the moc from 4.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_MoodBox__InfoWidget[] = { // content: 2, // revision 0, // classname 0, 0, // classinfo 2, 12, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors // signals: signature, parameters, type, tag, flags 21, 20, 20, 20, 0x05, // slots: signature, parameters, type, tag, flags 32, 20, 20, 20, 0x08, 0 // eod }; static const char qt_meta_stringdata_MoodBox__InfoWidget[] = { "MoodBox::InfoWidget\0\0finished()\0" "onFinishLinkAction()\0" }; const QMetaObject MoodBox::InfoWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_MoodBox__InfoWidget, qt_meta_data_MoodBox__InfoWidget, 0 } }; const QMetaObject *MoodBox::InfoWidget::metaObject() const { return &staticMetaObject; } void *MoodBox::InfoWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_MoodBox__InfoWidget)) return static_cast<void*>(const_cast< InfoWidget*>(this)); if (!strcmp(_clname, "InfoWidgetClass")) return static_cast< InfoWidgetClass*>(const_cast< InfoWidget*>(this)); return QWidget::qt_metacast(_clname); } int MoodBox::InfoWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: finished(); break; case 1: onFinishLinkAction(); break; default: ; } _id -= 2; } return _id; } // SIGNAL 0 void MoodBox::InfoWidget::finished() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../../src/algorithms_data_structs/phone_numbers_transform.h" namespace { using namespace testing; using cppchallenge::algorithms_data_structs::phone_numbers_transform; using cppchallenge::algorithms_data_structs::phone_number_transform; TEST(PhoneNumbersTransformTest, EmptyContainerShouldReturnEmpty) { std::vector<std::string> testee; phone_numbers_transform(testee.begin(), testee.end(), "44"); ASSERT_THAT(testee, IsEmpty()); } TEST(PhoneNumbersTransformTest, SampleTransformations) { auto testee = std::vector<std::string>{"07555 123456", "07555123456", "+447555123456", "447555123456", "7555123456"}; phone_numbers_transform(testee.begin(), testee.end(), "44"); for (const auto& number : testee) { ASSERT_EQ(number, "+447555123456"); } } TEST(PhoneNumbersTransformTest, DifferentCountryShouldNotModify) { auto result = phone_number_transform("+48123456789", "44"); ASSERT_EQ(result, "+48123456789"); } }
#pragma once #include "vertex.hpp" #include "camera3d.hpp" #include "transform.hpp" #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/Color.hpp> class Renderer; class Renderable; struct RenderStackState { public: RenderStackState(Renderer& renderer); RenderStackState(sf::RenderTarget& target); ~RenderStackState(); private: sf::RenderTarget& myTarget; }; class Renderer { public: Renderer(sf::RenderTarget& target); const Camera3D& getCamera() const; Camera3D& accessCamera(); void clear(); void draw(const std::vector<Vertex>& vertices, sf::PrimitiveType primitive, Transform transform = Transform::Identity, sf::Shader* shader = nullptr); void draw(const std::vector<Vertex>& vertices, const std::vector<IndexType>& indices, sf::PrimitiveType primitive, Transform transform = Transform::Identity, sf::Shader* shader = nullptr); void draw(const sf::Drawable& drawable, sf::RenderStates states = sf::RenderStates::Default); void draw(const Renderable& renderable, sf::Shader* shader = nullptr); private: friend class RenderStackState; void setActive(); void applyTransformation(Transform transform); void applyInverseTransformation(Transform transform); void setupShader(sf::Shader* shader); sf::RenderTarget& myTarget; Camera3D myCamera; sf::Color myClearColor = sf::Color::Black; };
#define BZ #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> using ll = int64_t; using ld = long double; using ull = uint64_t; using namespace std; using namespace __gnu_pbds; typedef vector <int> vi; typedef pair <int, int> ii; const int INF = 1 << 30; int f(int n) { string s = to_string(n); while(s.size() < 6) s = "0" + s; int cnt = 0; for(int i = 0; i < 3; i++) { cnt += s[i] - '0'; cnt -= s[s.size() - i - 1] - '0'; } return cnt; } int main() { #ifdef BZ freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.setf(ios::fixed); cout.precision(20); int n; cin >> n; if(f(n + 1) == 0 || f(n - 1) == 0) cout << "Yes\n"; else cout << "No\n"; }
//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the Link Time Optimization library. This library is // intended to be used by linker to optimize code at link time. // //===----------------------------------------------------------------------===// #include "llvm/LTO/legacy/LTOCodeGenerator.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Analysis/Passes.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/CodeGen/ParallelCG.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/Config/config.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfo.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LLVMRemarkStreamer.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Mangler.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassTimingInfo.h" #include "llvm/IR/Verifier.h" #include "llvm/InitializePasses.h" #include "llvm/LTO/LTO.h" #include "llvm/LTO/legacy/LTOModule.h" #include "llvm/LTO/legacy/UpdateCompilerUsed.h" #include "llvm/Linker/Linker.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/SubtargetFeature.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/YAMLTraits.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/Internalize.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/IPO/WholeProgramDevirt.h" #include "llvm/Transforms/ObjCARC.h" #include "llvm/Transforms/Utils/ModuleUtils.h" #include <system_error> using namespace llvm; const char* LTOCodeGenerator::getVersionString() { #ifdef LLVM_VERSION_INFO return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO; #else return PACKAGE_NAME " version " PACKAGE_VERSION; #endif } namespace llvm { cl::opt<bool> LTODiscardValueNames( "lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), #ifdef NDEBUG cl::init(true), #else cl::init(false), #endif cl::Hidden); cl::opt<bool> RemarksWithHotness( "lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden); cl::opt<std::string> RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename")); cl::opt<std::string> RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex")); cl::opt<std::string> RemarksFormat( "lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml")); cl::opt<std::string> LTOStatsFile( "lto-stats-file", cl::desc("Save statistics to the specified file"), cl::Hidden); } LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context) : Context(Context), MergedModule(new Module("ld-temp.o", Context)), TheLinker(new Linker(*MergedModule)) { Context.setDiscardValueNames(LTODiscardValueNames); Context.enableDebugTypeODRUniquing(); initializeLTOPasses(); } LTOCodeGenerator::~LTOCodeGenerator() {} // Initialize LTO passes. Please keep this function in sync with // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO // passes are initialized. void LTOCodeGenerator::initializeLTOPasses() { PassRegistry &R = *PassRegistry::getPassRegistry(); initializeInternalizeLegacyPassPass(R); initializeIPSCCPLegacyPassPass(R); initializeGlobalOptLegacyPassPass(R); initializeConstantMergeLegacyPassPass(R); initializeDAHPass(R); initializeInstructionCombiningPassPass(R); initializeSimpleInlinerPass(R); initializePruneEHPass(R); initializeGlobalDCELegacyPassPass(R); initializeArgPromotionPass(R); initializeJumpThreadingPass(R); initializeSROALegacyPassPass(R); initializeAttributorLegacyPassPass(R); initializePostOrderFunctionAttrsLegacyPassPass(R); initializeReversePostOrderFunctionAttrsLegacyPassPass(R); initializeGlobalsAAWrapperPassPass(R); initializeLegacyLICMPassPass(R); initializeMergedLoadStoreMotionLegacyPassPass(R); initializeGVNLegacyPassPass(R); initializeMemCpyOptLegacyPassPass(R); initializeDCELegacyPassPass(R); initializeCFGSimplifyPassPass(R); } void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) { const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs(); for (int i = 0, e = undefs.size(); i != e; ++i) AsmUndefinedRefs.insert(undefs[i]); } bool LTOCodeGenerator::addModule(LTOModule *Mod) { assert(&Mod->getModule().getContext() == &Context && "Expected module in same context"); bool ret = TheLinker->linkInModule(Mod->takeModule()); setAsmUndefinedRefs(Mod); // We've just changed the input, so let's make sure we verify it. HasVerifiedInput = false; return !ret; } void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) { assert(&Mod->getModule().getContext() == &Context && "Expected module in same context"); AsmUndefinedRefs.clear(); MergedModule = Mod->takeModule(); TheLinker = std::make_unique<Linker>(*MergedModule); setAsmUndefinedRefs(&*Mod); // We've just changed the input, so let's make sure we verify it. HasVerifiedInput = false; } void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) { this->Options = Options; } void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) { switch (Debug) { case LTO_DEBUG_MODEL_NONE: EmitDwarfDebugInfo = false; return; case LTO_DEBUG_MODEL_DWARF: EmitDwarfDebugInfo = true; return; } llvm_unreachable("Unknown debug format!"); } void LTOCodeGenerator::setOptLevel(unsigned Level) { OptLevel = Level; switch (OptLevel) { case 0: CGOptLevel = CodeGenOpt::None; return; case 1: CGOptLevel = CodeGenOpt::Less; return; case 2: CGOptLevel = CodeGenOpt::Default; return; case 3: CGOptLevel = CodeGenOpt::Aggressive; return; } llvm_unreachable("Unknown optimization level!"); } bool LTOCodeGenerator::writeMergedModules(StringRef Path) { if (!determineTarget()) return false; // We always run the verifier once on the merged module. verifyMergedModuleOnce(); // mark which symbols can not be internalized applyScopeRestrictions(); // create output file std::error_code EC; ToolOutputFile Out(Path, EC, sys::fs::OF_None); if (EC) { std::string ErrMsg = "could not open bitcode file for writing: "; ErrMsg += Path.str() + ": " + EC.message(); emitError(ErrMsg); return false; } // write bitcode to it WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists); Out.os().close(); if (Out.os().has_error()) { std::string ErrMsg = "could not write bitcode file: "; ErrMsg += Path.str() + ": " + Out.os().error().message(); emitError(ErrMsg); Out.os().clear_error(); return false; } Out.keep(); return true; } bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) { // make unique temp output file to put generated code SmallString<128> Filename; int FD; StringRef Extension (FileType == CGFT_AssemblyFile ? "s" : "o"); std::error_code EC = sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename); if (EC) { emitError(EC.message()); return false; } // generate object file ToolOutputFile objFile(Filename, FD); bool genResult = compileOptimized(&objFile.os()); objFile.os().close(); if (objFile.os().has_error()) { emitError((Twine("could not write object file: ") + Filename + ": " + objFile.os().error().message()) .str()); objFile.os().clear_error(); sys::fs::remove(Twine(Filename)); return false; } objFile.keep(); if (!genResult) { sys::fs::remove(Twine(Filename)); return false; } NativeObjectPath = Filename.c_str(); *Name = NativeObjectPath.c_str(); return true; } std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compileOptimized() { const char *name; if (!compileOptimizedToFile(&name)) return nullptr; // read .o file into memory buffer ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(name, -1, false); if (std::error_code EC = BufferOrErr.getError()) { emitError(EC.message()); sys::fs::remove(NativeObjectPath); return nullptr; } // remove temp files sys::fs::remove(NativeObjectPath); return std::move(*BufferOrErr); } bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization) { if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, DisableVectorization)) return false; return compileOptimizedToFile(Name); } std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization) { if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE, DisableVectorization)) return nullptr; return compileOptimized(); } bool LTOCodeGenerator::determineTarget() { if (TargetMach) return true; TripleStr = MergedModule->getTargetTriple(); if (TripleStr.empty()) { TripleStr = sys::getDefaultTargetTriple(); MergedModule->setTargetTriple(TripleStr); } llvm::Triple Triple(TripleStr); // create target machine from info for merged modules std::string ErrMsg; MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg); if (!MArch) { emitError(ErrMsg); return false; } // Construct LTOModule, hand over ownership of module and target. Use MAttr as // the default set of features. SubtargetFeatures Features(MAttr); Features.getDefaultSubtargetFeatures(Triple); FeatureStr = Features.getString(); // Set a default CPU for Darwin triples. if (MCpu.empty() && Triple.isOSDarwin()) { if (Triple.getArch() == llvm::Triple::x86_64) MCpu = "core2"; else if (Triple.getArch() == llvm::Triple::x86) MCpu = "yonah"; else if (Triple.getArchName() == "arm64e") MCpu = "vortex"; else if (Triple.getArch() == llvm::Triple::aarch64 || Triple.getArch() == llvm::Triple::aarch64_32) MCpu = "cyclone"; } TargetMach = createTargetMachine(); return true; } std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() { return std::unique_ptr<TargetMachine>(MArch->createTargetMachine( TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel)); } // If a linkonce global is present in the MustPreserveSymbols, we need to make // sure we honor this. To force the compiler to not drop it, we add it to the // "llvm.compiler.used" global. void LTOCodeGenerator::preserveDiscardableGVs( Module &TheModule, llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) { std::vector<GlobalValue *> Used; auto mayPreserveGlobal = [&](GlobalValue &GV) { if (!GV.isDiscardableIfUnused() || GV.isDeclaration() || !mustPreserveGV(GV)) return; if (GV.hasAvailableExternallyLinkage()) return emitWarning( (Twine("Linker asked to preserve available_externally global: '") + GV.getName() + "'").str()); if (GV.hasInternalLinkage()) return emitWarning((Twine("Linker asked to preserve internal global: '") + GV.getName() + "'").str()); Used.push_back(&GV); }; for (auto &GV : TheModule) mayPreserveGlobal(GV); for (auto &GV : TheModule.globals()) mayPreserveGlobal(GV); for (auto &GV : TheModule.aliases()) mayPreserveGlobal(GV); if (Used.empty()) return; appendToCompilerUsed(TheModule, Used); } void LTOCodeGenerator::applyScopeRestrictions() { if (ScopeRestrictionsDone) return; // Declare a callback for the internalize pass that will ask for every // candidate GlobalValue if it can be internalized or not. Mangler Mang; SmallString<64> MangledName; auto mustPreserveGV = [&](const GlobalValue &GV) -> bool { // Unnamed globals can't be mangled, but they can't be preserved either. if (!GV.hasName()) return false; // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled // with the linker supplied name, which on Darwin includes a leading // underscore. MangledName.clear(); MangledName.reserve(GV.getName().size() + 1); Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false); return MustPreserveSymbols.count(MangledName); }; // Preserve linkonce value on linker request preserveDiscardableGVs(*MergedModule, mustPreserveGV); if (!ShouldInternalize) return; if (ShouldRestoreGlobalsLinkage) { // Record the linkage type of non-local symbols so they can be restored // prior // to module splitting. auto RecordLinkage = [&](const GlobalValue &GV) { if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() && GV.hasName()) ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage())); }; for (auto &GV : *MergedModule) RecordLinkage(GV); for (auto &GV : MergedModule->globals()) RecordLinkage(GV); for (auto &GV : MergedModule->aliases()) RecordLinkage(GV); } // Update the llvm.compiler_used globals to force preserving libcalls and // symbols referenced from asm updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs); internalizeModule(*MergedModule, mustPreserveGV); MergedModule->addModuleFlag(Module::Error, "LTOPostLink", 1); ScopeRestrictionsDone = true; } /// Restore original linkage for symbols that may have been internalized void LTOCodeGenerator::restoreLinkageForExternals() { if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage) return; assert(ScopeRestrictionsDone && "Cannot externalize without internalization!"); if (ExternalSymbols.empty()) return; auto externalize = [this](GlobalValue &GV) { if (!GV.hasLocalLinkage() || !GV.hasName()) return; auto I = ExternalSymbols.find(GV.getName()); if (I == ExternalSymbols.end()) return; GV.setLinkage(I->second); }; llvm::for_each(MergedModule->functions(), externalize); llvm::for_each(MergedModule->globals(), externalize); llvm::for_each(MergedModule->aliases(), externalize); } void LTOCodeGenerator::verifyMergedModuleOnce() { // Only run on the first call. if (HasVerifiedInput) return; HasVerifiedInput = true; bool BrokenDebugInfo = false; if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo)) report_fatal_error("Broken module found, compilation aborted!"); if (BrokenDebugInfo) { emitWarning("Invalid debug info found, debug info will be stripped"); StripDebugInfo(*MergedModule); } } void LTOCodeGenerator::finishOptimizationRemarks() { if (DiagnosticOutputFile) { DiagnosticOutputFile->keep(); // FIXME: LTOCodeGenerator dtor is not invoked on Darwin DiagnosticOutputFile->os().flush(); } } /// Optimize merged modules using various IPO passes bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE, bool DisableVectorization) { if (!this->determineTarget()) return false; auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, RemarksFormat, RemarksWithHotness); if (!DiagFileOrErr) { errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n"; report_fatal_error("Can't get an output file for the remarks"); } DiagnosticOutputFile = std::move(*DiagFileOrErr); // Setup output file to emit statistics. auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile); if (!StatsFileOrErr) { errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n"; report_fatal_error("Can't get an output file for the statistics"); } StatsFile = std::move(StatsFileOrErr.get()); // Currently there is no support for enabling whole program visibility via a // linker option in the old LTO API, but this call allows it to be specified // via the internal option. Must be done before WPD invoked via the optimizer // pipeline run below. updateVCallVisibilityInModule(*MergedModule, /* WholeProgramVisibilityEnabledInLTO */ false); // We always run the verifier once on the merged module, the `DisableVerify` // parameter only applies to subsequent verify. verifyMergedModuleOnce(); // Mark which symbols can not be internalized this->applyScopeRestrictions(); // Instantiate the pass manager to organize the passes. legacy::PassManager passes; // Add an appropriate DataLayout instance for this module... MergedModule->setDataLayout(TargetMach->createDataLayout()); passes.add( createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis())); Triple TargetTriple(TargetMach->getTargetTriple()); PassManagerBuilder PMB; PMB.DisableGVNLoadPRE = DisableGVNLoadPRE; PMB.LoopVectorize = !DisableVectorization; PMB.SLPVectorize = !DisableVectorization; if (!DisableInline) PMB.Inliner = createFunctionInliningPass(); PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple); if (Freestanding) PMB.LibraryInfo->disableAllFunctions(); PMB.OptLevel = OptLevel; PMB.VerifyInput = !DisableVerify; PMB.VerifyOutput = !DisableVerify; PMB.populateLTOPassManager(passes); // Run our queue of passes all at once now, efficiently. passes.run(*MergedModule); return true; } bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) { if (!this->determineTarget()) return false; // We always run the verifier once on the merged module. If it has already // been called in optimize(), this call will return early. verifyMergedModuleOnce(); legacy::PassManager preCodeGenPasses; // If the bitcode files contain ARC code and were compiled with optimization, // the ObjCARCContractPass must be run, so do it unconditionally here. preCodeGenPasses.add(createObjCARCContractPass()); preCodeGenPasses.run(*MergedModule); // Re-externalize globals that may have been internalized to increase scope // for splitting restoreLinkageForExternals(); // Do code generation. We need to preserve the module in case the client calls // writeMergedModules() after compilation, but we only need to allow this at // parallelism level 1. This is achieved by having splitCodeGen return the // original module at parallelism level 1 which we then assign back to // MergedModule. MergedModule = splitCodeGen(std::move(MergedModule), Out, {}, [&]() { return createTargetMachine(); }, FileType, ShouldRestoreGlobalsLinkage); // If statistics were requested, save them to the specified file or // print them out after codegen. if (StatsFile) PrintStatisticsJSON(StatsFile->os()); else if (AreStatisticsEnabled()) PrintStatistics(); reportAndResetTimings(); finishOptimizationRemarks(); return true; } void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<const char *> Options) { for (StringRef Option : Options) CodegenOptions.push_back(std::string(Option)); } void LTOCodeGenerator::parseCodeGenDebugOptions() { // if options were requested, set them if (!CodegenOptions.empty()) { // ParseCommandLineOptions() expects argv[0] to be program name. std::vector<const char *> CodegenArgv(1, "libLLVMLTO"); for (std::string &Arg : CodegenOptions) CodegenArgv.push_back(Arg.c_str()); cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data()); } } void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) { // Map the LLVM internal diagnostic severity to the LTO diagnostic severity. lto_codegen_diagnostic_severity_t Severity; switch (DI.getSeverity()) { case DS_Error: Severity = LTO_DS_ERROR; break; case DS_Warning: Severity = LTO_DS_WARNING; break; case DS_Remark: Severity = LTO_DS_REMARK; break; case DS_Note: Severity = LTO_DS_NOTE; break; } // Create the string that will be reported to the external diagnostic handler. std::string MsgStorage; raw_string_ostream Stream(MsgStorage); DiagnosticPrinterRawOStream DP(Stream); DI.print(DP); Stream.flush(); // If this method has been called it means someone has set up an external // diagnostic handler. Assert on that. assert(DiagHandler && "Invalid diagnostic handler"); (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext); } namespace { struct LTODiagnosticHandler : public DiagnosticHandler { LTOCodeGenerator *CodeGenerator; LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr) : CodeGenerator(CodeGenPtr) {} bool handleDiagnostics(const DiagnosticInfo &DI) override { CodeGenerator->DiagnosticHandler(DI); return true; } }; } void LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler, void *Ctxt) { this->DiagHandler = DiagHandler; this->DiagContext = Ctxt; if (!DiagHandler) return Context.setDiagnosticHandler(nullptr); // Register the LTOCodeGenerator stub in the LLVMContext to forward the // diagnostic to the external DiagHandler. Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this), true); } namespace { class LTODiagnosticInfo : public DiagnosticInfo { const Twine &Msg; public: LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error) : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} void print(DiagnosticPrinter &DP) const override { DP << Msg; } }; } void LTOCodeGenerator::emitError(const std::string &ErrMsg) { if (DiagHandler) (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext); else Context.diagnose(LTODiagnosticInfo(ErrMsg)); } void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) { if (DiagHandler) (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext); else Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning)); }
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. 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. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************************************************/ #include "ThermalZonesTabView.hpp" namespace openstudio { ThermalZonesTabView::ThermalZonesTabView(QWidget * parent) : MainTabView("Thermal Zones", MainTabView::MAIN_TAB, parent) { } } // openstudio
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * numeric_codegen.inl * template implementation of numeric codegen. * * IDENTIFICATION * src/gausskernel/runtime/codegen/codegenutil/numeric_codegen.inl * * --------------------------------------------------------------------------------------- */ #ifndef NUMERICCODEGEN_INL #define NUMERICCODEGEN_INL #include "codegen/gscodegen.h" #include "codegen/builtinscodegen.h" #include "codegen/codegendebuger.h" #include "utils/biginteger.h" extern const int64 ScaleMultipler[20]; extern const int64 Int64MultiOutOfBound[20]; namespace dorado { /* declare llvm function with two arguments */ #define DEFINE_FUNCTION_WITH_2_ARGS(jitted_funptr, func_type, name, arg1, arg1Type, arg2, arg2Type)\ GsCodeGen::FnPrototype func_type(llvmCodeGen, name, int64Type);\ (func_type).addArgument(GsCodeGen::NamedVariable(arg1, arg1Type));\ (func_type).addArgument(GsCodeGen::NamedVariable(arg2, arg2Type));\ jitted_funptr = (func_type).generatePrototype(&builder, &llvmargs[0]);\ /** * @Description : Generate IR function to codegen numeric operation, which includes * +, - , *, /, =, !=, <, <=, >, >=. 'lhs_arg' and 'rhs_arg' are the * parameters used by LLVM function. Since in most cases, numeric * data can be stored in BI64 data type, we codegen all the operations * for bi64 type. * @return : LLVM IR Function that point to the special codegened operation func. */ template<biop op> llvm::Function *numeric_sop_codegen() { GsCodeGen *llvmCodeGen = (GsCodeGen *)t_thrd.codegen_cxt.thr_codegen_obj; llvm::LLVMContext& context = llvmCodeGen->context(); GsCodeGen::LlvmBuilder builder(context); /* Define the datatype and variables that needed */ DEFINE_CG_TYPE(int16Type, INT2OID); DEFINE_CG_TYPE(int32Type, INT4OID); DEFINE_CG_TYPE(int64Type, INT8OID); DEFINE_CG_TYPE(FuncCallInfoType, "struct.FunctionCallInfoData"); DEFINE_CGVAR_INT16(val_mask, NUMERIC_BI_MASK); DEFINE_CGVAR_INT16(val_nan, NUMERIC_NAN); DEFINE_CGVAR_INT16(val_binum128, NUMERIC_128); DEFINE_CGVAR_INT32(int32_0, 0); DEFINE_CGVAR_INT32(int32_1, 1); DEFINE_CGVAR_INT32(int32_6, 6); DEFINE_CGVAR_INT64(int64_0, 0); DEFINE_CGVAR_INT64(int64_1, 1); llvm::Value *llvmargs[2]; llvm::Value *tmpval = NULL; llvm::Value *res1 = NULL, *res2 = NULL, *res3 = NULL; llvm::Value *oparg1 = NULL, *oparg2 = NULL; llvm::Value *Vals[2] = {int64_0, int64_0}; llvm::Value *Vals4[4] = {int64_0, int32_0, int32_0, int32_0}; /* the jitted function pointer */ llvm::Function *jitted_numfuncptr = NULL; /* Define the right jitted function through op type and left arg type. */ switch (op) { case BIADD: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, ADD, "Jitted_numericadd", "arg1", int64Type, "arg2", int64Type); } break; case BISUB: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, SUB, "Jitted_numericsub", "arg1", int64Type, "arg2", int64Type); } break; case BIMUL: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, MUL, "Jitted_numericmul", "arg1", int64Type, "arg2", int64Type); } break; case BIDIV: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, DIV, "Jitted_numericdiv", "arg1", int64Type, "arg2", int64Type); } break; case BIEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, EQ, "Jitted_numericeq", "arg1", int64Type, "arg2", int64Type); } break; case BINEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, NEQ, "Jitted_numericne", "arg1", int64Type, "arg2", int64Type); } break; case BILE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, LE, "Jitted_numericle", "arg1", int64Type, "arg2", int64Type); } break; case BILT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, LT, "Jitted_numericlt", "arg1", int64Type, "arg2", int64Type); } break; case BIGE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, GE, "Jitted_numericge", "arg1", int64Type, "arg2", int64Type); } break; case BIGT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, GT, "Jitted_numericgt", "arg1", int64Type, "arg2", int64Type); } break; default: break; } llvm::Value *arg1 = llvmargs[0]; llvm::Value *arg2 = llvmargs[1]; llvm::BasicBlock *entry = &jitted_numfuncptr->getEntryBlock(); DEFINE_BLOCK(bi_numeric_op, jitted_numfuncptr); DEFINE_BLOCK(org_numeric_op, jitted_numfuncptr); DEFINE_BLOCK(bi64_op, jitted_numfuncptr); DEFINE_BLOCK(bi128_op, jitted_numfuncptr); DEFINE_BLOCK(ret_bb, jitted_numfuncptr); builder.SetInsertPoint(entry); /* get BI numeric val from datum */ llvm::Value *leftarg = DatumGetBINumericCodeGen(&builder, arg1); llvm::Value *rightarg = DatumGetBINumericCodeGen(&builder, arg2); /* get numFlags : NUMERIC_NB_FLAGBITS(arg) */ Vals4[0] = int64_0; Vals4[1] = int32_1; Vals4[2] = int32_0; Vals4[3] = int32_0; tmpval = builder.CreateInBoundsGEP(leftarg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "lheader"); llvm::Value *lnumFlags = builder.CreateAnd(tmpval, val_mask); tmpval = builder.CreateInBoundsGEP(rightarg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "rheader"); llvm::Value *rnumFlags = builder.CreateAnd(tmpval, val_mask); /* check : NUMERIC_FLAG_IS_BI(numFlags) */ llvm::Value *cmp1 = builder.CreateICmpUGT(lnumFlags, val_nan); llvm::Value *cmp2 = builder.CreateICmpUGT(rnumFlags, val_nan); llvm::Value *cmpand = builder.CreateAnd(cmp1, cmp2); builder.CreateCondBr(cmpand, bi_numeric_op, org_numeric_op); /* * when arguments can be respented by BI numeric, further check * their if it is bi64 or bi128. */ builder.SetInsertPoint(bi_numeric_op); oparg1 = builder.CreateICmpEQ(lnumFlags, val_binum128); oparg2 = builder.CreateICmpEQ(rnumFlags, val_binum128); llvm::Value *cmpor = builder.CreateOr(oparg1, oparg2); builder.CreateCondBr(cmpor, bi128_op, bi64_op); builder.SetInsertPoint(bi64_op); llvm::Function *jitted_func = NULL; switch (op) { case BIADD: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64add64s"); if (jitted_func == NULL) jitted_func = bi64add64_codegen(false); } break; case BISUB: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64sub64"); if (jitted_func == NULL) jitted_func = bi64sub64_codegen(); } break; case BIMUL: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64mul64"); if (jitted_func == NULL) jitted_func = bi64mul64_codegen(); } break; case BIDIV: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64div64"); if (jitted_func == NULL) jitted_func = bi64div64_codegen(); } break; case BIEQ: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64eq64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BIEQ>(); } break; case BINEQ: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64ne64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BINEQ>(); } break; case BILE: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64le64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BILE>(); } break; case BILT: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64lt64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BILT>(); } break; case BIGE: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64ge64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BIGE>(); } break; case BIGT: { jitted_func = llvmCodeGen->module()->getFunction("Jitted_bi64gt64"); if (jitted_func == NULL) jitted_func = bi64cmp64_codegen<BIGT>(); } break; default: break; } res1 = builder.CreateCall(jitted_func, {leftarg, rightarg}); builder.CreateBr(ret_bb); builder.SetInsertPoint(bi128_op); oparg1 = builder.CreateZExt(oparg1, int32Type); oparg2 = builder.CreateZExt(oparg2, int32Type); llvm::Value *cop = llvmCodeGen->getIntConstant(INT4OID, op); res2 = WrapBiFunMatrixCodeGen(&builder, cop, oparg1, oparg2, leftarg, rightarg); builder.CreateBr(ret_bb); /* call original numeric function according to the 'op' */ builder.SetInsertPoint(org_numeric_op); DEFINE_CG_ARRTYPE(int64ArrType, int64Type, 2); llvm::Value *finfo = builder.CreateAlloca(FuncCallInfoType); llvm::Value *args = builder.CreateAlloca(int64ArrType); llvm::Value *arghead = builder.CreateInBoundsGEP(args, Vals); Vals[1] = int32_6; llvm::Value *fihead = builder.CreateInBoundsGEP(finfo, Vals); builder.CreateStore(arghead, fihead); oparg1 = builder.CreatePtrToInt(leftarg, int64Type); builder.CreateStore(oparg1, arghead); oparg2 = builder.CreatePtrToInt(rightarg, int64Type); Vals[1] = int64_1; tmpval = builder.CreateInBoundsGEP(args, Vals); builder.CreateStore(oparg2, tmpval); res3 = WrapnumericFuncCodeGen<op>(&builder, finfo); builder.CreateBr(ret_bb); builder.SetInsertPoint(ret_bb); llvm::PHINode *phi_ret = builder.CreatePHI(int64Type, 3); phi_ret->addIncoming(res1, bi64_op); phi_ret->addIncoming(res2, bi128_op); phi_ret->addIncoming(res3, org_numeric_op); (void)builder.CreateRet(phi_ret); llvmCodeGen->FinalizeFunction(jitted_numfuncptr); return jitted_numfuncptr; } /** * @Description : Generate IR function to codegen bi64 operation, which includes * =, !=, <, <=, >, >=. 'lhs_arg' and 'rhs_arg' are the * parameters used by LLVM function with numeric data type. * @return : LLVM IR Function that point to the special codegened operation func. */ template<biop op> llvm::Function *bi64cmp64_codegen() { GsCodeGen *llvmCodeGen = (GsCodeGen *)t_thrd.codegen_cxt.thr_codegen_obj; llvm::LLVMContext& context = llvmCodeGen->context(); GsCodeGen::LlvmBuilder builder(context); /* Define the datatype and variables that needed */ DEFINE_CG_TYPE(int16Type, INT2OID); DEFINE_CG_TYPE(int32Type, INT4OID); DEFINE_CG_TYPE(int64Type, INT8OID); DEFINE_CG_NINTTYP(int128Type, 128); DEFINE_CG_PTRTYPE(int64PtrType, INT8OID); DEFINE_CG_PTRTYPE(numericPtrType, "struct.NumericData"); DEFINE_CGVAR_INT16(val_scalemask, NUMERIC_BI_SCALEMASK); DEFINE_CGVAR_INT1(int1_0, 0); DEFINE_CGVAR_INT1(int1_1, 1); DEFINE_CGVAR_INT32(int32_0, 0); DEFINE_CGVAR_INT32(int32_1, 1); DEFINE_CGVAR_INT64(int64_0, 0); llvm::Value *llvmargs[2]; llvm::Value *cmpval = NULL; llvm::Value *tmpval = NULL; llvm::Value *mulscale = NULL; llvm::Value *phi_val = NULL; llvm::Value *multi_bound = NULL; llvm::Value *left_scaled1= NULL, *left_scaled2 = NULL; llvm::Value *right_scaled1 = NULL, *right_scaled2 = NULL; llvm::PHINode *left_scaled = NULL, *right_scaled = NULL; llvm::Value *res1 = NULL, *res2 = NULL, *res3 = NULL; llvm::Value *phi_left = NULL, *phi_right = NULL; llvm::Value *Vals4[4] = {int64_0, int32_0, int32_0, int32_0}; /* the jitted function pointer */ llvm::Function *jitted_funcptr = NULL; /* Define the right jitted function through op type and left arg type. */ switch (op) { case BIEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, EQ, "Jitted_bi64eq64", "arg1", numericPtrType, "arg2", numericPtrType); } break; case BINEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, NEQ, "Jitted_bi64ne64", "arg1", numericPtrType, "arg2", numericPtrType); } break; case BILE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, LE, "Jitted_bi64le64", "arg1", numericPtrType, "arg2", numericPtrType); } break; case BILT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, LT, "Jitted_bi64lt64", "arg1", numericPtrType, "arg2", numericPtrType); } break; case BIGE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, GE, "Jitted_bi64ge64", "arg1", numericPtrType, "arg2", numericPtrType); } break; case BIGT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_funcptr, GT, "Jitted_bi64gt64", "arg1", numericPtrType, "arg2", numericPtrType); } break; default: break; } llvm::Value *larg = llvmargs[0]; llvm::Value *rarg = llvmargs[1]; /* get value scale : NUMERIC_BI_SCALE */ Vals4[0] = int64_0; Vals4[1] = int32_1; Vals4[2] = int32_0; Vals4[3] = int32_0; tmpval = builder.CreateInBoundsGEP(larg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "lheader"); llvm::Value *lvalscale = builder.CreateAnd(tmpval, val_scalemask); lvalscale = builder.CreateSExt(lvalscale, int32Type, "lscale"); tmpval = builder.CreateInBoundsGEP(rarg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "rheader"); llvm::Value *rvalscale = builder.CreateAnd(tmpval, val_scalemask); rvalscale = builder.CreateSExt(rvalscale, int32Type, "rscale"); /* get value : NUMERIC_64VALUE */ Vals4[3] = int32_1; tmpval = builder.CreateInBoundsGEP(larg, Vals4); tmpval = builder.CreateBitCast(tmpval, int64PtrType); llvm::Value* leftval = builder.CreateLoad(int64Type, tmpval, "lval"); tmpval = builder.CreateInBoundsGEP(rarg, Vals4); tmpval = builder.CreateBitCast(tmpval, int64PtrType); llvm::Value* rightval = builder.CreateLoad(int64Type, tmpval, "rval"); llvm::BasicBlock *entry = &jitted_funcptr->getEntryBlock(); DEFINE_BLOCK(delta_large, jitted_funcptr); DEFINE_BLOCK(delta_small, jitted_funcptr); DEFINE_BLOCK(adjust_true, jitted_funcptr); DEFINE_BLOCK(left_out_bound, jitted_funcptr); DEFINE_BLOCK(right_out_bound, jitted_funcptr); DEFINE_BLOCK(ret_bb, jitted_funcptr); builder.SetInsertPoint(entry); /* delta_scale = lvalscale - rvalscale */ llvm::Value* delta_scale = builder.CreateSub(lvalscale, rvalscale, "delta_scale"); /* check delta_scale >= 0 or not */ cmpval = builder.CreateICmpSGE(delta_scale, int32_0, "cmp_delta_scale"); builder.CreateCondBr(cmpval, delta_large, delta_small); /* corresponding to delta_scale >= 0 */ builder.SetInsertPoint(delta_large); /* tmpval = y < 0 ? y : -y */ tmpval = builder.CreateSub(int64_0, rightval); cmpval = builder.CreateICmpSLT(rightval, int64_0, "negative_cmp"); phi_val = builder.CreateSelect(cmpval, rightval, tmpval); left_scaled1 = leftval; mulscale = ScaleMultiCodeGen(&builder, delta_scale); /* corresponding to y_scaled = y * ScaleMultipler[delta_scale] */ right_scaled1 = builder.CreateMul(rightval, mulscale); /* the result of tmpval * ScaleMultipler[delta_scale] * doesn't out of int64 bound. */ multi_bound = GetInt64MulOutofBoundCodeGen(&builder, delta_scale); cmpval = builder.CreateICmpSGE(phi_val, multi_bound, "bound_check"); builder.CreateCondBr(cmpval, adjust_true, right_out_bound); builder.SetInsertPoint(delta_small); /* tmpval = x < 0 ? x : -x */ tmpval = builder.CreateSub(int64_0, leftval); cmpval = builder.CreateICmpSLT(leftval, int64_0, "negative_cmp"); phi_val = builder.CreateSelect(cmpval, leftval, tmpval); /* corresponding to x_scaled = x * ScaleMultipler[-delta_scale] */ llvm::Value* mdelta_scale = builder.CreateSub(int32_0, delta_scale); llvm::Value* mmulscale = ScaleMultiCodeGen(&builder, mdelta_scale); left_scaled2 = builder.CreateMul(leftval, mmulscale); right_scaled2 = rightval; /* the result of tmpval * ScaleMultipler[delta_scale] * doesn't out of int64 bound. */ multi_bound = GetInt64MulOutofBoundCodeGen(&builder, mdelta_scale); cmpval = builder.CreateICmpSGE(phi_val, multi_bound, "bound_check"); builder.CreateCondBr(cmpval, adjust_true, left_out_bound); builder.SetInsertPoint(adjust_true); left_scaled = builder.CreatePHI(int64Type, 2); left_scaled->addIncoming(left_scaled1, delta_large); left_scaled->addIncoming(left_scaled2, delta_small); right_scaled = builder.CreatePHI(int64Type, 2); right_scaled->addIncoming(right_scaled1, delta_large); right_scaled->addIncoming(right_scaled2, delta_small); /* compare leftval with rightval directly, both are int64 type */ switch (op) { case BIEQ: { res1 = builder.CreateICmpEQ(left_scaled, right_scaled, "bi64_eq"); } break; case BINEQ: { res1 = builder.CreateICmpNE(left_scaled, right_scaled, "bi64_ne"); } break; case BILE: { res1 = builder.CreateICmpSLE(left_scaled, right_scaled, "bi64_le"); } break; case BILT: { res1 = builder.CreateICmpSLT(left_scaled, right_scaled, "bi64_lt"); } break; case BIGE: { res1 = builder.CreateICmpSGE(left_scaled, right_scaled, "bi64_ge"); } break; case BIGT: { res1 = builder.CreateICmpSGT(left_scaled, right_scaled, "bi64_gt"); } break; default: break; } res1 = builder.CreateZExt(res1, int64Type); builder.CreateBr(ret_bb); /* right_scaled must be out of int64 bound, so leftval_scaled != right_scaled */ builder.SetInsertPoint(right_out_bound); phi_left = builder.CreateSExt(leftval, int128Type); tmpval = GetScaleMultiCodeGen(&builder, delta_scale); tmpval = builder.CreateSExt(tmpval, int128Type); phi_right = builder.CreateSExt(rightval, int128Type); phi_right = builder.CreateMul(phi_right, tmpval, "right_scale"); switch (op) { case BIEQ: { res2 = int1_0; } break; case BINEQ: { res2 = int1_1; } break; case BILE: { res2 = builder.CreateICmpSLE(phi_left, phi_right, "bi64_le"); } break; case BILT: { res2 = builder.CreateICmpSLT(phi_left, phi_right, "bi64_lt"); } break; case BIGE: { res2 = builder.CreateICmpSGE(phi_left, phi_right, "bi64_ge"); } break; case BIGT: { res2 = builder.CreateICmpSGT(phi_left, phi_right, "bi64_gt"); } break; default: break; } res2 = builder.CreateZExt(res2, int64Type); builder.CreateBr(ret_bb); /* leftval_scaled must be out of int64 bound, so leftval_scaled != right_scaled */ builder.SetInsertPoint(left_out_bound); tmpval = GetScaleMultiCodeGen(&builder, mdelta_scale); tmpval = builder.CreateSExt(tmpval, int128Type); phi_left = builder.CreateSExt(leftval, int128Type); phi_left = builder.CreateMul(phi_left, tmpval, "left_scale"); phi_right = builder.CreateSExt(rightval, int128Type); switch (op) { case BIEQ: { res3 = int1_0; } break; case BINEQ: { res3 = int1_1; } break; case BILE: { res3 = builder.CreateICmpSLE(phi_left, phi_right, "bi64_le"); } break; case BILT: { res3 = builder.CreateICmpSLT(phi_left, phi_right, "bi64_lt"); } break; case BIGE: { res3 = builder.CreateICmpSGE(phi_left, phi_right, "bi64_ge"); } break; case BIGT: { res3 = builder.CreateICmpSGT(phi_left, phi_right, "bi64_gt"); } break; default: break; } res3 = builder.CreateZExt(res3, int64Type); builder.CreateBr(ret_bb); builder.SetInsertPoint(ret_bb); llvm::PHINode *phi_ret = builder.CreatePHI(int64Type, 3); phi_ret->addIncoming(res1, adjust_true); phi_ret->addIncoming(res2, right_out_bound); phi_ret->addIncoming(res3, left_out_bound); (void)builder.CreateRet(phi_ret); llvmCodeGen->FinalizeFunction(jitted_funcptr); return jitted_funcptr; } /** * @Description : Generate IR function to codegen numeric operation, which includes * =, !=, <, <=, >, >=. 'lhs_arg' and 'rhs_arg' are the * parameters used by LLVM function with numeric data type. 'lhs_arg' * and 'rhs_arg' can be both represented by BI64. * @return : LLVM IR Function that point to the special codegened operation func. */ template<biop op> llvm::Function *fast_numericbi_sop_codegen() { dorado::GsCodeGen *llvmCodeGen = (GsCodeGen *)t_thrd.codegen_cxt.thr_codegen_obj; llvm::LLVMContext& context = llvmCodeGen->context(); GsCodeGen::LlvmBuilder builder(context); DEFINE_CG_TYPE(int16Type, INT2OID); DEFINE_CG_TYPE(int32Type, INT4OID); DEFINE_CG_TYPE(int64Type, INT8OID); DEFINE_CG_NINTTYP(int128Type, 128); DEFINE_CG_PTRTYPE(int64PtrType, INT8OID); DEFINE_CG_TYPE(FuncCallInfoType, "struct.FunctionCallInfoData"); DEFINE_CGVAR_INT16(val_nan, NUMERIC_NAN); DEFINE_CGVAR_INT16(val_mask, NUMERIC_BI_MASK); DEFINE_CGVAR_INT16(val_scalemask, NUMERIC_BI_SCALEMASK); DEFINE_CGVAR_INT1(int1_0, 0); DEFINE_CGVAR_INT1(int1_1, 1); DEFINE_CGVAR_INT32(int32_0, 0); DEFINE_CGVAR_INT32(int32_1, 1); DEFINE_CGVAR_INT32(int32_6, 6); DEFINE_CGVAR_INT64(int64_0, 0); DEFINE_CGVAR_INT64(int64_1, 1); llvm::Value* llvmargs[2]; llvm::Value* cmpval = NULL; llvm::Value* tmpval = NULL; llvm::Value* phi_val = NULL; llvm::Value* mulscale = NULL; llvm::Value* multi_bound = NULL; llvm::Value *left_scaled1 = NULL, *left_scaled2 = NULL; llvm::Value *right_scaled1 = NULL, *right_scaled2 = NULL; llvm::PHINode *left_scaled = NULL, *right_scaled = NULL; llvm::Value *res1 = NULL, *res2 = NULL, *res3 = NULL, *res4 = NULL; llvm::Value* phi_left = NULL; llvm::Value* phi_right = NULL; llvm::Value* Vals[2] = {int64_0, int64_0}; llvm::Value* Vals4[4] = {int64_0, int32_0, int32_0, int32_0}; /* the jitted function pointer */ llvm::Function *jitted_numfuncptr = NULL; /* Define the right jitted function through op type and left arg type. */ switch (op) { case BIEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, EQ, "Jitted_fast_numericeq", "arg1", int64Type, "arg2", int64Type); } break; case BINEQ: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, NEQ, "Jitted_fast_numericne", "arg1", int64Type, "arg2", int64Type); } break; case BILE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, LE, "Jitted_fast_numericle", "arg1", int64Type, "arg2", int64Type); } break; case BILT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, LT, "Jitted_fast_numericlt", "arg1", int64Type, "arg2", int64Type); } break; case BIGE: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, GE, "Jitted_fast_numericge", "arg1", int64Type, "arg2", int64Type); } break; case BIGT: { DEFINE_FUNCTION_WITH_2_ARGS(jitted_numfuncptr, GT, "Jitted_fast_numericgt", "arg1", int64Type, "arg2", int64Type); } break; default: break; } llvm::Value* arg = llvmargs[0]; llvm::Value* cst = llvmargs[1]; DEFINE_BLOCK(fast_bi, jitted_numfuncptr); DEFINE_BLOCK(fast_numeric, jitted_numfuncptr); DEFINE_BLOCK(delta_large, jitted_numfuncptr); DEFINE_BLOCK(delta_small, jitted_numfuncptr); DEFINE_BLOCK(adjust_true, jitted_numfuncptr); DEFINE_BLOCK(left_out_bound, jitted_numfuncptr); DEFINE_BLOCK(right_out_bound, jitted_numfuncptr); DEFINE_BLOCK(ret_bb, jitted_numfuncptr); llvm::Value* varg = DatumGetBINumericCodeGen(&builder, arg); llvm::Value* rcst = DatumGetBINumericCodeGen(&builder, cst); Vals4[0] = int64_0; Vals4[1] = int32_1; Vals4[2] = int32_0; Vals4[3] = int32_0; tmpval = builder.CreateInBoundsGEP(varg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "lheader"); llvm::Value* varnumFlags = builder.CreateAnd(tmpval, val_mask); llvm::Value* varisbi = builder.CreateICmpUGT(varnumFlags, val_nan); builder.CreateCondBr(varisbi, fast_bi, fast_numeric); builder.SetInsertPoint(fast_bi); /* parse the variable argument */ /* get value scale : NUMERIC_BI_SCALE */ Vals4[0] = int64_0; Vals4[1] = int32_1; Vals4[2] = int32_0; Vals4[3] = int32_0; tmpval = builder.CreateInBoundsGEP(varg, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "header"); llvm::Value* argscale = builder.CreateAnd(tmpval, val_scalemask); argscale = builder.CreateSExt(argscale, int32Type, "scale"); /* get value : NUMERIC_64VALUE */ Vals4[3] = int32_1; tmpval = builder.CreateInBoundsGEP(varg, Vals4); tmpval = builder.CreateBitCast(tmpval, int64PtrType); llvm::Value* argval = builder.CreateLoad(int64Type, tmpval, "val"); /* parse the const argument */ /* get value scale : NUMERIC_BI_SCALE */ Vals4[0] = int64_0; Vals4[1] = int32_1; Vals4[2] = int32_0; Vals4[3] = int32_0; tmpval = builder.CreateInBoundsGEP(rcst, Vals4); tmpval = builder.CreateLoad(int16Type, tmpval, "header"); llvm::Value* cstscale = builder.CreateAnd(tmpval, val_scalemask); cstscale = builder.CreateSExt(cstscale, int32Type, "scale"); /* get value : NUMERIC_64VALUE */ Vals4[3] = int32_1; tmpval = builder.CreateInBoundsGEP(rcst, Vals4); tmpval = builder.CreateBitCast(tmpval, int64PtrType); llvm::Value* cstval = builder.CreateLoad(int64Type, tmpval, "val"); /* delta_scale = lvalscale - rvalscale */ llvm::Value* delta_scale = builder.CreateSub(argscale, cstscale, "delta_scale"); /* check delta_scale >= 0 or not */ cmpval = builder.CreateICmpSGE(delta_scale, int32_0, "cmp_delta_scale"); builder.CreateCondBr(cmpval, delta_large, delta_small); /* corresponding to delta_scale >= 0 */ builder.SetInsertPoint(delta_large); /* tmpval = y < 0 ? y : -y */ tmpval = builder.CreateSub(int64_0, cstval); cmpval = builder.CreateICmpSLT(cstval, int64_0, "negative_cmp"); phi_val = builder.CreateSelect(cmpval, cstval, tmpval); left_scaled1 = argval; mulscale = ScaleMultiCodeGen(&builder, delta_scale); /* corresponding to y_scaled = y * ScaleMultipler[delta_scale] */ right_scaled1 = builder.CreateMul(cstval, mulscale); /* the result of tmpval * ScaleMultipler[delta_scale] * doesn't out of int64 bound. */ multi_bound = GetInt64MulOutofBoundCodeGen(&builder, delta_scale); cmpval = builder.CreateICmpSGE(phi_val, multi_bound, "bound_check"); builder.CreateCondBr(cmpval, adjust_true, right_out_bound); builder.SetInsertPoint(delta_small); /* tmpval = x < 0 ? x : -x */ tmpval = builder.CreateSub(int64_0, argval); cmpval = builder.CreateICmpSLT(argval, int64_0, "negative_cmp"); phi_val = builder.CreateSelect(cmpval, argval, tmpval); /* corresponding to x_scaled = x * ScaleMultipler[-delta_scale] */ llvm::Value* mdelta_scale = builder.CreateSub(int32_0, delta_scale); llvm::Value* mmulscale = ScaleMultiCodeGen(&builder, mdelta_scale); left_scaled2 = builder.CreateMul(argval, mmulscale); right_scaled2 = cstval; /* the result of tmpval * ScaleMultipler[delta_scale] * doesn't out of int64 bound. */ multi_bound = GetInt64MulOutofBoundCodeGen(&builder, mdelta_scale); cmpval = builder.CreateICmpSGE(phi_val, multi_bound, "bound_check"); builder.CreateCondBr(cmpval, adjust_true, left_out_bound); builder.SetInsertPoint(adjust_true); left_scaled = builder.CreatePHI(int64Type, 2); left_scaled->addIncoming(left_scaled1, delta_large); left_scaled->addIncoming(left_scaled2, delta_small); right_scaled = builder.CreatePHI(int64Type, 2); right_scaled->addIncoming(right_scaled1, delta_large); right_scaled->addIncoming(right_scaled2, delta_small); /* compare leftval with rightval directly, both are int64 type */ switch (op) { case BIEQ: { res1 = builder.CreateICmpEQ(left_scaled, right_scaled, "bi64_eq"); } break; case BINEQ: { res1 = builder.CreateICmpNE(left_scaled, right_scaled, "bi64_ne"); } break; case BILE: { res1 = builder.CreateICmpSLE(left_scaled, right_scaled, "bi64_le"); } break; case BILT: { res1 = builder.CreateICmpSLT(left_scaled, right_scaled, "bi64_lt"); } break; case BIGE: { res1 = builder.CreateICmpSGE(left_scaled, right_scaled, "bi64_ge"); } break; case BIGT: { res1 = builder.CreateICmpSGT(left_scaled, right_scaled, "bi64_gt"); } break; default: break; } res1 = builder.CreateZExt(res1, int64Type); builder.CreateBr(ret_bb); /* right_scaled must be out of int64 bound, so leftval_scaled != right_scaled */ builder.SetInsertPoint(right_out_bound); phi_left = builder.CreateSExt(argval, int128Type); tmpval = GetScaleMultiCodeGen(&builder, delta_scale); tmpval = builder.CreateSExt(tmpval, int128Type); phi_right = builder.CreateSExt(cstval, int128Type); phi_right = builder.CreateMul(phi_right, tmpval, "right_scale"); switch (op) { case BIEQ: { res2 = int1_0; } break; case BINEQ: { res2 = int1_1; } break; case BILE: { res2 = builder.CreateICmpSLE(phi_left, phi_right, "bi64_le"); } break; case BILT: { res2 = builder.CreateICmpSLT(phi_left, phi_right, "bi64_lt"); } break; case BIGE: { res2 = builder.CreateICmpSGE(phi_left, phi_right, "bi64_ge"); } break; case BIGT: { res2 = builder.CreateICmpSGT(phi_left, phi_right, "bi64_gt"); } break; default: break; } res2 = builder.CreateZExt(res2, int64Type); builder.CreateBr(ret_bb); /* leftval_scaled must be out of int64 bound, so leftval_scaled != right_scaled */ builder.SetInsertPoint(left_out_bound); tmpval = GetScaleMultiCodeGen(&builder, mdelta_scale); tmpval = builder.CreateSExt(tmpval, int128Type); phi_left = builder.CreateSExt(argval, int128Type); phi_left = builder.CreateMul(phi_left, tmpval, "left_scale"); phi_right = builder.CreateSExt(cstval, int128Type); switch (op) { case BIEQ: { res3 = int1_0; } break; case BINEQ: { res3 = int1_1; } break; case BILE: { res3 = builder.CreateICmpSLE(phi_left, phi_right, "bi64_le"); } break; case BILT: { res3 = builder.CreateICmpSLT(phi_left, phi_right, "bi64_lt"); } break; case BIGE: { res3 = builder.CreateICmpSGE(phi_left, phi_right, "bi64_ge"); } break; case BIGT: { res3 = builder.CreateICmpSGT(phi_left, phi_right, "bi64_gt"); } break; default: break; } res3 = builder.CreateZExt(res3, int64Type); builder.CreateBr(ret_bb); builder.SetInsertPoint(fast_numeric); DEFINE_CG_ARRTYPE(int64ArrType, int64Type, 2); llvm::Value* finfo = builder.CreateAlloca(FuncCallInfoType); llvm::Value* args = builder.CreateAlloca(int64ArrType); llvm::Value* arghead = builder.CreateInBoundsGEP(args, Vals); Vals[1] = int32_6; llvm::Value* fihead = builder.CreateInBoundsGEP(finfo, Vals); builder.CreateStore(arghead, fihead); llvm::Value* oparg1 = builder.CreatePtrToInt(varg, int64Type); builder.CreateStore(oparg1, arghead); llvm::Value* oparg2 = builder.CreatePtrToInt(rcst, int64Type); Vals[1] = int64_1; tmpval = builder.CreateInBoundsGEP(args, Vals); builder.CreateStore(oparg2, tmpval); res4 = WrapnumericFuncCodeGen<op>(&builder, finfo); builder.CreateBr(ret_bb); builder.SetInsertPoint(ret_bb); llvm::PHINode *phi_ret = builder.CreatePHI(int64Type, 4); phi_ret->addIncoming(res1, adjust_true); phi_ret->addIncoming(res2, right_out_bound); phi_ret->addIncoming(res3, left_out_bound); phi_ret->addIncoming(res4, fast_numeric); (void)builder.CreateRet(phi_ret); llvmCodeGen->FinalizeFunction(jitted_numfuncptr); return jitted_numfuncptr; } /** * @Description : Call the original numeric row function with input arguments in LLVM. * @in ptrbuilder : LLVM Builder associated with the current module. * @in arg : FuncCallInfoData structure which contains the input arguments * needed by numericFunc. */ template<biop op> llvm::Value* WrapnumericFuncCodeGen(GsCodeGen::LlvmBuilder* ptrbuilder, llvm::Value* arg) { GsCodeGen *llvmCodeGen = (GsCodeGen *)t_thrd.codegen_cxt.thr_codegen_obj; llvm::LLVMContext& context = llvmCodeGen->context(); GsCodeGen::LlvmBuilder builder(context); DEFINE_CG_TYPE(int64Type, INT8OID); DEFINE_CG_PTRTYPE(FuncCallInfoPtrType, "struct.FunctionCallInfoData"); llvm::Value* result = NULL; llvm::Function *jitted_numfunc = NULL; switch (op) { case BIADD: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncadd"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncadd", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncadd", (void *)numeric_add); } } break; case BISUB: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncsub"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncsub", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncsub", (void *)numeric_sub); } } break; case BIMUL: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncmul"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncmul", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncmul", (void *)numeric_mul); } } break; case BIDIV: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncdiv"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncdiv", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncdiv", (void *)numeric_div); } } break; case BIEQ: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfunceq"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfunceq", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfunceq", (void *)numeric_eq); } } break; case BINEQ: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncneq"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncneq", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncneq", (void *)numeric_ne); } } break; case BILE: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncle"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncle", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncle", (void *)numeric_le); } } break; case BILT: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfunclt"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfunclt", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfunclt", (void *)numeric_lt); } } break; case BIGE: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncge"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncge", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncge", (void *)numeric_ge); } } break; case BIGT: { jitted_numfunc = llvmCodeGen->module()->getFunction("LLVMWrapnumfuncgt"); if (jitted_numfunc == NULL) { GsCodeGen::FnPrototype fn_prototype(llvmCodeGen, "LLVMWrapnumfuncgt", int64Type); fn_prototype.addArgument(GsCodeGen::NamedVariable("arg", FuncCallInfoPtrType)); jitted_numfunc = fn_prototype.generatePrototype(NULL, NULL); llvm::sys::DynamicLibrary::AddSymbol("LLVMWrapnumfuncgt", (void *)numeric_gt); } } break; default: break; } llvmCodeGen->FinalizeFunction(jitted_numfunc); result = ptrbuilder->CreateCall(jitted_numfunc, arg); return result; } } #endif
#include <glt/shader.hpp> #include <glt/fileutils.hpp> #include <utility> #include <sstream> namespace glt { bool compileSource(const Shader& shader, const char * source, GLenum shadertype, std::ostream& out) { gl::ShaderSource(shader, 1, static_cast<const GLchar * const *>(&source), nullptr); gl::CompileShader(shader); GLint success; gl::GetShaderiv(shader, gl::COMPILE_STATUS, &success); if (success == gl::FALSE_) { const GLsizei SIZE = 512; GLchar log[SIZE] = {0}; gl::GetShaderInfoLog(shader, SIZE, nullptr, log); out << log; return false; } return true; } Shader compileShader(const std::string& filename) { auto shader_t = shaderType(filename); if (shader_t == -1) return Shader(); else return compileShader(filename, shader_t); } Shader compileShader(const std::string& filename, GLenum shadertype) { std::ostringstream dump; return compileShader(filename, shadertype, dump); } Shader compileShader(const std::string& filename, std::ostream &out) { auto shader_t = shaderType(filename); if (shader_t == -1) return Shader(); else return compileShader(filename, shader_t, out); } Shader compileShader(const std::string& filename, GLenum shadertype, std::ostream &out) { std::ostringstream contents; if (!readAllAsciiText(filename, contents)) return Shader(); auto shader = Shader(shadertype); auto asStr = contents.str(); auto source = asStr.c_str(); if (compileSource(shader, source, shadertype, out)) return shader; return Shader(); } Shader compileShaderSource(const char * source, GLenum shadertype, std::ostream &out) { auto shader = Shader(shadertype); if (compileSource(shader, source, shadertype, out)) return shader; return Shader(); } Shader compileShaderSource(const char * source, GLenum shadertype) { std::ostringstream dump; return compileShaderSource(source, shadertype, dump); } } // end namespace glt
// // Created by Bradley Austin Davis on 2017-01-11 // Copyright 2013-2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "OffscreenQmlSurfaceCache.h" #include <QtGui/QOpenGLContext> #include <QtQml/QQmlContext> #include <PathUtils.h> #include "OffscreenQmlSurface.h" #include "Profile.h" OffscreenQmlSurfaceCache::OffscreenQmlSurfaceCache() { } OffscreenQmlSurfaceCache::~OffscreenQmlSurfaceCache() { _cache.clear(); } QSharedPointer<OffscreenQmlSurface> OffscreenQmlSurfaceCache::acquire(const QString& rootSource) { auto& list = _cache[rootSource]; if (list.empty()) { list.push_back(buildSurface(rootSource)); } auto result = list.front(); list.pop_front(); return result; } void OffscreenQmlSurfaceCache::reserve(const QString& rootSource, int count) { auto& list = _cache[rootSource]; while (list.size() < count) { list.push_back(buildSurface(rootSource)); } } void OffscreenQmlSurfaceCache::release(const QString& rootSource, const QSharedPointer<OffscreenQmlSurface>& surface) { PROFILE_RANGE(app, "buildSurface"); surface->pause(); _cache[rootSource].push_back(surface); } QSharedPointer<OffscreenQmlSurface> OffscreenQmlSurfaceCache::buildSurface(const QString& rootSource) { auto surface = QSharedPointer<OffscreenQmlSurface>::create(); QObject::connect(surface.data(), &hifi::qml::OffscreenSurface::rootContextCreated, [this, rootSource](QQmlContext* surfaceContext) { if (_onRootContextCreated) { _onRootContextCreated(rootSource, surfaceContext); } }); surface->load(rootSource); surface->resize(QSize(100, 100)); return surface; } void OffscreenQmlSurfaceCache::setOnRootContextCreated(const std::function<void(const QString& rootSource, QQmlContext* rootContext)>& onRootContextCreated) { _onRootContextCreated = onRootContextCreated; }
// RUN: %clang_cc1 -fsycl-is-device -internal-isystem %S/Inputs -sycl-std=2017 -triple spir64-unknown-unknown -disable-llvm-passes -emit-llvm -o - %s | FileCheck %s #include "sycl.hpp" using namespace cl::sycl; queue q; class Functor { public: [[intel::reqd_sub_group_size(4), cl::reqd_work_group_size(32, 16, 16)]] void operator()() const {} }; class Functor1 { public: [[intel::reqd_sub_group_size(2), sycl::reqd_work_group_size(64, 32, 32)]] void operator()() const {} }; template <int SIZE, int SIZE1, int SIZE2> class Functor2 { public: [[sycl::reqd_work_group_size(SIZE, SIZE1, SIZE2)]] void operator()() const {} }; template <int N, int N1, int N2> [[sycl::reqd_work_group_size(N, N1, N2)]] void func() {} int main() { q.submit([&](handler &h) { Functor foo; h.single_task<class kernel_name1>(foo); Functor1 foo1; h.single_task<class kernel_name2>(foo1); Functor2<2, 2, 2> foo2; h.single_task<class kernel_name3>(foo2); h.single_task<class kernel_name4>([]() { func<8, 4, 4>(); }); }); return 0; } // CHECK: define {{.*}}spir_kernel void @{{.*}}kernel_name1() #0 {{.*}} !reqd_work_group_size ![[WGSIZE:[0-9]+]] !intel_reqd_sub_group_size ![[SGSIZE:[0-9]+]] // CHECK: define {{.*}}spir_kernel void @{{.*}}kernel_name2() #0 {{.*}} !reqd_work_group_size ![[WGSIZE1:[0-9]+]] !intel_reqd_sub_group_size ![[SGSIZE1:[0-9]+]] // CHECK: define {{.*}}spir_kernel void @{{.*}}kernel_name3() #0 {{.*}} !reqd_work_group_size ![[WGSIZE2:[0-9]+]] // CHECK: define {{.*}}spir_kernel void @{{.*}}kernel_name4() #0 {{.*}} !reqd_work_group_size ![[WGSIZE3:[0-9]+]] // CHECK: ![[WGSIZE]] = !{i32 16, i32 16, i32 32} // CHECK: ![[SGSIZE]] = !{i32 4} // CHECK: ![[WGSIZE1]] = !{i32 32, i32 32, i32 64} // CHECK: ![[SGSIZE1]] = !{i32 2} // CHECK: ![[WGSIZE2]] = !{i32 2, i32 2, i32 2} // CHECK: ![[WGSIZE3]] = !{i32 4, i32 4, i32 8}
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "proposaltablemodel.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "proposalrecord.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "rpcserver.h" #include "obfuscation.h" //#include "governance-vote.h" //#include "governance-object.h" #include "core_io.h" //#include "validation.h" #include "sync.h" #include "uint256.h" #include "util.h" #include <cmath> #include <QColor> #include <QDateTime> #include <QDebug> #include <QIcon> #include <QList> #include <univalue.h> static int column_alignments[] = { Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter, Qt::AlignLeft|Qt::AlignVCenter }; ProposalTableModel::ProposalTableModel( QObject *parent): QAbstractTableModel(parent) { columns << tr("Proposal") << tr("Amount") << tr("Start Block") << tr("End Block") << tr("Yes") << tr("No") << tr("Abstain") << tr("Votes Needed"); networkManager = new QNetworkAccessManager(this); connect(networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*))); refreshProposals(); } ProposalTableModel::~ProposalTableModel() { } void budgetToST(CBudgetProposal* pbudgetProposal, UniValue& bObj) { CTxDestination address; ExtractDestination(pbudgetProposal->GetPayee(), address); bObj.push_back(pbudgetProposal->GetName()); bObj.push_back(pbudgetProposal->GetURL()); bObj.push_back(pbudgetProposal->GetHash().ToString()); bObj.push_back(pbudgetProposal->nFeeTXHash.ToString()); bObj.push_back(pbudgetProposal->GetBlockStart()); bObj.push_back(pbudgetProposal->GetBlockEnd()); bObj.push_back(pbudgetProposal->GetTotalPaymentCount()); bObj.push_back(pbudgetProposal->GetRemainingPaymentCount()); bObj.push_back(EncodeDestination(address)); bObj.push_back(pbudgetProposal->GetYeas()); bObj.push_back(pbudgetProposal->GetNays()); bObj.push_back(pbudgetProposal->GetAbstains()); bObj.push_back(ValueFromAmount(pbudgetProposal->GetAmount() * pbudgetProposal->GetTotalPaymentCount())); bObj.push_back(pbudgetProposal->GetAmount()); bObj.push_back(pbudgetProposal->IsEstablished()); std::string strError = ""; bObj.push_back(Pair("IsValid", pbudgetProposal->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); bObj.push_back(Pair("fValid", pbudgetProposal->fValid)); } void ProposalTableModel::refreshProposals() { beginResetModel(); proposalRecords.clear(); int mnCount = mnodeman.CountEnabled(); std::vector<CBudgetProposal*> bObj = budget.GetAllProposals(); for (CBudgetProposal* pbudgetProposal : bObj) { //if(CBudgetProposal::CBudgetProposal() != GOVERNANCE_OBJECT_PROPOSAL) continue; //UniValue objResult(UniValue::VOBJ); //UniValue dataObj(UniValue::VOBJ); //objResult.read(pbudgetProposal->GetDataAsPlainString()); // not need as time being //std::vector<UniValue> arr1 = objResult.getValues(); //std::vector<UniValue> arr2 = arr1.at( 0 ).getValues(); //dataObj = arr2.at( 1 ); UniValue bObj(UniValue::VOBJ); budgetToST(pbudgetProposal, bObj); int votesNeeded = 0; int voteGap = 0; if(mnCount > 0) { voteGap = ceil( (mnCount / 10) - (pbudgetProposal->GetYeas() - pbudgetProposal->GetNays()) ); votesNeeded = (voteGap < 0) ? 0 : voteGap; }; proposalRecords.append(new ProposalRecord( QString::fromStdString(pbudgetProposal->GetHash().ToString()), (long long)pbudgetProposal->GetBlockStart(), (long long)pbudgetProposal->GetBlockEnd(), QString::fromStdString(pbudgetProposal->GetURL()), QString::fromStdString(pbudgetProposal->GetName()), (long long)pbudgetProposal->GetYeas(), (long long)pbudgetProposal->GetNays(), (long long)pbudgetProposal->GetAbstains(), (long long)pbudgetProposal->GetAmount(), (long long)votesNeeded)); } endResetModel(); } void ProposalTableModel::onResult(QNetworkReply *result) { /**/ } int ProposalTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return proposalRecords.size(); } int ProposalTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant ProposalTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); ProposalRecord *rec = static_cast<ProposalRecord*>(index.internalPointer()); switch(role) { case Qt::DisplayRole: switch(index.column()) { case Proposal: return rec->name; case YesVotes: return (long long)(rec->yesVotes); case NoVotes: return (long long)(rec->noVotes); case AbstainVotes: return (long long)(rec->abstainVotes); case StartDate: return (long long)(rec->start_epoch); case EndDate: return (long long)(rec->end_epoch); case VotesNeeded: return QString("%1").arg(rec->votesNeeded); case Amount: return BitcoinUnits::format(BitcoinUnits::PHR, rec->amount); } break; case Qt::EditRole: switch(index.column()) { case Proposal: return rec->name; case StartDate: return (long long)(rec->start_epoch); case EndDate: return (long long)(rec->end_epoch); case YesVotes: return (long long)(rec->yesVotes); case NoVotes: return (long long)(rec->noVotes); case AbstainVotes: return (long long)(rec->abstainVotes); case Amount: return qint64(rec->amount); case VotesNeeded: return (long long)(rec->votesNeeded); } break; case Qt::TextAlignmentRole: return column_alignments[index.column()]; case Qt::ForegroundRole: if(index.column() == VotesNeeded) { if(rec->votesNeeded > 0) { return COLOR_NEGATIVE; } else { return QColor(23, 168, 26); } } return COLOR_BAREADDRESS; break; case ProposalRole: return rec->name; case AmountRole: return (long long)(rec->amount); case StartDateRole: return (long long)(rec->start_epoch); case EndDateRole: return (long long)(rec->end_epoch); case YesVotesRole: return (long long)(rec->yesVotes); case NoVotesRole: return (long long)(rec->noVotes); case AbstainVotesRole: return (long long)(rec->abstainVotes); case VotesNeededRole: return (long long)(rec->votesNeeded); case ProposalUrlRole: return rec->url; case ProposalHashRole: return rec->hash; } return QVariant(); } QVariant ProposalTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { return columns[section]; } else if (role == Qt::TextAlignmentRole) { return Qt::AlignVCenter; } else if (role == Qt::ToolTipRole) { switch(section) { case Proposal: return tr("Proposal name"); case StartDate: return tr("Date and time that the proposal starts"); case EndDate: return tr("Date and time that the proposal ends"); case YesVotes: return tr("Obtained yes votes"); case NoVotes: return tr("Obtained no votes"); case AbstainVotes: return tr("Obtained abstain votes"); case Amount: return tr("Proposed amount"); case VotesNeeded: return tr("Current votes needed to pass"); } } } return QVariant(); } QModelIndex ProposalTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); if(row >= 0 && row < proposalRecords.size()) { ProposalRecord *rec = proposalRecords[row]; return createIndex(row, column, rec); } return QModelIndex(); }
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/compiler/relocation.h" #include "vm/code_patcher.h" #include "vm/heap/pages.h" #include "vm/instructions.h" #include "vm/object_store.h" #include "vm/stub_code.h" namespace dart { #if defined(DART_PRECOMPILER) && !defined(TARGET_ARCH_IA32) // Only for testing. DEFINE_FLAG(bool, always_generate_trampolines_for_testing, false, "Generate always trampolines (for testing purposes)."); const intptr_t kTrampolineSize = Utils::RoundUp(PcRelativeTrampolineJumpPattern::kLengthInBytes, compiler::target::Instructions::kBarePayloadAlignment); CodeRelocator::CodeRelocator(Thread* thread, GrowableArray<CodePtr>* code_objects, GrowableArray<ImageWriterCommand>* commands) : StackResource(thread), thread_(thread), code_objects_(code_objects), commands_(commands), kind_type_and_offset_(Smi::Handle(thread->zone())), target_(Object::Handle(thread->zone())), destination_(Code::Handle(thread->zone())) {} void CodeRelocator::Relocate(bool is_vm_isolate) { Zone* zone = Thread::Current()->zone(); auto& current_caller = Code::Handle(zone); auto& call_targets = Array::Handle(zone); // Do one linear pass over all code objects and determine: // // * the maximum instruction size // * the maximum number of calls // * the maximum offset into a target instruction // FindInstructionAndCallLimits(); // Emit all instructions and do relocations on the way. for (intptr_t i = 0; i < code_objects_->length(); ++i) { current_caller = (*code_objects_)[i]; const intptr_t code_text_offset = next_text_offset_; if (!AddInstructionsToText(current_caller.ptr())) { continue; } call_targets = current_caller.static_calls_target_table(); ScanCallTargets(current_caller, call_targets, code_text_offset); // Any unresolved calls to this instruction can be fixed now. ResolveUnresolvedCallsTargeting(current_caller.instructions()); // If we have forward/backwards calls which are almost out-of-range, we'll // create trampolines now. BuildTrampolinesForAlmostOutOfRangeCalls(); } // We're guaranteed to have all calls resolved, since // * backwards calls are resolved eagerly // * forward calls are resolved once the target is written if (!all_unresolved_calls_.IsEmpty()) { for (auto call : all_unresolved_calls_) { OS::PrintErr("Unresolved call to %s from %s\n", Object::Handle(call->callee).ToCString(), Object::Handle(call->caller).ToCString()); } } RELEASE_ASSERT(all_unresolved_calls_.IsEmpty()); RELEASE_ASSERT(unresolved_calls_by_destination_.IsEmpty()); // Any trampolines we created must be patched with the right offsets. auto it = trampolines_by_destination_.GetIterator(); while (true) { auto entry = it.Next(); if (entry == nullptr) break; UnresolvedTrampolineList* trampoline_list = entry->value; while (!trampoline_list->IsEmpty()) { auto unresolved_trampoline = trampoline_list->RemoveFirst(); ResolveTrampoline(unresolved_trampoline); delete unresolved_trampoline; } delete trampoline_list; } trampolines_by_destination_.Clear(); // Don't drop static call targets table yet. Snapshotter will skip it anyway // however we might need it to write information into V8 snapshot profile. } void CodeRelocator::FindInstructionAndCallLimits() { auto zone = thread_->zone(); auto& current_caller = Code::Handle(zone); auto& call_targets = Array::Handle(zone); for (intptr_t i = 0; i < code_objects_->length(); ++i) { current_caller = (*code_objects_)[i]; const intptr_t size = ImageWriter::SizeInSnapshot(current_caller.instructions()); if (size > max_instructions_size_) { max_instructions_size_ = size; } call_targets = current_caller.static_calls_target_table(); if (!call_targets.IsNull()) { intptr_t num_calls = 0; StaticCallsTable calls(call_targets); for (auto call : calls) { kind_type_and_offset_ = call.Get<Code::kSCallTableKindAndOffset>(); const auto kind = Code::KindField::decode(kind_type_and_offset_.Value()); const auto return_pc_offset = Code::OffsetField::decode(kind_type_and_offset_.Value()); const auto call_entry_point = Code::EntryPointField::decode(kind_type_and_offset_.Value()); if (kind == Code::kCallViaCode) { continue; } destination_ = GetTarget(call); num_calls++; // A call site can decide to jump not to the beginning of a function but // rather jump into it at a certain (positive) offset. int32_t offset_into_target = 0; if (kind == Code::kPcRelativeCall || kind == Code::kPcRelativeTTSCall) { const intptr_t call_instruction_offset = return_pc_offset - PcRelativeCallPattern::kLengthInBytes; PcRelativeCallPattern call(current_caller.PayloadStart() + call_instruction_offset); ASSERT(call.IsValid()); offset_into_target = call.distance(); } else { ASSERT(kind == Code::kPcRelativeTailCall); const intptr_t call_instruction_offset = return_pc_offset - PcRelativeTailCallPattern::kLengthInBytes; PcRelativeTailCallPattern call(current_caller.PayloadStart() + call_instruction_offset); ASSERT(call.IsValid()); offset_into_target = call.distance(); } const uword destination_payload = destination_.PayloadStart(); const uword entry_point = call_entry_point == Code::kUncheckedEntry ? destination_.UncheckedEntryPoint() : destination_.EntryPoint(); offset_into_target += (entry_point - destination_payload); if (offset_into_target > max_offset_into_target_) { max_offset_into_target_ = offset_into_target; } } if (num_calls > max_calls_) { max_calls_ = num_calls; } } } } bool CodeRelocator::AddInstructionsToText(CodePtr code) { InstructionsPtr instructions = Code::InstructionsOf(code); // If two [Code] objects point to the same [Instructions] object, we'll just // use the first one (they are equivalent for all practical purposes). if (text_offsets_.HasKey(instructions)) { return false; } text_offsets_.Insert({instructions, next_text_offset_}); commands_->Add(ImageWriterCommand(next_text_offset_, code)); next_text_offset_ += ImageWriter::SizeInSnapshot(instructions); return true; } UnresolvedTrampoline* CodeRelocator::FindTrampolineFor( UnresolvedCall* unresolved_call) { auto destination = Code::InstructionsOf(unresolved_call->callee); auto entry = trampolines_by_destination_.Lookup(destination); if (entry != nullptr) { UnresolvedTrampolineList* trampolines = entry->value; ASSERT(!trampolines->IsEmpty()); // For the destination of [unresolved_call] we might have multiple // trampolines. The trampolines are sorted according to insertion order, // which guarantees increasing text_offset's. So we go from the back of the // list as long as we have trampolines that are in-range and then check // whether the target offset matches. auto it = trampolines->End(); --it; do { UnresolvedTrampoline* trampoline = *it; if (!IsTargetInRangeFor(unresolved_call, trampoline->text_offset)) { break; } if (trampoline->offset_into_target == unresolved_call->offset_into_target) { return trampoline; } --it; } while (it != trampolines->Begin()); } return nullptr; } void CodeRelocator::AddTrampolineToText(InstructionsPtr destination, uint8_t* trampoline_bytes, intptr_t trampoline_length) { commands_->Add(ImageWriterCommand(next_text_offset_, trampoline_bytes, trampoline_length)); next_text_offset_ += trampoline_length; } void CodeRelocator::ScanCallTargets(const Code& code, const Array& call_targets, intptr_t code_text_offset) { if (call_targets.IsNull()) { return; } StaticCallsTable calls(call_targets); for (auto call : calls) { kind_type_and_offset_ = call.Get<Code::kSCallTableKindAndOffset>(); const auto kind = Code::KindField::decode(kind_type_and_offset_.Value()); const auto return_pc_offset = Code::OffsetField::decode(kind_type_and_offset_.Value()); const auto call_entry_point = Code::EntryPointField::decode(kind_type_and_offset_.Value()); if (kind == Code::kCallViaCode) { continue; } destination_ = GetTarget(call); // A call site can decide to jump not to the beginning of a function but // rather jump into it at a certain offset. int32_t offset_into_target = 0; bool is_tail_call; intptr_t call_instruction_offset; if (kind == Code::kPcRelativeCall || kind == Code::kPcRelativeTTSCall) { call_instruction_offset = return_pc_offset - PcRelativeCallPattern::kLengthInBytes; PcRelativeCallPattern call(code.PayloadStart() + call_instruction_offset); ASSERT(call.IsValid()); offset_into_target = call.distance(); is_tail_call = false; } else { ASSERT(kind == Code::kPcRelativeTailCall); call_instruction_offset = return_pc_offset - PcRelativeTailCallPattern::kLengthInBytes; PcRelativeTailCallPattern call(code.PayloadStart() + call_instruction_offset); ASSERT(call.IsValid()); offset_into_target = call.distance(); is_tail_call = true; } const uword destination_payload = destination_.PayloadStart(); const uword entry_point = call_entry_point == Code::kUncheckedEntry ? destination_.UncheckedEntryPoint() : destination_.EntryPoint(); offset_into_target += (entry_point - destination_payload); const intptr_t text_offset = code_text_offset + AdjustPayloadOffset(call_instruction_offset); UnresolvedCall unresolved_call(code.ptr(), call_instruction_offset, text_offset, destination_.ptr(), offset_into_target, is_tail_call); if (!TryResolveBackwardsCall(&unresolved_call)) { EnqueueUnresolvedCall(new UnresolvedCall(unresolved_call)); } } } void CodeRelocator::EnqueueUnresolvedCall(UnresolvedCall* unresolved_call) { // Add it to the min-heap by .text offset. all_unresolved_calls_.Append(unresolved_call); // Add it to callers of destination. InstructionsPtr destination = Code::InstructionsOf(unresolved_call->callee); if (!unresolved_calls_by_destination_.HasKey(destination)) { unresolved_calls_by_destination_.Insert( {destination, new SameDestinationUnresolvedCallsList()}); } unresolved_calls_by_destination_.LookupValue(destination) ->Append(unresolved_call); } void CodeRelocator::EnqueueUnresolvedTrampoline( UnresolvedTrampoline* unresolved_trampoline) { auto destination = Code::InstructionsOf(unresolved_trampoline->callee); auto entry = trampolines_by_destination_.Lookup(destination); UnresolvedTrampolineList* trampolines = nullptr; if (entry == nullptr) { trampolines = new UnresolvedTrampolineList(); trampolines_by_destination_.Insert({destination, trampolines}); } else { trampolines = entry->value; } trampolines->Append(unresolved_trampoline); } bool CodeRelocator::TryResolveBackwardsCall(UnresolvedCall* unresolved_call) { auto callee = Code::InstructionsOf(unresolved_call->callee); auto map_entry = text_offsets_.Lookup(callee); if (map_entry == nullptr) return false; ResolveCall(unresolved_call); return true; } void CodeRelocator::ResolveUnresolvedCallsTargeting( const InstructionsPtr instructions) { if (unresolved_calls_by_destination_.HasKey(instructions)) { SameDestinationUnresolvedCallsList* calls = unresolved_calls_by_destination_.LookupValue(instructions); auto it = calls->Begin(); while (it != calls->End()) { UnresolvedCall* unresolved_call = *it; ++it; ASSERT(Code::InstructionsOf(unresolved_call->callee) == instructions); ResolveCall(unresolved_call); // Remove the call from both lists. calls->Remove(unresolved_call); all_unresolved_calls_.Remove(unresolved_call); delete unresolved_call; } ASSERT(calls->IsEmpty()); delete calls; bool ok = unresolved_calls_by_destination_.Remove(instructions); ASSERT(ok); } } void CodeRelocator::ResolveCall(UnresolvedCall* unresolved_call) { const intptr_t destination_text = FindDestinationInText(Code::InstructionsOf(unresolved_call->callee), unresolved_call->offset_into_target); ResolveCallToDestination(unresolved_call, destination_text); } void CodeRelocator::ResolveCallToDestination(UnresolvedCall* unresolved_call, intptr_t destination_text) { const intptr_t call_text_offset = unresolved_call->text_offset; const intptr_t call_offset = unresolved_call->call_offset; const int32_t distance = destination_text - call_text_offset; { auto const caller = unresolved_call->caller; uword addr = Code::PayloadStartOf(caller) + call_offset; if (FLAG_write_protect_code) { addr -= OldPage::Of(Code::InstructionsOf(caller))->AliasOffset(); } if (unresolved_call->is_tail_call) { PcRelativeTailCallPattern call(addr); ASSERT(call.IsValid()); call.set_distance(static_cast<int32_t>(distance)); ASSERT(call.distance() == distance); } else { PcRelativeCallPattern call(addr); ASSERT(call.IsValid()); call.set_distance(static_cast<int32_t>(distance)); ASSERT(call.distance() == distance); } } unresolved_call->caller = nullptr; unresolved_call->callee = nullptr; } void CodeRelocator::ResolveTrampoline( UnresolvedTrampoline* unresolved_trampoline) { const intptr_t trampoline_text_offset = unresolved_trampoline->text_offset; const uword trampoline_start = reinterpret_cast<uword>(unresolved_trampoline->trampoline_bytes); auto callee = Code::InstructionsOf(unresolved_trampoline->callee); auto destination_text = FindDestinationInText(callee, unresolved_trampoline->offset_into_target); const int32_t distance = destination_text - trampoline_text_offset; PcRelativeTrampolineJumpPattern pattern(trampoline_start); pattern.Initialize(); pattern.set_distance(distance); ASSERT(pattern.distance() == distance); } bool CodeRelocator::IsTargetInRangeFor(UnresolvedCall* unresolved_call, intptr_t target_text_offset) { const auto forward_distance = target_text_offset - unresolved_call->text_offset; if (unresolved_call->is_tail_call) { return PcRelativeTailCallPattern::kLowerCallingRange < forward_distance && forward_distance < PcRelativeTailCallPattern::kUpperCallingRange; } else { return PcRelativeCallPattern::kLowerCallingRange < forward_distance && forward_distance < PcRelativeCallPattern::kUpperCallingRange; } } CodePtr CodeRelocator::GetTarget(const StaticCallsTableEntry& call) { // The precompiler should have already replaced all function entries // with code entries. ASSERT(call.Get<Code::kSCallTableFunctionTarget>() == Function::null()); target_ = call.Get<Code::kSCallTableCodeOrTypeTarget>(); if (target_.IsAbstractType()) { target_ = AbstractType::Cast(target_).type_test_stub(); destination_ = Code::Cast(target_).ptr(); // The AssertAssignableInstr will emit pc-relative calls to the TTS iff // dst_type is instantiated. If we happened to not install an optimized // TTS but rather a default one, it will live in the vm-isolate (to // which we cannot make pc-relative calls). // Though we have "equivalent" isolate-specific stubs we can use as // targets instead. // // (We could make the AOT compiler install isolate-specific stubs // into the types directly, but that does not work for types which // live in the "vm-isolate" - such as `Type::dynamic_type()`). if (destination_.InVMIsolateHeap()) { auto object_store = thread_->isolate_group()->object_store(); if (destination_.ptr() == StubCode::DefaultTypeTest().ptr()) { destination_ = object_store->default_tts_stub(); } else if (destination_.ptr() == StubCode::DefaultNullableTypeTest().ptr()) { destination_ = object_store->default_nullable_tts_stub(); } else if (destination_.ptr() == StubCode::TopTypeTypeTest().ptr()) { destination_ = object_store->top_type_tts_stub(); } else if (destination_.ptr() == StubCode::UnreachableTypeTest().ptr()) { destination_ = object_store->unreachable_tts_stub(); } else if (destination_.ptr() == StubCode::SlowTypeTest().ptr()) { destination_ = object_store->slow_tts_stub(); } else if (destination_.ptr() == StubCode::NullableTypeParameterTypeTest().ptr()) { destination_ = object_store->nullable_type_parameter_tts_stub(); } else if (destination_.ptr() == StubCode::TypeParameterTypeTest().ptr()) { destination_ = object_store->type_parameter_tts_stub(); } else { UNREACHABLE(); } } } else { ASSERT(target_.IsCode()); destination_ = Code::Cast(target_).ptr(); } ASSERT(!destination_.InVMIsolateHeap()); return destination_.ptr(); } void CodeRelocator::BuildTrampolinesForAlmostOutOfRangeCalls() { while (!all_unresolved_calls_.IsEmpty()) { UnresolvedCall* unresolved_call = all_unresolved_calls_.First(); // If we can emit another instructions object without causing the unresolved // forward calls to become out-of-range, we'll not resolve it yet (maybe the // target function will come very soon and we don't need a trampoline at // all). const intptr_t future_boundary = next_text_offset_ + max_instructions_size_ + kTrampolineSize * (unresolved_calls_by_destination_.Length() + max_calls_); if (IsTargetInRangeFor(unresolved_call, future_boundary) && !FLAG_always_generate_trampolines_for_testing) { break; } // We have a "critical" [unresolved_call] we have to resolve. If an // existing trampoline is in range, we use that otherwise we create a new // trampoline. // In the worst case we'll make a new trampoline here, in which case the // current text offset must be in range for the "critical" // [unresolved_call]. ASSERT(IsTargetInRangeFor(unresolved_call, next_text_offset_)); // See if there is already a trampoline we could use. intptr_t trampoline_text_offset = -1; auto callee = Code::InstructionsOf(unresolved_call->callee); if (!FLAG_always_generate_trampolines_for_testing) { auto old_trampoline_entry = FindTrampolineFor(unresolved_call); if (old_trampoline_entry != nullptr) { trampoline_text_offset = old_trampoline_entry->text_offset; } } // If there is no trampoline yet, we'll create a new one. if (trampoline_text_offset == -1) { // The ownership of the trampoline bytes will be transferred to the // [ImageWriter], which will eventually write out the bytes and delete the // buffer. auto trampoline_bytes = new uint8_t[kTrampolineSize]; ASSERT((kTrampolineSize % compiler::target::kWordSize) == 0); for (uint8_t* cur = trampoline_bytes; cur < trampoline_bytes + kTrampolineSize; cur += compiler::target::kWordSize) { *reinterpret_cast<compiler::target::uword*>(cur) = kBreakInstructionFiller; } auto unresolved_trampoline = new UnresolvedTrampoline{ unresolved_call->callee, unresolved_call->offset_into_target, trampoline_bytes, next_text_offset_, }; AddTrampolineToText(callee, trampoline_bytes, kTrampolineSize); EnqueueUnresolvedTrampoline(unresolved_trampoline); trampoline_text_offset = unresolved_trampoline->text_offset; } // Let the unresolved call to [destination] jump to the trampoline // instead. auto destination = Code::InstructionsOf(unresolved_call->callee); ResolveCallToDestination(unresolved_call, trampoline_text_offset); // Remove this unresolved call from the global list and the per-destination // list. auto calls = unresolved_calls_by_destination_.LookupValue(destination); calls->Remove(unresolved_call); all_unresolved_calls_.Remove(unresolved_call); delete unresolved_call; // If this destination has no longer any unresolved calls, remove it. if (calls->IsEmpty()) { unresolved_calls_by_destination_.Remove(destination); delete calls; } } } intptr_t CodeRelocator::FindDestinationInText(const InstructionsPtr destination, intptr_t offset_into_target) { auto const destination_offset = text_offsets_.LookupValue(destination); return destination_offset + AdjustPayloadOffset(offset_into_target); } intptr_t CodeRelocator::AdjustPayloadOffset(intptr_t payload_offset) { if (FLAG_precompiled_mode && FLAG_use_bare_instructions) { return payload_offset; } return compiler::target::Instructions::HeaderSize() + payload_offset; } #endif // defined(DART_PRECOMPILER) && !defined(TARGET_ARCH_IA32) } // namespace dart
#include "sync.h" #include <fcntl.h> #include <sys/stat.h> #include <cerrno> #include "names.h" Sync::Sync(const char *name, bool open) : ISync(), name(name) { } Sync::~Sync() { } ISync* Sync::create(const char *name) { //sem_open(name, //O_CREAT | O_EXCL, //S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP, 0); } ISync* Sync::open(const char* name) { //sem_open(name, 0); } void Sync::destroy(const char* name) { //sem_unlink(name); } void Sync::wait() { // Implementar el método wait() } void Sync::signal() { // Implementar el método signal() } void Sync::close() { // Implementarel método close() }
// Supported with union (c) 2020 Union team // User API for zCView // Add your methods here
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/svg/SkSVGDevice.h" #include <memory> #include "include/core/SkBitmap.h" #include "include/core/SkBlendMode.h" #include "include/core/SkColorFilter.h" #include "include/core/SkData.h" #include "include/core/SkImage.h" #include "include/core/SkImageEncoder.h" #include "include/core/SkPaint.h" #include "include/core/SkPathBuilder.h" #include "include/core/SkShader.h" #include "include/core/SkStream.h" #include "include/core/SkTypeface.h" #include "include/private/SkChecksum.h" #include "include/private/SkTHash.h" #include "include/private/SkTPin.h" #include "include/private/SkTo.h" #include "include/svg/SkSVGCanvas.h" #include "include/utils/SkBase64.h" #include "src/codec/SkJpegCodec.h" #include "src/core/SkAnnotationKeys.h" #include "src/core/SkClipStack.h" #include "src/core/SkDraw.h" #include "src/core/SkFontPriv.h" #include "src/core/SkUtils.h" #include "src/image/SkImage_Base.h" #include "src/shaders/SkShaderBase.h" #include "src/xml/SkXMLWriter.h" namespace { static SkString svg_color(SkColor color) { // https://www.w3.org/TR/css-color-3/#html4 auto named_color = [](SkColor c) -> const char* { switch (c & 0xffffff) { case 0x000000: return "black"; case 0x000080: return "navy"; case 0x0000ff: return "blue"; case 0x008000: return "green"; case 0x008080: return "teal"; case 0x00ff00: return "lime"; case 0x00ffff: return "aqua"; case 0x800000: return "maroon"; case 0x800080: return "purple"; case 0x808000: return "olive"; case 0x808080: return "gray"; case 0xc0c0c0: return "silver"; case 0xff0000: return "red"; case 0xff00ff: return "fuchsia"; case 0xffff00: return "yellow"; case 0xffffff: return "white"; default: break; } return nullptr; }; if (const auto* nc = named_color(color)) { return SkString(nc); } uint8_t r = SkColorGetR(color); uint8_t g = SkColorGetG(color); uint8_t b = SkColorGetB(color); // Some users care about every byte here, so we'll use hex colors with single-digit channels // when possible. uint8_t rh = r >> 4; uint8_t rl = r & 0xf; uint8_t gh = g >> 4; uint8_t gl = g & 0xf; uint8_t bh = b >> 4; uint8_t bl = b & 0xf; if ((rh == rl) && (gh == gl) && (bh == bl)) { return SkStringPrintf("#%1X%1X%1X", rh, gh, bh); } return SkStringPrintf("#%02X%02X%02X", r, g, b); } static SkScalar svg_opacity(SkColor color) { return SkIntToScalar(SkColorGetA(color)) / SK_AlphaOPAQUE; } // Keep in sync with SkPaint::Cap static const char* cap_map[] = { nullptr, // kButt_Cap (default) "round", // kRound_Cap "square" // kSquare_Cap }; static_assert(SK_ARRAY_COUNT(cap_map) == SkPaint::kCapCount, "missing_cap_map_entry"); static const char* svg_cap(SkPaint::Cap cap) { SkASSERT(cap < SK_ARRAY_COUNT(cap_map)); return cap_map[cap]; } // Keep in sync with SkPaint::Join static const char* join_map[] = { nullptr, // kMiter_Join (default) "round", // kRound_Join "bevel" // kBevel_Join }; static_assert(SK_ARRAY_COUNT(join_map) == SkPaint::kJoinCount, "missing_join_map_entry"); static const char* svg_join(SkPaint::Join join) { SkASSERT(join < SK_ARRAY_COUNT(join_map)); return join_map[join]; } static SkString svg_transform(const SkMatrix& t) { SkASSERT(!t.isIdentity()); SkString tstr; switch (t.getType()) { case SkMatrix::kPerspective_Mask: // TODO: handle perspective matrices? break; case SkMatrix::kTranslate_Mask: tstr.printf("translate(%g %g)", t.getTranslateX(), t.getTranslateY()); break; case SkMatrix::kScale_Mask: tstr.printf("scale(%g %g)", t.getScaleX(), t.getScaleY()); break; default: // http://www.w3.org/TR/SVG/coords.html#TransformMatrixDefined // | a c e | // | b d f | // | 0 0 1 | tstr.printf("matrix(%g %g %g %g %g %g)", t.getScaleX(), t.getSkewY(), t.getSkewX(), t.getScaleY(), t.getTranslateX(), t.getTranslateY()); break; } return tstr; } struct Resources { Resources(const SkPaint& paint) : fPaintServer(svg_color(paint.getColor())) {} SkString fPaintServer; SkString fColorFilter; }; // Determine if the paint requires us to reset the viewport. // Currently, we do this whenever the paint shader calls // for a repeating image. bool RequiresViewportReset(const SkPaint& paint) { SkShader* shader = paint.getShader(); if (!shader) return false; SkTileMode xy[2]; SkImage* image = shader->isAImage(nullptr, xy); if (!image) return false; for (int i = 0; i < 2; i++) { if (xy[i] == SkTileMode::kRepeat) return true; } return false; } void AddPath(const SkGlyphRun& glyphRun, const SkPoint& offset, SkPath* path) { struct Rec { SkPath* fPath; const SkPoint fOffset; const SkPoint* fPos; } rec = { path, offset, glyphRun.positions().data() }; glyphRun.font().getPaths(glyphRun.glyphsIDs().data(), SkToInt(glyphRun.glyphsIDs().size()), [](const SkPath* path, const SkMatrix& mx, void* ctx) { Rec* rec = reinterpret_cast<Rec*>(ctx); if (path) { SkMatrix total = mx; total.postTranslate(rec->fPos->fX + rec->fOffset.fX, rec->fPos->fY + rec->fOffset.fY); rec->fPath->addPath(*path, total); } else { // TODO: this is going to drop color emojis. } rec->fPos += 1; // move to the next glyph's position }, &rec); } } // namespace // For now all this does is serve unique serial IDs, but it will eventually evolve to track // and deduplicate resources. class SkSVGDevice::ResourceBucket : ::SkNoncopyable { public: ResourceBucket() : fGradientCount(0) , fPathCount(0) , fImageCount(0) , fPatternCount(0) , fColorFilterCount(0) {} SkString addLinearGradient() { return SkStringPrintf("gradient_%d", fGradientCount++); } SkString addPath() { return SkStringPrintf("path_%d", fPathCount++); } SkString addImage() { return SkStringPrintf("img_%d", fImageCount++); } SkString addColorFilter() { return SkStringPrintf("cfilter_%d", fColorFilterCount++); } SkString addPattern() { return SkStringPrintf("pattern_%d", fPatternCount++); } private: uint32_t fGradientCount; uint32_t fPathCount; uint32_t fImageCount; uint32_t fPatternCount; uint32_t fColorFilterCount; }; struct SkSVGDevice::MxCp { const SkMatrix* fMatrix; const SkClipStack* fClipStack; MxCp(const SkMatrix* mx, const SkClipStack* cs) : fMatrix(mx), fClipStack(cs) {} MxCp(SkSVGDevice* device) : fMatrix(&device->localToDevice()), fClipStack(&device->cs()) {} }; class SkSVGDevice::AutoElement : ::SkNoncopyable { public: AutoElement(const char name[], SkXMLWriter* writer) : fWriter(writer) , fResourceBucket(nullptr) { fWriter->startElement(name); } AutoElement(const char name[], const std::unique_ptr<SkXMLWriter>& writer) : AutoElement(name, writer.get()) {} AutoElement(const char name[], SkSVGDevice* svgdev, ResourceBucket* bucket, const MxCp& mc, const SkPaint& paint) : fWriter(svgdev->fWriter.get()) , fResourceBucket(bucket) { svgdev->syncClipStack(*mc.fClipStack); Resources res = this->addResources(mc, paint); fWriter->startElement(name); this->addPaint(paint, res); if (!mc.fMatrix->isIdentity()) { this->addAttribute("transform", svg_transform(*mc.fMatrix)); } } ~AutoElement() { fWriter->endElement(); } void addAttribute(const char name[], const char val[]) { fWriter->addAttribute(name, val); } void addAttribute(const char name[], const SkString& val) { fWriter->addAttribute(name, val.c_str()); } void addAttribute(const char name[], int32_t val) { fWriter->addS32Attribute(name, val); } void addAttribute(const char name[], SkScalar val) { fWriter->addScalarAttribute(name, val); } void addText(const SkString& text) { fWriter->addText(text.c_str(), text.size()); } void addRectAttributes(const SkRect&); void addPathAttributes(const SkPath&, SkParsePath::PathEncoding); void addTextAttributes(const SkFont&); private: Resources addResources(const MxCp&, const SkPaint& paint); void addShaderResources(const SkPaint& paint, Resources* resources); void addGradientShaderResources(const SkShader* shader, const SkPaint& paint, Resources* resources); void addColorFilterResources(const SkColorFilter& cf, Resources* resources); void addImageShaderResources(const SkShader* shader, const SkPaint& paint, Resources* resources); void addPatternDef(const SkBitmap& bm); void addPaint(const SkPaint& paint, const Resources& resources); SkString addLinearGradientDef(const SkShader::GradientInfo& info, const SkShader* shader); SkXMLWriter* fWriter; ResourceBucket* fResourceBucket; }; void SkSVGDevice::AutoElement::addPaint(const SkPaint& paint, const Resources& resources) { // Path effects are applied to all vector graphics (rects, rrects, ovals, // paths etc). This should only happen when a path effect is attached to // non-vector graphics (text, image) or a new vector graphics primitive is //added that is not handled by base drawPath() routine. if (paint.getPathEffect() != nullptr) { SkDebugf("Unsupported path effect in addPaint."); } SkPaint::Style style = paint.getStyle(); if (style == SkPaint::kFill_Style || style == SkPaint::kStrokeAndFill_Style) { static constexpr char kDefaultFill[] = "black"; if (!resources.fPaintServer.equals(kDefaultFill)) { this->addAttribute("fill", resources.fPaintServer); if (SK_AlphaOPAQUE != SkColorGetA(paint.getColor())) { this->addAttribute("fill-opacity", svg_opacity(paint.getColor())); } } } else { SkASSERT(style == SkPaint::kStroke_Style); this->addAttribute("fill", "none"); } if (!resources.fColorFilter.isEmpty()) { this->addAttribute("filter", resources.fColorFilter.c_str()); } if (style == SkPaint::kStroke_Style || style == SkPaint::kStrokeAndFill_Style) { this->addAttribute("stroke", resources.fPaintServer); SkScalar strokeWidth = paint.getStrokeWidth(); if (strokeWidth == 0) { // Hairline stroke strokeWidth = 1; this->addAttribute("vector-effect", "non-scaling-stroke"); } this->addAttribute("stroke-width", strokeWidth); if (const char* cap = svg_cap(paint.getStrokeCap())) { this->addAttribute("stroke-linecap", cap); } if (const char* join = svg_join(paint.getStrokeJoin())) { this->addAttribute("stroke-linejoin", join); } if (paint.getStrokeJoin() == SkPaint::kMiter_Join) { this->addAttribute("stroke-miterlimit", paint.getStrokeMiter()); } if (SK_AlphaOPAQUE != SkColorGetA(paint.getColor())) { this->addAttribute("stroke-opacity", svg_opacity(paint.getColor())); } } else { SkASSERT(style == SkPaint::kFill_Style); // SVG default stroke value is "none". } } Resources SkSVGDevice::AutoElement::addResources(const MxCp& mc, const SkPaint& paint) { Resources resources(paint); if (paint.getShader()) { AutoElement defs("defs", fWriter); this->addShaderResources(paint, &resources); } if (const SkColorFilter* cf = paint.getColorFilter()) { // TODO: Implement skia color filters for blend modes other than SrcIn SkBlendMode mode; if (cf->asAColorMode(nullptr, &mode) && mode == SkBlendMode::kSrcIn) { this->addColorFilterResources(*cf, &resources); } } return resources; } void SkSVGDevice::AutoElement::addGradientShaderResources(const SkShader* shader, const SkPaint& paint, Resources* resources) { SkShader::GradientInfo grInfo; memset(&grInfo, 0, sizeof(grInfo)); const auto gradient_type = shader->asAGradient(&grInfo); if (gradient_type != SkShader::kColor_GradientType && gradient_type != SkShader::kLinear_GradientType) { // TODO: other gradient support return; } SkAutoSTArray<16, SkColor> grColors(grInfo.fColorCount); SkAutoSTArray<16, SkScalar> grOffsets(grInfo.fColorCount); grInfo.fColors = grColors.get(); grInfo.fColorOffsets = grOffsets.get(); // One more call to get the actual colors/offsets. shader->asAGradient(&grInfo); SkASSERT(grInfo.fColorCount <= grColors.count()); SkASSERT(grInfo.fColorCount <= grOffsets.count()); SkASSERT(grColors.size() > 0); resources->fPaintServer = gradient_type == SkShader::kColor_GradientType ? svg_color(grColors[0]) : SkStringPrintf("url(#%s)", addLinearGradientDef(grInfo, shader).c_str()); } void SkSVGDevice::AutoElement::addColorFilterResources(const SkColorFilter& cf, Resources* resources) { SkString colorfilterID = fResourceBucket->addColorFilter(); { AutoElement filterElement("filter", fWriter); filterElement.addAttribute("id", colorfilterID); filterElement.addAttribute("x", "0%"); filterElement.addAttribute("y", "0%"); filterElement.addAttribute("width", "100%"); filterElement.addAttribute("height", "100%"); SkColor filterColor; SkBlendMode mode; bool asAColorMode = cf.asAColorMode(&filterColor, &mode); SkAssertResult(asAColorMode); SkASSERT(mode == SkBlendMode::kSrcIn); { // first flood with filter color AutoElement floodElement("feFlood", fWriter); floodElement.addAttribute("flood-color", svg_color(filterColor)); floodElement.addAttribute("flood-opacity", svg_opacity(filterColor)); floodElement.addAttribute("result", "flood"); } { // apply the transform to filter color AutoElement compositeElement("feComposite", fWriter); compositeElement.addAttribute("in", "flood"); compositeElement.addAttribute("operator", "in"); } } resources->fColorFilter.printf("url(#%s)", colorfilterID.c_str()); } namespace { bool is_png(const void* bytes, size_t length) { constexpr uint8_t kPngSig[] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; return length >= sizeof(kPngSig) && !memcmp(bytes, kPngSig, sizeof(kPngSig)); } } // namespace // Returns data uri from bytes. // it will use any cached data if available, otherwise will // encode as png. sk_sp<SkData> AsDataUri(SkImage* image) { sk_sp<SkData> imageData = image->encodeToData(); if (!imageData) { return nullptr; } const char* selectedPrefix = nullptr; size_t selectedPrefixLength = 0; #ifdef SK_CODEC_DECODES_JPEG if (SkJpegCodec::IsJpeg(imageData->data(), imageData->size())) { const static char jpgDataPrefix[] = "data:image/jpeg;base64,"; selectedPrefix = jpgDataPrefix; selectedPrefixLength = sizeof(jpgDataPrefix); } else #endif { if (!is_png(imageData->data(), imageData->size())) { #ifdef SK_ENCODE_PNG imageData = image->encodeToData(SkEncodedImageFormat::kPNG, 100); #else return nullptr; #endif } const static char pngDataPrefix[] = "data:image/png;base64,"; selectedPrefix = pngDataPrefix; selectedPrefixLength = sizeof(pngDataPrefix); } size_t b64Size = SkBase64::Encode(imageData->data(), imageData->size(), nullptr); sk_sp<SkData> dataUri = SkData::MakeUninitialized(selectedPrefixLength + b64Size); char* dest = (char*)dataUri->writable_data(); memcpy(dest, selectedPrefix, selectedPrefixLength); SkBase64::Encode(imageData->data(), imageData->size(), dest + selectedPrefixLength - 1); dest[dataUri->size() - 1] = 0; return dataUri; } void SkSVGDevice::AutoElement::addImageShaderResources(const SkShader* shader, const SkPaint& paint, Resources* resources) { SkMatrix outMatrix; SkTileMode xy[2]; SkImage* image = shader->isAImage(&outMatrix, xy); SkASSERT(image); SkString patternDims[2]; // width, height sk_sp<SkData> dataUri = AsDataUri(image); if (!dataUri) { return; } SkIRect imageSize = image->bounds(); for (int i = 0; i < 2; i++) { int imageDimension = i == 0 ? imageSize.width() : imageSize.height(); switch (xy[i]) { case SkTileMode::kRepeat: patternDims[i].appendScalar(imageDimension); break; default: // TODO: other tile modes? patternDims[i] = "100%"; } } SkString patternID = fResourceBucket->addPattern(); { AutoElement pattern("pattern", fWriter); pattern.addAttribute("id", patternID); pattern.addAttribute("patternUnits", "userSpaceOnUse"); pattern.addAttribute("patternContentUnits", "userSpaceOnUse"); pattern.addAttribute("width", patternDims[0]); pattern.addAttribute("height", patternDims[1]); pattern.addAttribute("x", 0); pattern.addAttribute("y", 0); { SkString imageID = fResourceBucket->addImage(); AutoElement imageTag("image", fWriter); imageTag.addAttribute("id", imageID); imageTag.addAttribute("x", 0); imageTag.addAttribute("y", 0); imageTag.addAttribute("width", image->width()); imageTag.addAttribute("height", image->height()); imageTag.addAttribute("xlink:href", static_cast<const char*>(dataUri->data())); } } resources->fPaintServer.printf("url(#%s)", patternID.c_str()); } void SkSVGDevice::AutoElement::addShaderResources(const SkPaint& paint, Resources* resources) { const SkShader* shader = paint.getShader(); SkASSERT(shader); if (shader->asAGradient(nullptr) != SkShader::kNone_GradientType) { this->addGradientShaderResources(shader, paint, resources); } else if (shader->isAImage()) { this->addImageShaderResources(shader, paint, resources); } // TODO: other shader types? } SkString SkSVGDevice::AutoElement::addLinearGradientDef(const SkShader::GradientInfo& info, const SkShader* shader) { SkASSERT(fResourceBucket); SkString id = fResourceBucket->addLinearGradient(); { AutoElement gradient("linearGradient", fWriter); gradient.addAttribute("id", id); gradient.addAttribute("gradientUnits", "userSpaceOnUse"); gradient.addAttribute("x1", info.fPoint[0].x()); gradient.addAttribute("y1", info.fPoint[0].y()); gradient.addAttribute("x2", info.fPoint[1].x()); gradient.addAttribute("y2", info.fPoint[1].y()); if (!as_SB(shader)->getLocalMatrix().isIdentity()) { this->addAttribute("gradientTransform", svg_transform(as_SB(shader)->getLocalMatrix())); } SkASSERT(info.fColorCount >= 2); for (int i = 0; i < info.fColorCount; ++i) { SkColor color = info.fColors[i]; SkString colorStr(svg_color(color)); { AutoElement stop("stop", fWriter); stop.addAttribute("offset", info.fColorOffsets[i]); stop.addAttribute("stop-color", colorStr.c_str()); if (SK_AlphaOPAQUE != SkColorGetA(color)) { stop.addAttribute("stop-opacity", svg_opacity(color)); } } } } return id; } void SkSVGDevice::AutoElement::addRectAttributes(const SkRect& rect) { // x, y default to 0 if (rect.x() != 0) { this->addAttribute("x", rect.x()); } if (rect.y() != 0) { this->addAttribute("y", rect.y()); } this->addAttribute("width", rect.width()); this->addAttribute("height", rect.height()); } void SkSVGDevice::AutoElement::addPathAttributes(const SkPath& path, SkParsePath::PathEncoding encoding) { SkString pathData; SkParsePath::ToSVGString(path, &pathData, encoding); this->addAttribute("d", pathData); } void SkSVGDevice::AutoElement::addTextAttributes(const SkFont& font) { this->addAttribute("font-size", font.getSize()); SkString familyName; SkTHashSet<SkString> familySet; sk_sp<SkTypeface> tface = font.refTypefaceOrDefault(); SkASSERT(tface); SkFontStyle style = tface->fontStyle(); if (style.slant() == SkFontStyle::kItalic_Slant) { this->addAttribute("font-style", "italic"); } else if (style.slant() == SkFontStyle::kOblique_Slant) { this->addAttribute("font-style", "oblique"); } int weightIndex = (SkTPin(style.weight(), 100, 900) - 50) / 100; if (weightIndex != 3) { static constexpr const char* weights[] = { "100", "200", "300", "normal", "400", "500", "600", "bold", "800", "900" }; this->addAttribute("font-weight", weights[weightIndex]); } int stretchIndex = style.width() - 1; if (stretchIndex != 4) { static constexpr const char* stretches[] = { "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", "normal", "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" }; this->addAttribute("font-stretch", stretches[stretchIndex]); } sk_sp<SkTypeface::LocalizedStrings> familyNameIter(tface->createFamilyNameIterator()); SkTypeface::LocalizedString familyString; if (familyNameIter) { while (familyNameIter->next(&familyString)) { if (familySet.contains(familyString.fString)) { continue; } familySet.add(familyString.fString); familyName.appendf((familyName.isEmpty() ? "%s" : ", %s"), familyString.fString.c_str()); } } if (!familyName.isEmpty()) { this->addAttribute("font-family", familyName); } } sk_sp<SkBaseDevice> SkSVGDevice::Make(const SkISize& size, std::unique_ptr<SkXMLWriter> writer, uint32_t flags) { return writer ? sk_sp<SkBaseDevice>(new SkSVGDevice(size, std::move(writer), flags)) : nullptr; } SkSVGDevice::SkSVGDevice(const SkISize& size, std::unique_ptr<SkXMLWriter> writer, uint32_t flags) : INHERITED(SkImageInfo::MakeUnknown(size.fWidth, size.fHeight), SkSurfaceProps(0, kUnknown_SkPixelGeometry)) , fWriter(std::move(writer)) , fResourceBucket(new ResourceBucket) , fFlags(flags) { SkASSERT(fWriter); fWriter->writeHeader(); // The root <svg> tag gets closed by the destructor. fRootElement = std::make_unique<AutoElement>("svg", fWriter); fRootElement->addAttribute("xmlns", "http://www.w3.org/2000/svg"); fRootElement->addAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink"); fRootElement->addAttribute("width", size.width()); fRootElement->addAttribute("height", size.height()); } SkSVGDevice::~SkSVGDevice() { // Pop order is important. while (!fClipStack.empty()) { fClipStack.pop_back(); } } SkParsePath::PathEncoding SkSVGDevice::pathEncoding() const { return (fFlags & SkSVGCanvas::kRelativePathEncoding_Flag) ? SkParsePath::PathEncoding::Relative : SkParsePath::PathEncoding::Absolute; } void SkSVGDevice::syncClipStack(const SkClipStack& cs) { SkClipStack::B2TIter iter(cs); const SkClipStack::Element* elem; size_t rec_idx = 0; // First, find/preserve the common bottom. while ((elem = iter.next()) && (rec_idx < fClipStack.size())) { if (fClipStack[SkToInt(rec_idx)].fGenID != elem->getGenID()) { break; } rec_idx++; } // Discard out-of-date stack top. while (fClipStack.size() > rec_idx) { fClipStack.pop_back(); } auto define_clip = [this](const SkClipStack::Element* e) { const auto cid = SkStringPrintf("cl_%x", e->getGenID()); AutoElement clip_path("clipPath", fWriter); clip_path.addAttribute("id", cid); // TODO: handle non-intersect clips. switch (e->getDeviceSpaceType()) { case SkClipStack::Element::DeviceSpaceType::kEmpty: { // TODO: can we skip this? AutoElement rect("rect", fWriter); } break; case SkClipStack::Element::DeviceSpaceType::kRect: { AutoElement rect("rect", fWriter); rect.addRectAttributes(e->getDeviceSpaceRect()); } break; case SkClipStack::Element::DeviceSpaceType::kRRect: { // TODO: complex rrect handling? const auto& rr = e->getDeviceSpaceRRect(); const auto radii = rr.getSimpleRadii(); AutoElement rrect("rect", fWriter); rrect.addRectAttributes(rr.rect()); rrect.addAttribute("rx", radii.x()); rrect.addAttribute("ry", radii.y()); } break; case SkClipStack::Element::DeviceSpaceType::kPath: { const auto& p = e->getDeviceSpacePath(); AutoElement path("path", fWriter); path.addPathAttributes(p, this->pathEncoding()); if (p.getFillType() == SkPathFillType::kEvenOdd) { path.addAttribute("clip-rule", "evenodd"); } } break; case SkClipStack::Element::DeviceSpaceType::kShader: // TODO: handle shader clipping, perhaps rasterize and apply as a mask image? break; } return cid; }; // Rebuild the top. while (elem) { const auto cid = define_clip(elem); auto clip_grp = std::make_unique<AutoElement>("g", fWriter); clip_grp->addAttribute("clip-path", SkStringPrintf("url(#%s)", cid.c_str())); fClipStack.push_back({ std::move(clip_grp), elem->getGenID() }); elem = iter.next(); } } void SkSVGDevice::drawPaint(const SkPaint& paint) { AutoElement rect("rect", this, fResourceBucket.get(), MxCp(this), paint); rect.addRectAttributes(SkRect::MakeWH(SkIntToScalar(this->width()), SkIntToScalar(this->height()))); } void SkSVGDevice::drawAnnotation(const SkRect& rect, const char key[], SkData* value) { if (!value) { return; } if (!strcmp(SkAnnotationKeys::URL_Key(), key) || !strcmp(SkAnnotationKeys::Link_Named_Dest_Key(), key)) { this->cs().save(); this->cs().clipRect(rect, this->localToDevice(), SkClipOp::kIntersect, true); SkRect transformedRect = this->cs().bounds(this->getGlobalBounds()); this->cs().restore(); if (transformedRect.isEmpty()) { return; } SkString url(static_cast<const char*>(value->data()), value->size() - 1); AutoElement a("a", fWriter); a.addAttribute("xlink:href", url.c_str()); { AutoElement r("rect", fWriter); r.addAttribute("fill-opacity", "0.0"); r.addRectAttributes(transformedRect); } } } void SkSVGDevice::drawPoints(SkCanvas::PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) { SkPathBuilder path; switch (mode) { // todo case SkCanvas::kPoints_PointMode: // TODO? break; case SkCanvas::kLines_PointMode: count -= 1; for (size_t i = 0; i < count; i += 2) { path.moveTo(pts[i]); path.lineTo(pts[i+1]); } break; case SkCanvas::kPolygon_PointMode: if (count > 1) { path.addPolygon(pts, SkToInt(count), false); } break; } this->drawPath(path.detach(), paint, true); } void SkSVGDevice::drawRect(const SkRect& r, const SkPaint& paint) { std::unique_ptr<AutoElement> svg; if (RequiresViewportReset(paint)) { svg = std::make_unique<AutoElement>("svg", this, fResourceBucket.get(), MxCp(this), paint); svg->addRectAttributes(r); } AutoElement rect("rect", this, fResourceBucket.get(), MxCp(this), paint); if (svg) { rect.addAttribute("x", 0); rect.addAttribute("y", 0); rect.addAttribute("width", "100%"); rect.addAttribute("height", "100%"); } else { rect.addRectAttributes(r); } } void SkSVGDevice::drawOval(const SkRect& oval, const SkPaint& paint) { AutoElement ellipse("ellipse", this, fResourceBucket.get(), MxCp(this), paint); ellipse.addAttribute("cx", oval.centerX()); ellipse.addAttribute("cy", oval.centerY()); ellipse.addAttribute("rx", oval.width() / 2); ellipse.addAttribute("ry", oval.height() / 2); } void SkSVGDevice::drawRRect(const SkRRect& rr, const SkPaint& paint) { AutoElement elem("path", this, fResourceBucket.get(), MxCp(this), paint); elem.addPathAttributes(SkPath::RRect(rr), this->pathEncoding()); } void SkSVGDevice::drawPath(const SkPath& path, const SkPaint& paint, bool pathIsMutable) { if (path.isInverseFillType()) { SkDebugf("Inverse path fill type not yet implemented."); return; } SkPath pathStorage; SkPath* pathPtr = const_cast<SkPath*>(&path); SkTCopyOnFirstWrite<SkPaint> path_paint(paint); // Apply path effect from paint to path. if (path_paint->getPathEffect()) { if (!pathIsMutable) { pathPtr = &pathStorage; } bool fill = path_paint->getFillPath(path, pathPtr); if (fill) { // Path should be filled. path_paint.writable()->setStyle(SkPaint::kFill_Style); } else { // Path should be drawn with a hairline (width == 0). path_paint.writable()->setStyle(SkPaint::kStroke_Style); path_paint.writable()->setStrokeWidth(0); } path_paint.writable()->setPathEffect(nullptr); // path effect processed } // Create path element. AutoElement elem("path", this, fResourceBucket.get(), MxCp(this), *path_paint); elem.addPathAttributes(*pathPtr, this->pathEncoding()); // TODO: inverse fill types? if (pathPtr->getFillType() == SkPathFillType::kEvenOdd) { elem.addAttribute("fill-rule", "evenodd"); } } static sk_sp<SkData> encode(const SkBitmap& src) { SkDynamicMemoryWStream buf; return SkEncodeImage(&buf, src, SkEncodedImageFormat::kPNG, 80) ? buf.detachAsData() : nullptr; } void SkSVGDevice::drawBitmapCommon(const MxCp& mc, const SkBitmap& bm, const SkPaint& paint) { sk_sp<SkData> pngData = encode(bm); if (!pngData) { return; } size_t b64Size = SkBase64::Encode(pngData->data(), pngData->size(), nullptr); SkAutoTMalloc<char> b64Data(b64Size); SkBase64::Encode(pngData->data(), pngData->size(), b64Data.get()); SkString svgImageData("data:image/png;base64,"); svgImageData.append(b64Data.get(), b64Size); SkString imageID = fResourceBucket->addImage(); { AutoElement defs("defs", fWriter); { AutoElement image("image", fWriter); image.addAttribute("id", imageID); image.addAttribute("width", bm.width()); image.addAttribute("height", bm.height()); image.addAttribute("xlink:href", svgImageData); } } { AutoElement imageUse("use", this, fResourceBucket.get(), mc, paint); imageUse.addAttribute("xlink:href", SkStringPrintf("#%s", imageID.c_str())); } } void SkSVGDevice::drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst, const SkSamplingOptions& sampling, const SkPaint& paint, SkCanvas::SrcRectConstraint constraint) { SkBitmap bm; // TODO: support gpu images if (!as_IB(image)->getROPixels(nullptr, &bm)) { return; } SkClipStack* cs = &this->cs(); SkClipStack::AutoRestore ar(cs, false); if (src && *src != SkRect::Make(bm.bounds())) { cs->save(); cs->clipRect(dst, this->localToDevice(), SkClipOp::kIntersect, paint.isAntiAlias()); } SkMatrix adjustedMatrix = this->localToDevice() * SkMatrix::RectToRect(src ? *src : SkRect::Make(bm.bounds()), dst); drawBitmapCommon(MxCp(&adjustedMatrix, cs), bm, paint); } class SVGTextBuilder : SkNoncopyable { public: SVGTextBuilder(SkPoint origin, const SkGlyphRun& glyphRun) : fOrigin(origin) { auto runSize = glyphRun.runSize(); SkAutoSTArray<64, SkUnichar> unichars(runSize); SkFontPriv::GlyphsToUnichars(glyphRun.font(), glyphRun.glyphsIDs().data(), runSize, unichars.get()); auto positions = glyphRun.positions(); for (size_t i = 0; i < runSize; ++i) { this->appendUnichar(unichars[i], positions[i]); } } const SkString& text() const { return fText; } const SkString& posX() const { return fPosXStr; } const SkString& posY() const { return fHasConstY ? fConstYStr : fPosYStr; } private: void appendUnichar(SkUnichar c, SkPoint position) { bool discardPos = false; bool isWhitespace = false; switch(c) { case ' ': case '\t': // consolidate whitespace to match SVG's xml:space=default munging // (http://www.w3.org/TR/SVG/text.html#WhiteSpace) if (fLastCharWasWhitespace) { discardPos = true; } else { fText.appendUnichar(c); } isWhitespace = true; break; case '\0': // SkPaint::glyphsToUnichars() returns \0 for inconvertible glyphs, but these // are not legal XML characters (http://www.w3.org/TR/REC-xml/#charsets) discardPos = true; isWhitespace = fLastCharWasWhitespace; // preserve whitespace consolidation break; case '&': fText.append("&amp;"); break; case '"': fText.append("&quot;"); break; case '\'': fText.append("&apos;"); break; case '<': fText.append("&lt;"); break; case '>': fText.append("&gt;"); break; default: fText.appendUnichar(c); break; } fLastCharWasWhitespace = isWhitespace; if (discardPos) { return; } position += fOrigin; fPosXStr.appendf("%.8g, ", position.fX); fPosYStr.appendf("%.8g, ", position.fY); if (fConstYStr.isEmpty()) { fConstYStr = fPosYStr; fConstY = position.fY; } else { fHasConstY &= SkScalarNearlyEqual(fConstY, position.fY); } } const SkPoint fOrigin; SkString fText, fPosXStr, fPosYStr, fConstYStr; SkScalar fConstY; bool fLastCharWasWhitespace = true, // start off in whitespace mode to strip leading space fHasConstY = true; }; void SkSVGDevice::onDrawGlyphRunList(SkCanvas* canvas, const SkGlyphRunList& glyphRunList, const SkPaint& paint) { SkASSERT(!glyphRunList.hasRSXForm()); const auto draw_as_path = (fFlags & SkSVGCanvas::kConvertTextToPaths_Flag) || paint.getPathEffect(); if (draw_as_path) { // Emit a single <path> element. SkPath path; for (auto& glyphRun : glyphRunList) { AddPath(glyphRun, glyphRunList.origin(), &path); } this->drawPath(path, paint); return; } // Emit one <text> element for each run. for (auto& glyphRun : glyphRunList) { AutoElement elem("text", this, fResourceBucket.get(), MxCp(this), paint); elem.addTextAttributes(glyphRun.font()); SVGTextBuilder builder(glyphRunList.origin(), glyphRun); elem.addAttribute("x", builder.posX()); elem.addAttribute("y", builder.posY()); elem.addText(builder.text()); } } void SkSVGDevice::drawVertices(const SkVertices*, sk_sp<SkBlender>, const SkPaint&) { // todo } void SkSVGDevice::drawCustomMesh(SkCustomMesh, sk_sp<SkBlender>, const SkPaint&) { // todo }
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef THORCOMMON_HPP #define THORCOMMON_HPP #include "jiface.hpp" #include "jcrc.hpp" #include "jsort.hpp" #include "jdebug.hpp" #include "jfile.hpp" #include "eclhelper.hpp" #include "thorhelper.hpp" #include "thorxmlwrite.hpp" static unsigned const defaultDaliResultOutputMax = 2000; // MB static unsigned const defaultDaliResultLimit = 10; // MB static unsigned const defaultMaxCsvRowSize = 10; // MB #define OPT_OUTPUTLIMIT_LEGACY "outputLimit" // OUTPUT Mb limit (legacy property name, renamed to outputLimitMb in 5.2) #define OPT_OUTPUTLIMIT "outputLimitMb" // OUTPUT Mb limit (default = 10 [MB]) #define OPT_MAXCSVROWSIZE "maxCsvRowSizeMb" // Upper limit on csv read line size (default = 10 [MB]) class THORHELPER_API CSizingSerializer : implements IRowSerializerTarget { size32_t totalsize; public: inline CSizingSerializer() { reset(); } inline void reset() { totalsize = 0; } inline size32_t size() { return totalsize; } virtual void put(size32_t len, const void * ptr); virtual size32_t beginNested(size32_t count); virtual void endNested(size32_t position); }; class THORHELPER_API CMemoryRowSerializer: implements IRowSerializerTarget { MemoryBuffer & buffer; unsigned nesting; public: inline CMemoryRowSerializer(MemoryBuffer & _buffer) : buffer(_buffer) { nesting = 0; } virtual void put(size32_t len, const void * ptr); virtual size32_t beginNested(size32_t count); virtual void endNested(size32_t sizePos); }; // useful package interface IRowInterfaces: extends IInterface { virtual IEngineRowAllocator * queryRowAllocator()=0; virtual IOutputRowSerializer * queryRowSerializer()=0; virtual IOutputRowDeserializer * queryRowDeserializer()=0; virtual IOutputMetaData *queryRowMetaData()=0; virtual unsigned queryActivityId() const=0; virtual ICodeContext *queryCodeContext()=0; }; extern THORHELPER_API void useMemoryMappedRead(bool on); extern THORHELPER_API IRowInterfaces *createRowInterfaces(IOutputMetaData *meta, unsigned actid, ICodeContext *context); enum RowReaderWriterFlags { rw_grouped = 0x1, rw_crc = 0x2, rw_extend = 0x4, rw_compress = 0x8, rw_compressblkcrc = 0x10, // block compression, this sets/checks crc's at block level rw_fastlz = 0x20, // if rw_compress rw_autoflush = 0x40, rw_buffered = 0x80 }; #define DEFAULT_RWFLAGS (rw_buffered|rw_autoflush|rw_compressblkcrc) inline bool TestRwFlag(unsigned flags, RowReaderWriterFlags flag) { return 0 != (flags & flag); } interface IExtRowStream: extends IRowStream { virtual offset_t getOffset() = 0; virtual void stop(CRC32 *crcout=NULL) = 0; virtual const void *prefetchRow(size32_t *sz=NULL) = 0; virtual void prefetchDone() = 0; virtual void reinit(offset_t offset,offset_t len,unsigned __int64 maxrows) = 0; virtual unsigned __int64 getStatistic(StatisticKind kind) = 0; }; interface IExtRowWriter: extends IRowWriter { virtual offset_t getPosition() = 0; virtual void flush(CRC32 *crcout=NULL) = 0; }; interface IExpander; extern THORHELPER_API IExtRowStream *createRowStream(IFile *file, IRowInterfaces *rowif, unsigned flags=DEFAULT_RWFLAGS, IExpander *eexp=NULL); extern THORHELPER_API IExtRowStream *createRowStreamEx(IFile *file, IRowInterfaces *rowif, offset_t offset=0, offset_t len=(offset_t)-1, unsigned __int64 maxrows=(unsigned __int64)-1, unsigned flags=DEFAULT_RWFLAGS, IExpander *eexp=NULL); interface ICompressor; extern THORHELPER_API IExtRowWriter *createRowWriter(IFile *file, IRowInterfaces *rowIf, unsigned flags=DEFAULT_RWFLAGS, ICompressor *compressor=NULL); extern THORHELPER_API IExtRowWriter *createRowWriter(IFileIO *fileIO, IRowInterfaces *rowIf, unsigned flags=DEFAULT_RWFLAGS); extern THORHELPER_API IExtRowWriter *createRowWriter(IFileIOStream *strm, IRowInterfaces *rowIf, unsigned flags=DEFAULT_RWFLAGS); // strm should be unbuffered interface THORHELPER_API IDiskMerger : extends IInterface { virtual void put(const void **rows, unsigned numrows) = 0; virtual void putIndirect(const void ***rowptrs, unsigned numrows) = 0; // like put only with an additional dereference, i.e. row i is *(rowptrs[i]) virtual void put(ISortedRowProvider * rows) = 0; virtual IRowStream *merge(ICompare *icompare,bool partdedup=false) = 0; virtual count_t mergeTo(IRowWriter *dest,ICompare *icompare,bool partdedup=false) = 0; // alternative to merge virtual IRowWriter *createWriteBlock() = 0; }; extern THORHELPER_API IDiskMerger *createDiskMerger(IRowInterfaces *rowInterfaces, IRowLinkCounter *linker, const char *tempnamebase); extern THORHELPER_API void testDiskSort(); #define TIME_ACTIVITIES class ActivityTimeAccumulator { friend class ActivityTimer; public: ActivityTimeAccumulator() { startCycles = 0; totalCycles = 0; endCycles = 0; firstRow = 0; firstExitCycles = 0; } public: cycle_t startCycles; // Wall clock time of first entry to this activity cycle_t totalCycles; // Time spent in this activity cycle_t endCycles; // Wall clock time of last entry to this activity unsigned __int64 firstRow; // Timestamp of first row (nanoseconds since epoch) cycle_t firstExitCycles; // Wall clock time of first exit from this activity // Return the total amount of time (in nanoseconds) spent in this activity (first entry to last exit) inline unsigned __int64 elapsed() const { return cycle_to_nanosec(endCycles-startCycles); } // Return the total amount of time (in nanoseconds) spent in the first call of this activity (first entry to first exit) inline unsigned __int64 latency() const { return cycle_to_nanosec(firstExitCycles-startCycles); } void addStatistics(IStatisticGatherer & builder) const { if (totalCycles) { builder.addStatistic(StWhenFirstRow, firstRow); builder.addStatistic(StTimeElapsed, elapsed()); builder.addStatistic(StTimeTotalExecute, cycle_to_nanosec(totalCycles)); builder.addStatistic(StTimeFirstExecute, latency()); } } }; #ifdef TIME_ACTIVITIES #include "jdebug.hpp" class ActivityTimer { unsigned __int64 startCycles; ActivityTimeAccumulator &accumulator; protected: const bool enabled; bool isFirstRow; public: ActivityTimer(ActivityTimeAccumulator &_accumulator, const bool _enabled) : accumulator(_accumulator), enabled(_enabled), isFirstRow(false) { if (enabled) { startCycles = get_cycles_now(); if (!accumulator.firstRow) { isFirstRow = true; accumulator.startCycles = startCycles; accumulator.firstRow = getTimeStampNowValue(); } } else startCycles = 0; } ~ActivityTimer() { if (enabled) { cycle_t nowCycles = get_cycles_now(); accumulator.endCycles = nowCycles; cycle_t elapsedCycles = nowCycles - startCycles; accumulator.totalCycles += elapsedCycles; if (isFirstRow) accumulator.firstExitCycles = nowCycles; } } }; class SimpleActivityTimer { cycle_t startCycles; cycle_t &accumulator; protected: const bool enabled; public: inline SimpleActivityTimer(cycle_t &_accumulator, const bool _enabled) : accumulator(_accumulator), enabled(_enabled) { if (enabled) startCycles = get_cycles_now(); else startCycles = 0; } inline ~SimpleActivityTimer() { if (enabled) { cycle_t nowCycles = get_cycles_now(); cycle_t elapsedCycles = nowCycles - startCycles; accumulator += elapsedCycles; } } }; #else struct ActivityTimer { inline ActivityTimer(ActivityTimeAccumulator &_accumulator, const bool _enabled) { } }; struct SimpleActivityTimer { inline SimpleActivityTimer(unsigned __int64 &_accumulator, const bool _enabled) { } }; #endif class THORHELPER_API IndirectCodeContext : implements ICodeContext { public: IndirectCodeContext(ICodeContext * _ctx = NULL) : ctx(_ctx) {} void set(ICodeContext * _ctx) { ctx = _ctx; } virtual const char *loadResource(unsigned id) { return ctx->loadResource(id); } virtual void setResultBool(const char *name, unsigned sequence, bool value) { ctx->setResultBool(name, sequence, value); } virtual void setResultData(const char *name, unsigned sequence, int len, const void * data) { ctx->setResultData(name, sequence, len, data); } virtual void setResultDecimal(const char * stepname, unsigned sequence, int len, int precision, bool isSigned, const void *val) { ctx->setResultDecimal(stepname, sequence, len, precision, isSigned, val); } virtual void setResultInt(const char *name, unsigned sequence, __int64 value, unsigned size) { ctx->setResultInt(name, sequence, value, size); } virtual void setResultRaw(const char *name, unsigned sequence, int len, const void * data) { ctx->setResultRaw(name, sequence, len, data); } virtual void setResultReal(const char * stepname, unsigned sequence, double value) { ctx->setResultReal(stepname, sequence, value); } virtual void setResultSet(const char *name, unsigned sequence, bool isAll, size32_t len, const void * data, ISetToXmlTransformer * transformer) { ctx->setResultSet(name, sequence, isAll, len, data, transformer); } virtual void setResultString(const char *name, unsigned sequence, int len, const char * str) { ctx->setResultString(name, sequence, len, str); } virtual void setResultUInt(const char *name, unsigned sequence, unsigned __int64 value, unsigned size) { ctx->setResultUInt(name, sequence, value, size); } virtual void setResultUnicode(const char *name, unsigned sequence, int len, UChar const * str) { ctx->setResultUnicode(name, sequence, len, str); } virtual void setResultVarString(const char * name, unsigned sequence, const char * value) { ctx->setResultVarString(name, sequence, value); } virtual void setResultVarUnicode(const char * name, unsigned sequence, UChar const * value) { ctx->setResultVarUnicode(name, sequence, value); } virtual bool getResultBool(const char * name, unsigned sequence) { return ctx->getResultBool(name, sequence); } virtual void getResultData(unsigned & tlen, void * & tgt, const char * name, unsigned sequence) { ctx->getResultData(tlen, tgt, name, sequence); } virtual void getResultDecimal(unsigned tlen, int precision, bool isSigned, void * tgt, const char * stepname, unsigned sequence) { ctx->getResultDecimal(tlen, precision, isSigned, tgt, stepname, sequence); } virtual void getResultRaw(unsigned & tlen, void * & tgt, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { ctx->getResultRaw(tlen, tgt, name, sequence, xmlTransformer, csvTransformer); } virtual void getResultSet(bool & isAll, size32_t & tlen, void * & tgt, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { ctx->getResultSet(isAll, tlen, tgt, name, sequence, xmlTransformer, csvTransformer); } virtual __int64 getResultInt(const char * name, unsigned sequence) { return ctx->getResultInt(name, sequence); } virtual double getResultReal(const char * name, unsigned sequence) { return ctx->getResultReal(name, sequence); } virtual void getResultString(unsigned & tlen, char * & tgt, const char * name, unsigned sequence) { ctx->getResultString(tlen, tgt, name, sequence); } virtual void getResultStringF(unsigned tlen, char * tgt, const char * name, unsigned sequence) { ctx->getResultStringF(tlen, tgt, name, sequence); } virtual void getResultUnicode(unsigned & tlen, UChar * & tgt, const char * name, unsigned sequence) { ctx->getResultUnicode(tlen, tgt, name, sequence); } virtual char *getResultVarString(const char * name, unsigned sequence) { return ctx->getResultVarString(name, sequence); } virtual UChar *getResultVarUnicode(const char * name, unsigned sequence) { return ctx->getResultVarUnicode(name, sequence); } virtual unsigned getResultHash(const char * name, unsigned sequence) { return ctx->getResultHash(name, sequence); } virtual unsigned getExternalResultHash(const char * wuid, const char * name, unsigned sequence) { return ctx->getExternalResultHash(wuid, name, sequence); } virtual char *getWuid() { return ctx->getWuid(); } virtual void getExternalResultRaw(unsigned & tlen, void * & tgt, const char * wuid, const char * stepname, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { ctx->getExternalResultRaw(tlen, tgt, wuid, stepname, sequence, xmlTransformer, csvTransformer); } virtual void executeGraph(const char * graphName, bool realThor, size32_t parentExtractSize, const void * parentExtract) { ctx->executeGraph(graphName, realThor, parentExtractSize, parentExtract); } virtual char * getExpandLogicalName(const char * logicalName) { return ctx->getExpandLogicalName(logicalName); } virtual void addWuException(const char * text, unsigned code, unsigned severity, const char *source) { ctx->addWuException(text, code, severity, source); } virtual void addWuAssertFailure(unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, bool isAbort) { ctx->addWuAssertFailure(code, text, filename, lineno, column, isAbort); } virtual IUserDescriptor *queryUserDescriptor() { return ctx->queryUserDescriptor(); } virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal) { return ctx->resolveChildQuery(activityId, colocal); } virtual unsigned __int64 getDatasetHash(const char * name, unsigned __int64 hash) { return ctx->getDatasetHash(name, hash); } virtual unsigned getNodes() { return ctx->getNodes(); } virtual unsigned getNodeNum() { return ctx->getNodeNum(); } virtual char *getFilePart(const char *logicalPart, bool create) { return ctx->getFilePart(logicalPart, create); } virtual unsigned __int64 getFileOffset(const char *logicalPart) { return ctx->getFileOffset(logicalPart); } virtual IDistributedFileTransaction *querySuperFileTransaction() { return ctx->querySuperFileTransaction(); } virtual char *getEnv(const char *name, const char *defaultValue) const { return ctx->getEnv(name, defaultValue); } virtual char *getJobName() { return ctx->getJobName(); } virtual char *getJobOwner() { return ctx->getJobOwner(); } virtual char *getClusterName() { return ctx->getClusterName(); } virtual char *getGroupName() { return ctx->getGroupName(); } virtual char * queryIndexMetaData(char const * lfn, char const * xpath) { return ctx->queryIndexMetaData(lfn, xpath); } virtual unsigned getPriority() const { return ctx->getPriority(); } virtual char *getPlatform() { return ctx->getPlatform(); } virtual char *getOS() { return ctx->getOS(); } virtual IEclGraphResults * resolveLocalQuery(__int64 activityId) { return ctx->resolveLocalQuery(activityId); } virtual char *getEnv(const char *name, const char *defaultValue) { return ctx->getEnv(name, defaultValue); } virtual unsigned logString(const char *text) const { return ctx->logString(text); } virtual const IContextLogger &queryContextLogger() const { return ctx->queryContextLogger(); } virtual IDebuggableContext *queryDebugContext() const { return ctx->queryDebugContext(); } virtual IEngineRowAllocator * getRowAllocator(IOutputMetaData * meta, unsigned activityId) const { return ctx->getRowAllocator(meta, activityId); } virtual const char *cloneVString(const char *str) const { return ctx->cloneVString(str); } virtual const char *cloneVString(size32_t len, const char *str) const { return ctx->cloneVString(len, str); } virtual void getResultRowset(size32_t & tcount, byte * * & tgt, const char * name, unsigned sequence, IEngineRowAllocator * _rowAllocator, bool isGrouped, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer) { ctx->getResultRowset(tcount, tgt, name, sequence, _rowAllocator, isGrouped, xmlTransformer, csvTransformer); } virtual void getResultDictionary(size32_t & tcount, byte * * & tgt, IEngineRowAllocator * _rowAllocator, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, ICsvToRowTransformer * csvTransformer, IHThorHashLookupInfo * hasher) { ctx->getResultDictionary(tcount, tgt, _rowAllocator, name, sequence, xmlTransformer, csvTransformer, hasher); } virtual void getRowXML(size32_t & lenResult, char * & result, IOutputMetaData & info, const void * row, unsigned flags) { convertRowToXML(lenResult, result, info, row, flags); } virtual void getRowJSON(size32_t & lenResult, char * & result, IOutputMetaData & info, const void * row, unsigned flags) { convertRowToJSON(lenResult, result, info, row, flags); } virtual const void * fromXml(IEngineRowAllocator * _rowAllocator, size32_t len, const char * utf8, IXmlToRowTransformer * xmlTransformer, bool stripWhitespace) { return ctx->fromXml(_rowAllocator, len, utf8, xmlTransformer, stripWhitespace); } virtual const void * fromJson(IEngineRowAllocator * _rowAllocator, size32_t len, const char * utf8, IXmlToRowTransformer * xmlTransformer, bool stripWhitespace) { return ctx->fromJson(_rowAllocator, len, utf8, xmlTransformer, stripWhitespace); } virtual IEngineContext *queryEngineContext() { return ctx->queryEngineContext(); } virtual char *getDaliServers() { return ctx->getDaliServers(); } virtual IWorkUnit *updateWorkUnit() const { return ctx->updateWorkUnit(); } protected: ICodeContext * ctx; }; extern THORHELPER_API bool isActivitySink(ThorActivityKind kind); extern THORHELPER_API bool isActivitySource(ThorActivityKind kind); extern THORHELPER_API const char * getActivityText(ThorActivityKind kind); #endif // THORHELPER_HPP
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include <stdarg.h> #include "dt_send.h" #include "dt.h" #include "dt_recv.h" #include "dt_encode.h" #include "convar.h" #include "commonmacros.h" #include "tier1/strtools.h" #include "tier0/dbg.h" #include "dt_stack.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define PROPINDEX_NUMBITS 12 #define MAX_TOTAL_SENDTABLE_PROPS (1 << PROPINDEX_NUMBITS) ConVar g_CV_DTWatchEnt("dtwatchent", "-1", 0, "Watch this entities data table encoding."); ConVar g_CV_DTWatchVar("dtwatchvar", "", 0, "Watch the named variable."); ConVar g_CV_DTWarning("dtwarning", "0", 0, "Print data table warnings?"); ConVar g_CV_DTWatchClass("dtwatchclass", "", 0, "Watch all fields encoded with this table."); // ----------------------------------------------------------------------------- // // // CBuildHierarchyStruct // // Used while building a CSendNode hierarchy. // // ----------------------------------------------------------------------------- // class CBuildHierarchyStruct { public: const ExcludeProp *m_pExcludeProps; int m_nExcludeProps; const SendProp *m_pDatatableProps[MAX_TOTAL_SENDTABLE_PROPS]; int m_nDatatableProps; const SendProp *m_pProps[MAX_TOTAL_SENDTABLE_PROPS]; unsigned char m_PropProxyIndices[MAX_TOTAL_SENDTABLE_PROPS]; int m_nProps; unsigned char m_nPropProxies; }; // ----------------------------------------------------------------------------- // // CSendNode. // ----------------------------------------------------------------------------- // CSendNode::CSendNode() { m_iDatatableProp = -1; m_pTable = NULL; m_iFirstRecursiveProp = m_nRecursiveProps = 0; m_DataTableProxyIndex = DATATABLE_PROXY_INDEX_INVALID; // set it to a questionable value. } CSendNode::~CSendNode() { int c = GetNumChildren(); for (int i = c - 1; i >= 0; i--) { delete GetChild(i); } m_Children.Purge(); } // ----------------------------------------------------------------------------- // // CSendTablePrecalc // ----------------------------------------------------------------------------- // bool PropOffsetLT(const unsigned short &a, const unsigned short &b) { return a < b; } CSendTablePrecalc::CSendTablePrecalc() : m_PropOffsetToIndexMap(0, 0, PropOffsetLT) { m_pDTITable = NULL; m_pSendTable = 0; m_nDataTableProxies = 0; } CSendTablePrecalc::~CSendTablePrecalc() { if (m_pSendTable) m_pSendTable->m_pPrecalc = 0; } const ExcludeProp *FindExcludeProp( char const *pTableName, char const *pPropName, const ExcludeProp *pExcludeProps, int nExcludeProps) { for (int i = 0; i < nExcludeProps; i++) { if (stricmp(pExcludeProps[i].m_pTableName, pTableName) == 0 && stricmp(pExcludeProps[i].m_pPropName, pPropName) == 0) return &pExcludeProps[i]; } return NULL; } // Fill in a list of all the excluded props. static bool SendTable_GetPropsExcluded(const SendTable *pTable, ExcludeProp *pExcludeProps, int &nExcludeProps, int nMaxExcludeProps) { for (int i = 0; i < pTable->m_nProps; i++) { SendProp *pProp = &pTable->m_pProps[i]; if (pProp->IsExcludeProp()) { char const *pName = pProp->GetExcludeDTName(); ErrorIfNot(pName, ("Found an exclude prop missing a name.") ); ErrorIfNot(nExcludeProps < nMaxExcludeProps, ("SendTable_GetPropsExcluded: Overflowed max exclude props with %s.", pName) ); pExcludeProps[nExcludeProps].m_pTableName = pName; pExcludeProps[nExcludeProps].m_pPropName = pProp->GetName(); nExcludeProps++; } else if (pProp->GetDataTable()) { if (!SendTable_GetPropsExcluded(pProp->GetDataTable(), pExcludeProps, nExcludeProps, nMaxExcludeProps)) return false; } } return true; } // Set the datatable proxy indices in all datatable SendProps. static void SetDataTableProxyIndices_R( CSendTablePrecalc *pMainTable, CSendNode *pCurTable, CBuildHierarchyStruct *bhs) { for (int i = 0; i < pCurTable->GetNumChildren(); i++) { CSendNode *pNode = pCurTable->GetChild(i); const SendProp *pProp = bhs->m_pDatatableProps[pNode->m_iDatatableProp]; if (pProp->GetFlags() & SPROP_PROXY_ALWAYS_YES) { pNode->SetDataTableProxyIndex(DATATABLE_PROXY_INDEX_NOPROXY); } else { pNode->SetDataTableProxyIndex(pMainTable->GetNumDataTableProxies()); pMainTable->SetNumDataTableProxies(pMainTable->GetNumDataTableProxies() + 1); } SetDataTableProxyIndices_R(pMainTable, pNode, bhs); } } // Set the datatable proxy indices in all datatable SendProps. static void SetRecursiveProxyIndices_R( SendTable *pBaseTable, CSendNode *pCurTable, int &iCurProxyIndex) { if (iCurProxyIndex >= CDatatableStack::MAX_PROXY_RESULTS) Error("Too many proxies for datatable %s.", pBaseTable->GetName()); pCurTable->SetRecursiveProxyIndex(iCurProxyIndex); iCurProxyIndex++; for (int i = 0; i < pCurTable->GetNumChildren(); i++) { CSendNode *pNode = pCurTable->GetChild(i); SetRecursiveProxyIndices_R(pBaseTable, pNode, iCurProxyIndex); } } void SendTable_BuildHierarchy( CSendNode *pNode, const SendTable *pTable, CBuildHierarchyStruct *bhs ); void SendTable_BuildHierarchy_IterateProps( CSendNode *pNode, const SendTable *pTable, CBuildHierarchyStruct *bhs, const SendProp *pNonDatatableProps[MAX_TOTAL_SENDTABLE_PROPS], int &nNonDatatableProps) { int i; for (i = 0; i < pTable->m_nProps; i++) { const SendProp *pProp = &pTable->m_pProps[i]; if (pProp->IsExcludeProp() || pProp->IsInsideArray() || FindExcludeProp(pTable->GetName(), pProp->GetName(), bhs->m_pExcludeProps, bhs->m_nExcludeProps)) { continue; } if (pProp->GetType() == DPT_DataTable) { if (pProp->GetFlags() & SPROP_COLLAPSIBLE) { // This is a base class.. no need to make a new CSendNode (and trigger a bunch of // unnecessary send proxy calls in the datatable stacks). SendTable_BuildHierarchy_IterateProps( pNode, pProp->GetDataTable(), bhs, pNonDatatableProps, nNonDatatableProps); } else { // Setup a child datatable reference. CSendNode *pChild = new CSendNode; // Setup a datatable prop for this node to reference (so the recursion // routines can get at the proxy). if (bhs->m_nDatatableProps >= ARRAYSIZE(bhs->m_pDatatableProps)) Error("Overflowed datatable prop list in SendTable '%s'.", pTable->GetName()); bhs->m_pDatatableProps[bhs->m_nDatatableProps] = pProp; pChild->m_iDatatableProp = bhs->m_nDatatableProps; ++bhs->m_nDatatableProps; pNode->m_Children.AddToTail(pChild); // Recurse into the new child datatable. SendTable_BuildHierarchy(pChild, pProp->GetDataTable(), bhs); } } else { if (nNonDatatableProps >= MAX_TOTAL_SENDTABLE_PROPS) Error("SendTable_BuildHierarchy: overflowed non-datatable props with '%s'.", pProp->GetName()); pNonDatatableProps[nNonDatatableProps] = pProp; ++nNonDatatableProps; } } } void SendTable_BuildHierarchy( CSendNode *pNode, const SendTable *pTable, CBuildHierarchyStruct *bhs ) { pNode->m_pTable = pTable; pNode->m_iFirstRecursiveProp = bhs->m_nProps; Assert(bhs->m_nPropProxies < 255); unsigned char curPropProxy = bhs->m_nPropProxies; ++bhs->m_nPropProxies; const SendProp *pNonDatatableProps[MAX_TOTAL_SENDTABLE_PROPS]; int nNonDatatableProps = 0; // First add all the child datatables. SendTable_BuildHierarchy_IterateProps( pNode, pTable, bhs, pNonDatatableProps, nNonDatatableProps); // Now add the properties. // Make sure there's room, then just copy the pointers from the loop above. ErrorIfNot(bhs->m_nProps + nNonDatatableProps < ARRAYSIZE(bhs->m_pProps), ("SendTable_BuildHierarchy: overflowed prop buffer.") ); for (int i = 0; i < nNonDatatableProps; i++) { bhs->m_pProps[bhs->m_nProps] = pNonDatatableProps[i]; bhs->m_PropProxyIndices[bhs->m_nProps] = curPropProxy; ++bhs->m_nProps; } pNode->m_nRecursiveProps = bhs->m_nProps - pNode->m_iFirstRecursiveProp; } void SendTable_SortByPriority(CBuildHierarchyStruct *bhs) { int i, start = 0; while (true) { for (i = start; i < bhs->m_nProps; i++) { const SendProp *p = bhs->m_pProps[i]; unsigned char c = bhs->m_PropProxyIndices[i]; if (p->GetFlags() & SPROP_CHANGES_OFTEN) { bhs->m_pProps[i] = bhs->m_pProps[start]; bhs->m_PropProxyIndices[i] = bhs->m_PropProxyIndices[start]; bhs->m_pProps[start] = p; bhs->m_PropProxyIndices[start] = c; start++; break; } } if (i == bhs->m_nProps) return; } } void CalcPathLengths_R(CSendNode *pNode, CUtlVector<int> &pathLengths, int curPathLength, int &totalPathLengths) { pathLengths[pNode->GetRecursiveProxyIndex()] = curPathLength; totalPathLengths += curPathLength; for (int i = 0; i < pNode->GetNumChildren(); i++) { CalcPathLengths_R(pNode->GetChild(i), pathLengths, curPathLength + 1, totalPathLengths); } } void FillPathEntries_R(CSendTablePrecalc *pPrecalc, CSendNode *pNode, CSendNode *pParent, int &iCurEntry) { // Fill in this node's path. CSendTablePrecalc::CProxyPath &outProxyPath = pPrecalc->m_ProxyPaths[pNode->GetRecursiveProxyIndex()]; outProxyPath.m_iFirstEntry = (unsigned short) iCurEntry; // Copy all the proxies leading to the parent. if (pParent) { CSendTablePrecalc::CProxyPath &parentProxyPath = pPrecalc->m_ProxyPaths[pParent->GetRecursiveProxyIndex()]; outProxyPath.m_nEntries = parentProxyPath.m_nEntries + 1; for (int i = 0; i < parentProxyPath.m_nEntries; i++) pPrecalc->m_ProxyPathEntries[iCurEntry++] = pPrecalc->m_ProxyPathEntries[parentProxyPath.m_iFirstEntry + i]; // Now add this node's own proxy. pPrecalc->m_ProxyPathEntries[iCurEntry].m_iProxy = pNode->GetRecursiveProxyIndex(); pPrecalc->m_ProxyPathEntries[iCurEntry].m_iDatatableProp = pNode->m_iDatatableProp; ++iCurEntry; } else { outProxyPath.m_nEntries = 0; } for (int i = 0; i < pNode->GetNumChildren(); i++) { FillPathEntries_R(pPrecalc, pNode->GetChild(i), pNode, iCurEntry); } } void SendTable_GenerateProxyPaths(CSendTablePrecalc *pPrecalc, int nProxyIndices) { // Initialize the array. pPrecalc->m_ProxyPaths.SetSize(nProxyIndices); for (int i = 0; i < nProxyIndices; i++) pPrecalc->m_ProxyPaths[i].m_iFirstEntry = pPrecalc->m_ProxyPaths[i].m_nEntries = 0xFFFF; // Figure out how long the path down the tree is to each node. int totalPathLengths = 0; CUtlVector<int> pathLengths; pathLengths.SetSize(nProxyIndices); memset(pathLengths.Base(), 0, sizeof(pathLengths[0]) * nProxyIndices); CalcPathLengths_R(pPrecalc->GetRootNode(), pathLengths, 0, totalPathLengths); // int iCurEntry = 0; pPrecalc->m_ProxyPathEntries.SetSize(totalPathLengths); FillPathEntries_R(pPrecalc, pPrecalc->GetRootNode(), NULL, iCurEntry); } bool CSendTablePrecalc::SetupFlatPropertyArray() { SendTable *pTable = GetSendTable(); // First go through and set SPROP_INSIDEARRAY when appropriate, and set array prop pointers. SetupArrayProps_R<SendTable, SendTable::PropType>(pTable); // Make a list of which properties are excluded. ExcludeProp excludeProps[MAX_EXCLUDE_PROPS]; int nExcludeProps = 0; if (!SendTable_GetPropsExcluded(pTable, excludeProps, nExcludeProps, MAX_EXCLUDE_PROPS)) return false; // Now build the hierarchy. CBuildHierarchyStruct bhs; bhs.m_pExcludeProps = excludeProps; bhs.m_nExcludeProps = nExcludeProps; bhs.m_nProps = bhs.m_nDatatableProps = 0; bhs.m_nPropProxies = 0; SendTable_BuildHierarchy(GetRootNode(), pTable, &bhs); SendTable_SortByPriority(&bhs); // Copy the SendProp pointers into the precalc. MEM_ALLOC_CREDIT(); m_Props.CopyArray(bhs.m_pProps, bhs.m_nProps); m_DatatableProps.CopyArray(bhs.m_pDatatableProps, bhs.m_nDatatableProps); m_PropProxyIndices.CopyArray(bhs.m_PropProxyIndices, bhs.m_nProps); // Assign the datatable proxy indices. SetNumDataTableProxies(0); SetDataTableProxyIndices_R(this, GetRootNode(), &bhs); int nProxyIndices = 0; SetRecursiveProxyIndices_R(pTable, GetRootNode(), nProxyIndices); SendTable_GenerateProxyPaths(this, nProxyIndices); return true; } // ---------------------------------------------------------------------------------------- // // Helpers. // ---------------------------------------------------------------------------------------- // // Compares two arrays of bits. // Returns true if they are equal. bool AreBitArraysEqual( void const *pvBits1, void const *pvBits2, int nBits) { unsigned int const *pBits1 = (unsigned int const *) pvBits1; unsigned int const *pBits2 = (unsigned int const *) pvBits2; // Compare words. int nWords = nBits >> 5; for (int i = 0; i < nWords; ++i) { if (pBits1[i] != pBits2[i]) return false; } if (nBits & 31) { // Compare remaining bits. unsigned int mask = (1 << (nBits & 31)) - 1; return ((pBits1[nWords] ^ pBits2[nWords]) & mask) == 0; } return true; } // Does a fast memcmp-based test to determine if the two bit arrays are different. // Returns true if they are equal. bool CompareBitArrays( void const *pPacked1, void const *pPacked2, int nBits1, int nBits2 ) { if (nBits1 >= 0 && nBits1 == nBits2) { if (pPacked1 == pPacked2) { return true; } else { return AreBitArraysEqual(pPacked1, pPacked2, nBits1); } } else return false; } // Looks at the DTWatchEnt and DTWatchProp console variables and returns true // if the user wants to watch this property. bool ShouldWatchThisProp(const SendTable *pTable, int objectID, const char *pPropName) { if (g_CV_DTWatchEnt.GetInt() != -1 && g_CV_DTWatchEnt.GetInt() == objectID) { const char *pStr = g_CV_DTWatchVar.GetString(); if (pStr && pStr[0] != 0) { return stricmp(pStr, pPropName) == 0; } else { return true; } } if (g_CV_DTWatchClass.GetString()[0] && Q_stristr(pTable->GetName(), g_CV_DTWatchClass.GetString())) return true; return false; } bool Sendprop_UsingDebugWatch() { if (g_CV_DTWatchEnt.GetInt() != -1) return true; if (g_CV_DTWatchClass.GetString()[0]) return true; return false; } // Prints a datatable warning into the console. void DataTable_Warning(const char *pInMessage, ...) { char msg[4096]; va_list marker; #if 0 #if !defined(_DEBUG) if(!g_CV_DTWarning.GetInt()) return; #endif #endif va_start(marker, pInMessage); Q_vsnprintf(msg, sizeof(msg), pInMessage, marker); va_end(marker); Warning("DataTable warning: %s", msg); }
#include <network/ping_handler.hpp> PingHandler::PingHandler(): last_ping_date(microsec_clock::universal_time()), latency(0, 0, 0, 0) { } PingHandler::~PingHandler() { } void PingHandler::ping_sent() { this->last_ping_date = microsec_clock::universal_time(); } void PingHandler::pong_received() { ptime current_time(microsec_clock::universal_time()); this->latency = current_time - this->last_ping_date; } long PingHandler::get_latency() { return this->latency.total_microseconds(); }
#include <Klein/Render/PBRInstancedMaterial.h> #include <Klein/Render/ResourceManager.h> #include <Klein/Render/ShaderProgram.h> #include <QString> #include <Qt3DRender/QEffect> namespace Klein { PBRInstancedMaterial::PBRInstancedMaterial(Qt3DCore::QNode* parent) : BasePBRMaterial(parent) { m_useInstanceColor = new Qt3DRender::QParameter( QStringLiteral("useInstanceColor"), false, this); this->addParameter(m_useInstanceColor); this->setEffect(getEffectVariant(isShadowCastingEnabled())); } Qt3DRender::QEffect* PBRInstancedMaterial::createEffect(bool castShadow) { const QString shaderPath("data/shader/"); const auto shader = createShader(shaderPath + QStringLiteral("ShadingInstanced.vert"), shaderPath + QStringLiteral("PBR.frag")); return createEffectImpl(shader, castShadow); } Qt3DRender::QEffect* PBRInstancedMaterial::getEffectVariant(bool castShadow) { Qt3DRender::QEffect* effect = nullptr; if (castShadow) { effect = gResourceManager().get<Qt3DRender::QEffect>(effectName_CastShadow); if (effect == nullptr) { effect = createEffect(castShadow); gResourceManager().put(effectName_CastShadow, effect); } } else { effect = gResourceManager().get<Qt3DRender::QEffect>(effectName_NoShadow); if (effect == nullptr) { effect = createEffect(castShadow); gResourceManager().put(effectName_NoShadow, effect); } } return effect; } } // namespace Klein
#pragma once #include <xcb/xcb_icccm.h> #include "common.hpp" POLYBAR_NS namespace icccm_util { string get_wm_name(xcb_connection_t* conn, xcb_window_t win); string get_reply_string(xcb_icccm_get_text_property_reply_t* reply); } POLYBAR_NS_END
#include <iostream> #include <set> using namespace std; set<int> online; int a[200000]; int main(){ ios::sync_with_stdio(false); int n, k,k1 = 0, q, tmp1,tmp2; cin >> n >> k >> q; for(int i = 1; i<=n; i++) cin >> a[i]; for(int i = 0; i<q; i++) { cin >> tmp1 >> tmp2; tmp2 = a[tmp2]; if(tmp1==1) {online.insert(tmp2); k1+=(k1!=k); } else { bool was = 0; set<int>::reverse_iterator it = online.rbegin(); for(int i = 0; i < k1; i++) { if(*it==tmp2) { cout << "YES\n"; was = 1; break; } it++; } if(!was)cout << "NO\n"; } } return 0; }
// generated from // rosidl_typesupport_fastrtps_cpp/resource/msg__rosidl_typesupport_fastrtps_cpp.hpp.em // generated code does not contain a copyright notice #ifndef MAP_MSGS__SRV__PROJECTED_MAPS_INFO__REQUEST__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_ #define MAP_MSGS__SRV__PROJECTED_MAPS_INFO__REQUEST__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_ #include "rosidl_generator_c/message_type_support_struct.h" #include "rosidl_typesupport_interface/macros.h" #include "map_msgs/msg/rosidl_typesupport_fastrtps_cpp__visibility_control.h" #include "map_msgs/srv/projected_maps_info__request__struct.hpp" #ifndef _WIN32 # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-parameter" # ifdef __clang__ # pragma clang diagnostic ignored "-Wdeprecated-register" # pragma clang diagnostic ignored "-Wreturn-type-c-linkage" # endif #endif #ifndef _WIN32 # pragma GCC diagnostic pop #endif #include "fastcdr/Cdr.h" namespace map_msgs { namespace srv { namespace typesupport_fastrtps_cpp { bool ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_map_msgs cdr_serialize( const map_msgs::srv::ProjectedMapsInfo_Request & ros_message, eprosima::fastcdr::Cdr & cdr); bool ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_map_msgs cdr_deserialize( eprosima::fastcdr::Cdr & cdr, map_msgs::srv::ProjectedMapsInfo_Request & ros_message); size_t ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_map_msgs get_serialized_size( const map_msgs::srv::ProjectedMapsInfo_Request & ros_message, size_t current_alignment); size_t ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_map_msgs max_serialized_size_ProjectedMapsInfo_Request( bool & full_bounded, size_t current_alignment); } // namespace typesupport_fastrtps_cpp } // namespace srv } // namespace map_msgs #ifdef __cplusplus extern "C" { #endif ROSIDL_TYPESUPPORT_FASTRTPS_CPP_PUBLIC_map_msgs const rosidl_message_type_support_t * ROSIDL_TYPESUPPORT_INTERFACE__MESSAGE_SYMBOL_NAME(rosidl_typesupport_fastrtps_cpp, map_msgs, srv, ProjectedMapsInfo_Request)(); #ifdef __cplusplus } #endif #endif // MAP_MSGS__SRV__PROJECTED_MAPS_INFO__REQUEST__ROSIDL_TYPESUPPORT_FASTRTPS_CPP_HPP_
/* This file is a part of libcds - Concurrent Data Structures library (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017 Source code repo: http://github.com/khizmax/libcds/ Download: http://sourceforge.net/projects/libcds/files/ 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "test_generic_queue.h" #include <cds/gc/hp.h> #include <cds/container/moir_queue.h> namespace { namespace cc = cds::container; typedef cds::gc::HP gc_type; class MoirQueue_HP : public cds_test::generic_queue { protected: void SetUp() { typedef cc::MoirQueue< gc_type, int > queue_type; cds::gc::hp::GarbageCollector::Construct( queue_type::c_nHazardPtrCount, 1, 16 ); cds::threading::Manager::attachThread(); } void TearDown() { cds::threading::Manager::detachThread(); cds::gc::hp::GarbageCollector::Destruct( true ); } }; TEST_F( MoirQueue_HP, defaulted ) { typedef cds::container::MoirQueue< gc_type, int > test_queue; test_queue q; test(q); } TEST_F( MoirQueue_HP, item_counting ) { typedef cds::container::MoirQueue < gc_type, int, typename cds::container::msqueue::make_traits < cds::opt::item_counter < cds::atomicity::item_counter > > ::type > test_queue; test_queue q; test( q ); } TEST_F( MoirQueue_HP, relaxed ) { typedef cds::container::MoirQueue < gc_type, int, typename cds::container::msqueue::make_traits < cds::opt::item_counter< cds::atomicity::item_counter > , cds::opt::memory_model < cds::opt::v::relaxed_ordering > > ::type > test_queue; test_queue q; test( q ); } TEST_F( MoirQueue_HP, aligned ) { typedef cds::container::MoirQueue < gc_type, int, typename cds::container::msqueue::make_traits < cds::opt::memory_model< cds::opt::v::relaxed_ordering> , cds::opt::padding < 32 > >::type > test_queue; test_queue q; test( q ); } TEST_F( MoirQueue_HP, seq_cst ) { struct traits : public cc::msqueue::traits { typedef cds::opt::v::sequential_consistent memory_model; typedef cds::atomicity::item_counter item_counter; enum { padding = 64 }; }; typedef cds::container::MoirQueue < gc_type, int, traits > test_queue; test_queue q; test( q ); } TEST_F( MoirQueue_HP, move ) { typedef cds::container::MoirQueue< gc_type, std::string > test_queue; test_queue q; test_string( q ); } TEST_F( MoirQueue_HP, move_item_counting ) { struct traits : public cc::msqueue::traits { typedef cds::atomicity::item_counter item_counter; }; typedef cds::container::MoirQueue< gc_type, std::string, traits > test_queue; test_queue q; test_string( q ); } } // namespace
/**************************************************************************** * * Copyright (c) 2014 PX4 Development Team. 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. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file mission_block.cpp * * Helper class to use mission items * * @author Julian Oes <julian@oes.ch> * @author Sander Smeets <sander@droneslab.com> * @author Andreas Antener <andreas@uaventure.com> */ #include "mission_block.h" #include "navigator.h" #include <math.h> #include <float.h> #include <lib/ecl/geo/geo.h> #include <systemlib/mavlink_log.h> #include <mathlib/mathlib.h> #include <uORB/uORB.h> #include <uORB/topics/actuator_controls.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/vtol_vehicle_status.h> using matrix::wrap_pi; MissionBlock::MissionBlock(Navigator *navigator) : NavigatorMode(navigator) { _mission_item.lat = (double)NAN; _mission_item.lon = (double)NAN; _mission_item.yaw = NAN; _mission_item.loiter_radius = _navigator->get_loiter_radius(); _mission_item.acceptance_radius = _navigator->get_acceptance_radius(); _mission_item.time_inside = 0.0f; _mission_item.autocontinue = true; _mission_item.origin = ORIGIN_ONBOARD; } bool MissionBlock::is_mission_item_reached() { /* handle non-navigation or indefinite waypoints */ switch (_mission_item.nav_cmd) { case NAV_CMD_DO_SET_SERVO: return true; case NAV_CMD_LAND: /* fall through */ case NAV_CMD_VTOL_LAND: return _navigator->get_land_detected()->landed; case NAV_CMD_IDLE: /* fall through */ case NAV_CMD_LOITER_UNLIMITED: return false; case NAV_CMD_DO_LAND_START: case NAV_CMD_DO_TRIGGER_CONTROL: case NAV_CMD_DO_DIGICAM_CONTROL: case NAV_CMD_IMAGE_START_CAPTURE: case NAV_CMD_IMAGE_STOP_CAPTURE: case NAV_CMD_VIDEO_START_CAPTURE: case NAV_CMD_VIDEO_STOP_CAPTURE: case NAV_CMD_DO_MOUNT_CONFIGURE: case NAV_CMD_DO_MOUNT_CONTROL: case NAV_CMD_DO_SET_ROI: case NAV_CMD_DO_SET_ROI_LOCATION: case NAV_CMD_DO_SET_ROI_WPNEXT_OFFSET: case NAV_CMD_DO_SET_ROI_NONE: case NAV_CMD_DO_SET_CAM_TRIGG_DIST: case NAV_CMD_DO_SET_CAM_TRIGG_INTERVAL: case NAV_CMD_SET_CAMERA_MODE: return true; case NAV_CMD_DO_VTOL_TRANSITION: /* * We wait half a second to give the transition command time to propagate. * Then monitor the transition status for completion. */ // TODO: check desired transition state achieved and drop _action_start if (hrt_absolute_time() - _action_start > 500000 && !_navigator->get_vstatus()->in_transition_mode) { _action_start = 0; return true; } else { return false; } case NAV_CMD_DO_CHANGE_SPEED: case NAV_CMD_DO_SET_HOME: return true; default: /* do nothing, this is a 3D waypoint */ break; } hrt_abstime now = hrt_absolute_time(); if (!_navigator->get_land_detected()->landed && !_waypoint_position_reached) { float dist = -1.0f; float dist_xy = -1.0f; float dist_z = -1.0f; float altitude_amsl = _mission_item.altitude_is_relative ? _mission_item.altitude + _navigator->get_home_position()->alt : _mission_item.altitude; dist = get_distance_to_point_global_wgs84(_mission_item.lat, _mission_item.lon, altitude_amsl, _navigator->get_global_position()->lat, _navigator->get_global_position()->lon, _navigator->get_global_position()->alt, &dist_xy, &dist_z); /* FW special case for NAV_CMD_WAYPOINT to achieve altitude via loiter */ if (!_navigator->get_vstatus()->is_rotary_wing && (_mission_item.nav_cmd == NAV_CMD_WAYPOINT)) { struct position_setpoint_s *curr_sp = &_navigator->get_position_setpoint_triplet()->current; /* close to waypoint, but altitude error greater than twice acceptance */ if ((dist >= 0.0f) && (dist_z > 2 * _navigator->get_altitude_acceptance_radius()) && (dist_xy < 2 * _navigator->get_loiter_radius())) { /* SETPOINT_TYPE_POSITION -> SETPOINT_TYPE_LOITER */ if (curr_sp->type == position_setpoint_s::SETPOINT_TYPE_POSITION) { curr_sp->type = position_setpoint_s::SETPOINT_TYPE_LOITER; curr_sp->loiter_radius = _navigator->get_loiter_radius(); curr_sp->loiter_direction = 1; _navigator->set_position_setpoint_triplet_updated(); } } else { /* restore SETPOINT_TYPE_POSITION */ if (curr_sp->type == position_setpoint_s::SETPOINT_TYPE_LOITER) { /* loiter acceptance criteria required to revert back to SETPOINT_TYPE_POSITION */ if ((dist >= 0.0f) && (dist_z < _navigator->get_loiter_radius()) && (dist_xy <= _navigator->get_loiter_radius() * 1.2f)) { curr_sp->type = position_setpoint_s::SETPOINT_TYPE_POSITION; _navigator->set_position_setpoint_triplet_updated(); } } } } if ((_mission_item.nav_cmd == NAV_CMD_TAKEOFF || _mission_item.nav_cmd == NAV_CMD_VTOL_TAKEOFF) && _navigator->get_vstatus()->is_rotary_wing) { /* We want to avoid the edge case where the acceptance radius is bigger or equal than * the altitude of the takeoff waypoint above home. Otherwise, we do not really follow * take-off procedures like leaving the landing gear down. */ float takeoff_alt = _mission_item.altitude_is_relative ? _mission_item.altitude : (_mission_item.altitude - _navigator->get_home_position()->alt); float altitude_acceptance_radius = _navigator->get_altitude_acceptance_radius(); /* It should be safe to just use half of the takoeff_alt as an acceptance radius. */ if (takeoff_alt > 0 && takeoff_alt < altitude_acceptance_radius) { altitude_acceptance_radius = takeoff_alt / 2.0f; } /* require only altitude for takeoff for multicopter */ if (_navigator->get_global_position()->alt > altitude_amsl - altitude_acceptance_radius) { _waypoint_position_reached = true; } } else if (_mission_item.nav_cmd == NAV_CMD_TAKEOFF) { /* for takeoff mission items use the parameter for the takeoff acceptance radius */ if (dist >= 0.0f && dist <= _navigator->get_acceptance_radius() && dist_z <= _navigator->get_altitude_acceptance_radius()) { _waypoint_position_reached = true; } } else if (!_navigator->get_vstatus()->is_rotary_wing && (_mission_item.nav_cmd == NAV_CMD_LOITER_UNLIMITED || _mission_item.nav_cmd == NAV_CMD_LOITER_TIME_LIMIT)) { /* Loiter mission item on a non rotary wing: the aircraft is going to circle the * coordinates with a radius equal to the loiter_radius field. It is not flying * through the waypoint center. * Therefore the item is marked as reached once the system reaches the loiter * radius (+ some margin). Time inside and turn count is handled elsewhere. */ if (dist >= 0.0f && dist <= _navigator->get_acceptance_radius(fabsf(_mission_item.loiter_radius) * 1.2f) && dist_z <= _navigator->get_altitude_acceptance_radius()) { _waypoint_position_reached = true; } else { _time_first_inside_orbit = 0; } } else if (!_navigator->get_vstatus()->is_rotary_wing && (_mission_item.nav_cmd == NAV_CMD_LOITER_TO_ALT)) { // NAV_CMD_LOITER_TO_ALT only uses mission item altitude once it's in the loiter // first check if the altitude setpoint is the mission setpoint struct position_setpoint_s *curr_sp = &_navigator->get_position_setpoint_triplet()->current; if (fabsf(curr_sp->alt - altitude_amsl) >= FLT_EPSILON) { // check if the initial loiter has been accepted dist_xy = -1.0f; dist_z = -1.0f; dist = get_distance_to_point_global_wgs84(_mission_item.lat, _mission_item.lon, curr_sp->alt, _navigator->get_global_position()->lat, _navigator->get_global_position()->lon, _navigator->get_global_position()->alt, &dist_xy, &dist_z); if (dist >= 0.0f && dist <= _navigator->get_acceptance_radius(fabsf(_mission_item.loiter_radius) * 1.2f) && dist_z <= _navigator->get_default_altitude_acceptance_radius()) { // now set the loiter to the final altitude in the NAV_CMD_LOITER_TO_ALT mission item curr_sp->alt = altitude_amsl; _navigator->set_position_setpoint_triplet_updated(); } } else { if (dist >= 0.0f && dist <= _navigator->get_acceptance_radius(fabsf(_mission_item.loiter_radius) * 1.2f) && dist_z <= _navigator->get_altitude_acceptance_radius()) { _waypoint_position_reached = true; // set required yaw from bearing to the next mission item if (_mission_item.force_heading) { const position_setpoint_s &next_sp = _navigator->get_position_setpoint_triplet()->next; if (next_sp.valid) { _mission_item.yaw = get_bearing_to_next_waypoint(_navigator->get_global_position()->lat, _navigator->get_global_position()->lon, next_sp.lat, next_sp.lon); _waypoint_yaw_reached = false; } else { _waypoint_yaw_reached = true; } } } } } else if (_mission_item.nav_cmd == NAV_CMD_DELAY) { _waypoint_position_reached = true; _waypoint_yaw_reached = true; _time_wp_reached = now; } else { /* for normal mission items used their acceptance radius */ float mission_acceptance_radius = _navigator->get_acceptance_radius(_mission_item.acceptance_radius); /* if set to zero use the default instead */ if (mission_acceptance_radius < NAV_EPSILON_POSITION) { mission_acceptance_radius = _navigator->get_acceptance_radius(); } /* for vtol back transition calculate acceptance radius based on time and ground speed */ if (_mission_item.vtol_back_transition && !_navigator->get_vstatus()->is_rotary_wing) { float velocity = sqrtf(_navigator->get_local_position()->vx * _navigator->get_local_position()->vx + _navigator->get_local_position()->vy * _navigator->get_local_position()->vy); const float back_trans_dec = _navigator->get_vtol_back_trans_deceleration(); const float reverse_delay = _navigator->get_vtol_reverse_delay(); if (back_trans_dec > FLT_EPSILON && velocity > FLT_EPSILON) { mission_acceptance_radius = ((velocity / back_trans_dec / 2) * velocity) + reverse_delay * velocity; } } if (dist >= 0.0f && dist <= mission_acceptance_radius && dist_z <= _navigator->get_altitude_acceptance_radius()) { _waypoint_position_reached = true; } } if (_waypoint_position_reached) { // reached just now _time_wp_reached = now; } } /* Check if the waypoint and the requested yaw setpoint. */ if (_waypoint_position_reached && !_waypoint_yaw_reached) { if ((_navigator->get_vstatus()->is_rotary_wing || (_mission_item.nav_cmd == NAV_CMD_LOITER_TO_ALT && _mission_item.force_heading)) && PX4_ISFINITE(_navigator->get_yaw_acceptance(_mission_item.yaw))) { /* check course if defined only for rotary wing except takeoff */ float cog = _navigator->get_vstatus()->is_rotary_wing ? _navigator->get_global_position()->yaw : atan2f( _navigator->get_global_position()->vel_e, _navigator->get_global_position()->vel_n); float yaw_err = wrap_pi(_mission_item.yaw - cog); /* accept yaw if reached or if timeout is set in which case we ignore not forced headings */ if (fabsf(yaw_err) < math::radians(_navigator->get_yaw_threshold()) || (_navigator->get_yaw_timeout() >= FLT_EPSILON && !_mission_item.force_heading)) { _waypoint_yaw_reached = true; } /* if heading needs to be reached, the timeout is enabled and we don't make it, abort mission */ if (!_waypoint_yaw_reached && _mission_item.force_heading && (_navigator->get_yaw_timeout() >= FLT_EPSILON) && (now - _time_wp_reached >= (hrt_abstime)_navigator->get_yaw_timeout() * 1e6f)) { _navigator->set_mission_failure("unable to reach heading within timeout"); } } else { _waypoint_yaw_reached = true; } } /* Once the waypoint and yaw setpoint have been reached we can start the loiter time countdown */ if (_waypoint_position_reached && _waypoint_yaw_reached) { if (_time_first_inside_orbit == 0) { _time_first_inside_orbit = now; } /* check if the MAV was long enough inside the waypoint orbit */ if ((get_time_inside(_mission_item) < FLT_EPSILON) || (now - _time_first_inside_orbit >= (hrt_abstime)(get_time_inside(_mission_item) * 1e6f))) { position_setpoint_s &curr_sp = _navigator->get_position_setpoint_triplet()->current; const position_setpoint_s &next_sp = _navigator->get_position_setpoint_triplet()->next; const float range = get_distance_to_next_waypoint(curr_sp.lat, curr_sp.lon, next_sp.lat, next_sp.lon); // exit xtrack location // reset lat/lon of loiter waypoint so vehicle follows a tangent if (_mission_item.loiter_exit_xtrack && next_sp.valid && PX4_ISFINITE(range) && (_mission_item.nav_cmd == NAV_CMD_LOITER_TIME_LIMIT || _mission_item.nav_cmd == NAV_CMD_LOITER_TO_ALT)) { float bearing = get_bearing_to_next_waypoint(curr_sp.lat, curr_sp.lon, next_sp.lat, next_sp.lon); float inner_angle = M_PI_2_F - asinf(_mission_item.loiter_radius / range); // Compute "ideal" tangent origin if (curr_sp.loiter_direction > 0) { bearing -= inner_angle; } else { bearing += inner_angle; } // Replace current setpoint lat/lon with tangent coordinate waypoint_from_heading_and_distance(curr_sp.lat, curr_sp.lon, bearing, curr_sp.loiter_radius, &curr_sp.lat, &curr_sp.lon); } return true; } } // all acceptance criteria must be met in the same iteration _waypoint_position_reached = false; _waypoint_yaw_reached = false; return false; } void MissionBlock::reset_mission_item_reached() { _waypoint_position_reached = false; _waypoint_yaw_reached = false; _time_first_inside_orbit = 0; _time_wp_reached = 0; } void MissionBlock::issue_command(const mission_item_s &item) { if (item_contains_position(item)) { return; } // NAV_CMD_DO_LAND_START is only a marker if (item.nav_cmd == NAV_CMD_DO_LAND_START) { return; } if (item.nav_cmd == NAV_CMD_DO_SET_SERVO) { PX4_INFO("DO_SET_SERVO command"); // XXX: we should issue a vehicle command and handle this somewhere else actuator_controls_s actuators = {}; actuators.timestamp = hrt_absolute_time(); // params[0] actuator number to be set 0..5 (corresponds to AUX outputs 1..6) // params[1] new value for selected actuator in ms 900...2000 actuators.control[(int)item.params[0]] = 1.0f / 2000 * -item.params[1]; if (_actuator_pub != nullptr) { orb_publish(ORB_ID(actuator_controls_2), _actuator_pub, &actuators); } else { _actuator_pub = orb_advertise(ORB_ID(actuator_controls_2), &actuators); } } else { _action_start = hrt_absolute_time(); // mission_item -> vehicle_command // we're expecting a mission command item here so assign the "raw" inputs to the command // (MAV_FRAME_MISSION mission item) vehicle_command_s vcmd = {}; vcmd.command = item.nav_cmd; vcmd.param1 = item.params[0]; vcmd.param2 = item.params[1]; vcmd.param3 = item.params[2]; vcmd.param4 = item.params[3]; if (item.nav_cmd == NAV_CMD_DO_SET_ROI_LOCATION && item.altitude_is_relative) { vcmd.param5 = item.lat; vcmd.param6 = item.lon; vcmd.param7 = item.altitude + _navigator->get_home_position()->alt; } else { vcmd.param5 = (double)item.params[4]; vcmd.param6 = (double)item.params[5]; vcmd.param7 = item.params[6]; } _navigator->publish_vehicle_cmd(&vcmd); } } float MissionBlock::get_time_inside(const mission_item_s &item) const { if ((item.nav_cmd == NAV_CMD_WAYPOINT && _navigator->get_vstatus()->is_rotary_wing) || item.nav_cmd == NAV_CMD_LOITER_TIME_LIMIT || item.nav_cmd == NAV_CMD_DELAY) { // a negative time inside would be invalid return math::max(item.time_inside, 0.0f); } return 0.0f; } bool MissionBlock::item_contains_position(const mission_item_s &item) { return item.nav_cmd == NAV_CMD_WAYPOINT || item.nav_cmd == NAV_CMD_LOITER_UNLIMITED || item.nav_cmd == NAV_CMD_LOITER_TIME_LIMIT || item.nav_cmd == NAV_CMD_LAND || item.nav_cmd == NAV_CMD_TAKEOFF || item.nav_cmd == NAV_CMD_LOITER_TO_ALT || item.nav_cmd == NAV_CMD_VTOL_TAKEOFF || item.nav_cmd == NAV_CMD_VTOL_LAND || item.nav_cmd == NAV_CMD_DO_FOLLOW_REPOSITION; } bool MissionBlock::mission_item_to_position_setpoint(const mission_item_s &item, position_setpoint_s *sp) { /* don't change the setpoint for non-position items */ if (!item_contains_position(item)) { return false; } sp->lat = item.lat; sp->lon = item.lon; sp->alt = get_absolute_altitude_for_item(item); sp->yaw = item.yaw; sp->yaw_valid = PX4_ISFINITE(item.yaw); sp->loiter_radius = (fabsf(item.loiter_radius) > NAV_EPSILON_POSITION) ? fabsf(item.loiter_radius) : _navigator->get_loiter_radius(); sp->loiter_direction = (item.loiter_radius > 0) ? 1 : -1; if (item.acceptance_radius > 0.0f && PX4_ISFINITE(item.acceptance_radius)) { // if the mission item has a specified acceptance radius, overwrite the default one from parameters sp->acceptance_radius = item.acceptance_radius; } else { sp->acceptance_radius = _navigator->get_default_acceptance_radius(); } sp->cruising_speed = _navigator->get_cruising_speed(); sp->cruising_throttle = _navigator->get_cruising_throttle(); switch (item.nav_cmd) { case NAV_CMD_IDLE: sp->type = position_setpoint_s::SETPOINT_TYPE_IDLE; break; case NAV_CMD_TAKEOFF: // if already flying (armed and !landed) treat TAKEOFF like regular POSITION if ((_navigator->get_vstatus()->arming_state == vehicle_status_s::ARMING_STATE_ARMED) && !_navigator->get_land_detected()->landed && !_navigator->get_land_detected()->maybe_landed) { sp->type = position_setpoint_s::SETPOINT_TYPE_POSITION; } else { sp->type = position_setpoint_s::SETPOINT_TYPE_TAKEOFF; // set pitch and ensure that the hold time is zero sp->pitch_min = item.pitch_min; } break; case NAV_CMD_VTOL_TAKEOFF: sp->type = position_setpoint_s::SETPOINT_TYPE_TAKEOFF; break; case NAV_CMD_LAND: case NAV_CMD_VTOL_LAND: sp->type = position_setpoint_s::SETPOINT_TYPE_LAND; break; case NAV_CMD_LOITER_TO_ALT: // initially use current altitude, and switch to mission item altitude once in loiter position if (_navigator->get_loiter_min_alt() > 0.0f) { // ignore _param_loiter_min_alt if smaller than 0 (-1) sp->alt = math::max(_navigator->get_global_position()->alt, _navigator->get_home_position()->alt + _navigator->get_loiter_min_alt()); } else { sp->alt = _navigator->get_global_position()->alt; } // fall through case NAV_CMD_LOITER_TIME_LIMIT: case NAV_CMD_LOITER_UNLIMITED: sp->type = position_setpoint_s::SETPOINT_TYPE_LOITER; break; default: sp->type = position_setpoint_s::SETPOINT_TYPE_POSITION; break; } sp->valid = true; return sp->valid; } void MissionBlock::set_loiter_item(struct mission_item_s *item, float min_clearance) { if (_navigator->get_land_detected()->landed) { /* landed, don't takeoff, but switch to IDLE mode */ item->nav_cmd = NAV_CMD_IDLE; } else { item->nav_cmd = NAV_CMD_LOITER_UNLIMITED; struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); if (_navigator->get_can_loiter_at_sp() && pos_sp_triplet->current.valid) { /* use current position setpoint */ item->lat = pos_sp_triplet->current.lat; item->lon = pos_sp_triplet->current.lon; item->altitude = pos_sp_triplet->current.alt; } else { /* use current position and use return altitude as clearance */ item->lat = _navigator->get_global_position()->lat; item->lon = _navigator->get_global_position()->lon; item->altitude = _navigator->get_global_position()->alt; if (min_clearance > 0.0f && item->altitude < _navigator->get_home_position()->alt + min_clearance) { item->altitude = _navigator->get_home_position()->alt + min_clearance; } } item->altitude_is_relative = false; item->yaw = NAN; item->loiter_radius = _navigator->get_loiter_radius(); item->acceptance_radius = _navigator->get_acceptance_radius(); item->time_inside = 0.0f; item->autocontinue = false; item->origin = ORIGIN_ONBOARD; } } void MissionBlock::set_takeoff_item(struct mission_item_s *item, float abs_altitude, float min_pitch) { item->nav_cmd = NAV_CMD_TAKEOFF; /* use current position */ item->lat = _navigator->get_global_position()->lat; item->lon = _navigator->get_global_position()->lon; item->yaw = _navigator->get_global_position()->yaw; item->altitude = abs_altitude; item->altitude_is_relative = false; item->loiter_radius = _navigator->get_loiter_radius(); item->pitch_min = min_pitch; item->autocontinue = false; item->origin = ORIGIN_ONBOARD; } void MissionBlock::set_land_item(struct mission_item_s *item, bool at_current_location) { /* VTOL transition to RW before landing */ if (_navigator->force_vtol()) { vehicle_command_s vcmd = {}; vcmd.command = NAV_CMD_DO_VTOL_TRANSITION; vcmd.param1 = vtol_vehicle_status_s::VEHICLE_VTOL_STATE_MC; _navigator->publish_vehicle_cmd(&vcmd); } /* set the land item */ item->nav_cmd = NAV_CMD_LAND; /* use current position */ if (at_current_location) { item->lat = (double)NAN; //descend at current position item->lon = (double)NAN; //descend at current position item->yaw = _navigator->get_local_position()->yaw; } else { /* use home position */ item->lat = _navigator->get_home_position()->lat; item->lon = _navigator->get_home_position()->lon; item->yaw = _navigator->get_home_position()->yaw; } item->altitude = 0; item->altitude_is_relative = false; item->loiter_radius = _navigator->get_loiter_radius(); item->acceptance_radius = _navigator->get_acceptance_radius(); item->time_inside = 0.0f; item->autocontinue = true; item->origin = ORIGIN_ONBOARD; } void MissionBlock::set_idle_item(struct mission_item_s *item) { item->nav_cmd = NAV_CMD_IDLE; item->lat = _navigator->get_home_position()->lat; item->lon = _navigator->get_home_position()->lon; item->altitude_is_relative = false; item->altitude = _navigator->get_home_position()->alt; item->yaw = NAN; item->loiter_radius = _navigator->get_loiter_radius(); item->acceptance_radius = _navigator->get_acceptance_radius(); item->time_inside = 0.0f; item->autocontinue = true; item->origin = ORIGIN_ONBOARD; } void MissionBlock::set_vtol_transition_item(struct mission_item_s *item, const uint8_t new_mode) { item->nav_cmd = NAV_CMD_DO_VTOL_TRANSITION; item->params[0] = (float) new_mode; item->yaw = _navigator->get_global_position()->yaw; item->autocontinue = true; } void MissionBlock::mission_apply_limitation(mission_item_s &item) { /* * Limit altitude */ /* do nothing if altitude max is negative */ if (_navigator->get_land_detected()->alt_max > 0.0f) { /* absolute altitude */ float altitude_abs = item.altitude_is_relative ? item.altitude + _navigator->get_home_position()->alt : item.altitude; /* limit altitude to maximum allowed altitude */ if ((_navigator->get_land_detected()->alt_max + _navigator->get_home_position()->alt) < altitude_abs) { item.altitude = item.altitude_is_relative ? _navigator->get_land_detected()->alt_max : _navigator->get_land_detected()->alt_max + _navigator->get_home_position()->alt; } } /* * Add other limitations here */ } float MissionBlock::get_absolute_altitude_for_item(const mission_item_s &mission_item) const { if (mission_item.altitude_is_relative) { return mission_item.altitude + _navigator->get_home_position()->alt; } else { return mission_item.altitude; } }
#include "list.h" #include "exception.h" #include <sstream> namespace Bencode { List::List() { } List::~List() { } Element* List::clone() { // Deep copy list List* list = new List(); for (std::shared_ptr<Element> const& element : this->elements) { list->addElement(std::shared_ptr<Element>(element->clone())); } return list; } Type List::getType() const { return Type::LIST; } void List::toBencode(std::ostream &ss) { ss << 'l'; // Conver list's elements for (std::shared_ptr<Element> element : this->elements) { element->toBencode(ss); } ss << 'e'; } bool List::operator==(const Element& other) { if (other.getType() != Type::LIST) { return false; } return this->operator==(dynamic_cast<const List&>(other)); } bool List::operator==(const List& other) { if (this->elements.size() != other.elements.size()) { return false; } int nOfElements = this->elements.size(); for (int i = 0; i < nOfElements; ++i) { if (this->elements[i] != other.elements[i]) { return false; } } return true; } bool List::operator!=(const List& other) { return !this->operator==(other); } void List::addElement(std::shared_ptr<Element> element) { if (! element) { throw NullptrElementException(); } this->elements.push_back(element); } std::shared_ptr<Element> List::getElement(int index) { return this->elements[index]; } ListIterator List::begin() { return ListIterator(this, 0); } ListIterator List::end() { return ListIterator(this, this->elements.size()); } bool ListIterator::operator!=(const ListIterator& other) { return curIndex != other.curIndex; } std::shared_ptr<Element> ListIterator::operator*() { return list->getElement(curIndex); } const ListIterator& ListIterator::operator++() { ++curIndex; return *this; } }
/** Copyright (c) 2017, Philip Deegan. 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 Philip Deegan 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. */ #ifndef _MAIKEN_PROCESSOR_HPP_ #define _MAIKEN_PROCESSOR_HPP_ #include "maiken/defs.hpp" namespace maiken { class ProcessException : public mkn::kul::Exception { public: ProcessException(char const* f, uint16_t const& l, std::string const& s) : mkn::kul::Exception(f, l, s) {} }; class Application; /* class GraphNode { Application *app; }; class Graph { private: std::unordered_map<size_t, std::vector<GraphNode>> nodes; };*/ class Processor : public Constants { public: static void process(std::vector<Application*> apps); }; } // namespace maiken #endif /* _MAIKEN_PROCESSOR_HPP_ */
// AUTOGENERATED FILE - DO NOT MODIFY! // This file generated by Djinni from varnames.djinni #include "NativeVarnameInterface.hpp" // my header #include "NativeVarnameRecord.hpp" namespace djinni_generated { NativeVarnameInterface::NativeVarnameInterface() : ::djinni::JniInterface<::testsuite::VarnameInterface, NativeVarnameInterface>("com/dropbox/djinni/test/VarnameInterface$CppProxy") {} NativeVarnameInterface::~NativeVarnameInterface() = default; CJNIEXPORT void JNICALL Java_com_dropbox_djinni_test_VarnameInterface_00024CppProxy_nativeDestroy(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); delete reinterpret_cast<::djinni::CppProxyHandle<::testsuite::VarnameInterface>*>(nativeRef); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, ) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_VarnameInterface_00024CppProxy_native_1Rmethod(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_RArg) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::VarnameInterface>(nativeRef); auto r = ref->_rmethod_(::djinni_generated::NativeVarnameRecord::toCpp(jniEnv, j_RArg)); return ::djinni::release(::djinni_generated::NativeVarnameRecord::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } CJNIEXPORT jobject JNICALL Java_com_dropbox_djinni_test_VarnameInterface_00024CppProxy_native_1Imethod(JNIEnv* jniEnv, jobject /*this*/, jlong nativeRef, jobject j_IArg) { try { DJINNI_FUNCTION_PROLOGUE1(jniEnv, nativeRef); const auto& ref = ::djinni::objectFromHandleAddress<::testsuite::VarnameInterface>(nativeRef); auto r = ref->_imethod_(::djinni_generated::NativeVarnameInterface::toCpp(jniEnv, j_IArg)); return ::djinni::release(::djinni_generated::NativeVarnameInterface::fromCpp(jniEnv, r)); } JNI_TRANSLATE_EXCEPTIONS_RETURN(jniEnv, 0 /* value doesn't matter */) } } // namespace djinni_generated
#include "openvslam/feature/orb_extractor_node.h" namespace openvslam { namespace feature { std::array<orb_extractor_node, 4> orb_extractor_node::divide_node() { // Half width/height of the allocated patch area const unsigned int half_x = cvCeil((pt_end_.x - pt_begin_.x) / 2.0); const unsigned int half_y = cvCeil((pt_end_.y - pt_begin_.y) / 2.0); // Four new child nodes std::array<orb_extractor_node, 4> child_nodes; // A position of center top, left center, center, right center, and center // bottom These positions are used to determine new split areas const auto pt_top = cv::Point2i(pt_begin_.x + half_x, pt_begin_.y); const auto pt_left = cv::Point2i(pt_begin_.x, pt_begin_.y + half_y); const auto pt_center = cv::Point2i(pt_begin_.x + half_x, pt_begin_.y + half_y); const auto pt_right = cv::Point2i(pt_end_.x, pt_begin_.y + half_y); const auto pt_bottom = cv::Point2i(pt_begin_.x + half_x, pt_end_.y); // Assign new patch border for each child nodes child_nodes.at(0).pt_begin_ = pt_begin_; child_nodes.at(0).pt_end_ = pt_center; child_nodes.at(1).pt_begin_ = pt_top; child_nodes.at(1).pt_end_ = pt_right; child_nodes.at(2).pt_begin_ = pt_left; child_nodes.at(2).pt_end_ = pt_bottom; child_nodes.at(3).pt_begin_ = pt_center; child_nodes.at(3).pt_end_ = pt_end_; // Memory reservation for child nodes for (auto& node : child_nodes) { node.keypts_.reserve(keypts_.size()); } // Distribute keypoints to child nodes for (const auto& keypt : keypts_) { unsigned int idx = 0; if (pt_begin_.x + half_x <= keypt.pt.x) { idx += 1; } if (pt_begin_.y + half_y <= keypt.pt.y) { idx += 2; } child_nodes.at(idx).keypts_.push_back(keypt); } return child_nodes; } } // namespace feature } // namespace openvslam
/* * box2dmousejoint.cpp * Copyright (c) 2011 Joonas Erkinheimo <joonas.erkinheimo@nokia.com> * * This file is part of the Box2D QML plugin. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "box2dgearjoint.h" #include "box2dworld.h" #include "box2dbody.h" Box2DGearJoint::Box2DGearJoint(QObject *parent) : Box2DJoint(parent), mGearJoint(0) { } Box2DGearJoint::~Box2DGearJoint() { cleanup(world()); } float Box2DGearJoint::ratio() const { if (mGearJoint) mGearJoint->GetRatio(); return mGearJointDef.ratio; } void Box2DGearJoint::setRatio(float _ratio) { if (qFuzzyCompare(_ratio,ratio())) return; mGearJointDef.ratio = _ratio; if (mGearJoint) mGearJoint->SetRatio(_ratio); emit ratioChanged(); } Box2DJoint *Box2DGearJoint::joint1() const { if (mGearJoint) return toBox2DJoint(mGearJoint->GetJoint1()); return toBox2DJoint(mGearJointDef.joint1); } void Box2DGearJoint::setJoint1(Box2DJoint *_joint1) { if (_joint1 == joint1()) return; mGearJointDef.joint1 = _joint1->joint(); if (mGearJointDef.joint1) { initialize(); emit joint1Changed(); } else connect(_joint1,SIGNAL(created()),this,SLOT(joint1Created())); } Box2DJoint *Box2DGearJoint::joint2() const { if (mGearJoint) return toBox2DJoint(mGearJoint->GetJoint2()); return toBox2DJoint(mGearJointDef.joint2); } void Box2DGearJoint::setJoint2(Box2DJoint *_joint2) { if (_joint2 == joint2()) return; mGearJointDef.joint2 = _joint2->joint(); if (mGearJointDef.joint2) { initialize(); emit joint2Changed(); } else connect(_joint2,SIGNAL(created()),this,SLOT(joint2Created())); } void Box2DGearJoint::nullifyJoint() { mGearJoint = 0; } void Box2DGearJoint::createJoint() { if (!mGearJointDef.joint1 || !mGearJointDef.joint2) return; mGearJointDef.bodyA = bodyA()->body(); mGearJointDef.bodyB = bodyB()->body(); mGearJoint = static_cast<b2GearJoint*>(world()->CreateJoint(&mGearJointDef)); mGearJoint->SetUserData(this); mInitializePending = false; emit created(); } void Box2DGearJoint::cleanup(b2World *world) { if (!world) { qWarning() << "GearJoint: There is no world connected"; return; } if (mGearJoint) { mGearJoint->SetUserData(0); world->DestroyJoint(mGearJoint); mGearJoint = 0; } } b2Joint *Box2DGearJoint::joint() const { return mGearJoint; } void Box2DGearJoint::joint1Created() { Box2DJoint * joint1 = static_cast<Box2DJoint *>(sender()); mGearJointDef.joint1 = joint1->joint(); initialize(); } void Box2DGearJoint::joint2Created() { Box2DJoint * joint2 = static_cast<Box2DJoint *>(sender()); mGearJointDef.joint2 = joint2->joint(); initialize(); }
#include "lobster/stdafx.h" #include "script_interface.h" #include "lobster/vmdata.h" #include "lobster/natreg.h" #include "lobster/compiler.h" #include "lobster/vm.h" using namespace lobster; namespace script { ScriptInterface *si = nullptr; void AddTreeSheets() { STARTDECL(ts_goto_root) () { si->GoToRoot(); return Value(); } ENDDECL0(ts_goto_root, "", "", "", "makes the root of the document the current cell. this is the default at the start" "of any script, so this function is only needed to return there."); STARTDECL(ts_goto_view) () { si->GoToView(); return Value(); } ENDDECL0(ts_goto_view, "", "", "", "makes what the user has zoomed into the current cell."); STARTDECL(ts_has_selection) () { return Value(si->HasSelection()); } ENDDECL0(ts_has_selection, "", "", "I", "wether there is a selection."); STARTDECL(ts_goto_selection) () { si->GoToSelection(); return Value(); } ENDDECL0(ts_goto_selection, "", "", "", "makes the current cell the one containing the selection, or does nothing on no" "selection."); STARTDECL(ts_has_parent) () { return Value(si->HasParent()); } ENDDECL0(ts_has_parent, "", "", "I", "wether the current cell has a parent (is the root cell)."); STARTDECL(ts_goto_parent) () { si->GoToParent(); return Value(); } ENDDECL0(ts_goto_parent, "", "", "", "makes the current cell the parent of the current cell, if any."); STARTDECL(ts_num_children) () { return Value(si->NumChildren()); } ENDDECL0(ts_num_children, "", "", "I", "returns the total number of children of the current cell (rows * columns)." "returns 0 if this cell doesn't have a sub-grid at all."); STARTDECL(ts_num_columns_rows) () { return Value(ToValueINT(int2(si->NumColumnsRows()))); } ENDDECL0(ts_num_columns_rows, "", "", "I}:2", "returns the number of columns & rows in the current cell."); STARTDECL(ts_selection) () { auto b = si->SelectionBox(); g_vm->Push(ToValueINT(int2(b.second))); return ToValueINT(int2(b.first)); } ENDDECL0(ts_selection, "", "", "I}:2I}:2", "returns the (x,y) and (xs,ys) of the current selection, or zeroes if none."); STARTDECL(ts_goto_child) (Value &n) { si->GoToChild(n.intval()); return Value(); } ENDDECL1(ts_goto_child, "n", "I", "", "makes the current cell the nth child of the current cell."); STARTDECL(ts_goto_column_row) (Value &x, Value &y) { si->GoToColumnRow(x.intval(), y.intval()); return Value(); } ENDDECL2(ts_goto_column_row, "col,row", "II", "", "makes the current cell the child at col / row."); STARTDECL(ts_get_text) () { return Value(g_vm->NewString(si->GetText())); } ENDDECL0(ts_get_text, "", "", "S", "gets the text of the current cell."); STARTDECL(ts_set_text) (Value &s) { si->SetText(s.sval()->strv()); s.DECRT(); return Value(); } ENDDECL1(ts_set_text, "text", "S", "", "sets the text of the current cell."); STARTDECL(ts_create_grid) (Value &x, Value &y) { si->CreateGrid(x.intval(), y.intval()); return Value(); } ENDDECL2(ts_create_grid, "cols,rows", "II", "", "creates a grid in the current cell if there isn't one yet."); STARTDECL(ts_insert_columns) (Value &x, Value &n) { si->InsertColumns(x.intval(), n.intval()); return Value(); } ENDDECL2(ts_insert_columns, "c,n", "II", "", "insert n columns before column c in an existing grid."); STARTDECL(ts_insert_rows) (Value &x, Value &n) { si->InsertRows(x.intval(), n.intval()); return Value(); } ENDDECL2(ts_insert_rows, "r,n", "II", "", "insert n rows before row r in an existing grid."); STARTDECL(ts_delete) (Value &pos, Value &size) { auto p = ValueDecToINT<2>(pos); auto s = ValueDecToINT<2>(size); si->Delete(p.x, p.y, s.x, s.y); return Value(); } ENDDECL2(ts_delete, "pos,size", "I}:2I}:2", "", "clears the cells denoted by pos/size. also removes columns/rows if they become" "completely empty, or the entire grid."); STARTDECL(ts_set_background_color) (Value &col) { si->SetBackgroundColor(*(uint *)quantizec(ValueDecToFLT<3>(col)).data()); return Value(); } ENDDECL1(ts_set_background_color, "col", "F}:4", "", "sets the background color of the current cell"); STARTDECL(ts_set_text_color) (Value &col) { si->SetTextColor(*(uint *)quantizec(ValueDecToFLT<3>(col)).data()); return Value(); } ENDDECL1(ts_set_text_color, "col", "F}:4", "", "sets the text color of the current cell"); STARTDECL(ts_set_relative_size) (Value &s) { si->SetRelativeSize(geom::clamp(s.intval(), -10, 10)); return Value(); } ENDDECL1(ts_set_relative_size, "s", "I", "", "sets the relative size (0 is normal, -1 is smaller etc.) of the current cell"); STARTDECL(ts_set_style_bits) (Value &s) { si->SetStyle(s.intval()); return Value(); } ENDDECL1(ts_set_style_bits, "s", "I", "", "sets one or more styles (bold = 1, italic = 2, fixed = 4, underline = 8," " strikethru = 16) on the current cell."); STARTDECL(ts_set_status_message) (Value &s) { si->SetStatusMessage(s.sval()->strv()); s.DECRT(); return Value(); } ENDDECL1(ts_set_status_message, "msg", "S", "", "sets the status message in TreeSheets."); STARTDECL(ts_get_filename_from_user) (Value &is_save) { return Value(g_vm->NewString(si->GetFileNameFromUser(is_save.True()))); } ENDDECL1(ts_get_filename_from_user, "is_save", "I", "S", "gets a filename using a file dialog. empty string if cancelled."); } string InitLobster(ScriptInterface *_si, const char *exefilepath, const char *auxfilepath, bool from_bundle, ScriptLoader sl) { si = _si; min_output_level = OUTPUT_PROGRAM; string err = ""; try { InitPlatform(exefilepath, auxfilepath, from_bundle, sl); RegisterBuiltin("treesheets", AddTreeSheets); RegisterCoreLanguageBuiltins(); } catch (string &s) { err = s; } return err; } string RunLobster(const char *filename, const char *code, bool dump_builtins) { string err = ""; try { string bytecode; Compile(filename, code, bytecode, nullptr, nullptr, dump_builtins); RunBytecode(filename, bytecode, nullptr, nullptr, vector<string>()); } catch (string &s) { err = s; } if (g_vm) delete g_vm; g_vm = nullptr; return err; } }
/** ****************************************************************************** * * @file mapgraphicitem.cpp * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @brief The main graphicsItem used on the widget, contains the map and map logic * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "uavitem.h" #include "gpsitem.h" #include "homeitem.h" #include "mapgraphicitem.h" #include "waypointlineitem.h" namespace mapcontrol { MapGraphicItem::MapGraphicItem(internals::Core *core, Configuration *configuration):core(core), config(configuration), MapRenderTransform(1), maxZoom(17), minZoom(2), zoomReal(0), rotation(0), zoomDigi(0), isSelected(false) { dragons.load(QString::fromUtf8(":/markers/images/dragons1.jpg")); showTileGridLines=false; isMouseOverMarker=false; maprect=QRectF(0,0,1022,680); core->SetCurrentRegion(internals::Rectangle(0, 0, maprect.width(), maprect.height())); core->SetMapType(MapType::GoogleHybrid); this->SetZoom(2); connect(core,SIGNAL(OnNeedInvalidation()),this,SLOT(Core_OnNeedInvalidation())); connect(core,SIGNAL(OnMapDrag()),this,SLOT(ChildPosRefresh())); connect(core,SIGNAL(OnMapZoomChanged()),this,SLOT(ChildPosRefresh())); //resize(); } void MapGraphicItem::start() { core->StartSystem(); } void MapGraphicItem::resize(const QRectF &rect) { Q_UNUSED(rect); { this->prepareGeometryChange(); maprect=boundingBox(scene()->sceneRect(),rotation); this->setTransform(QTransform().translate(-(maprect.width()-scene()->width())/2,-(maprect.height()-scene()->height())/2)); this->setTransformOriginPoint(maprect.center().x(),maprect.center().y()); this->setRotation(rotation); } core->OnMapSizeChanged(maprect.width(),maprect.height()); core->SetCurrentRegion(internals::Rectangle(0, 0, maprect.width(), maprect.height())); if(isVisible()) { core->GoToCurrentPosition(); } } QRectF MapGraphicItem::boundingRect() const { const int Margin = 1; return maprect.adjusted(-Margin, -Margin, +Margin, +Margin); } void MapGraphicItem::Core_OnNeedInvalidation() { this->update(); foreach(QGraphicsItem* i,this->childItems()) { WayPointItem* w=qgraphicsitem_cast<WayPointItem*>(i); if(w) w->RefreshPos(); UAVItem* ww=qgraphicsitem_cast<UAVItem*>(i); if(ww) ww->RefreshPos(); HomeItem* www=qgraphicsitem_cast<HomeItem*>(i); if(www) www->RefreshPos(); GPSItem* wwww=qgraphicsitem_cast<GPSItem*>(i); if(wwww) wwww->RefreshPos(); emit mapChanged(); } } void MapGraphicItem::ChildPosRefresh() { foreach(QGraphicsItem* i,this->childItems()) { WayPointItem* w=qgraphicsitem_cast<WayPointItem*>(i); if(w) w->RefreshPos(); UAVItem* ww=qgraphicsitem_cast<UAVItem*>(i); if(ww) ww->RefreshPos(); HomeItem* www=qgraphicsitem_cast<HomeItem*>(i); if(www) www->RefreshPos(); GPSItem* wwww=qgraphicsitem_cast<GPSItem*>(i); if(wwww) wwww->RefreshPos(); emit mapChanged(); } } void MapGraphicItem::ConstructLastImage(int const& zoomdiff) { QImage temp; QSize size=boundingRect().size().toSize(); size.setWidth(size.width()*2*zoomdiff); size.setHeight(size.height()*2*zoomdiff); temp=QImage(size, QImage::Format_ARGB32_Premultiplied); temp.fill(0); if (!temp.isNull()) { QPainter imagePainter(&temp); imagePainter.translate(-boundingRect().topLeft()); imagePainter.scale(2*zoomdiff,2*zoomdiff); paintImage(&imagePainter); imagePainter.end(); lastimagepoint=Point(core->GetrenderOffset().X()*2*zoomdiff,core->GetrenderOffset().Y()*2*zoomdiff); lastimage=temp; } } void MapGraphicItem::paintImage(QPainter *painter) { if(MapRenderTransform!=1) { QTransform transform; transform.translate(-((boundingRect().width()*MapRenderTransform)-(boundingRect().width()))/2,-((boundingRect().height()*MapRenderTransform)-(boundingRect().height()))/2); transform.scale(MapRenderTransform,MapRenderTransform); painter->setWorldTransform(transform); { DrawMap2D(painter); } painter->resetTransform(); } else { DrawMap2D(painter); } //painter->drawRect(maprect); } void MapGraphicItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); if(MapRenderTransform!=1) { QTransform transform; transform.translate(-((boundingRect().width()*MapRenderTransform)-(boundingRect().width()))/2,-((boundingRect().height()*MapRenderTransform)-(boundingRect().height()))/2); transform.scale(MapRenderTransform,MapRenderTransform); painter->setWorldTransform(transform); painter->setRenderHint(QPainter::SmoothPixmapTransform,true); painter->setRenderHint(QPainter::HighQualityAntialiasing,true); { DrawMap2D(painter); } painter->resetTransform(); } else { DrawMap2D(painter); } } void MapGraphicItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if(core->IsDragging()) { if(MapRenderTransform!=1) { qreal dx= (event->pos().x()-core->mouseDown.X())/(MapRenderTransform); qreal dy= (event->pos().y()-core->mouseDown.Y())/(MapRenderTransform); qreal nx=core->mouseDown.X()+dx; qreal ny=core->mouseDown.Y()+dy; core->mouseCurrent.SetX(nx); core->mouseCurrent.SetY(ny); } else { core->mouseCurrent.SetX(event->pos().x()); core->mouseCurrent.SetY(event->pos().y()); } { core->Drag(core->mouseCurrent); } } else if(isSelected && !selectionStart.IsEmpty() && (event->modifiers() == Qt::AltModifier || event->modifiers() == Qt::ShiftModifier)) { selectionEnd = FromLocalToLatLng(event->pos().x(), event->pos().y()); { internals::PointLatLng p1 = selectionStart; internals::PointLatLng p2 = selectionEnd; double x1 = qMin(p1.Lng(), p2.Lng()); double y1 = qMax(p1.Lat(), p2.Lat()); double x2 = qMax(p1.Lng(), p2.Lng()); double y2 = qMin(p1.Lat(), p2.Lat()); SetSelectedArea(internals::RectLatLng(y1, x1, x2 - x1, y1 - y2)); } } QGraphicsItem::mouseMoveEvent(event); } void MapGraphicItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(!IsMouseOverMarker()) { if(event->button() == config->DragButton && CanDragMap()&& !((event->modifiers()==Qt::AltModifier)||(event->modifiers()==Qt::ShiftModifier))) { core->mouseDown.SetX(event->pos().x()); core->mouseDown.SetY(event->pos().y()); this->setCursor(Qt::SizeAllCursor); core->BeginDrag(core->mouseDown); this->update(); } else if(!isSelected && ((event->modifiers()==Qt::AltModifier)||(event->modifiers()==Qt::ShiftModifier))) { isSelected = true; SetSelectedArea (internals::RectLatLng::Empty); selectionEnd = internals::PointLatLng::Empty; selectionStart = FromLocalToLatLng(event->pos().x(), event->pos().y()); } } } void MapGraphicItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if(isSelected) { isSelected = false; } if(core->IsDragging()) { core->EndDrag(); this->setCursor(Qt::ArrowCursor); if(!BoundsOfMap.IsEmpty() && !BoundsOfMap.Contains(core->CurrentPosition())) { if(!core->LastLocationInBounds.IsEmpty()) { core->SetCurrentPosition(core->LastLocationInBounds); } } } else { if(!selectionEnd.IsEmpty() && !selectionStart.IsEmpty()) { if(!selectedArea.IsEmpty() && event->modifiers() == Qt::ShiftModifier) { SetZoomToFitRect(SelectedArea()); } } } } bool MapGraphicItem::SetZoomToFitRect(internals::RectLatLng const& rect) { int maxZoom = core->GetMaxZoomToFitRect(rect); if(maxZoom > 0) { internals::PointLatLng center=internals::PointLatLng(rect.Lat()-(rect.HeightLat()/2), rect.Lng()+(rect.WidthLng()/2)); core->SetCurrentPosition(center); if(maxZoom > MaxZoom()) { maxZoom = MaxZoom(); } if((int) Zoom() != maxZoom) { SetZoom(maxZoom); } return true; } return false; } void MapGraphicItem::wheelEvent(QGraphicsSceneWheelEvent *event) { if(!IsMouseOverMarker() && !IsDragging()) { if(core->GetmouseLastZoom().X() != event->pos().x() && core->mouseLastZoom.Y() != event->pos().y()) { if(GetMouseWheelZoomType() == internals::MouseWheelZoomType::MousePositionAndCenter) { core->SetCurrentPosition(FromLocalToLatLng(event->pos().x(), event->pos().y())); } else if(GetMouseWheelZoomType() == internals::MouseWheelZoomType::ViewCenter) { core->SetCurrentPosition(FromLocalToLatLng((int) maprect.width()/2, (int) maprect.height()/2)); } else if(GetMouseWheelZoomType() == internals::MouseWheelZoomType::MousePositionWithoutCenter) { core->SetCurrentPosition(FromLocalToLatLng(event->pos().x(), event->pos().y())); } core->mouseLastZoom.SetX((event->pos().x())); core->mouseLastZoom.SetY((event->pos().y())); } // set mouse position to map center if(GetMouseWheelZoomType() != internals::MouseWheelZoomType::MousePositionWithoutCenter) { { // System.Drawing.Point p = PointToScreen(new System.Drawing.Point(Width/2, Height/2)); // Stuff.SetCursorPos((int) p.X, (int) p.Y); } } core->MouseWheelZooming = true; if(event->delta() > 0) { SetZoom(ZoomTotal()+1); } else if(event->delta() < 0) { SetZoom(ZoomTotal()-1); } core->MouseWheelZooming = false; } } void MapGraphicItem::DrawMap2D(QPainter *painter) { painter->setBackground(QBrush(Qt::black)); if(!lastimage.isNull()) painter->drawImage(core->GetrenderOffset().X()-lastimagepoint.X(),core->GetrenderOffset().Y()-lastimagepoint.Y(),lastimage); for(int i = -core->GetsizeOfMapArea().Width(); i <= core->GetsizeOfMapArea().Width(); i++) { for(int j = -core->GetsizeOfMapArea().Height(); j <= core->GetsizeOfMapArea().Height(); j++) { core->SettilePoint (core->GetcenterTileXYLocation()); core->SettilePoint(Point(core->GettilePoint().X()+ i,core->GettilePoint().Y()+j)); { internals::Tile* t = core->Matrix.TileAt(core->GettilePoint()); if(true) { core->tileRect.SetX(core->GettilePoint().X()*core->tileRect.Width()); core->tileRect.SetY(core->GettilePoint().Y()*core->tileRect.Height()); core->tileRect.Offset(core->GetrenderOffset()); if(core->GetCurrentRegion().IntersectsWith(core->tileRect)) { bool found = false; // render tile //lock(t.Overlays) if(t!=0) { foreach(QByteArray img,t->Overlays) { if(img.count()!=0) { if(!found) found = true; { painter->drawPixmap(core->tileRect.X(),core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height(),PureImageProxy::FromStream(img)); // qDebug()<<"tile:"<<core->tileRect.X()<<core->tileRect.Y(); } } } } if(showTileGridLines) { painter->setPen(config->EmptyTileBorders); painter->drawRect(core->tileRect.X(), core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height()); { painter->setFont(config->MissingDataFont); painter->setPen(Qt::red); painter->drawText(QRectF(core->tileRect.X(), core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height()),Qt::AlignCenter,(core->GettilePoint() == core->GetcenterTileXYLocation()? "CENTER: " :"TILE: ")+core->GettilePoint().ToString()); //qDebug()<<"ShowTileGridLine:"<<core->GettilePoint().ToString()<<"=="<<core->GetcenterTileXYLocation().ToString(); } } // add text if tile is missing if(false) { painter->fillRect(QRectF(core->tileRect.X(), core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height()),config->EmptytileBrush); painter->setFont(config->MissingDataFont); painter->drawText(QRectF(core->tileRect.X(), core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height()),config->EmptyTileText); painter->setPen(config->EmptyTileBorders); painter->drawRect(core->tileRect.X(), core->tileRect.Y(), core->tileRect.Width(), core->tileRect.Height()); // raise error } if(!SelectedArea().IsEmpty()) { core::Point p1 = FromLatLngToLocal(SelectedArea().LocationTopLeft()); core::Point p2 = FromLatLngToLocal(SelectedArea().LocationRightBottom()); int x1 = p1.X(); int y1 = p1.Y(); int x2 = p2.X(); int y2 = p2.Y(); painter->setPen(Qt::black); painter->setBrush(QBrush(QColor(50,50,100,20))); painter->drawRect(x1,y1,x2-x1,y2-y1); } } } } } } // painter->drawRect(core->GetrenderOffset().X()-lastimagepoint.X()-3,core->GetrenderOffset().Y()-lastimagepoint.Y()-3,lastimage.width(),lastimage.height()); // painter->setPen(Qt::red); // painter->drawLine(-10,-10,10,10); // painter->drawLine(10,10,-10,-10); // painter->drawRect(boundingRect().adjusted(100,100,-100,-100)); } core::Point MapGraphicItem::FromLatLngToLocal(internals::PointLatLng const& point) { core::Point ret = core->FromLatLngToLocal(point); if(MapRenderTransform!=1) { ret.SetX((int) (ret.X() * MapRenderTransform)); ret.SetY((int) (ret.Y() * MapRenderTransform)); ret.SetX(ret.X()-((boundingRect().width()*MapRenderTransform)-(boundingRect().width()))/2); ret.SetY(ret.Y()-((boundingRect().height()*MapRenderTransform)-(boundingRect().height()))/2); } return ret; } internals::PointLatLng MapGraphicItem::FromLocalToLatLng(int x, int y) { if(MapRenderTransform!=1) { x=x+((boundingRect().width()*MapRenderTransform)-(boundingRect().width()))/2; y=y+((boundingRect().height()*MapRenderTransform)-(boundingRect().height()))/2; x = (int) (x / MapRenderTransform); y = (int) (y / MapRenderTransform); } return core->FromLocalToLatLng(x, y); } float MapGraphicItem::metersToPixels(double meters, internals::PointLatLng coord) { return meters/this->Projection()->GetGroundResolution(this->ZoomTotal(),coord.Lat()); } double MapGraphicItem::Zoom() { return zoomReal; } double MapGraphicItem::ZoomDigi() { return zoomDigi; } double MapGraphicItem::ZoomTotal() { return zoomDigi+zoomReal; } void MapGraphicItem::SetZoom(double const& value) { if(ZoomTotal() != value) { if(value > MaxZoom()) { zoomReal = MaxZoom(); zoomDigi =value-MaxZoom(); } else if(value < MinZoom()) { zoomDigi=0; zoomReal = MinZoom(); } else { zoomDigi=0; zoomReal = value; } double integer; double remainder = modf (value , &integer); if(zoomDigi!=0||remainder != 0) { float scaleValue = zoomDigi+remainder + 1; { MapRenderTransform = scaleValue; // qDebug()<<"scale="<<scaleValue<<"zoomdigi:"<<ZoomDigi()<<"integer:"<<integer; } if(integer>MaxZoom()) integer=MaxZoom(); SetZoomStep((qint32)(integer)); // core->GoToCurrentPositionOnZoom(); this->update(); } else { MapRenderTransform = 1; SetZoomStep ((qint32)(value)); zoomReal = ZoomStep(); this->update(); } } } int MapGraphicItem::ZoomStep()const { return core->Zoom(); } void MapGraphicItem::SetZoomStep(int const& value) { if(value-core->Zoom()>0 && value<= MaxZoom()) ConstructLastImage(value-core->Zoom()); else if(value!=MaxZoom()) lastimage=QImage(); if(value > MaxZoom()) { core->SetZoom(MaxZoom()); emit zoomChanged(MaxZoom()+ZoomDigi(),Zoom(),ZoomDigi()); } else if(value < MinZoom()) { core->SetZoom(MinZoom()); emit zoomChanged(MinZoom()+ZoomDigi(),Zoom(),ZoomDigi()); } else { core->SetZoom(value); emit zoomChanged(value+ZoomDigi(),Zoom(),ZoomDigi());; } } void MapGraphicItem::Offset(int const& x, int const& y) { core->DragOffset(Point(x, y)); } void MapGraphicItem::mapRotate(qreal angle) { if (rotation != angle) { rotation=angle; resize(scene()->sceneRect()); } } QRectF MapGraphicItem::boundingBox(const QRectF &rect, const qreal &angle) { QRectF ret(rect); float c=cos(angle*2*M_PI/360); float s=sin(angle*2*M_PI/360); ret.setHeight(rect.height()*fabs(c)+rect.width()*fabs(s)); ret.setWidth(rect.width()*fabs(c)+rect.height()*fabs(s)); return ret; } QSize MapGraphicItem::sizeHint()const { core::Size size=core->projection->GetTileMatrixMaxXY(MinZoom()); core::Size tilesize=core->projection->TileSize(); QSize rsize((size.Width()+1)*tilesize.Width(),(size.Height()+1)*tilesize.Height()); return rsize; } }
// Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/local_function #ifndef BOOST_LOCAL_FUNCTION_AUX_MEMBER_HPP_ #define BOOST_LOCAL_FUNCTION_AUX_MEMBER_HPP_ namespace boost { namespace local_function { namespace aux { // Metafunctions to manipulate data members. template <typename T> struct member_type { typedef T &reference; typedef T *pointer; }; template <typename T> struct member_type<T *> { typedef T *&reference; typedef T *pointer; }; template <typename T> struct member_type<T *const> { typedef T *const &reference; typedef T *pointer; }; template <typename T> struct member_type<T const *> { typedef T const *&reference; typedef T const *pointer; }; template <typename T> struct member_type<T const *const> { typedef T const *const &reference; typedef T const *pointer; }; // NOTE: Do not add specializations for T const[&/*] (ambiguous on VACPP). template <typename T> T *member_addr(T &data) { return &data; } template <typename T> T *member_addr(T *data) { return data; } // NOTE: Do not add specializations for T const[&/*] (ambiguous on VACPP). template <typename T> T &member_deref(T &data) { return data; } template <typename T> T &member_deref(T *data) { return *data; } } // namespace aux } // namespace local_function } // namespace boost #endif // #include guard
// // Created by andgel on 31/01/2020 // #include "Warrior.hpp" namespace DungeonIntern { Warrior::Warrior(Rendering::Screen &screen, Map &map, float maxSpeed, float x, float y, unsigned sx, unsigned sy, unsigned maxHealth) : Enemy({screen, "assets/entities/warrior.json", map}, <#initializer#>, maxSpeed, x, y, sx, sy, maxHealth) {} void Warrior::update() { } }
/*********************************************************************** created: 20/8/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "Demo6.h" #include "CEGUI/CEGUI.h" #include <stdlib.h> #include <stdio.h> #include <string> using namespace CEGUI; Demo6Sample::Demo6Sample() { Sample::d_name = "Demo6Sample"; Sample::d_credits = "The CEGUI team"; Sample::d_summary = "Demo6Sample"; Sample::d_description = "Demo6Sample"; } /************************************************************************* Sample specific initialisation goes here. *************************************************************************/ bool Demo6Sample::initialise(CEGUI::GUIContext* guiContext) { d_usedFiles = CEGUI::String(__FILE__); // we will use of the WindowManager. WindowManager& winMgr = WindowManager::getSingleton(); // load scheme and set up defaults SchemeManager::getSingleton().createFromFile("TaharezLook.scheme"); guiContext->getCursor().setDefaultImage("TaharezLook/MouseArrow"); // load font and setup default if not loaded via scheme FontManager::FontList loadedFonts = FontManager::getSingleton().createFromFile("DejaVuSans-12.font"); Font* defaultFont = loadedFonts.empty() ? 0 : loadedFonts.front(); // Set default font for the gui context guiContext->setDefaultFont(defaultFont); // load an image to use as a background if (!ImageManager::getSingleton().isDefined("SpaceBackgroundImage")) ImageManager::getSingleton().addBitmapImageFromFile("SpaceBackgroundImage", "SpaceBackground.jpg"); // here we will use a StaticImage as the root, then we can use it to place a background image Window* background = winMgr.createWindow("TaharezLook/StaticImage", "root_wnd"); // set position and size background->setPosition(UVector2(cegui_reldim(0), cegui_reldim(0))); background->setSize(USize(cegui_reldim(1), cegui_reldim(1))); // disable frame and standard background background->setProperty("FrameEnabled", "false"); background->setProperty("BackgroundEnabled", "false"); // set the background image background->setProperty("Image", "SpaceBackgroundImage"); // install this as the root GUI sheet guiContext->setRootWindow(background); // do demo stuff createDemoWindows(background); initDemoEventWiring(background); // success! return true; } /************************************************************************* Cleans up resources allocated in the initialiseSample call. *************************************************************************/ void Demo6Sample::deinitialise() { // nothing to do here! } /************************************************************************* Create the windows and widgets for the demo *************************************************************************/ void Demo6Sample::createDemoWindows(CEGUI::Window* root) { using namespace CEGUI; WindowManager& winMgr = WindowManager::getSingleton(); // create the main list. MultiColumnList* mcl = static_cast<MultiColumnList*>(winMgr.createWindow("TaharezLook/MultiColumnList", "MainList")); root->addChild(mcl); mcl->setPosition(UVector2(cegui_reldim(0.01f), cegui_reldim(0.1f))); mcl->setSize(USize(cegui_reldim(0.5f), cegui_reldim(0.8f))); // create frame window for control panel FrameWindow* fwnd = static_cast<FrameWindow*>(winMgr.createWindow("TaharezLook/FrameWindow", "ControlPanel")); root->addChild(fwnd); fwnd->setPosition(UVector2(cegui_reldim(0.53f), cegui_reldim(0.03f))); fwnd->setMaxSize(USize(cegui_reldim(1.0f), cegui_reldim(1.0f))); fwnd->setSize(USize(cegui_reldim(0.44f), cegui_reldim(0.94f))); fwnd->setText("Demo 6 - Control Panel"); // create combo-box. Combobox* cbbo = static_cast<Combobox*>(winMgr.createWindow("TaharezLook/Combobox", "SelModeBox")); fwnd->addChild(cbbo); cbbo->setPosition(UVector2(cegui_reldim(0.04f), cegui_reldim(0.06f))); cbbo->setSize(USize(cegui_reldim(0.66f), cegui_reldim(0.33f))); //cbbo->setSortingEnabled(true); // populate combobox with possible selection modes cbbo->addItem(new StandardItem("Full Row (Single)", 0)); cbbo->addItem(new StandardItem("Full Row (Multiple)", 1)); cbbo->addItem(new StandardItem("Full Column (Single)", 2)); cbbo->addItem(new StandardItem("Full Column (Multiple)", 3)); cbbo->addItem(new StandardItem("Single Cell (Single)", 4)); cbbo->addItem(new StandardItem("Single Cell (Multiple)", 5)); cbbo->addItem(new StandardItem("Nominated Column (Single)", 6)); StandardItem* pStore = new StandardItem("Nominated Column (Multiple)", 7); cbbo->addItem(pStore); cbbo->addItem(new StandardItem("Nominated Row (Single)", 8)); cbbo->addItem(new StandardItem("Nominated Row (Multiple)", 9)); cbbo->setReadOnly(true); // Now change the text to test the sorting pStore->setText("Abracadabra"); cbbo->setSortingEnabled(true); cbbo->handleUpdatedListItemData(); // column control section Window* st = winMgr.createWindow("TaharezLook/StaticText", "ColumnPanel"); fwnd->addChild(st); st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.12f))); st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Column Control"); st->setProperty("VertFormatting", "TopAligned"); Window* label = winMgr.createWindow("TaharezLook/StaticText", "Label1"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("ID Code:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label2"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Width:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label3"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Caption:"); PushButton* btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "AddColButton")); st->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Add"); Editbox* ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "NewColIDBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox->setText("Test -- "); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "NewColWidthBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "NewColTextBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); label = winMgr.createWindow("TaharezLook/StaticText", "Label4"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("ID Code:"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "DelColIDBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "DelColButton")); st->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.67f))); btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim(0.2f))); btn->setText("Delete Column"); // Row control box st = winMgr.createWindow("TaharezLook/StaticText", "RowControl"); fwnd->addChild(st); st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.38f))); st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Row Control"); st->setProperty("VertFormatting", "TopAligned"); label = winMgr.createWindow("TaharezLook/StaticText", "Label5"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Col ID:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label6"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.55f), cegui_reldim(0.12f))); label->setText("Item Text:"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "RowColIDBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "RowTextBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.55f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "AddRowButton")); st->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Add"); label = winMgr.createWindow("TaharezLook/StaticText", "Label7"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Row Idx:"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "DelRowIdxBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "DelRowButton")); st->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.67f))); btn->setSize(USize(cegui_reldim(0.4f), cegui_reldim(0.2f))); btn->setText("Delete Row"); // set item box st = winMgr.createWindow("TaharezLook/StaticText", "SetItemPanel"); fwnd->addChild(st); st->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.65f))); st->setSize(USize(cegui_reldim(0.96f), cegui_reldim(0.25f))); st->setText("Item Modification"); st->setProperty("VertFormatting", "TopAligned"); label = winMgr.createWindow("TaharezLook/StaticText", "Label8"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Row Idx:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label9"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Col ID:"); label = winMgr.createWindow("TaharezLook/StaticText", "Label10"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.2f))); label->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.12f))); label->setText("Item Text:"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "SetItemRowBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "SetItemIDBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.23f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.2f), cegui_reldim(0.2f))); ebox->setValidationString("\\d*"); ebox = static_cast<Editbox*>(winMgr.createWindow("TaharezLook/Editbox", "SetItemTextBox")); st->addChild(ebox); ebox->setPosition(UVector2(cegui_reldim(0.44f), cegui_reldim(0.32f))); ebox->setSize(USize(cegui_reldim(0.36f), cegui_reldim(0.2f))); ebox->setValidationString(".*"); btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "SetItemButton")); st->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.81f), cegui_reldim(0.32f))); btn->setSize(USize(cegui_reldim(0.15f), cegui_reldim(0.2f))); btn->setText("Set"); label = winMgr.createWindow("TaharezLook/StaticText", "RowCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.55f))); label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Row Count:"); label = winMgr.createWindow("TaharezLook/StaticText", "ColCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.67f))); label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Column Count:"); label = winMgr.createWindow("TaharezLook/StaticText", "SelCount"); st->addChild(label); label->setProperty("FrameEnabled", "false"); label->setProperty("BackgroundEnabled", "false"); label->setPosition(UVector2(cegui_reldim(0.02f), cegui_reldim(0.79f))); label->setSize(USize(cegui_reldim(1.0f), cegui_reldim(0.12f))); label->setText("Current Selected Count:"); btn = static_cast<PushButton*>(winMgr.createWindow("TaharezLook/Button", "QuitButton")); fwnd->addChild(btn); btn->setPosition(UVector2(cegui_reldim(0.25f), cegui_reldim(0.93f))); btn->setSize(USize(cegui_reldim(0.50f), cegui_reldim(0.05f))); btn->setText("Quit This Demo!"); } void Demo6Sample::initDemoEventWiring(CEGUI::Window* root) { using namespace CEGUI; // subscribe handler that adds a new column root->getChild("ControlPanel/ColumnPanel/AddColButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleAddColumn, this)); // subscribe handler that deletes a column root->getChild("ControlPanel/ColumnPanel/DelColButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleDeleteColumn, this)); // subscribe handler that adds a new row root->getChild("ControlPanel/RowControl/AddRowButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleAddRow, this)); // subscribe handler that deletes a row root->getChild("ControlPanel/RowControl/DelRowButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleDeleteRow, this)); // subscribe handler that sets the text for an existing item root->getChild("ControlPanel/SetItemPanel/SetItemButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleSetItem, this)); // subscribe handler that quits the application root->getChild("ControlPanel/QuitButton")-> subscribeEvent(PushButton::EventClicked, Event::Subscriber(&Demo6Sample::handleQuit, this)); // subscribe handler that processes a change in the 'selection mode' combobox root->getChild("ControlPanel/SelModeBox")-> subscribeEvent(Combobox::EventListSelectionAccepted, Event::Subscriber(&Demo6Sample::handleSelectModeChanged, this)); // subscribe handler that processes a change in the item(s) selected in the list root->getChild("MainList")-> subscribeEvent(MultiColumnList::EventSelectionChanged, Event::Subscriber(&Demo6Sample::handleSelectChanged, this)); // subscribe handler that processes a change in the list content. root->getChild("MainList")-> subscribeEvent(MultiColumnList::EventListContentsChanged, Event::Subscriber(&Demo6Sample::handleContentsChanged, this)); } bool Demo6Sample::handleQuit(const CEGUI::EventArgs&) { // event was handled return true; } bool Demo6Sample::handleAddColumn(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to the widgets that contain details about the column to add MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Editbox* idbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/ColumnPanel/NewColIDBox")); Editbox* widthbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/ColumnPanel/NewColWidthBox")); Editbox* textbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/ColumnPanel/NewColTextBox")); // get ID for new column unsigned int id = atoi(idbox->getText().c_str()); // get width to use for new column (in pixels) float width = static_cast<float>(atof(widthbox->getText().c_str())); // get column label text String text = textbox->getText(); // re-set the widget contents idbox->setText(""); widthbox->setText(""); textbox->setText(""); // ensure a minimum width of 10 pixels if (width < 10.0f) width = 10.0f; // finally, add the new column to the list. mcl->addColumn(text, id, cegui_absdim(width)); // event was handled. return true; } bool Demo6Sample::handleDeleteColumn(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to the widgets that contain details about the column to delete MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Editbox* idbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/ColumnPanel/DelColIDBox")); // obtain the id of the column to be deleted unsigned int id = atoi(idbox->getText().c_str()); // attempt to delete the column, ignoring any errors. try { mcl->removeColumnWithID(id); } catch (InvalidRequestException) {} // reset the delete column ID box. idbox->setText(""); // event was handled. return true; } bool Demo6Sample::handleAddRow(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to the widgets that contain details about the row to add MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Editbox* idbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/RowControl/RowColIDBox")); Editbox* textbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/RowControl/RowTextBox")); // get the ID of the initial column item to set unsigned int id = atoi(idbox->getText().c_str()); // get the text that is to be set initially into the specified column of the new row String text = textbox->getText(); // reset input boxes idbox->setText(""); textbox->setText(""); // construct a new ListboxTextItem with the required string ListboxTextItem* item = new ListboxTextItem(text); // set the selection brush to use for this item. item->setSelectionBrushImage("TaharezLook/MultiListSelectionBrush"); // attempt to add a new row, using the new ListboxTextItem as the initial content for one of the columns try { mcl->addRow(item, id); } // something went wrong, so cleanup the ListboxTextItem catch (InvalidRequestException) { delete item; } // event was handled. return true; } bool Demo6Sample::handleDeleteRow(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to the widgets that contain details about the row to delete. MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Editbox* idxbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/RowControl/DelRowIdxBox")); // get index of row to delete. unsigned int idx = atoi(idxbox->getText().c_str()); // attempt to delete the row, ignoring any errors. try { mcl->removeRow(idx); } catch (InvalidRequestException) {} // clear the row index box idxbox->setText(""); // event was handled. return true; } bool Demo6Sample::handleSetItem(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to the widgets that contain details about the item to be modified MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Editbox* idbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/SetItemIDBox")); Editbox* rowbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/SetItemRowBox")); Editbox* textbox = static_cast<Editbox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/SetItemTextBox")); // get ID of column to be affected unsigned int id = atoi(idbox->getText().c_str()); // get index of row to be affected unsigned int row = atoi(rowbox->getText().c_str()); // get new text for item String text = textbox->getText(); // reset input boxes idbox->setText(""); rowbox->setText(""); textbox->setText(""); // create a new ListboxTextItem using the new text string ListboxTextItem* item = new ListboxTextItem(text); // set the selection brush to be used for this item. item->setSelectionBrushImage("TaharezLook/MultiListSelectionBrush"); // attempt to set the new item in place try { mcl->setItem(item, id, row); } // something went wrong, so cleanup the ListboxTextItem. catch (InvalidRequestException) { delete item; } // event was handled. return true; } bool Demo6Sample::handleSelectChanged(const CEGUI::EventArgs& args) { using namespace CEGUI; // Get access to the list MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); // update the selected count std::string tmp("Current Selected Count: "); char buff[16]; sprintf(buff, "%d", mcl->getSelectedCount()); tmp += buff; static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/SelCount")->setText(tmp.c_str()); // event was handled. return true; } bool Demo6Sample::handleSelectModeChanged(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to list MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); // get access to the combobox Combobox* combo = static_cast<Combobox*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SelModeBox")); // find the selected item in the combobox StandardItem* item = combo->findItemWithText(combo->getText(), 0); // set new selection mode according to ID of selected ListboxItem if (item) { switch (item->getId()) { case 0: mcl->setSelectionMode(MultiColumnList::RowSingle); break; case 1: mcl->setSelectionMode(MultiColumnList::RowMultiple); break; case 2: mcl->setSelectionMode(MultiColumnList::ColumnSingle); break; case 3: mcl->setSelectionMode(MultiColumnList::ColumnMultiple); break; case 4: mcl->setSelectionMode(MultiColumnList::CellSingle); break; case 5: mcl->setSelectionMode(MultiColumnList::CellMultiple); break; case 6: mcl->setSelectionMode(MultiColumnList::NominatedColumnSingle); break; case 7: mcl->setSelectionMode(MultiColumnList::NominatedColumnMultiple); break; case 8: mcl->setSelectionMode(MultiColumnList::NominatedRowSingle); break; case 9: mcl->setSelectionMode(MultiColumnList::NominatedRowMultiple); break; default: mcl->setSelectionMode(MultiColumnList::RowSingle); break; } } // event was handled. return true; } bool Demo6Sample::handleContentsChanged(const CEGUI::EventArgs& args) { using namespace CEGUI; // get access to required widgets MultiColumnList* mcl = static_cast<MultiColumnList*>(static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("MainList")); Window* colText = static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/ColCount"); Window* rowText = static_cast<const WindowEventArgs&>(args).window->getRootWindow()->getChild("ControlPanel/SetItemPanel/RowCount"); std::string tmp; char buff[16]; // update the column count tmp = "Current Column Count: "; sprintf(buff, "%d", mcl->getColumnCount()); tmp += buff; colText->setText(tmp.c_str()); // update the row count tmp = "Current Row Count: "; sprintf(buff, "%d", mcl->getRowCount()); tmp += buff; rowText->setText(tmp.c_str()); // event was handled. return true; }
#pragma once #include "./abs_recv_allocator.hh" namespace rdmaio { namespace qp { /*! helper data struture for two-sided QP recv */ template <usize N> struct RecvEntries { /*! internal data structure used for send/recv verbs */ struct ibv_recv_wr rs[N]; struct ibv_sge sges[N]; struct ibv_wc wcs[N]; /*! current recv entry which points to one position in *rs* */ usize header = 0; ibv_recv_wr *wr_ptr(const usize &idx) { // idx should be in [0,N) return rs + idx; } ibv_recv_wr *header_ptr() { return wr_ptr(header); } void sanity_check() { for (uint i = 0; i < N - 1; ++i) { RDMA_ASSERT((u64)(wr_ptr(i)->next) == (u64)(wr_ptr(i + 1))); RDMA_ASSERT((u64)(wr_ptr(i)->sg_list) == (u64)(&sges[i])); RDMA_ASSERT(wr_ptr(i)->num_sge == 1); } } }; // AbsAllocator must inherit from *AbsRecvAllocator* defined in // abs_recv_allocator.hh template <class AbsAllocator, usize N, usize entry_sz> class RecvEntriesFactory { public: static Arc<RecvEntries<N>> create(AbsAllocator &allocator) { Arc<RecvEntries<N>> ret(new RecvEntries<N>); for (uint i = 0; i < N; ++i) { auto recv_buf = allocator.alloc_one(entry_sz).value(); struct ibv_sge sge = { .addr = reinterpret_cast<uintptr_t>(std::get<0>(recv_buf)), .length = static_cast<u32>(entry_sz), .lkey = std::get<1>(recv_buf)}; { // unsafe code ret->rs[i].wr_id = sge.addr; ret->rs[i].sg_list = &(ret->sges[i]); ret->rs[i].num_sge = 1; ret->rs[i].next = (i < N - 1) ? (&(ret->rs[i + 1])) : (&(ret->rs[0])); ret->sges[i] = sge; } } return ret; } }; /*! This version only uses one template: N */ template <usize N> class RecvEntriesFactoryv2 { public: static Arc<RecvEntries<N>> create(Arc<AbsRecvAllocator> &alloc_p, const usize &msg_sz) { Arc<RecvEntries<N>> ret(new RecvEntries<N>); for (uint i = 0; i < N; ++i) { auto recv_buf = alloc_p->alloc_one(msg_sz).value(); struct ibv_sge sge = { .addr = reinterpret_cast<uintptr_t>(std::get<0>(recv_buf)), .length = static_cast<u32>(msg_sz), .lkey = std::get<1>(recv_buf)}; { // unsafe code ret->rs[i].wr_id = sge.addr; ret->rs[i].sg_list = &(ret->sges[i]); ret->rs[i].num_sge = 1; ret->rs[i].next = (i < N - 1) ? (&(ret->rs[i + 1])) : (&(ret->rs[0])); ret->sges[i] = sge; } } return ret; } }; } // namespace qp } // namespace rdmaio
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_MATH_FACTORIAL_HPP #define SPROUT_MATH_FACTORIAL_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/workaround/std/cstddef.hpp> #include <sprout/cstdint.hpp> #include <sprout/array/array.hpp> #include <sprout/type_traits/is_sint.hpp> #include <sprout/type_traits/is_uint.hpp> #include <sprout/assert.hpp> namespace sprout { namespace math { namespace detail { # define SPROUT_FACTORIAL_TABLE_DEF_INT_1 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_UINT_1 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_INT_2 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120, \ 720, \ 5040 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_UINT_2 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120, \ 720, \ 5040, \ 40320 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_INT_4 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120, \ 720, \ 5040, \ 40320, \ 362880, \ 3628800, \ 39916800 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_UINT_4 \ {{ \ 1, \ 1, \ 2, \ 6, \ 24, \ 120, \ 720, \ 5040, \ 40320, \ 362880, \ 3628800, \ 39916800 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_INT_8 \ {{ \ SPROUT_INT64_C(1), \ SPROUT_INT64_C(1), \ SPROUT_INT64_C(2), \ SPROUT_INT64_C(6), \ SPROUT_INT64_C(24), \ SPROUT_INT64_C(120), \ SPROUT_INT64_C(720), \ SPROUT_INT64_C(5040), \ SPROUT_INT64_C(40320), \ SPROUT_INT64_C(362880), \ SPROUT_INT64_C(3628800), \ SPROUT_INT64_C(39916800), \ SPROUT_INT64_C(479001600), \ SPROUT_INT64_C(6227020800), \ SPROUT_INT64_C(87178291200), \ SPROUT_INT64_C(1307674368000), \ SPROUT_INT64_C(20922789888000), \ SPROUT_INT64_C(355687428096000), \ SPROUT_INT64_C(6402373705728000), \ SPROUT_INT64_C(121645100408832000), \ SPROUT_INT64_C(2432902008176640000) \ }} # define SPROUT_FACTORIAL_TABLE_DEF_UINT_8 \ {{ \ SPROUT_UINT64_C(1), \ SPROUT_UINT64_C(1), \ SPROUT_UINT64_C(2), \ SPROUT_UINT64_C(6), \ SPROUT_UINT64_C(24), \ SPROUT_UINT64_C(120), \ SPROUT_UINT64_C(720), \ SPROUT_UINT64_C(5040), \ SPROUT_UINT64_C(40320), \ SPROUT_UINT64_C(362880), \ SPROUT_UINT64_C(3628800), \ SPROUT_UINT64_C(39916800), \ SPROUT_UINT64_C(479001600), \ SPROUT_UINT64_C(6227020800), \ SPROUT_UINT64_C(87178291200), \ SPROUT_UINT64_C(1307674368000), \ SPROUT_UINT64_C(20922789888000), \ SPROUT_UINT64_C(355687428096000), \ SPROUT_UINT64_C(6402373705728000), \ SPROUT_UINT64_C(121645100408832000), \ SPROUT_UINT64_C(2432902008176640000) \ }} # define SPROUT_FACTORIAL_TABLE_DEF_FLOAT \ {{ \ 1.0F, \ 1.0F, \ 2.0F, \ 6.0F, \ 24.0F, \ 120.0F, \ 720.0F, \ 5040.0F, \ 40320.0F, \ 362880.0F, \ 3628800.0F, \ 39916800.0F, \ 479001600.0F, \ 6227020800.0F, \ 87178291200.0F, \ 1307674368000.0F, \ 20922789888000.0F, \ 355687428096000.0F, \ 6402373705728000.0F, \ 121645100408832000.0F, \ 0.243290200817664e19F, \ 0.5109094217170944e20F, \ 0.112400072777760768e22F, \ 0.2585201673888497664e23F, \ 0.62044840173323943936e24F, \ 0.15511210043330985984e26F, \ 0.403291461126605635584e27F, \ 0.10888869450418352160768e29F, \ 0.304888344611713860501504e30F, \ 0.8841761993739701954543616e31F, \ 0.26525285981219105863630848e33F, \ 0.822283865417792281772556288e34F, \ 0.26313083693369353016721801216e36F, \ 0.868331761881188649551819440128e37F, \ 0.29523279903960414084761860964352e39F \ }} # define SPROUT_FACTORIAL_TABLE_DEF_DOUBLE \ {{ \ 1.0, \ 1.0, \ 2.0, \ 6.0, \ 24.0, \ 120.0, \ 720.0, \ 5040.0, \ 40320.0, \ 362880.0, \ 3628800.0, \ 39916800.0, \ 479001600.0, \ 6227020800.0, \ 87178291200.0, \ 1307674368000.0, \ 20922789888000.0, \ 355687428096000.0, \ 6402373705728000.0, \ 121645100408832000.0, \ 0.243290200817664e19, \ 0.5109094217170944e20, \ 0.112400072777760768e22, \ 0.2585201673888497664e23, \ 0.62044840173323943936e24, \ 0.15511210043330985984e26, \ 0.403291461126605635584e27, \ 0.10888869450418352160768e29, \ 0.304888344611713860501504e30, \ 0.8841761993739701954543616e31, \ 0.26525285981219105863630848e33, \ 0.822283865417792281772556288e34, \ 0.26313083693369353016721801216e36, \ 0.868331761881188649551819440128e37, \ 0.29523279903960414084761860964352e39, \ 0.103331479663861449296666513375232e41, \ 0.3719933267899012174679994481508352e42, \ 0.137637530912263450463159795815809024e44, \ 0.5230226174666011117600072241000742912e45, \ 0.203978820811974433586402817399028973568e47, \ 0.815915283247897734345611269596115894272e48, \ 0.3345252661316380710817006205344075166515e50, \ 0.1405006117752879898543142606244511569936e52, \ 0.6041526306337383563735513206851399750726e53, \ 0.265827157478844876804362581101461589032e55, \ 0.1196222208654801945619631614956577150644e57, \ 0.5502622159812088949850305428800254892962e58, \ 0.2586232415111681806429643551536119799692e60, \ 0.1241391559253607267086228904737337503852e62, \ 0.6082818640342675608722521633212953768876e63, \ 0.3041409320171337804361260816606476884438e65, \ 0.1551118753287382280224243016469303211063e67, \ 0.8065817517094387857166063685640376697529e68, \ 0.427488328406002556429801375338939964969e70, \ 0.2308436973392413804720927426830275810833e72, \ 0.1269640335365827592596510084756651695958e74, \ 0.7109985878048634518540456474637249497365e75, \ 0.4052691950487721675568060190543232213498e77, \ 0.2350561331282878571829474910515074683829e79, \ 0.1386831185456898357379390197203894063459e81, \ 0.8320987112741390144276341183223364380754e82, \ 0.507580213877224798800856812176625227226e84, \ 0.3146997326038793752565312235495076408801e86, \ 0.1982608315404440064116146708361898137545e88, \ 0.1268869321858841641034333893351614808029e90, \ 0.8247650592082470666723170306785496252186e91, \ 0.5443449390774430640037292402478427526443e93, \ 0.3647111091818868528824985909660546442717e95, \ 0.2480035542436830599600990418569171581047e97, \ 0.1711224524281413113724683388812728390923e99, \ 0.1197857166996989179607278372168909873646e101, \ 0.8504785885678623175211676442399260102886e102, \ 0.6123445837688608686152407038527467274078e104, \ 0.4470115461512684340891257138125051110077e106, \ 0.3307885441519386412259530282212537821457e108, \ 0.2480914081139539809194647711659403366093e110, \ 0.188549470166605025498793226086114655823e112, \ 0.1451830920282858696340707840863082849837e114, \ 0.1132428117820629783145752115873204622873e116, \ 0.8946182130782975286851441715398316520698e117, \ 0.7156945704626380229481153372318653216558e119, \ 0.5797126020747367985879734231578109105412e121, \ 0.4753643337012841748421382069894049466438e123, \ 0.3945523969720658651189747118012061057144e125, \ 0.3314240134565353266999387579130131288001e127, \ 0.2817104114380550276949479442260611594801e129, \ 0.2422709538367273238176552320344125971528e131, \ 0.210775729837952771721360051869938959523e133, \ 0.1854826422573984391147968456455462843802e135, \ 0.1650795516090846108121691926245361930984e137, \ 0.1485715964481761497309522733620825737886e139, \ 0.1352001527678402962551665687594951421476e141, \ 0.1243841405464130725547532432587355307758e143, \ 0.1156772507081641574759205162306240436215e145, \ 0.1087366156656743080273652852567866010042e147, \ 0.103299784882390592625997020993947270954e149, \ 0.9916779348709496892095714015418938011582e150, \ 0.9619275968248211985332842594956369871234e152, \ 0.942689044888324774562618574305724247381e154, \ 0.9332621544394415268169923885626670049072e156, \ 0.9332621544394415268169923885626670049072e158, \ 0.9425947759838359420851623124482936749562e160, \ 0.9614466715035126609268655586972595484554e162, \ 0.990290071648618040754671525458177334909e164, \ 0.1029901674514562762384858386476504428305e167, \ 0.1081396758240290900504101305800329649721e169, \ 0.1146280563734708354534347384148349428704e171, \ 0.1226520203196137939351751701038733888713e173, \ 0.132464181945182897449989183712183259981e175, \ 0.1443859583202493582204882102462797533793e177, \ 0.1588245541522742940425370312709077287172e179, \ 0.1762952551090244663872161047107075788761e181, \ 0.1974506857221074023536820372759924883413e183, \ 0.2231192748659813646596607021218715118256e185, \ 0.2543559733472187557120132004189335234812e187, \ 0.2925093693493015690688151804817735520034e189, \ 0.339310868445189820119825609358857320324e191, \ 0.396993716080872089540195962949863064779e193, \ 0.4684525849754290656574312362808384164393e195, \ 0.5574585761207605881323431711741977155627e197, \ 0.6689502913449127057588118054090372586753e199, \ 0.8094298525273443739681622845449350829971e201, \ 0.9875044200833601362411579871448208012564e203, \ 0.1214630436702532967576624324188129585545e206, \ 0.1506141741511140879795014161993280686076e208, \ 0.1882677176888926099743767702491600857595e210, \ 0.237217324288004688567714730513941708057e212, \ 0.3012660018457659544809977077527059692324e214, \ 0.3856204823625804217356770659234636406175e216, \ 0.4974504222477287440390234150412680963966e218, \ 0.6466855489220473672507304395536485253155e220, \ 0.8471580690878820510984568758152795681634e222, \ 0.1118248651196004307449963076076169029976e225, \ 0.1487270706090685728908450891181304809868e227, \ 0.1992942746161518876737324194182948445223e229, \ 0.269047270731805048359538766214698040105e231, \ 0.3659042881952548657689727220519893345429e233, \ 0.5012888748274991661034926292112253883237e235, \ 0.6917786472619488492228198283114910358867e237, \ 0.9615723196941089004197195613529725398826e239, \ 0.1346201247571752460587607385894161555836e242, \ 0.1898143759076170969428526414110767793728e244, \ 0.2695364137888162776588507508037290267094e246, \ 0.3854370717180072770521565736493325081944e248, \ 0.5550293832739304789551054660550388118e250, \ 0.80479260574719919448490292577980627711e252, \ 0.1174997204390910823947958271638517164581e255, \ 0.1727245890454638911203498659308620231933e257, \ 0.2556323917872865588581178015776757943262e259, \ 0.380892263763056972698595524350736933546e261, \ 0.571338395644585459047893286526105400319e263, \ 0.8627209774233240431623188626544191544816e265, \ 0.1311335885683452545606724671234717114812e268, \ 0.2006343905095682394778288746989117185662e270, \ 0.308976961384735088795856467036324046592e272, \ 0.4789142901463393876335775239063022722176e274, \ 0.7471062926282894447083809372938315446595e276, \ 0.1172956879426414428192158071551315525115e279, \ 0.1853271869493734796543609753051078529682e281, \ 0.2946702272495038326504339507351214862195e283, \ 0.4714723635992061322406943211761943779512e285, \ 0.7590705053947218729075178570936729485014e287, \ 0.1229694218739449434110178928491750176572e290, \ 0.2004401576545302577599591653441552787813e292, \ 0.3287218585534296227263330311644146572013e294, \ 0.5423910666131588774984495014212841843822e296, \ 0.9003691705778437366474261723593317460744e298, \ 0.1503616514864999040201201707840084015944e301, \ 0.2526075744973198387538018869171341146786e303, \ 0.4269068009004705274939251888899566538069e305, \ 0.7257415615307998967396728211129263114717e307 \ }} # define SPROUT_FACTORIAL_TABLE_DEF_LONG_DOUBLE \ {{ \ 1.0L, \ 1.0L, \ 2.0L, \ 6.0L, \ 24.0L, \ 120.0L, \ 720.0L, \ 5040.0L, \ 40320.0L, \ 362880.0L, \ 3628800.0L, \ 39916800.0L, \ 479001600.0L, \ 6227020800.0L, \ 87178291200.0L, \ 1307674368000.0L, \ 20922789888000.0L, \ 355687428096000.0L, \ 6402373705728000.0L, \ 121645100408832000.0L, \ 0.243290200817664e19L, \ 0.5109094217170944e20L, \ 0.112400072777760768e22L, \ 0.2585201673888497664e23L, \ 0.62044840173323943936e24L, \ 0.15511210043330985984e26L, \ 0.403291461126605635584e27L, \ 0.10888869450418352160768e29L, \ 0.304888344611713860501504e30L, \ 0.8841761993739701954543616e31L, \ 0.26525285981219105863630848e33L, \ 0.822283865417792281772556288e34L, \ 0.26313083693369353016721801216e36L, \ 0.868331761881188649551819440128e37L, \ 0.29523279903960414084761860964352e39L, \ 0.103331479663861449296666513375232e41L, \ 0.3719933267899012174679994481508352e42L, \ 0.137637530912263450463159795815809024e44L, \ 0.5230226174666011117600072241000742912e45L, \ 0.203978820811974433586402817399028973568e47L, \ 0.815915283247897734345611269596115894272e48L, \ 0.3345252661316380710817006205344075166515e50L, \ 0.1405006117752879898543142606244511569936e52L, \ 0.6041526306337383563735513206851399750726e53L, \ 0.265827157478844876804362581101461589032e55L, \ 0.1196222208654801945619631614956577150644e57L, \ 0.5502622159812088949850305428800254892962e58L, \ 0.2586232415111681806429643551536119799692e60L, \ 0.1241391559253607267086228904737337503852e62L, \ 0.6082818640342675608722521633212953768876e63L, \ 0.3041409320171337804361260816606476884438e65L, \ 0.1551118753287382280224243016469303211063e67L, \ 0.8065817517094387857166063685640376697529e68L, \ 0.427488328406002556429801375338939964969e70L, \ 0.2308436973392413804720927426830275810833e72L, \ 0.1269640335365827592596510084756651695958e74L, \ 0.7109985878048634518540456474637249497365e75L, \ 0.4052691950487721675568060190543232213498e77L, \ 0.2350561331282878571829474910515074683829e79L, \ 0.1386831185456898357379390197203894063459e81L, \ 0.8320987112741390144276341183223364380754e82L, \ 0.507580213877224798800856812176625227226e84L, \ 0.3146997326038793752565312235495076408801e86L, \ 0.1982608315404440064116146708361898137545e88L, \ 0.1268869321858841641034333893351614808029e90L, \ 0.8247650592082470666723170306785496252186e91L, \ 0.5443449390774430640037292402478427526443e93L, \ 0.3647111091818868528824985909660546442717e95L, \ 0.2480035542436830599600990418569171581047e97L, \ 0.1711224524281413113724683388812728390923e99L, \ 0.1197857166996989179607278372168909873646e101L, \ 0.8504785885678623175211676442399260102886e102L, \ 0.6123445837688608686152407038527467274078e104L, \ 0.4470115461512684340891257138125051110077e106L, \ 0.3307885441519386412259530282212537821457e108L, \ 0.2480914081139539809194647711659403366093e110L, \ 0.188549470166605025498793226086114655823e112L, \ 0.1451830920282858696340707840863082849837e114L, \ 0.1132428117820629783145752115873204622873e116L, \ 0.8946182130782975286851441715398316520698e117L, \ 0.7156945704626380229481153372318653216558e119L, \ 0.5797126020747367985879734231578109105412e121L, \ 0.4753643337012841748421382069894049466438e123L, \ 0.3945523969720658651189747118012061057144e125L, \ 0.3314240134565353266999387579130131288001e127L, \ 0.2817104114380550276949479442260611594801e129L, \ 0.2422709538367273238176552320344125971528e131L, \ 0.210775729837952771721360051869938959523e133L, \ 0.1854826422573984391147968456455462843802e135L, \ 0.1650795516090846108121691926245361930984e137L, \ 0.1485715964481761497309522733620825737886e139L, \ 0.1352001527678402962551665687594951421476e141L, \ 0.1243841405464130725547532432587355307758e143L, \ 0.1156772507081641574759205162306240436215e145L, \ 0.1087366156656743080273652852567866010042e147L, \ 0.103299784882390592625997020993947270954e149L, \ 0.9916779348709496892095714015418938011582e150L, \ 0.9619275968248211985332842594956369871234e152L, \ 0.942689044888324774562618574305724247381e154L, \ 0.9332621544394415268169923885626670049072e156L, \ 0.9332621544394415268169923885626670049072e158L, \ 0.9425947759838359420851623124482936749562e160L, \ 0.9614466715035126609268655586972595484554e162L, \ 0.990290071648618040754671525458177334909e164L, \ 0.1029901674514562762384858386476504428305e167L, \ 0.1081396758240290900504101305800329649721e169L, \ 0.1146280563734708354534347384148349428704e171L, \ 0.1226520203196137939351751701038733888713e173L, \ 0.132464181945182897449989183712183259981e175L, \ 0.1443859583202493582204882102462797533793e177L, \ 0.1588245541522742940425370312709077287172e179L, \ 0.1762952551090244663872161047107075788761e181L, \ 0.1974506857221074023536820372759924883413e183L, \ 0.2231192748659813646596607021218715118256e185L, \ 0.2543559733472187557120132004189335234812e187L, \ 0.2925093693493015690688151804817735520034e189L, \ 0.339310868445189820119825609358857320324e191L, \ 0.396993716080872089540195962949863064779e193L, \ 0.4684525849754290656574312362808384164393e195L, \ 0.5574585761207605881323431711741977155627e197L, \ 0.6689502913449127057588118054090372586753e199L, \ 0.8094298525273443739681622845449350829971e201L, \ 0.9875044200833601362411579871448208012564e203L, \ 0.1214630436702532967576624324188129585545e206L, \ 0.1506141741511140879795014161993280686076e208L, \ 0.1882677176888926099743767702491600857595e210L, \ 0.237217324288004688567714730513941708057e212L, \ 0.3012660018457659544809977077527059692324e214L, \ 0.3856204823625804217356770659234636406175e216L, \ 0.4974504222477287440390234150412680963966e218L, \ 0.6466855489220473672507304395536485253155e220L, \ 0.8471580690878820510984568758152795681634e222L, \ 0.1118248651196004307449963076076169029976e225L, \ 0.1487270706090685728908450891181304809868e227L, \ 0.1992942746161518876737324194182948445223e229L, \ 0.269047270731805048359538766214698040105e231L, \ 0.3659042881952548657689727220519893345429e233L, \ 0.5012888748274991661034926292112253883237e235L, \ 0.6917786472619488492228198283114910358867e237L, \ 0.9615723196941089004197195613529725398826e239L, \ 0.1346201247571752460587607385894161555836e242L, \ 0.1898143759076170969428526414110767793728e244L, \ 0.2695364137888162776588507508037290267094e246L, \ 0.3854370717180072770521565736493325081944e248L, \ 0.5550293832739304789551054660550388118e250L, \ 0.80479260574719919448490292577980627711e252L, \ 0.1174997204390910823947958271638517164581e255L, \ 0.1727245890454638911203498659308620231933e257L, \ 0.2556323917872865588581178015776757943262e259L, \ 0.380892263763056972698595524350736933546e261L, \ 0.571338395644585459047893286526105400319e263L, \ 0.8627209774233240431623188626544191544816e265L, \ 0.1311335885683452545606724671234717114812e268L, \ 0.2006343905095682394778288746989117185662e270L, \ 0.308976961384735088795856467036324046592e272L, \ 0.4789142901463393876335775239063022722176e274L, \ 0.7471062926282894447083809372938315446595e276L, \ 0.1172956879426414428192158071551315525115e279L, \ 0.1853271869493734796543609753051078529682e281L, \ 0.2946702272495038326504339507351214862195e283L, \ 0.4714723635992061322406943211761943779512e285L, \ 0.7590705053947218729075178570936729485014e287L, \ 0.1229694218739449434110178928491750176572e290L, \ 0.2004401576545302577599591653441552787813e292L, \ 0.3287218585534296227263330311644146572013e294L, \ 0.5423910666131588774984495014212841843822e296L, \ 0.9003691705778437366474261723593317460744e298L, \ 0.1503616514864999040201201707840084015944e301L, \ 0.2526075744973198387538018869171341146786e303L, \ 0.4269068009004705274939251888899566538069e305L, \ 0.7257415615307998967396728211129263114717e307L \ }} template<typename T, typename Enable = void> struct factorials; template<typename T> struct factorials<T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 1>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 5; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_INT_1) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 1>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 1>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_INT_1); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 1>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 5; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_UINT_1) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 1>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 1>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_UINT_1); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 2>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 7; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_INT_2) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 2>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 2>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_INT_2); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 2>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 8; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_UINT_2) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 2>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 2>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_UINT_2); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 4>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 11; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_INT_4) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 4>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 4>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_INT_4); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 4>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 11; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_UINT_4) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 4>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 4>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_UINT_4); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 8>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 20; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_INT_8) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 8>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_sint<T>::value && sizeof(T) == 8>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_INT_8); template<typename T> struct factorials<T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 8>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 20; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_UINT_8) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 8>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<sprout::is_uint<T>::value && sizeof(T) == 8>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_UINT_8); template<typename T> struct factorials<T, typename std::enable_if<std::is_same<T, float>::value>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 34; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_FLOAT) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, float>::value>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, float>::value>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_FLOAT); template<typename T> struct factorials<T, typename std::enable_if<std::is_same<T, double>::value>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 170; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_DOUBLE) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, double>::value>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, double>::value>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_DOUBLE); template<typename T> struct factorials<T, typename std::enable_if<std::is_same<T, long double>::value>::type> { public: typedef T type; public: SPROUT_STATIC_CONSTEXPR std::size_t limit = 170; public: typedef sprout::array<type, limit + 1> table_type; public: SPROUT_STATIC_CONSTEXPR table_type table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_INNER(SPROUT_FACTORIAL_TABLE_DEF_LONG_DOUBLE) ; }; template<typename T> SPROUT_CONSTEXPR_OR_CONST typename sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, long double>::value>::type >::table_type sprout::math::detail::factorials< T, typename std::enable_if<std::is_same<T, long double>::value>::type >::table SPROUT_STATIC_CONSTEXPR_DATA_MEMBER_OUTER(SPROUT_FACTORIAL_TABLE_DEF_LONG_DOUBLE); # undef SPROUT_FACTORIAL_TABLE_DEF_INT_1 # undef SPROUT_FACTORIAL_TABLE_DEF_UINT_1 # undef SPROUT_FACTORIAL_TABLE_DEF_INT_2 # undef SPROUT_FACTORIAL_TABLE_DEF_UINT_2 # undef SPROUT_FACTORIAL_TABLE_DEF_INT_4 # undef SPROUT_FACTORIAL_TABLE_DEF_UINT_4 # undef SPROUT_FACTORIAL_TABLE_DEF_INT_8 # undef SPROUT_FACTORIAL_TABLE_DEF_UINT_8 # undef SPROUT_FACTORIAL_TABLE_DEF_FLOAT # undef SPROUT_FACTORIAL_TABLE_DEF_DOUBLE # undef SPROUT_FACTORIAL_TABLE_DEF_LONG_DOUBLE } // namespace detail // // factorial_limit // template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> inline SPROUT_CONSTEXPR std::size_t factorial_limit() { typedef typename std::remove_cv<T>::type type; return sprout::math::detail::factorials<type>::limit; } // // unchecked_factorial // template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> inline SPROUT_CONSTEXPR T unchecked_factorial(std::size_t x) { typedef typename std::remove_cv<T>::type type; return sprout::math::detail::factorials<type>::table[x]; } // // factorial // template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type> inline SPROUT_CONSTEXPR T factorial(std::size_t x) { return SPROUT_ASSERT(x <= sprout::math::factorial_limit<typename std::remove_cv<T>::type>()), sprout::math::unchecked_factorial<T>(x) ; } } // namespace math using sprout::math::factorial_limit; using sprout::math::unchecked_factorial; using sprout::math::factorial; } // namespace sprout #endif // #ifndef SPROUT_MATH_FACTORIAL_HPP
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// #include "RocksDBOptionFeature.h" #include "Basics/process-utils.h" #include "Logger/Logger.h" #include "ProgramOptions/ProgramOptions.h" #include "ProgramOptions/Section.h" #include <rocksdb/options.h> #include <rocksdb/table.h> #include <rocksdb/utilities/transaction_db.h> using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::options; namespace { rocksdb::TransactionDBOptions rocksDBTrxDefaults; rocksdb::Options rocksDBDefaults; rocksdb::BlockBasedTableOptions rocksDBTableOptionsDefaults; } RocksDBOptionFeature::RocksDBOptionFeature( application_features::ApplicationServer* server) : application_features::ApplicationFeature(server, "RocksDBOption"), _transactionLockTimeout(rocksDBTrxDefaults.transaction_lock_timeout), _writeBufferSize(rocksDBDefaults.write_buffer_size), _maxWriteBufferNumber(rocksDBDefaults.max_write_buffer_number), _maxTotalWalSize(80 << 20), _delayedWriteRate(rocksDBDefaults.delayed_write_rate), _minWriteBufferNumberToMerge( rocksDBDefaults.min_write_buffer_number_to_merge), _numLevels(rocksDBDefaults.num_levels), _numUncompressedLevels(2), _maxBytesForLevelBase(rocksDBDefaults.max_bytes_for_level_base), _maxBytesForLevelMultiplier( rocksDBDefaults.max_bytes_for_level_multiplier), _maxBackgroundJobs(rocksDBDefaults.max_background_jobs), _maxSubcompactions(rocksDBDefaults.max_subcompactions), _numThreadsHigh(0), _numThreadsLow(0), _blockCacheSize((TRI_PhysicalMemory >= (static_cast<uint64_t>(4) << 30)) ? static_cast<uint64_t>(((TRI_PhysicalMemory - (static_cast<uint64_t>(2) << 30)) * 0.3)) : (256 << 20)), _blockCacheShardBits(-1), _tableBlockSize(std::max(rocksDBTableOptionsDefaults.block_size, static_cast<decltype(rocksDBTableOptionsDefaults.block_size)>(16 * 1024))), _recycleLogFileNum(rocksDBDefaults.recycle_log_file_num), _compactionReadaheadSize(2 * 1024 * 1024),//rocksDBDefaults.compaction_readahead_size _level0CompactionTrigger(2), _level0SlowdownTrigger(rocksDBDefaults.level0_slowdown_writes_trigger), _level0StopTrigger(rocksDBDefaults.level0_stop_writes_trigger), _enablePipelinedWrite(rocksDBDefaults.enable_pipelined_write), _optimizeFiltersForHits(rocksDBDefaults.optimize_filters_for_hits), _useDirectReads(rocksDBDefaults.use_direct_reads), _useDirectIoForFlushAndCompaction(rocksDBDefaults.use_direct_io_for_flush_and_compaction), _useFSync(rocksDBDefaults.use_fsync), _skipCorrupted(false), _dynamicLevelBytes(true), _enableStatistics(false) { // setting the number of background jobs to _maxBackgroundJobs = static_cast<int32_t>(std::max((size_t)2, std::min(TRI_numberProcessors(), (size_t)8))); #ifdef _WIN32 // Windows code does not (yet) support lowering thread priority of // compactions. Therefore it is possible for rocksdb to use all // CPU time on compactions. Essential network communications can be lost. // Save one CPU for ArangoDB network and other activities. if (2 < _maxBackgroundJobs) { --_maxBackgroundJobs; } // if #endif setOptional(true); requiresElevatedPrivileges(false); startsAfter("Daemon"); startsAfter("DatabasePath"); } void RocksDBOptionFeature::collectOptions( std::shared_ptr<ProgramOptions> options) { options->addSection("rocksdb", "Configure the RocksDB engine"); options->addObsoleteOption("--rocksdb.enabled", "obsolete always active - Whether or not the " "RocksDB engine is enabled for the persistent " "index", true); options->addOption("--rocksdb.wal-directory", "optional path to the RocksDB WAL directory. " "If not set, the WAL directory will be located inside the regular data directory", new StringParameter(&_walDirectory)); options->addOption("--rocksdb.transaction-lock-timeout", "If positive, specifies the wait timeout in milliseconds when " " a transaction attempts to lock a document. A negative value " "is not recommended as it can lead to deadlocks (0 = no waiting, < 0 no timeout)", new Int64Parameter(&_transactionLockTimeout)); options->addOption("--rocksdb.write-buffer-size", "amount of data to build up in memory before converting " "to a sorted on-disk file (0 = disabled)", new UInt64Parameter(&_writeBufferSize)); options->addOption("--rocksdb.max-write-buffer-number", "maximum number of write buffers that built up in memory", new UInt64Parameter(&_maxWriteBufferNumber)); options->addOption("--rocksdb.max-total-wal-size", "maximum total size of WAL files that will force flush stale column families", new UInt64Parameter(&_maxTotalWalSize)); options->addHiddenOption( "--rocksdb.delayed_write_rate", "limited write rate to DB (in bytes per second) if we are writing to the " "last mem-table allowed and we allow more than 3 mem-tables, or if we " "have surpassed a certain number of level-0 files and need to slowdown " "writes", new UInt64Parameter(&_delayedWriteRate)); options->addOption("--rocksdb.min-write-buffer-number-to-merge", "minimum number of write buffers that will be merged " "together before writing " "to storage", new UInt64Parameter(&_minWriteBufferNumberToMerge)); options->addOption("--rocksdb.num-levels", "number of levels for the database", new UInt64Parameter(&_numLevels)); options->addOption("--rocksdb.num-uncompressed-levels", "number of uncompressed levels for the database", new UInt64Parameter(&_numUncompressedLevels)); options->addOption("--rocksdb.dynamic-level-bytes", "if true, determine the number of bytes for each level " "dynamically to minimize space amplification", new BooleanParameter(&_dynamicLevelBytes)); options->addOption("--rocksdb.max-bytes-for-level-base", "if not using dynamic level sizes, this controls the " "maximum total data size for level-1", new UInt64Parameter(&_maxBytesForLevelBase)); options->addOption("--rocksdb.max-bytes-for-level-multiplier", "if not using dynamic level sizes, the maximum number of " "bytes for level L can be calculated as " " max-bytes-for-level-base * " "(max-bytes-for-level-multiplier ^ (L-1))", new DoubleParameter(&_maxBytesForLevelMultiplier)); options->addOption("--rocksdb.enable-pipelined-write", "if true, use a two stage write queue for WAL writes and memtable writes", new BooleanParameter(&_enablePipelinedWrite)); options->addOption("--rocksdb.enable-statistics", "whether or not RocksDB statistics should be turned on", new BooleanParameter(&_enableStatistics)); options->addHiddenOption( "--rocksdb.optimize-filters-for-hits", "this flag specifies that the implementation should optimize the filters " "mainly for cases where keys are found rather than also optimize for " "keys missed. This would be used in cases where the application knows " "that there are very few misses or the performance in the case of " "misses is not important", new BooleanParameter(&_optimizeFiltersForHits)); #ifdef __linux__ options->addHiddenOption("--rocksdb.use-direct-reads", "use O_DIRECT for reading files", new BooleanParameter(&_useDirectReads)); options->addHiddenOption("--rocksdb.use-direct-io-for-flush-and-compaction", "use O_DIRECT for flush and compaction", new BooleanParameter(&_useDirectIoForFlushAndCompaction)); #endif options->addHiddenOption("--rocksdb.use-fsync", "issue an fsync when writing to disk (set to true " "for issuing fdatasync only)", new BooleanParameter(&_useFSync)); options->addHiddenOption( "--rocksdb.max-background-jobs", "Maximum number of concurrent background jobs (compactions and flushes)", new Int32Parameter(&_maxBackgroundJobs)); options->addOption("--rocksdb.max-subcompactions", "maximum number of concurrent subjobs for a background " "compaction", new UInt64Parameter(&_maxSubcompactions)); options->addOption("--rocksdb.level0-compaction-trigger", "number of level-0 files that triggers a compaction", new Int64Parameter(&_level0CompactionTrigger)); options->addOption("--rocksdb.level0-slowdown-trigger", "number of level-0 files that triggers a write slowdown", new Int64Parameter(&_level0SlowdownTrigger)); options->addOption("--rocksdb.level0-stop-trigger", "number of level-0 files that triggers a full write stall", new Int64Parameter(&_level0StopTrigger)); options->addOption( "--rocksdb.num-threads-priority-high", "number of threads for high priority operations (e.g. flush)", new UInt32Parameter(&_numThreadsHigh)); options->addOption( "--rocksdb.num-threads-priority-low", "number of threads for low priority operations (e.g. compaction)", new UInt32Parameter(&_numThreadsLow)); options->addOption("--rocksdb.block-cache-size", "size of block cache in bytes", new UInt64Parameter(&_blockCacheSize)); options->addOption("--rocksdb.block-cache-shard-bits", "number of shard bits to use for block cache (use -1 for default value)", new Int64Parameter(&_blockCacheShardBits)); options->addOption("--rocksdb.table-block-size", "approximate size (in bytes) of user data packed per block", new UInt64Parameter(&_tableBlockSize)); options->addHiddenOption("--rocksdb.recycle-log-file-num", "number of log files to keep around for recycling", new UInt64Parameter(&_recycleLogFileNum)); options->addOption( "--rocksdb.compaction-read-ahead-size", "if non-zero, we perform bigger reads when doing compaction. If you're " "running RocksDB on spinning disks, you should set this to at least 2MB. " "that way RocksDB's compaction is doing sequential instead of random " "reads.", new UInt64Parameter(&_compactionReadaheadSize)); options->addHiddenOption("--rocksdb.wal-recovery-skip-corrupted", "skip corrupted records in WAL recovery", new BooleanParameter(&_skipCorrupted)); } void RocksDBOptionFeature::validateOptions( std::shared_ptr<ProgramOptions> options) { if (_writeBufferSize > 0 && _writeBufferSize < 1024 * 1024) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.write-buffer-size'"; FATAL_ERROR_EXIT(); } if (_maxBytesForLevelMultiplier <= 0.0) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.max-bytes-for-level-multiplier'"; FATAL_ERROR_EXIT(); } if (_numLevels < 1 || _numLevels > 20) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.num-levels'"; FATAL_ERROR_EXIT(); } if (_maxBackgroundJobs != -1 && (_maxBackgroundJobs < 1 || _maxBackgroundJobs > 128)) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.max-background-jobs'"; FATAL_ERROR_EXIT(); } if (_numThreadsHigh > 64) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.num-threads-priority-high'"; FATAL_ERROR_EXIT(); } if ( _numThreadsLow > 256) { LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.num-threads-priority-low'"; FATAL_ERROR_EXIT(); } if (_maxSubcompactions > _numThreadsLow) { _maxSubcompactions = _numThreadsLow; } if (_blockCacheShardBits >= 20 || _blockCacheShardBits < -1) { // -1 is RocksDB default value, but anything less is invalid LOG_TOPIC(FATAL, arangodb::Logger::FIXME) << "invalid value for '--rocksdb.block-cache-shard-bits'"; FATAL_ERROR_EXIT(); } } void RocksDBOptionFeature::start() { uint32_t max = _maxBackgroundJobs / 2; uint32_t clamped = std::max(std::min((uint32_t)TRI_numberProcessors(), max), 1U); // lets test this out if (_numThreadsHigh == 0) { _numThreadsHigh = clamped; } if (_numThreadsLow == 0) { _numThreadsLow = clamped; } LOG_TOPIC(TRACE, Logger::ROCKSDB) << "using RocksDB options:" << " wal_dir: " << _walDirectory << "'" << ", write_buffer_size: " << _writeBufferSize << ", max_write_buffer_number: " << _maxWriteBufferNumber << ", max_total_wal_size: " << _maxTotalWalSize << ", delayed_write_rate: " << _delayedWriteRate << ", min_write_buffer_number_to_merge: " << _minWriteBufferNumberToMerge << ", num_levels: " << _numLevels << ", num_uncompressed_levels: " << _numUncompressedLevels << ", max_bytes_for_level_base: " << _maxBytesForLevelBase << ", max_bytes_for_level_multiplier: " << _maxBytesForLevelMultiplier << ", max_background_jobs: " << _maxBackgroundJobs << ", max_sub_compactions: " << _maxSubcompactions << ", num_threads_high: " << _numThreadsHigh << ", num_threads_low: " << _numThreadsLow << ", block_cache_size: " << _blockCacheSize << ", block_cache_shard_bits: " << _blockCacheShardBits << ", table_block_size: " << _tableBlockSize << ", recycle_log_file_num: " << _recycleLogFileNum << ", compaction_read_ahead_size: " << _compactionReadaheadSize << ", level0_compaction_trigger: " << _level0CompactionTrigger << ", level0_slowdown_trigger: " << _level0SlowdownTrigger << ", enable_pipelined_write: " << _enablePipelinedWrite << ", optimize_filters_for_hits: " << _optimizeFiltersForHits << ", use_direct_reads: " << _useDirectReads << ", use_direct_io_for_flush_and_compaction: " << _useDirectIoForFlushAndCompaction << ", use_fsync: " << _useFSync << ", dynamic_level_bytes: " << std::boolalpha << _dynamicLevelBytes; }
#include <qpdf/QPDFTokenizer.hh> // DO NOT USE ctype -- it is locale dependent for some things, and // it's not worth the risk of including it in case it may accidentally // be used. #include <qpdf/QTC.hh> #include <qpdf/QPDFExc.hh> #include <qpdf/QUtil.hh> #include <qpdf/QPDFObjectHandle.hh> #include <stdexcept> #include <stdlib.h> #include <string.h> static bool is_delimiter(char ch) { return (strchr(" \t\n\v\f\r()<>[]{}/%", ch) != 0); } class QPDFWordTokenFinder: public InputSource::Finder { public: QPDFWordTokenFinder(PointerHolder<InputSource> is, std::string const& str) : is(is), str(str) { } virtual ~QPDFWordTokenFinder() { } virtual bool check(); private: PointerHolder<InputSource> is; std::string str; }; bool QPDFWordTokenFinder::check() { // Find a word token matching the given string, preceded by a // delimiter, and followed by a delimiter or EOF. QPDFTokenizer tokenizer; QPDFTokenizer::Token t = tokenizer.readToken(is, "finder", true); qpdf_offset_t pos = is->tell(); if (! (t == QPDFTokenizer::Token(QPDFTokenizer::tt_word, str))) { QTC::TC("qpdf", "QPDFTokenizer finder found wrong word"); return false; } qpdf_offset_t token_start = is->getLastOffset(); char next; bool next_okay = false; if (is->read(&next, 1) == 0) { QTC::TC("qpdf", "QPDFTokenizer inline image at EOF"); next_okay = true; } else { next_okay = is_delimiter(next); } is->seek(pos, SEEK_SET); if (! next_okay) { return false; } if (token_start == 0) { // Can't actually happen...we never start the search at the // beginning of the input. return false; } return true; } QPDFTokenizer::Members::Members() : pound_special_in_name(true), allow_eof(false), include_ignorable(false) { reset(); } void QPDFTokenizer::Members::reset() { state = st_top; type = tt_bad; val = ""; raw_val = ""; error_message = ""; unread_char = false; char_to_unread = '\0'; inline_image_bytes = 0; string_depth = 0; string_ignoring_newline = false; last_char_was_bs = false; last_char_was_cr = false; } QPDFTokenizer::Members::~Members() { } QPDFTokenizer::Token::Token(token_type_e type, std::string const& value) : type(type), value(value), raw_value(value) { if (type == tt_string) { raw_value = QPDFObjectHandle::newString(value).unparse(); } else if (type == tt_name) { raw_value = QPDFObjectHandle::newName(value).unparse(); } } QPDFTokenizer::QPDFTokenizer() : m(new Members()) { } void QPDFTokenizer::allowPoundAnywhereInName() { QTC::TC("qpdf", "QPDFTokenizer allow pound anywhere in name"); this->m->pound_special_in_name = false; } void QPDFTokenizer::allowEOF() { this->m->allow_eof = true; } void QPDFTokenizer::includeIgnorable() { this->m->include_ignorable = true; } bool QPDFTokenizer::isSpace(char ch) { return ((ch == '\0') || QUtil::is_space(ch)); } bool QPDFTokenizer::isDelimiter(char ch) { return is_delimiter(ch); } void QPDFTokenizer::resolveLiteral() { if ((this->m->val.length() > 0) && (this->m->val.at(0) == '/')) { this->m->type = tt_name; // Deal with # in name token. Note: '/' by itself is a // valid name, so don't strip leading /. That way we // don't have to deal with the empty string as a name. std::string nval = "/"; char const* valstr = this->m->val.c_str() + 1; for (char const* p = valstr; *p; ++p) { if ((*p == '#') && this->m->pound_special_in_name) { if (p[1] && p[2] && QUtil::is_hex_digit(p[1]) && QUtil::is_hex_digit(p[2])) { char num[3]; num[0] = p[1]; num[1] = p[2]; num[2] = '\0'; char ch = static_cast<char>(strtol(num, 0, 16)); if (ch == '\0') { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer null in name"); this->m->error_message = "null character not allowed in name token"; nval += "#00"; } else { nval += ch; } p += 2; } else { QTC::TC("qpdf", "QPDFTokenizer bad name"); this->m->type = tt_bad; this->m->error_message = "invalid name token"; nval += *p; } } else { nval += *p; } } this->m->val = nval; } else if (QUtil::is_number(this->m->val.c_str())) { if (this->m->val.find('.') != std::string::npos) { this->m->type = tt_real; } else { this->m->type = tt_integer; } } else if ((this->m->val == "true") || (this->m->val == "false")) { this->m->type = tt_bool; } else if (this->m->val == "null") { this->m->type = tt_null; } else { // I don't really know what it is, so leave it as tt_word. // Lots of cases ($, #, etc.) other than actual words fall // into this category, but that's okay at least for now. this->m->type = tt_word; } } void QPDFTokenizer::presentCharacter(char ch) { if (this->m->state == st_token_ready) { throw std::logic_error( "INTERNAL ERROR: QPDF tokenizer presented character " "while token is waiting"); } char orig_ch = ch; // State machine is implemented such that some characters may be // handled more than once. This happens whenever you have to use // the character that caused a state change in the new state. bool handled = true; if (this->m->state == st_top) { // Note: we specifically do not use ctype here. It is // locale-dependent. if (isSpace(ch)) { if (this->m->include_ignorable) { this->m->state = st_in_space; this->m->val += ch; } } else if (ch == '%') { this->m->state = st_in_comment; if (this->m->include_ignorable) { this->m->val += ch; } } else if (ch == '(') { this->m->string_depth = 1; this->m->string_ignoring_newline = false; memset(this->m->bs_num_register, '\0', sizeof(this->m->bs_num_register)); this->m->last_char_was_bs = false; this->m->last_char_was_cr = false; this->m->state = st_in_string; } else if (ch == '<') { this->m->state = st_lt; } else if (ch == '>') { this->m->state = st_gt; } else { this->m->val += ch; if (ch == ')') { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad )"); this->m->error_message = "unexpected )"; this->m->state = st_token_ready; } else if (ch == '[') { this->m->type = tt_array_open; this->m->state = st_token_ready; } else if (ch == ']') { this->m->type = tt_array_close; this->m->state = st_token_ready; } else if (ch == '{') { this->m->type = tt_brace_open; this->m->state = st_token_ready; } else if (ch == '}') { this->m->type = tt_brace_close; this->m->state = st_token_ready; } else { this->m->state = st_literal; } } } else if (this->m->state == st_in_space) { // We only enter this state if include_ignorable is true. if (! isSpace(ch)) { this->m->type = tt_space; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; } else { this->m->val += ch; } } else if (this->m->state == st_in_comment) { if ((ch == '\r') || (ch == '\n')) { if (this->m->include_ignorable) { this->m->type = tt_comment; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; } else { this->m->state = st_top; } } else if (this->m->include_ignorable) { this->m->val += ch; } } else if (this->m->state == st_lt) { if (ch == '<') { this->m->val = "<<"; this->m->type = tt_dict_open; this->m->state = st_token_ready; } else { handled = false; this->m->state = st_in_hexstring; } } else if (this->m->state == st_gt) { if (ch == '>') { this->m->val = ">>"; this->m->type = tt_dict_close; this->m->state = st_token_ready; } else { this->m->val = ">"; this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad >"); this->m->error_message = "unexpected >"; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; } } else if (this->m->state == st_in_string) { if (this->m->string_ignoring_newline && (ch != '\n')) { this->m->string_ignoring_newline = false; } size_t bs_num_count = strlen(this->m->bs_num_register); bool ch_is_octal = ((ch >= '0') && (ch <= '7')); if ((bs_num_count == 3) || ((bs_num_count > 0) && (! ch_is_octal))) { // We've accumulated \ddd. PDF Spec says to ignore // high-order overflow. this->m->val += static_cast<char>( strtol(this->m->bs_num_register, 0, 8)); memset(this->m->bs_num_register, '\0', sizeof(this->m->bs_num_register)); bs_num_count = 0; } if (this->m->string_ignoring_newline && (ch == '\n')) { // ignore this->m->string_ignoring_newline = false; } else if (ch_is_octal && (this->m->last_char_was_bs || (bs_num_count > 0))) { this->m->bs_num_register[bs_num_count++] = ch; } else if (this->m->last_char_was_bs) { switch (ch) { case 'n': this->m->val += '\n'; break; case 'r': this->m->val += '\r'; break; case 't': this->m->val += '\t'; break; case 'b': this->m->val += '\b'; break; case 'f': this->m->val += '\f'; break; case '\n': break; case '\r': this->m->string_ignoring_newline = true; break; default: // PDF spec says backslash is ignored before anything else this->m->val += ch; break; } } else if (ch == '\\') { // last_char_was_bs is set/cleared below as appropriate if (bs_num_count) { throw std::logic_error( "INTERNAL ERROR: QPDFTokenizer: bs_num_count != 0 " "when ch == '\\'"); } } else if (ch == '(') { this->m->val += ch; ++this->m->string_depth; } else if ((ch == ')') && (--this->m->string_depth == 0)) { this->m->type = tt_string; this->m->state = st_token_ready; } else if (ch == '\r') { // CR by itself is converted to LF this->m->val += '\n'; } else if (ch == '\n') { // CR LF is converted to LF if (! this->m->last_char_was_cr) { this->m->val += ch; } } else { this->m->val += ch; } this->m->last_char_was_cr = ((! this->m->string_ignoring_newline) && (ch == '\r')); this->m->last_char_was_bs = ((! this->m->last_char_was_bs) && (ch == '\\')); } else if (this->m->state == st_literal) { if (isDelimiter(ch)) { // A C-locale whitespace character or delimiter terminates // token. It is important to unread the whitespace // character even though it is ignored since it may be the // newline after a stream keyword. Removing it here could // make the stream-reading code break on some files, // though not on any files in the test suite as of this // writing. this->m->type = tt_word; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; } else { this->m->val += ch; } } else if (this->m->state == st_inline_image) { this->m->val += ch; size_t len = this->m->val.length(); if (len == this->m->inline_image_bytes) { QTC::TC("qpdf", "QPDFTokenizer found EI by byte count"); this->m->type = tt_inline_image; this->m->inline_image_bytes = 0; this->m->state = st_token_ready; } else if ((this->m->inline_image_bytes == 0) && (len >= 4) && isDelimiter(this->m->val.at(len-4)) && (this->m->val.at(len-3) == 'E') && (this->m->val.at(len-2) == 'I') && isDelimiter(this->m->val.at(len-1))) { QTC::TC("qpdf", "QPDFTokenizer found EI the old way"); this->m->val.erase(len - 1); this->m->type = tt_inline_image; this->m->unread_char = true; this->m->char_to_unread = ch; this->m->state = st_token_ready; } } else { handled = false; } if (handled) { // okay } else if (this->m->state == st_in_hexstring) { if (ch == '>') { this->m->type = tt_string; this->m->state = st_token_ready; if (this->m->val.length() % 2) { // PDF spec says odd hexstrings have implicit // trailing 0. this->m->val += '0'; } char num[3]; num[2] = '\0'; std::string nval; for (unsigned int i = 0; i < this->m->val.length(); i += 2) { num[0] = this->m->val.at(i); num[1] = this->m->val.at(i+1); char nch = static_cast<char>(strtol(num, 0, 16)); nval += nch; } this->m->val = nval; } else if (QUtil::is_hex_digit(ch)) { this->m->val += ch; } else if (isSpace(ch)) { // ignore } else { this->m->type = tt_bad; QTC::TC("qpdf", "QPDFTokenizer bad hexstring character"); this->m->error_message = std::string("invalid character (") + ch + ") in hexstring"; this->m->state = st_token_ready; } } else { throw std::logic_error( "INTERNAL ERROR: invalid state while reading token"); } if ((this->m->state == st_token_ready) && (this->m->type == tt_word)) { resolveLiteral(); } if (! (betweenTokens() || ((this->m->state == st_token_ready) && this->m->unread_char))) { this->m->raw_val += orig_ch; } } void QPDFTokenizer::presentEOF() { if (this->m->state == st_inline_image) { size_t len = this->m->val.length(); if ((len >= 3) && isDelimiter(this->m->val.at(len-3)) && (this->m->val.at(len-2) == 'E') && (this->m->val.at(len-1) == 'I')) { QTC::TC("qpdf", "QPDFTokenizer inline image at EOF the old way"); this->m->type = tt_inline_image; this->m->state = st_token_ready; } } if (this->m->state == st_literal) { QTC::TC("qpdf", "QPDFTokenizer EOF reading appendable token"); resolveLiteral(); } else if ((this->m->include_ignorable) && (this->m->state == st_in_space)) { this->m->type = tt_space; } else if ((this->m->include_ignorable) && (this->m->state == st_in_comment)) { this->m->type = tt_comment; } else if (betweenTokens()) { this->m->type = tt_eof; } else if (this->m->state != st_token_ready) { QTC::TC("qpdf", "QPDFTokenizer EOF reading token"); this->m->type = tt_bad; this->m->error_message = "EOF while reading token"; } this->m->state = st_token_ready; } void QPDFTokenizer::expectInlineImage() { expectInlineImage(PointerHolder<InputSource>()); } void QPDFTokenizer::expectInlineImage(PointerHolder<InputSource> input) { if (this->m->state != st_top) { throw std::logic_error("QPDFTokenizer::expectInlineImage called" " when tokenizer is in improper state"); } findEI(input); this->m->state = st_inline_image; } void QPDFTokenizer::findEI(PointerHolder<InputSource> input) { if (! input.getPointer()) { return; } qpdf_offset_t last_offset = input->getLastOffset(); qpdf_offset_t pos = input->tell(); // Use QPDFWordTokenFinder to find EI surrounded by delimiters. // Then read the next several tokens or up to EOF. If we find any // suspicious-looking or tokens, this is probably still part of // the image data, so keep looking for EI. Stop at the first EI // that passes. If we get to the end without finding one, return // the last EI we found. Store the number of bytes expected in the // inline image including the EI and use that to break out of // inline image, falling back to the old method if needed. bool okay = false; bool first_try = true; while (! okay) { QPDFWordTokenFinder f(input, "EI"); if (! input->findFirst("EI", input->tell(), 0, f)) { break; } this->m->inline_image_bytes = input->tell() - pos - 2; QPDFTokenizer check; bool found_bad = false; // Look at the next 10 tokens or up to EOF. The next inline // image's image data would look like bad tokens, but there // will always be at least 10 tokens between one inline // image's EI and the next valid one's ID since width, height, // bits per pixel, and color space are all required as well as // a BI and ID. If we get 10 good tokens in a row or hit EOF, // we can be pretty sure we've found the actual EI. for (int i = 0; i < 10; ++i) { QPDFTokenizer::Token t = check.readToken(input, "checker", true); token_type_e type = t.getType(); if (type == tt_eof) { okay = true; } else if (type == tt_bad) { found_bad = true; } else if (type == tt_word) { // The qpdf tokenizer lumps alphabetic and otherwise // uncategorized characters into "words". We recognize // strings of alphabetic characters as potential valid // operators for purposes of telling whether we're in // valid content or not. It's not perfect, but it // should work more reliably than what we used to do, // which was already good enough for the vast majority // of files. bool found_alpha = false; bool found_non_printable = false; bool found_other = false; std::string value = t.getValue(); for (std::string::iterator iter = value.begin(); iter != value.end(); ++iter) { char ch = *iter; if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) || (ch == '*')) { // Treat '*' as alpha since there are valid // PDF operators that contain * along with // alphabetic characters. found_alpha = true; } else if (((ch < 32) && (! isSpace(ch))) || (ch > 127)) { found_non_printable = true; break; } else { found_other = true; } } if (found_non_printable || (found_alpha && found_other)) { found_bad = true; } } if (okay || found_bad) { break; } } if (! found_bad) { okay = true; } if (! okay) { first_try = false; } } if (okay && (! first_try)) { QTC::TC("qpdf", "QPDFTokenizer found EI after more than one try"); } input->seek(pos, SEEK_SET); input->setLastOffset(last_offset); } bool QPDFTokenizer::getToken(Token& token, bool& unread_char, char& ch) { bool ready = (this->m->state == st_token_ready); unread_char = this->m->unread_char; ch = this->m->char_to_unread; if (ready) { if (this->m->type == tt_bad) { this->m->val = this->m->raw_val; } token = Token(this->m->type, this->m->val, this->m->raw_val, this->m->error_message); this->m->reset(); } return ready; } bool QPDFTokenizer::betweenTokens() { return ((this->m->state == st_top) || ((! this->m->include_ignorable) && ((this->m->state == st_in_comment) || (this->m->state == st_in_space)))); } QPDFTokenizer::Token QPDFTokenizer::readToken(PointerHolder<InputSource> input, std::string const& context, bool allow_bad, size_t max_len) { qpdf_offset_t offset = input->tell(); Token token; bool unread_char; char char_to_unread; bool presented_eof = false; while (! getToken(token, unread_char, char_to_unread)) { char ch; if (input->read(&ch, 1) == 0) { if (! presented_eof) { presentEOF(); presented_eof = true; if ((this->m->type == tt_eof) && (! this->m->allow_eof)) { // Nothing in the qpdf library calls readToken // without allowEOF anymore, so this case is not // exercised. this->m->type = tt_bad; this->m->error_message = "unexpected EOF"; offset = input->getLastOffset(); } } else { throw std::logic_error( "getToken returned false after presenting EOF"); } } else { presentCharacter(ch); if (betweenTokens() && (input->getLastOffset() == offset)) { ++offset; } if (max_len && (this->m->raw_val.length() >= max_len) && (this->m->state != st_token_ready)) { // terminate this token now QTC::TC("qpdf", "QPDFTokenizer block long token"); this->m->type = tt_bad; this->m->state = st_token_ready; this->m->error_message = "exceeded allowable length while reading token"; } } } if (unread_char) { input->unreadCh(char_to_unread); } if (token.getType() != tt_eof) { input->setLastOffset(offset); } if (token.getType() == tt_bad) { if (allow_bad) { QTC::TC("qpdf", "QPDFTokenizer allowing bad token"); } else { throw QPDFExc(qpdf_e_damaged_pdf, input->getName(), context, offset, token.getErrorMessage()); } } return token; }