text
string
size
int64
token_count
int64
/* Attention, kills and modifies globals ^g and ^counter Error handling via method rc() */ #include <iostream> #include <string> #include "ydb-global.h" using namespace std; int main() { c_ydb_global _g("^g"), _counter("^counter"); string ind, v = "Hello world"; cout << "counter: " << (_counter += 2) << endl; _g.kill(); _g[4][8] = "g_4_8"; _g["2"] = 222; _g[3] = 333; _g["A99"] = "This is A99"; _g["A100"] = v; _g["A2"] = v + " - " + v; _g[7] = 777; ind = ""; // now $ORDER-loop while (ind = _g[ind].next(), ind != "") { if (v = _g[ind], !_g.rc()) cout << ind << " = " << v << endl; else cout << ind << " = n.d." << endl; } return 0; }
668
320
#ifndef CSLIBS_MATH_SERIALIZATION_VECTOR_HPP #define CSLIBS_MATH_SERIALIZATION_VECTOR_HPP #include <cslibs_math/linear/vector.hpp> #include <yaml-cpp/yaml.h> namespace YAML { template<typename T, std::size_t Dim> struct convert<cslibs_math::linear::Vector<T, Dim>> { static Node encode(const cslibs_math::linear::Vector<T,Dim> &rhs) { Node n; for(std::size_t i = 0 ; i < Dim ; ++i) { n.push_back(rhs(i)); } return n; } static bool decode(const Node& n, cslibs_math::linear::Vector<T,Dim> &rhs) { if(!n.IsSequence() || n.size() != Dim) return false; for(std::size_t i = 0 ; i < Dim ; ++i) { rhs(i) = n[i].as<T>(); } return true; } }; } #endif // CSLIBS_MATH_SERIALIZATION_VECTOR_HPP
809
317
/** * copyright (c) 2018, James Flynn * SPDX-License-Identifier: MIT */ #include <stdlib.h> #include "iothub_client_core_common.h" #include "iothub_client_ll.h" #include "azure_c_shared_utility/platform.h" #include "azure_c_shared_utility/agenttime.h" #include "jsondecoder.h" #include "led.hpp" #include "lis2dw12.hpp" #include "adc.hpp" #include "barometer.hpp" #include "hts221.hpp" #include "gps.hpp" #include "azure_certs.h" #include "azIoTClient.h" #ifdef USE_MQTT #include "iothubtransportmqtt.h" #else #include "iothubtransporthttp.h" #endif //The following connection string must be updated for the individual users Azure IoT Device //static const char* connectionString = "HostName=XXXX;DeviceId=xxxx;SharedAccessKey=xxxx"; static const char* connectionString = "HostName=M18QxIoTClient.azure-devices.net;DeviceId=SK2-IMEI353087080010952;SharedAccessKey=3vyDD6lO1VRCfi1bCZ58QsTUsViEZ3Q4JBErtvQzBcA="; extern void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char* buffer, size_t size); extern void prty_json(char* src, int srclen); char* send_sensrpt(void); char* send_devrpt(void); char* send_locrpt(void); char* send_temprpt(void); char* send_posrpt(void); char* send_envrpt(void); IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback( IOTHUB_MESSAGE_HANDLE message, void *userContextCallback); void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char* buffer, size_t size) { IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)buffer, size); if (messageHandle == NULL) { printf("unable to create a new IoTHubMessage\r\n"); return; } if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK) printf("FAILED to send!\n"); else printf("OK\n"); IoTHubMessage_Destroy(messageHandle); } IOTHUB_CLIENT_LL_HANDLE setup_azure(void) { /* Setup IoTHub client configuration */ #ifndef USE_MQTT IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol); #else IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol); #endif if (iotHubClientHandle == NULL) { printf("Failed on IoTHubClient_Create\r\n"); return NULL; } // add the certificate information if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) { IoTHubClient_LL_Destroy(iotHubClientHandle); printf("failure to set option \"TrustedCerts\"\r\n"); return NULL; } // add the certificate information #ifndef USE_MQTT // polls will happen effectively at ~10 seconds. The default value of minimumPollingTime is 25 minutes. // For more information, see: // https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging unsigned int minimumPollingTime = 9; if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) { IoTHubClient_LL_Destroy(iotHubClientHandle); printf("failure to set option \"MinimumPollingTime\"\r\n"); return NULL; } #endif // set C2D and device method callback IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL); return iotHubClientHandle; } //------------------------------------------------------------------ #define SENS_REPORT "{" \ "\"ObjectName\":\"sensor-report\"," \ "\"SOM\":[\"ADC\",\"LIS2DW12-TEMP\",\"LIS2DW12-POS\",\"GPS\"]," \ "\"CLICK\":[" char* send_sensrpt(void) { int len = sizeof(SENS_REPORT)+30; char* ptr = (char*)malloc(len); snprintf(ptr,len,SENS_REPORT); if( click_modules & (BAROMETER_CLICK|HTS221_CLICK) ) { if (click_modules & BAROMETER_CLICK ) strcat(ptr,"\"BAROMETER\""); if (click_modules & HTS221_CLICK ) strcat(ptr,",\"TEMP&HUMID\""); } else strcat(ptr,"\"NONE\""); strcat(ptr,"]}"); return ptr; } //------------------------------------------------------------------ #define DEV_REPORT "{" \ "\"ObjectName\":\"Device-Info\"," \ "\"ReportingDevice\":\"M18QWG/M18Q2FG-1\"," \ "\"DeviceICCID\":\"%s\"," \ "\"DeviceIMEI\":\"%s\"" \ "}" char* send_devrpt(void) { int len = sizeof(DEV_REPORT)+50; char* ptr = (char*)malloc(len); snprintf(ptr,len,DEV_REPORT, iccid, imei); return ptr; } //------------------------------------------------------------------ #define LOC_REPORT "{" \ "\"ObjectName\":\"location-report\"," \ "\"last GPS fix\":\"%s\"," \ "\"lat\":%.02f," \ "\"long\":%.02f" \ "}" char* send_locrpt(void) { gpsstatus *loc; char temp[25]; struct tm *ptm; int len = sizeof(LOC_REPORT)+35; char* ptr = (char*)malloc(len); loc = gps.getLocation(); ptm = gmtime(&loc->last_good); strftime(temp,25,"%a %F %X",ptm); snprintf(ptr,len, LOC_REPORT, temp, loc->last_pos.lat, loc->last_pos.lng); return ptr; } //------------------------------------------------------------------ #define TEMP_REPORT "{" \ "\"ObjectName\":\"temp-report\"," \ "\"Temperature\":%.02f" \ "}" char* send_temprpt(void) { int len = sizeof(TEMP_REPORT)+10; char* ptr = (char*)malloc(len); snprintf(ptr,len,TEMP_REPORT, mems.lis2dw12_getTemp()); return ptr; } //------------------------------------------------------------------ #define POS_REPORT "{" \ "\"ObjectName\":\"board-position\"," \ "\"Board Moved\":%d," \ "\"Board Position\":%d" \ "}" char* send_posrpt(void) { int len = sizeof(POS_REPORT)+10; char* ptr = (char*)malloc(len); snprintf(ptr,len,POS_REPORT, mems.movement_ocured(), mems.lis2dw12_getPosition()); return ptr; } //------------------------------------------------------------------ #define ENV_REPORT "{" \ "\"ObjectName\":\"enviroment-report\"," \ "\"Barometer\":%.02f," \ "\"Humidity\":%.01f" \ "}" char* send_envrpt(void) { int len = sizeof(ENV_REPORT)+15; char* ptr = (char*)malloc(len); snprintf(ptr,len,ENV_REPORT, (click_modules & BAROMETER_CLICK )? barom.get_pressure():0, (click_modules & HTS221_CLICK )? humid.readHumidity():0 ); return ptr; } IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback( IOTHUB_MESSAGE_HANDLE message, void *userContextCallback) { const unsigned char *buffer = NULL; char* pmsg = NULL; size_t size = 0; if (IOTHUB_MESSAGE_OK != IoTHubMessage_GetByteArray(message, &buffer, &size)) return IOTHUBMESSAGE_ABANDONED; // message needs to be converted to zero terminated string char * temp = (char *)malloc(size + 1); if (temp == NULL) return IOTHUBMESSAGE_ABANDONED; strncpy(temp, (char*)buffer, size); temp[size] = '\0'; if( !strcmp(temp, "REPORT-SENSORS") ) pmsg = send_sensrpt(); else if( !strcmp(temp, "GET-DEV-INFO") ) pmsg = send_devrpt(); else if( !strcmp(temp, "GET-LOCATION") ) pmsg = send_locrpt(); else if( !strcmp(temp, "GET-TEMP") ) pmsg = send_temprpt(); else if( !strcmp(temp, "GET-POS") ) pmsg = send_posrpt(); else if( !strcmp(temp, "GET-ENV") ) pmsg = send_envrpt(); else if( !strcmp(temp, "LED-ON-MAGENTA") ){ status_led.action(Led::LED_ON,Led::MAGENTA); if( verbose ) printf("Turning LED on to Magenta.\n"); } else if( !strcmp(temp, "LED-BLINK-MAGENTA") ){ status_led.action(Led::LED_BLINK,Led::MAGENTA); if( verbose ) printf("Setting LED to blink Magenta\n"); } else if( !strcmp(temp, "LED-OFF") ){ status_led.action(Led::LED_OFF,Led::BLACK); if( verbose ) printf("Turning LED off.\n"); } else if( strstr(temp, "SET-PERIOD") ) { sscanf(temp,"SET-PERIOD %d",&report_period); int i=report_period % REPORT_PERIOD_RESOLUTION; if( i != 0 ) report_period += (REPORT_PERIOD_RESOLUTION-i); if( verbose ) printf("Report Period remotely set to %d.\n",report_period); } else printf("Received message: '%s'\r\n", temp); if( pmsg != NULL ) { printf("(----)Azure IoT Hub requested response sent - "); sendMessage(IoTHub_client_ll_handle, pmsg, strlen(pmsg)); if( verbose ) prty_json(pmsg,strlen(pmsg)); free(pmsg); } free(temp); return IOTHUBMESSAGE_ACCEPTED; }
8,960
3,240
// // Author: Joshua Cohen // Copyright 2017 // #include "Peg.h" using isceLib::Peg; Peg::Peg() { // Empty constructor return; } Peg::Peg(const Peg &p) { // Copy constructor lat = p.lat; lon = p.lon; hdg = p.hdg; }
248
112
// Copyright (c)2007 Nicholas Piegdon // See license.txt for license information #include "TrackTile.h" #include "libmidi/Midi.h" #include "Renderer.h" #include "Tga.h" const static int GraphicWidth = 36; const static int GraphicHeight = 36; TrackTile::TrackTile(int x, int y, size_t track_id, Track::TrackColor color, Track::Mode mode) : m_x(x), m_y(y), m_track_id(track_id), m_color(color), m_mode(mode), m_preview_on(false) { // Initialize the size and position of each button whole_tile = ButtonState(0, 0, TrackTileWidth, TrackTileHeight); button_mode_left = ButtonState( 2, 68, GraphicWidth, GraphicHeight); button_mode_right = ButtonState(192, 68, GraphicWidth, GraphicHeight); button_color = ButtonState(228, 68, GraphicWidth, GraphicHeight); button_preview = ButtonState(264, 68, GraphicWidth, GraphicHeight); } void TrackTile::Update(const MouseInfo &translated_mouse) { // Update the mouse state of each button whole_tile.Update(translated_mouse); button_preview.Update(translated_mouse); button_color.Update(translated_mouse); button_mode_left.Update(translated_mouse); button_mode_right.Update(translated_mouse); if (button_mode_left.hit) { int mode = static_cast<int>(m_mode) - 1; if (mode < 0) mode = 3; m_mode = static_cast<Track::Mode>(mode); } if (button_mode_right.hit) { int mode = static_cast<int>(m_mode) + 1; if (mode > 3) mode = 0; m_mode = static_cast<Track::Mode>(mode); } if (button_preview.hit) { m_preview_on = !m_preview_on; } if (button_color.hit && m_mode != Track::ModeNotPlayed && m_mode != Track::ModePlayedButHidden) { int color = static_cast<int>(m_color) + 1; if (color >= Track::UserSelectableColorCount) color = 0; m_color = static_cast<Track::TrackColor>(color); } } int TrackTile::LookupGraphic(TrackTileGraphic graphic, bool button_hovering) const { // There are three sets of graphics // set 0: window lit, hovering // set 1: window lit, not-hovering // set 2: window unlit, (implied not-hovering) int graphic_set = 2; if (whole_tile.hovering) graphic_set--; if (button_hovering) graphic_set--; const int set_offset = GraphicWidth * Graphic_COUNT; const int graphic_offset = GraphicWidth * graphic; return (set_offset * graphic_set) + graphic_offset; } void TrackTile::Draw(Renderer &renderer, const Midi *midi, Tga *buttons, Tga *box) const { const MidiTrack &track = midi->Tracks()[m_track_id]; bool gray_out_buttons = false; Color light = Track::ColorNoteWhite[m_color]; Color medium = Track::ColorNoteBlack[m_color]; if (m_mode == Track::ModePlayedButHidden || m_mode == Track::ModeNotPlayed) { gray_out_buttons = true; light = Renderer::ToColor(0xB0,0xB0,0xB0); medium = Renderer::ToColor(0x70,0x70,0x70); } Color color_tile = medium; Color color_tile_hovered = light; renderer.SetOffset(m_x, m_y); renderer.SetColor(whole_tile.hovering ? color_tile_hovered : color_tile); renderer.DrawTga(box, -10, -6); renderer.SetColor(White); // Write song info to the tile TextWriter instrument(95, 12, renderer, false, 14); instrument << track.InstrumentName(); TextWriter note_count(95, 33, renderer, false, 14); note_count << static_cast<const unsigned int>(track.Notes().size()); int color_offset = GraphicHeight * static_cast<int>(m_color); if (gray_out_buttons) color_offset = GraphicHeight * Track::UserSelectableColorCount; renderer.DrawTga(buttons, BUTTON_RECT(button_mode_left), LookupGraphic(GraphicLeftArrow, button_mode_left.hovering), color_offset); renderer.DrawTga(buttons, BUTTON_RECT(button_mode_right), LookupGraphic(GraphicRightArrow, button_mode_right.hovering), color_offset); renderer.DrawTga(buttons, BUTTON_RECT(button_color), LookupGraphic(GraphicColor, button_color.hovering), color_offset); TrackTileGraphic preview_graphic = GraphicPreviewTurnOn; if (m_preview_on) preview_graphic = GraphicPreviewTurnOff; renderer.DrawTga(buttons, BUTTON_RECT(button_preview), LookupGraphic(preview_graphic, button_preview.hovering), color_offset); // Draw mode text TextWriter mode(42, 76, renderer, false, 14); mode << Track::ModeText[m_mode]; renderer.ResetOffset(); }
4,478
1,642
/** * @file fuzzy_clang.cpp * @author Sirko Höer * @date 18.11.2017 * @brief Entrypoint for the fuzzy-clang ... * * @copyright Copyright (c) 2018 Code Intelligence. All rights reserved. */ #include <clang/Tooling/Tooling.h> #include <clang/Tooling/CommonOptionsParser.h> #include "PPContext.h" #include "LocationFinderAction.h" using namespace llvm; using namespace clang; using namespace clang::tooling; static cl::OptionCategory tool_category("location-finder-options"); static cl::opt<std::string> positionOption{"pos", cl::desc{"Startposition from function or element"}, cl::Optional, cl::cat{tool_category}}; static cl::opt<bool> jsonOption{"json", cl::desc{"Json output enable"}, cl::Optional, cl::cat{tool_category}}; int main(int argc, const char **argv) { // Initial CommonOptionParser with the args from the commandline CommonOptionsParser OptionsParser(argc, argv, tool_category); ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); // create und initialize the essential components for traversing an AST PPContext ppC{Tool, OptionsParser}; ppC.createPreprocessor(); ppC.createASTContext(); // Initialize a Rewriter Object and set the source manager Rewriter RW; RW.setSourceMgr( ppC.getCompilerInstance().getSourceManager(), ppC.getCompilerInstance().getLangOpts()); // Create a AST-Consumer LocationFinderASTConsumer TheASTConsumer(RW, positionOption.getValue()); // Set the AST-Consumer to the compiler instanze LocationFinderAction find_location(ppC); // start find location ... find_location.run(&TheASTConsumer); return 0; }
1,883
542
// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #ifndef MFEM_LOR_MMS_HPP #define MFEM_LOR_MMS_HPP extern bool grad_div_problem; namespace mfem { static constexpr double pi = M_PI, pi2 = M_PI*M_PI; // Exact solution for definite Helmholtz problem with RHS corresponding to f // defined below. double u(const Vector &xvec) { int dim = xvec.Size(); double x = pi*xvec[0], y = pi*xvec[1]; if (dim == 2) { return sin(x)*sin(y); } else { double z = pi*xvec[2]; return sin(x)*sin(y)*sin(z); } } double f(const Vector &xvec) { int dim = xvec.Size(); double x = pi*xvec[0], y = pi*xvec[1]; if (dim == 2) { return sin(x)*sin(y) + 2*pi2*sin(x)*sin(y); } else // dim == 3 { double z = pi*xvec[2]; return sin(x)*sin(y)*sin(z) + 3*pi2*sin(x)*sin(y)*sin(z); } } // Exact solution for definite Maxwell and grad-div problems with RHS // corresponding to f_vec below. void u_vec(const Vector &xvec, Vector &u) { int dim = xvec.Size(); double x = pi*xvec[0], y = pi*xvec[1]; if (dim == 2) { u[0] = cos(x)*sin(y); u[1] = sin(x)*cos(y); } else // dim == 3 { double z = pi*xvec[2]; u[0] = cos(x)*sin(y)*sin(z); u[1] = sin(x)*cos(y)*sin(z); u[2] = sin(x)*sin(y)*cos(z); } } void f_vec(const Vector &xvec, Vector &f) { int dim = xvec.Size(); double x = pi*xvec[0], y = pi*xvec[1]; if (grad_div_problem) { if (dim == 2) { f[0] = (1 + 2*pi2)*cos(x)*sin(y); f[1] = (1 + 2*pi2)*cos(y)*sin(x); } else // dim == 3 { double z = pi*xvec[2]; f[0] = (1 + 3*pi2)*cos(x)*sin(y)*sin(z); f[1] = (1 + 3*pi2)*cos(y)*sin(x)*sin(z); f[2] = (1 + 3*pi2)*cos(z)*sin(x)*sin(y); } } else { if (dim == 2) { f[0] = cos(x)*sin(y); f[1] = sin(x)*cos(y); } else // dim == 3 { double z = pi*xvec[2]; f[0] = cos(x)*sin(y)*sin(z); f[1] = sin(x)*cos(y)*sin(z); f[2] = sin(x)*sin(y)*cos(z); } } } } // namespace mfem #endif
2,575
1,097
#include <codegenvar/Eigen> #include <Eigen/Geometry> #include <iostream> using namespace codegenvar; int main() { const Symbol x("x"), y("y"), dx("dx"), dy("dy"), a("a"); const Vec2 p(x, y); const Vec3 P = p.homogeneous(); const Vec2 diff(dx, dy); std::cout << "p = " << p.transpose() << std::endl; std::cout << "translate by " << diff.transpose() << std::endl; std::cout << "rotate by " << a << std::endl << std::endl; std::cout << "P = " << P.transpose() << std::endl << std::endl; Mat23 t; t << Symbol(1), Symbol(0), diff(0), Symbol(0), Symbol(1), diff(1); std::cout << "p + diff = " << (p+diff).transpose() << std::endl << std::endl; std::cout << "t = " << std::endl << t << std::endl << std::endl; std::cout << "t*P = " << (t*P).transpose() << std::endl << std::endl; Mat3 T; T << t(0, 0), t(0, 1), t(0, 2), t(1, 0), t(1, 1), t(1, 2), Symbol(0), Symbol(0), Symbol(1); std::cout << "T = " << std::endl << T << std::endl << std::endl; std::cout << "T*P = " << (T*P).transpose() << std::endl << std::endl; Mat2 r; r << cos(a), -sin(a), sin(a), cos(a); std::cout << "r = " << std::endl << r << std::endl << std::endl; std::cout << "r*p = " << (r*p).transpose() << std::endl << std::endl; Mat3 R; R << r(0, 0) , r(0, 1), Symbol(0), r(1, 0) , r(1, 1), Symbol(0), Symbol(0), Symbol(0), Symbol(1); std::cout << "R = " << std::endl << R << std::endl << std::endl; std::cout << "R*P = " << (R*P).transpose() << std::endl << std::endl; std::cout << "T*R = " << std::endl << T*R << std::endl << std::endl; std::cout << "T*R*P = " << (T*R*P).transpose() << std::endl << std::endl; std::cout << "R*T = " << std::endl << R*T << std::endl << std::endl; std::cout << "R*T*P = " << (R*T*P).transpose() << std::endl << std::endl; return 0; }
1,924
786
#include "ScriptsComponent.hpp" #include <string> #include "afk/Afk.hpp" #include "afk/io/Log.hpp" #include "afk/io/Path.hpp" using Afk::ScriptsComponent; ScriptsComponent::ScriptsComponent(GameObject e, lua_State *lua_state) : loaded_files(), last_write(), lua(lua_state) { this->owning_entity = e; } auto ScriptsComponent::add_script(const path &script_path, EventManager *evt_mgr) -> ScriptsComponent & { const auto abs_path = Afk::get_absolute_path(script_path); auto lua_script = std::shared_ptr<LuaScript>(new LuaScript{evt_mgr, this->lua, this}); lua_script->load(abs_path); this->loaded_files.emplace(abs_path, lua_script); this->last_write.emplace(abs_path, std::filesystem::last_write_time(abs_path)); return *this; } auto ScriptsComponent::remove_script(const path &script_path) -> void { const auto abs_path = Afk::get_absolute_path(script_path); this->loaded_files.erase(abs_path); } auto ScriptsComponent::get_script_table(const std::string &script_path) -> LuaRef { const auto full_path = Afk::get_absolute_path(script_path); auto f = this->global_tables.find(full_path); if (f != this->global_tables.end()) { return f->second; } auto new_tbl = LuaRef::newTable(this->lua); this->global_tables.emplace(full_path, new_tbl); return new_tbl; } auto ScriptsComponent::check_live_reload() -> void { for (auto &script : this->loaded_files) { const auto &script_path = script.first; auto recent_write = std::filesystem::last_write_time(script_path); if (recent_write > this->last_write[script_path]) { script.second->unload(); script.second->load(script_path); this->last_write[script_path] = recent_write; } } }
1,728
613
// Copyright 2015 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webservd/log_manager.h" #include <arpa/inet.h> #include <netinet/in.h> #include <set> #include <vector> #include <base/files/file_enumerator.h> #include <base/files/file_util.h> #include <base/files/scoped_temp_dir.h> #include <base/strings/stringprintf.h> #include <gtest/gtest.h> namespace webservd { namespace { struct TestLogger : public LogManager::LoggerInterface { explicit TestLogger(std::string& last_entry) : last_entry_{last_entry} {} void Log(const base::Time& timestamp, const std::string& entry) override { last_entry_ = entry; } std::string& last_entry_; }; } // Anonymous namespace class LogManagerTest : public testing::Test { public: void SetUp() override { ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); } // Adds a test log entry to the file corresponding to the give |timestamp|. void LogEntry(const base::Time& timestamp) { sockaddr_in client_addr = {}; client_addr.sin_family = AF_INET; client_addr.sin_port = 80; inet_aton("10.11.12.13", &client_addr.sin_addr); LogManager::OnRequestCompleted( timestamp, reinterpret_cast<const sockaddr*>(&client_addr), "POST", "/test", "HTTP/1.0", 200, 123456); } // Get the list of current log files in the test log directory. std::set<std::string> GetLogFiles() const { std::set<std::string> log_files; base::FileEnumerator enumerator{temp_dir.GetPath(), false, base::FileEnumerator::FILES, "*.log"}; base::FilePath file = enumerator.Next(); while (!file.empty()) { log_files.insert(file.BaseName().value()); file = enumerator.Next(); } return log_files; } base::ScopedTempDir temp_dir; }; TEST_F(LogManagerTest, OnRequestCompleted) { std::string last_entry; LogManager::SetLogger( std::unique_ptr<LogManager::LoggerInterface>(new TestLogger{last_entry})); base::Time timestamp = base::Time::Now(); LogEntry(timestamp); tm time_buf = {}; char str_buf[32] = {}; time_t time = timestamp.ToTimeT(); strftime(str_buf, sizeof(str_buf), "%d/%b/%Y:%H:%M:%S %z", localtime_r(&time, &time_buf)); std::string match = base::StringPrintf( "10.11.12.13 - - [%s] \"POST /test HTTP/1.0\" 200 123456\n", str_buf); EXPECT_EQ(match, last_entry); } TEST_F(LogManagerTest, LogFileManagement) { LogManager::Init(temp_dir.GetPath()); EXPECT_TRUE(GetLogFiles().empty()); // Feb 25, 2015, 0:00:00 Local time tm date = {0, 0, 0, 25, 1, 115, 2, 55, 0}; base::Time timestamp = base::Time::FromTimeT(mktime(&date)); for (size_t i = 0; i < 10; i++) { LogEntry(timestamp); LogEntry(timestamp); LogEntry(timestamp); LogEntry(timestamp); timestamp += base::TimeDelta::FromDays(1); } std::set<std::string> expected_files{ "2015-02-28.log", "2015-03-01.log", "2015-03-02.log", "2015-03-03.log", "2015-03-04.log", "2015-03-05.log", "2015-03-06.log", }; EXPECT_EQ(expected_files, GetLogFiles()); } TEST_F(LogManagerTest, LargeLogs) { const size_t log_line_len = 78; // Test log entries are 78 chars long. LogManager::Init(temp_dir.GetPath()); EXPECT_TRUE(GetLogFiles().empty()); // Feb 25, 2015, 0:00:00 Local time tm date = {0, 0, 0, 25, 1, 115, 2, 55, 0}; base::Time timestamp = base::Time::FromTimeT(mktime(&date)); // Create 2015-02-25.log LogEntry(timestamp); timestamp += base::TimeDelta::FromDays(1); // Write a large 2015-02-26.log but with enough room for one more log line. std::vector<char> data(1024 * 1024 - (log_line_len * 3 / 2), ' '); base::FilePath current_file = temp_dir.GetPath().Append("2015-02-26.log"); ASSERT_EQ(static_cast<int>(data.size()), base::WriteFile(current_file, data.data(), data.size())); // Add the line. Should still go to the same file. LogEntry(timestamp); std::set<std::string> expected_files{ "2015-02-25.log", "2015-02-26.log", }; EXPECT_EQ(expected_files, GetLogFiles()); // Now this log entry will not fit and will end up creating a new file. LogEntry(timestamp); expected_files = { "2015-02-25.log", "2015-02-26-a.log", "2015-02-26.log", }; EXPECT_EQ(expected_files, GetLogFiles()); // Add some more data to the current file. ASSERT_TRUE(base::AppendToFile(current_file, data.data(), data.size())); LogEntry(timestamp); expected_files = { "2015-02-25.log", "2015-02-26-a.log", "2015-02-26-b.log", "2015-02-26.log", }; } } // namespace webservd
4,664
1,848
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/client/Waypoint.h" #include "carla/client/Map.h" namespace carla { namespace client { Waypoint::Waypoint(SharedPtr<const Map> parent, road::element::Waypoint waypoint) : _parent(std::move(parent)), _waypoint(std::move(waypoint)), _transform(_parent->GetMap().ComputeTransform(_waypoint)), _mark_record(_parent->GetMap().GetMarkRecord(_waypoint)) {} Waypoint::~Waypoint() = default; bool Waypoint::IsIntersection() const { return _parent->GetMap().IsJunction(_waypoint.road_id); } double Waypoint::GetLaneWidth() const { return _parent->GetMap().GetLaneWidth(_waypoint); } road::Lane::LaneType Waypoint::GetType() const { return _parent->GetMap().GetLaneType(_waypoint); } std::vector<SharedPtr<Waypoint>> Waypoint::GetNext(double distance) const { auto waypoints = _parent->GetMap().GetNext(_waypoint, distance); std::vector<SharedPtr<Waypoint>> result; result.reserve(waypoints.size()); for (auto &waypoint : waypoints) { result.emplace_back(SharedPtr<Waypoint>(new Waypoint(_parent, std::move(waypoint)))); } return result; } SharedPtr<Waypoint> Waypoint::GetRight() const { auto right_lane_waypoint = _parent->GetMap().GetRight(_waypoint); if (right_lane_waypoint.has_value()) { return SharedPtr<Waypoint>(new Waypoint(_parent, std::move(*right_lane_waypoint))); } return nullptr; } SharedPtr<Waypoint> Waypoint::GetLeft() const { auto left_lane_waypoint = _parent->GetMap().GetLeft(_waypoint); if (left_lane_waypoint.has_value()) { return SharedPtr<Waypoint>(new Waypoint(_parent, std::move(*left_lane_waypoint))); } return nullptr; } boost::optional<road::element::LaneMarking> Waypoint::GetRightLaneMarking() const { if (_mark_record.first != nullptr) { return road::element::LaneMarking(*_mark_record.first); } return boost::optional<road::element::LaneMarking>{}; } boost::optional<road::element::LaneMarking> Waypoint::GetLeftLaneMarking() const { if (_mark_record.first != nullptr) { return road::element::LaneMarking(*_mark_record.second); } return boost::optional<road::element::LaneMarking>{}; } template <typename EnumT> static EnumT operator&(EnumT lhs, EnumT rhs) { return static_cast<EnumT>( static_cast<typename std::underlying_type<EnumT>::type>(lhs) & static_cast<typename std::underlying_type<EnumT>::type>(rhs)); } template <typename EnumT> static EnumT operator|(EnumT lhs, EnumT rhs) { return static_cast<EnumT>( static_cast<typename std::underlying_type<EnumT>::type>(lhs) | static_cast<typename std::underlying_type<EnumT>::type>(rhs)); } road::element::LaneMarking::LaneChange Waypoint::GetLaneChange() const { using lane_change_type = road::element::LaneMarking::LaneChange; const auto lane_change_right_info = _mark_record.first; lane_change_type c_right; if (lane_change_right_info != nullptr) { const auto lane_change_right = lane_change_right_info->GetLaneChange(); c_right = static_cast<lane_change_type>(lane_change_right); } else { c_right = lane_change_type::Both; } const auto lane_change_left_info = _mark_record.second; lane_change_type c_left; if (lane_change_left_info != nullptr) { const auto lane_change_left = lane_change_left_info->GetLaneChange(); c_left = static_cast<lane_change_type>(lane_change_left); } else { c_left = lane_change_type::Both; } if (_waypoint.lane_id > 0) { // if road goes backward if (c_right == lane_change_type::Right) { c_right = lane_change_type::Left; } else if (c_right == lane_change_type::Left) { c_right = lane_change_type::Right; } } if (((_waypoint.lane_id > 0) ? _waypoint.lane_id - 1 : _waypoint.lane_id + 1) > 0) { // if road goes backward if (c_left == lane_change_type::Right) { c_left = lane_change_type::Left; } else if (c_left == lane_change_type::Left) { c_left = lane_change_type::Right; } } return (c_right & lane_change_type::Right) | (c_left & lane_change_type::Left); } } // namespace client } // namespace carla
4,502
1,553
#include <iostream> using namespace std; /* * Inheritance provides a way to create a new class from an existing class * New class is a specialized version of existing class * * Base Class (Parent) : inherited by child class * Derived class (Child) : inherits from the base class */ /* Here Undergrad class inherits Student Class class Student { }; class Undergrad : public Student { }; */ /* Rules classification * * An object of the child has: * 1. All members defined in the child class. * 2. All members declared in the parent class. * * An object of the child class can use: * 1. All public members defined in the child class * 2. All public members defined in the parent class * * Protected Members: * -> Protected members is similar to private - but accessible by objects of derived class * -> allows derived class to know details of parents * */ // Base Class class Shape { public: Shape() { length = 0; } void setlength(int l) { length = l; } protected: int length; }; // Derived Class class Square: public Shape{ public: Square(): Shape() { length = 0; } int get_Area() { return (length*length); } }; int main() { Square sq; sq.setlength(5); cout << "The total area of the square is: " << sq.get_Area() << endl; return 0; }
1,384
424
#include "stdafx.h" #include <string.h> #include <stdio.h> #include <string.h> #include <commdlg.h> #include <math.h> #include "mine.h" #include "dle-xp.h" #include "toolview.h" #include "PaletteManager.h" #include "TextureManager.h" //------------------------------------------------------------------------------ BEGIN_MESSAGE_MAP (CPaletteWnd, CWnd) #if 0 ON_WM_LBUTTONDOWN () ON_WM_RBUTTONDOWN () ON_WM_LBUTTONUP () ON_WM_RBUTTONUP () #endif END_MESSAGE_MAP () //------------------------------------------------------------------------------ BEGIN_MESSAGE_MAP (CTextureEdit, CDialog) ON_WM_PAINT () ON_WM_MOUSEMOVE () ON_WM_LBUTTONDOWN () ON_WM_RBUTTONDOWN () ON_WM_LBUTTONUP () ON_WM_RBUTTONUP () ON_BN_CLICKED (IDC_TEXEDIT_DEFAULT, OnDefault) ON_BN_CLICKED (IDC_TEXEDIT_UNDO, OnUndo) ON_BN_CLICKED (IDC_TEXEDIT_LOAD, OnLoad) ON_BN_CLICKED (IDC_TEXEDIT_SAVE, OnSave) END_MESSAGE_MAP () //------------------------------------------------------------------------------ CPaletteWnd::CPaletteWnd () { m_nWidth = m_nHeight = 0; m_pDC = null; m_pOldPal = null; } //------------------------------------------------------------------------------ CPaletteWnd::~CPaletteWnd () { } //------------------------------------------------------------------------------ #define MINRGB(rgb) (((rgb)->peRed < (rgb)->peGreen) ? ((rgb)->peRed < (rgb)->peBlue) ? (rgb)->peRed : (rgb)->peBlue : ((rgb)->peGreen < (rgb)->peBlue) ? (rgb)->peGreen : (rgb)->peBlue) #define MAXRGB(rgb) (((rgb)->peRed > (rgb)->peGreen) ? ((rgb)->peRed > (rgb)->peBlue) ? (rgb)->peRed : (rgb)->peBlue : ((rgb)->peGreen > (rgb)->peBlue) ? (rgb)->peGreen : (rgb)->peBlue) #define sqr(v) (((int)(v))*((int)(v))) int CPaletteWnd::CmpColors (PALETTEENTRY *c, PALETTEENTRY *m) { int i = c->peRed + c->peGreen + c->peBlue; //Luminance (c->peRed, c->peGreen, c->peBlue); int j = m->peRed + m->peGreen + m->peBlue; //Luminance (m->peRed, m->peGreen, m->peBlue); if (i < j) return -1; if (i > j) return 1; if (c->peRed < m->peRed) return -1; if (c->peRed > m->peRed) return 1; if (c->peGreen < m->peGreen) return -1; if (c->peGreen > m->peGreen) return 1; if (c->peBlue < m->peBlue) return -1; if (c->peBlue > m->peBlue) return 1; return 0; } //------------------------------------------------------------------------------ void CPaletteWnd::SortPalette (int left, int right) { int l = left, r = right; PALETTEENTRY m = m_palColors [(l + r) / 2]; do { while (CmpColors (m_palColors + l, &m) < 0) l++; while (CmpColors (m_palColors + r, &m) > 0) r--; if (l <= r) { if (l < r) { PALETTEENTRY h = m_palColors [l]; m_palColors [l] = h = m_palColors [r]; m_palColors [r] = h; ubyte i = m_nSortedPalIdx [l]; m_nSortedPalIdx [l] = m_nSortedPalIdx [r]; m_nSortedPalIdx [r] = i; } l++; r--; } } while (l <= r); if (left < r) SortPalette (left, r); if (l < right) SortPalette (l, right); } //------------------------------------------------------------------------------ void CPaletteWnd::CreatePalette () { for (int i = 0; i < 256; i++) { m_nSortedPalIdx [i] = i; RgbFromIndex (i, m_palColors [i]); } } //------------------------------------------------------------------------------ void CPaletteWnd::Update () { InvalidateRect (null); UpdateWindow (); } //------------------------------------------------------------------------------ int CPaletteWnd::Create (CWnd *pParentWnd, int nWidth, int nHeight) { CRect rc; m_pParentWnd = pParentWnd; pParentWnd->GetClientRect (rc); m_nWidth = nWidth; m_nHeight = nHeight; if (m_nWidth < 0) m_nWidth = rc.Width () / 8; if (m_nHeight < 0) { m_nHeight = rc.Height () / 8; if (m_nWidth * m_nHeight > 256) m_nHeight = (256 + m_nWidth - 1) / m_nWidth; } return CWnd::Create (null, null, WS_CHILD | WS_VISIBLE, rc, pParentWnd, 0); } //------------------------------------------------------------------------------ bool CPaletteWnd::SelectColor (CPoint& point, int& color, PALETTEENTRY *pRGB) { CRect rcPal; GetClientRect (rcPal); //ClientToScreen (rcPal); // if over palette, redefine foreground color if (PtInRect (rcPal, point)) { int x, y; // x = ((point.x - rcPal.left) >> 3)&127; // y = ((point.y - rcPal.top) >> 3)&31; x = (int) ((double) (point.x - rcPal.left) * ((double) m_nWidth / rcPal.Width ())); y = (int) ((double) (point.y - rcPal.top) * ((double) m_nHeight / rcPal.Height ())); int c = m_nWidth * y + x; if (c > 255) return false; color = m_nSortedPalIdx [c]; if (pRGB) *pRGB = m_palColors [c]; //RgbFromIndex (color, pRGB); return true; } return false; } //------------------------------------------------------------------------------ void CPaletteWnd::SetPalettePixel (int x, int y) { CRect rc; GetClientRect (&rc); int dx, dy; for (dy = 0; dy < 8; dy++) for (dx = 0; dx < 8; dx++) m_pDC->SetPixel ((x << 3) + dx + rc.left, (y << 3) + dy + rc.top, /*PALETTEINDEX*/ (y * m_nWidth + x)); } //------------------------------------------------------------------------------ void CPaletteWnd::DrawPalette (void) { if (!BeginPaint ()) return; CreatePalette (); //SortPalette (0, 255); CRect rc; GetClientRect (&rc); ubyte *bmPalette = new ubyte [m_nWidth * m_nHeight]; int h, i, c, w, x, y; for (c = 0, y = m_nHeight - 1; (y >= 0); y--) { for (x = 0, h = y * m_nWidth; x < m_nWidth; x++, h++) { if (!y) y = 0; bmPalette [h] = (c < 256) ? m_nSortedPalIdx [c++] : 0; } } BITMAPINFO* bmi = paletteManager.BMI (); bmi->bmiHeader.biWidth = m_nWidth; bmi->bmiHeader.biHeight = m_nHeight; bmi->bmiHeader.biBitCount = 8; bmi->bmiHeader.biClrUsed = 0; //CPalette *pOldPalette = m_pDC->SelectPalette (paletteManager.Render (), FALSE); //m_pDC->RealizePalette (); if (m_nWidth & 1) for (i = 0; i < m_nHeight; i++) { w = (i == m_nHeight - 1) ? 256 % m_nWidth : m_nWidth; StretchDIBits (m_pDC->m_hDC, 0, i * 8, w * 8, 8, 0, 0, w, 1, (void *) (bmPalette + (m_nHeight - i - 1) * m_nWidth), bmi, DIB_RGB_COLORS, SRCCOPY); } else StretchDIBits (m_pDC->m_hDC, 0, 0, m_nWidth * 8, m_nHeight * 8, 0, 0, m_nWidth, m_nHeight, (void *) bmPalette, bmi, DIB_RGB_COLORS, SRCCOPY); //m_pDC->SelectPalette (pOldPalette, FALSE); free (bmPalette); EndPaint (); } //------------------------------------------------------------------------------ bool CPaletteWnd::BeginPaint () { if (!IsWindow (m_hWnd)) return false; if (m_pDC) return false; if (!(m_pDC = GetDC ())) return false; m_pOldPal = m_pDC->SelectPalette (paletteManager.Render (), FALSE); m_pDC->RealizePalette (); return true; } //------------------------------------------------------------------------------ void CPaletteWnd::EndPaint () { if (m_pDC) { if (m_pOldPal) { m_pDC->SelectPalette (m_pOldPal, FALSE); m_pOldPal = null; } ReleaseDC (m_pDC); m_pDC = null; } Update (); } //------------------------------------------------------------------------------ #if 0 void CPaletteWnd::OnLButtonDown (UINT nFlags, CPoint point) { m_pParentWnd->SendMessage (WM_LBUTTONDOWN, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16)); } //------------------------------------------------------------------------------ void CPaletteWnd::OnRButtonDown (UINT nFlags, CPoint point) { m_pParentWnd->SendMessage (WM_RBUTTONDOWN, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16)); } //------------------------------------------------------------------------------ void CPaletteWnd::OnLButtonUp (UINT nFlags, CPoint point) { m_pParentWnd->SendMessage (WM_LBUTTONUP, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16)); } //------------------------------------------------------------------------------ void CPaletteWnd::OnRButtonUp (UINT nFlags, CPoint point) { m_pParentWnd->SendMessage (WM_RBUTTONUP, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16)); } #endif //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ CTextureEdit::CTextureEdit (const CTexture *pTexture, CWnd *pParent) : CDialog (IDD_EDITTEXTURE, pParent) { *m_szColors = '\0'; m_pDC = null; m_pPaintWnd = null; m_pOldPal = null; m_lBtnDown = m_rBtnDown = false; m_nTexAll = pTexture->Index (); strcpy_s (m_szName, sizeof (m_szName), pTexture->Name ()); _strlwr_s (m_szName, sizeof (m_szName)); } //------------------------------------------------------------------------------ CTextureEdit::~CTextureEdit () { m_texture [0].Clear (); m_texture [1].Clear (); } //------------------------------------------------------------------------------ BOOL CTextureEdit::OnInitDialog () { if (!textureManager.Available ()) return FALSE; CDialog::OnInitDialog (); CWnd* pWnd; CRect rc; const CTexture *pTexture = textureManager.TextureByIndex (m_nTexAll); pWnd = GetDlgItem (IDC_TEXEDIT_TEXTURE); pWnd->GetClientRect (rc); m_textureWnd.Create (null, null, WS_CHILD | WS_VISIBLE, rc, pWnd, 0); pWnd = GetDlgItem (IDC_TEXEDIT_PALETTE); pWnd->GetClientRect (rc); m_paletteWnd.Create (pWnd, 32, 8); pWnd = GetDlgItem (IDC_TEXEDIT_LAYERS); pWnd->GetClientRect (rc); m_layerWnd.Create (null, null, WS_CHILD | WS_VISIBLE, rc, pWnd, 0); // set cursor styles for bitmap windows SetCursor (LoadCursor (AfxGetInstanceHandle (), "PENCIL_CURSOR")); // PaletteButton->SetCursor(null, IDC_CROSS); m_fgColor = 0; // black m_bgColor = 1; // white m_lBtnDown = false; m_rBtnDown = false; m_bModified = false; m_bPendingRevert = false; if ((pTexture->Buffer () == null) || !pTexture->IsLoaded ()) { DEBUGMSG (" Texture tool: Invalid texture"); EndDialog (IDCANCEL); } else if (!m_texture [0].Copy (*pTexture)) { DEBUGMSG (" Texture tool: Not enough memory for texture editing"); EndDialog (IDCANCEL); } m_texture [1].Clear (); if (!m_texture [1].Copy (m_texture [0])) DEBUGMSG (" Texture tool: Not enough memory for undo function"); Backup (); Refresh (); m_nWidth = pTexture->Width (); m_nHeight = pTexture->Height (); return TRUE; } //------------------------------------------------------------------------------ void CTextureEdit::DoDataExchange (CDataExchange *pDX) { DDX_Text (pDX, IDC_TEXEDIT_COLORS, m_szColors, sizeof (m_szColors)); } //------------------------------------------------------------------------------ void CTextureEdit::Backup (void) { if (m_texture [1].Buffer ()) m_texture [1].Copy (m_texture [0]); } //------------------------------------------------------------------------------ bool CTextureEdit::PtInRect (CRect& rc, CPoint& pt) { return (pt.x >= rc.left) && (pt.x < rc.right) && (pt.y >= rc.top) && (pt.y < rc.bottom); } //------------------------------------------------------------------------------ void CTextureEdit::OnButtonDown (UINT nFlags, CPoint point, int& color) { CRect rcEdit, rcPal; GetClientRect (&m_textureWnd, rcEdit); GetClientRect (&m_paletteWnd, rcPal); if (PtInRect (rcEdit, point)) { Backup (); ColorPoint (nFlags, point, color); } else if (PtInRect (rcPal, point)) { point.x -= rcPal.left; point.y -= rcPal.top; if (m_paletteWnd.SelectColor (point, color)) DrawLayers (); } } //------------------------------------------------------------------------------ void CTextureEdit::OnOK () { if (m_bModified) textureManager.OverrideTexture (m_nTexAll, &m_texture [0]); else if (m_bPendingRevert) textureManager.RevertTexture (m_nTexAll); CDialog::OnOK (); } //------------------------------------------------------------------------------ void CTextureEdit::OnLButtonDown (UINT nFlags, CPoint point) { m_lBtnDown = TRUE; OnButtonDown (nFlags, point, m_fgColor); } //------------------------------------------------------------------------------ void CTextureEdit::OnRButtonDown (UINT nFlags, CPoint point) { m_rBtnDown = TRUE; OnButtonDown (nFlags, point, m_bgColor); } //------------------------------------------------------------------------------ void CTextureEdit::OnLButtonUp (UINT nFlags, CPoint point) { m_lBtnDown = FALSE; } //------------------------------------------------------------------------------ void CTextureEdit::OnRButtonUp (UINT nFlags, CPoint point) { m_rBtnDown = FALSE; } //------------------------------------------------------------------------------ void CTextureEdit::OnMouseMove (UINT nFlags, CPoint point) { if (m_lBtnDown) ColorPoint (nFlags, point, m_fgColor); else if (m_rBtnDown) ColorPoint (nFlags, point, m_bgColor); } //------------------------------------------------------------------------------ bool CTextureEdit::BeginPaint (CWnd *pWnd) { if (m_pDC) return false; if (!(m_pDC = pWnd->GetDC ())) return false; m_pPaintWnd = pWnd; m_pOldPal = m_pDC->SelectPalette (paletteManager.Render (), FALSE); m_pDC->RealizePalette (); return true; } //------------------------------------------------------------------------------ void CTextureEdit::EndPaint () { if (m_pPaintWnd) { if (m_pDC) { if (m_pOldPal) { m_pDC->SelectPalette (m_pOldPal, FALSE); m_pOldPal = null; } m_pPaintWnd->ReleaseDC (m_pDC); m_pDC = null; } Update (m_pPaintWnd); m_pPaintWnd = null; } } //------------------------------------------------------------------------------ void CTextureEdit::GetClientRect (CWnd *pWnd, CRect& rc) { CRect rcc; int dx, dy; pWnd->GetClientRect (&rcc); pWnd->GetWindowRect (rc); dx = rc.Width () - rcc.Width (); dy = rc.Height () - rcc.Height (); ScreenToClient (rc); rc.DeflateRect (dx / 2, dy / 2); } //------------------------------------------------------------------------------ // CTextureEdit - ColorPoint // // Action - Uses coordinates to determine which pixel mouse cursor is // over. If it is over the palette, the palette box will be updated with // the new color. If it is over the texture, the texture will be updated // with the color. // If control key is held down, color is defined by bitmap instead. //------------------------------------------------------------------------------ void CTextureEdit::ColorPoint (UINT nFlags, CPoint& point, int& color) { CRect rcEdit; GetClientRect (&m_textureWnd, rcEdit); if (m_texture [0].Format () == TGA) { m_lBtnDown = m_rBtnDown = false; ErrorMsg ("Cannot edit TGA images."); } else if (PtInRect (rcEdit, point)) { int x, y, nPixel; m_bModified = TRUE; // mark this as m_bModified // x = ((point.x - rcEdit.left) >> 2) & 63; // y = ((point.y - rcEdit.top) >> 2) & 63; x = (int) ((double) (point.x - rcEdit.left) * (double (m_nWidth) / rcEdit.Width ())); y = (int) ((double) (point.y - rcEdit.top) * (double (m_nHeight) / rcEdit.Height ())); nPixel = m_nWidth * (m_nHeight - 1 - y) + x; if (nFlags & MK_CONTROL) { color = paletteManager.ClosestColor (m_texture [0][nPixel]); DrawLayers (); } else if (BeginPaint (&m_textureWnd)) { m_texture [0][nPixel] = *paletteManager.Current (color); if (color >= 254) m_texture [0][nPixel].a = 0; SetTexturePixel (x, y); EndPaint (); } } } //------------------------------------------------------------------------------ void CTextureEdit::OnPaint () //EvDrawItem(UINT, DRAWITEMSTRUCT &) { CDialog::OnPaint (); Refresh (); } //------------------------------------------------------------------------------ void CTextureEdit::OnLoad () { char szFile [MAX_PATH] = {0}; const char *szDefExt = m_texture [0].Format () == BMP ? "bmp" : "tga"; CFileManager::tFileFilter filters [] = { { "Truevision Targa", "tga" }, { "256 color Bitmap Files", "bmp" } }; bool bFuncRes; sprintf_s (szFile, ARRAYSIZE (szFile), "*.%s", szDefExt); if (CFileManager::RunOpenFileDialog (szFile, ARRAYSIZE (szFile), filters, ARRAYSIZE (filters), m_hWnd)) { Backup (); bFuncRes = m_texture [0].LoadFromFile (szFile); if (bFuncRes) { Refresh (); m_nWidth = m_texture [0].Width (); m_nHeight = m_texture [0].Height (); m_nSize = m_texture [0].Size (); m_bModified = TRUE; } else OnUndo (); } } //------------------------------------------------------------------------------ void CTextureEdit::OnSave () { char szFile [MAX_PATH] = { 0 }; const char *szExt = m_texture [0].Format () == BMP ? "bmp" : "tga"; CFileManager::tFileFilter filters [] = { { "256 color Bitmap Files", "bmp" }, { "Truevision Targa", "tga" } }; CFileManager::tFileFilter *filter = m_texture [0].Format () == BMP ? &filters [0] : &filters [1]; sprintf_s (szFile, ARRAYSIZE (szFile), "%s.%s", m_szName, szExt); if (CFileManager::RunSaveFileDialog (szFile, ARRAYSIZE (szFile), filter, 1, m_hWnd)) { _strlwr_s (szFile, sizeof (szFile)); m_texture [0].Save (szFile); } } //------------------------------------------------------------------------------ void CTextureEdit::OnUndo () { if (m_texture [1].Buffer ()) { m_texture [0].Copy (m_texture [1]); // This combination should only happen immediately after OnDefault. // In this case we reverse it so the user is still prompted on save. if (m_bPendingRevert && !m_bModified) { m_bModified = true; m_bPendingRevert = false; } Refresh (); } } void CTextureEdit::Update (CWnd *pWnd) { pWnd->InvalidateRect (null); pWnd->UpdateWindow (); } //------------------------------------------------------------------------------ void CTextureEdit::OnDefault (void) { if (QueryMsg("Are you sure you want to restore this texture\n" "back to its original texture\n") == IDYES) { Backup (); m_texture [0].Copy (*textureManager.BaseTextures (m_nTexAll)); m_bModified = false; m_bPendingRevert = true; Refresh (); } } //------------------------------------------------------------------------------ void CTextureEdit::DrawTexture (void) { if (!BeginPaint (&m_textureWnd)) return; m_pDC->SetStretchBltMode (STRETCH_DELETESCANS); BITMAPINFO* bmi = paletteManager.BMI (); bmi->bmiHeader.biWidth = bmi->bmiHeader.biHeight = m_texture [0].RenderWidth (); bmi->bmiHeader.biBitCount = 32; //bmi->bmiHeader.biSizeImage = m_texture [0].BufSize (); bmi->bmiHeader.biClrUsed = 0; CRect rc; m_textureWnd.GetClientRect (&rc); StretchDIBits (m_pDC->m_hDC, 0, 0, rc.right, rc.bottom, 0, 0, m_texture [0].RenderWidth (), m_texture [0].RenderWidth (), (void *) m_texture [0].RenderBuffer (), bmi, DIB_RGB_COLORS, SRCCOPY); EndPaint (); } //------------------------------------------------------------------------------ void CTextureEdit::DrawPalette (void) { m_paletteWnd.DrawPalette (); } //------------------------------------------------------------------------------ void CTextureEdit::DrawLayers () { if (!BeginPaint (&m_layerWnd)) return; CRect rc; m_layerWnd.GetClientRect (&rc); rc.DeflateRect (10, 10); rc.right -= 10; rc.bottom -= 10; m_pDC->FillSolidRect (&rc, PALETTEINDEX (m_bgColor)); rc.OffsetRect (10, 10); m_pDC->FillSolidRect (&rc, PALETTEINDEX (m_fgColor)); EndPaint (); // set message char fg_color[30]; char bg_color[30]; switch(m_fgColor) { case 255: strcpy_s (fg_color, sizeof (fg_color), "transparent"); break; case 254: strcpy_s (fg_color, sizeof (fg_color), "see thru"); break; default : sprintf_s (fg_color, sizeof (fg_color), "color %d", m_fgColor); break; } switch(m_bgColor) { case 255: strcpy_s (bg_color, sizeof (bg_color), "transparent"); break; case 254: strcpy_s (bg_color, sizeof (bg_color), "see thru"); break; default : sprintf_s (bg_color, sizeof (bg_color), "color %d", m_bgColor); break; } sprintf_s (m_szColors, sizeof (m_szColors), "foreground = %s, background = %s.", fg_color, bg_color); UpdateData (FALSE); } //------------------------------------------------------------------------------ void CTextureEdit::Refresh (void) { DrawTexture (); DrawPalette (); DrawLayers (); } //------------------------------------------------------------------------------ void CTextureEdit::SetTexturePixel (int x, int y) { CRect rc; int cx, cy; double xs, ys; #ifdef _DEBUG CBGR& rgb = m_texture [0][(63 - y) * 64 + x]; int color = rgb.ColorRef (); #else int color = m_texture [0][(63 - y) * 64 + x].ColorRef (); #endif m_textureWnd.GetClientRect (&rc); cx = rc.Width (); cy = rc.Height (); xs = (double) cx / 64.0; ys = (double) cy / 64.0; x = rc.left + (int) ((double) x * xs); y = rc.top + (int) ((double) y * ys); int dx, dy; xs /= 4.0; ys /= 4.0; for (dy = 0; dy < 4; dy++) for (dx = 0; dx < 4; dx++) m_pDC->SetPixel (x + (int) ((double) dx * xs), y + (int) ((double) dy * ys), color); } //------------------------------------------------------------------------------ void CTextureEdit::SetPalettePixel (int x, int y) { CRect rc; m_paletteWnd.GetClientRect (&rc); int dx, dy; for (dy = 0; dy < 8; dy++) for (dx = 0; dx < 8; dx++) m_pDC->SetPixel ((x << 3) + dx + rc.left, (y << 3) + dy + rc.top, PALETTEINDEX (y * 32 + x)); } //------------------------------------------------------------------------------
20,771
8,054
// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include "..\hooks.hpp" using LockCursor_t = void(__thiscall*)(void*); void __stdcall hooks::hooked_lockcursor() { static auto original_fn = surface_hook->get_func_address <LockCursor_t> (67); if (!menu_open) return original_fn(m_surface()); m_surface()->UnlockCursor(); }
477
172
<?hh // strict namespace SebastianBergmann\TextTemplate; /* * This file is part of the Text_Template package. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use \InvalidArgumentException; use \RuntimeException; /** * A simple template engine. * * @since Class available since Release 1.0.0 */ class Template { /** * @var string */ protected string $template = ''; /** * @var string */ protected string $openDelimiter = '{'; /** * @var string */ protected string $closeDelimiter = '}'; /** * Constructor. * * @param string $file * @throws InvalidArgumentException */ public function __construct( string $file = '', string $openDelimiter = '{', string $closeDelimiter = '}', ) { $this->setFile($file); $this->openDelimiter = $openDelimiter; $this->closeDelimiter = $closeDelimiter; } /** * Sets the template file. * * @param string $file * @throws InvalidArgumentException */ public function setFile(string $file, string $extension = '.dist'): void { $distFile = $file.$extension; if (file_exists($file)) { $this->template = file_get_contents($file); } else if (file_exists($distFile)) { $this->template = file_get_contents($distFile); } else { throw new InvalidArgumentException( 'Template file could not be loaded. file='.$file, ); } } public function setOpenDelimiter(string $delim): void { $this->openDelimiter = $delim; } public function setCloseDelimiter(string $delim): void { $this->closeDelimiter = $delim; } /** * Renders the template and returns the result. * * @return string */ public function render( Map<string, mixed> $values, bool $trimTemplate = false, ): string { $searchStrings = array(); $replaceValues = array(); foreach ($values as $key => $value) { $templateKey = $this->openDelimiter.$key.$this->closeDelimiter; $searchStrings[] = $templateKey; $replaceValues[] = $value; } $rendered = str_replace($searchStrings, $replaceValues, $this->template); if ($trimTemplate === true) { return trim($rendered); } return $rendered; } /** * Renders the template and writes the result to a file. * * @param string $target */ public function renderTo(string $target, Map<string, mixed> $values): void { $fp = @fopen($target, 'wt'); if (is_resource($fp)) { fwrite($fp, $this->render($values)); fclose($fp); } else { $error = error_get_last(); throw new RuntimeException( sprintf( 'Could not write to %s: %s', $target, substr($error['message'], strpos($error['message'], ':') + 2), ), ); } } }
2,967
927
/** * \file TkModuleGroupSelector.cc * * \author Joerg Behr * \date May 2013 * $Revision: 1.5 $ * $Date: 2013/06/19 08:33:03 $ * (last update by $Author: jbehr $) */ #include "Alignment/CommonAlignmentAlgorithm/interface/TkModuleGroupSelector.h" #include "Alignment/CommonAlignmentAlgorithm/interface/AlignmentParameterSelector.h" #include "Alignment/CommonAlignment/interface/Alignable.h" #include "DataFormats/DetId/interface/DetId.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <vector> #include <map> #include <set> //============================================================================ TkModuleGroupSelector::TkModuleGroupSelector(AlignableTracker *aliTracker, const edm::ParameterSet &cfg, const std::vector<int> &sdets) : nparameters_(0), subdetids_(sdets) { //verify that all provided options are known std::vector<std::string> parameterNames = cfg.getParameterNames(); for (std::vector<std::string>::const_iterator iParam = parameterNames.begin(); iParam != parameterNames.end(); ++iParam) { const std::string name = (*iParam); if (name != "RunRange" && name != "ReferenceRun" && name != "Granularity") { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::TkModuleGroupSelector:" << " Unknown parameter name '" << name << "' in PSet. Maybe a typo?"; } } //extract the reference run range if defined const edm::RunNumber_t defaultReferenceRun = (cfg.exists("ReferenceRun") ? cfg.getParameter<edm::RunNumber_t>("ReferenceRun") : 0); //extract run range to be used for all module groups (if not locally overwritten) const std::vector<edm::RunNumber_t> defaultRunRange = (cfg.exists("RunRange") ? cfg.getParameter<std::vector<edm::RunNumber_t> >("RunRange") : std::vector<edm::RunNumber_t>()); // finally create everything from configuration this->createModuleGroups( aliTracker, cfg.getParameter<edm::VParameterSet>("Granularity"), defaultRunRange, defaultReferenceRun); } //============================================================================ void TkModuleGroupSelector::fillDetIdMap(const unsigned int detid, const unsigned int groupid) { //only add new entries if (mapDetIdGroupId_.find(detid) == mapDetIdGroupId_.end()) { mapDetIdGroupId_.insert(std::pair<unsigned int, unsigned int>(detid, groupid)); } else { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector:fillDetIdMap:" << " Module with det ID " << detid << " configured in group " << groupid << " but it was already selected" << " in group " << mapDetIdGroupId_[detid] << "."; } } //============================================================================ const bool TkModuleGroupSelector::testSplitOption(const edm::ParameterSet &pset) const { bool split = false; if (pset.exists("split")) { split = pset.getParameter<bool>("split"); } return split; } //============================================================================ bool TkModuleGroupSelector::createGroup(unsigned int &Id, const std::vector<edm::RunNumber_t> &range, const std::list<Alignable *> &selected_alis, const edm::RunNumber_t refrun) { bool modules_selected = false; referenceRun_.push_back(refrun); firstId_.push_back(Id); runRange_.push_back(range); for (std::list<Alignable *>::const_iterator it = selected_alis.begin(); it != selected_alis.end(); ++it) { this->fillDetIdMap((*it)->id(), firstId_.size() - 1); modules_selected = true; } if (refrun > 0 && !range.empty()) { //FIXME: last condition not really needed? Id += range.size() - 1; nparameters_ += range.size() - 1; } else { Id += range.size(); nparameters_ += range.size(); } if (refrun > 0 && range.front() > refrun) { //range.size() > 0 checked before throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createGroup:\n" << "Invalid combination of reference run number and specified run dependence" << "\n in module group " << firstId_.size() << "." << "\n Reference run number (" << refrun << ") is smaller than starting run " << "\n number (" << range.front() << ") of first IOV."; } return modules_selected; } //============================================================================ void TkModuleGroupSelector::verifyParameterNames(const edm::ParameterSet &pset, unsigned int psetnr) const { std::vector<std::string> parameterNames = pset.getParameterNames(); for (std::vector<std::string>::const_iterator iParam = parameterNames.begin(); iParam != parameterNames.end(); ++iParam) { const std::string name = (*iParam); if (name != "levels" && name != "RunRange" && name != "split" && name != "ReferenceRun") { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::verifyParameterNames:" << " Unknown parameter name '" << name << "' in PSet number " << psetnr << ". Maybe a typo?"; } } } //============================================================================ void TkModuleGroupSelector::createModuleGroups(AlignableTracker *aliTracker, const edm::VParameterSet &granularityConfig, const std::vector<edm::RunNumber_t> &defaultRunRange, edm::RunNumber_t defaultReferenceRun) { std::set<edm::RunNumber_t> localRunRange; nparameters_ = 0; unsigned int Id = 0; unsigned int psetnr = 0; //loop over all LA groups for (edm::VParameterSet::const_iterator pset = granularityConfig.begin(); pset != granularityConfig.end(); ++pset) { //test for unknown parameters this->verifyParameterNames((*pset), psetnr); psetnr++; bool modules_selected = false; //track whether at all a module has been selected in this group const std::vector<edm::RunNumber_t> range = ((*pset).exists("RunRange") ? pset->getParameter<std::vector<edm::RunNumber_t> >("RunRange") : defaultRunRange); if (range.empty()) { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createModuleGroups:\n" << "Run range array empty!"; } const bool split = this->testSplitOption((*pset)); edm::RunNumber_t refrun = 0; if ((*pset).exists("ReferenceRun")) { refrun = (*pset).getParameter<edm::RunNumber_t>("ReferenceRun"); } else { refrun = defaultReferenceRun; } AlignmentParameterSelector selector(aliTracker); selector.clear(); selector.addSelections((*pset).getParameter<edm::ParameterSet>("levels")); const auto &alis = selector.selectedAlignables(); std::list<Alignable *> selected_alis; for (const auto &it : alis) { const auto &aliDaughts = it->deepComponents(); for (const auto &iD : aliDaughts) { if (iD->alignableObjectId() == align::AlignableDetUnit || iD->alignableObjectId() == align::AlignableDet) { if (split) { modules_selected = this->createGroup(Id, range, std::list<Alignable *>(1, iD), refrun); } else { selected_alis.push_back(iD); } } } } if (!split) { modules_selected = this->createGroup(Id, range, selected_alis, refrun); } edm::RunNumber_t firstRun = 0; for (std::vector<edm::RunNumber_t>::const_iterator iRun = range.begin(); iRun != range.end(); ++iRun) { localRunRange.insert((*iRun)); if ((*iRun) > firstRun) { firstRun = (*iRun); } else { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::createModuleGroups:" << " Run range not sorted."; } } if (!modules_selected) { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector:createModuleGroups:" << " No module was selected in the module group selector in group " << (firstId_.size() - 1) << "."; } } //copy local set into the global vector of run boundaries for (std::set<edm::RunNumber_t>::const_iterator itRun = localRunRange.begin(); itRun != localRunRange.end(); ++itRun) { globalRunRange_.push_back((*itRun)); } } //============================================================================ unsigned int TkModuleGroupSelector::getNumberOfParameters() const { return nparameters_; } //============================================================================ unsigned int TkModuleGroupSelector::numIovs() const { return globalRunRange_.size(); } //============================================================================ edm::RunNumber_t TkModuleGroupSelector::firstRunOfIOV(unsigned int iovNum) const { return iovNum < this->numIovs() ? globalRunRange_.at(iovNum) : 0; } //====================================================================== int TkModuleGroupSelector::getParameterIndexFromDetId(unsigned int detId, edm::RunNumber_t run) const { // Return the index of the parameter that is used for this DetId. // If this DetId is not treated, return values < 0. const DetId temp_id(detId); int index = -1; bool sel = false; for (std::vector<int>::const_iterator itSubDets = subdetids_.begin(); itSubDets != subdetids_.end(); ++itSubDets) { if (temp_id.det() == DetId::Tracker && temp_id.subdetId() == (*itSubDets)) { sel = true; break; } } if (temp_id.det() != DetId::Tracker || !sel) return -1; std::map<unsigned int, unsigned int>::const_iterator it = mapDetIdGroupId_.find(detId); if (it != mapDetIdGroupId_.end()) { const unsigned int iAlignableGroup = (*it).second; const std::vector<edm::RunNumber_t> &runs = runRange_.at(iAlignableGroup); const unsigned int id0 = firstId_.at(iAlignableGroup); const edm::RunNumber_t refrun = referenceRun_.at(iAlignableGroup); unsigned int iovNum = 0; for (; iovNum < runs.size(); ++iovNum) { if (runs[iovNum] > run) break; } if (iovNum == 0) { throw cms::Exception("BadConfig") << "@SUB=TkModuleGroupSelector::getParameterIndexFromDetId:\n" << "Run " << run << " not foreseen for detid '" << detId << "'" << " in module group " << iAlignableGroup << "."; } else { --iovNum; } //test whether the iov contains the reference run if (refrun > 0) { //if > 0 a reference run number has been provided if (iovNum + 1 == runs.size()) { if (refrun >= runs[iovNum]) return -1; } else if ((iovNum + 1) < runs.size()) { if (refrun >= runs[iovNum] && refrun < runs[iovNum + 1]) { return -1; } } if (run > refrun) { //iovNum > 0 due to checks in createGroup(...) and createModuleGroups(...) //remove IOV in which the reference run can be found iovNum -= 1; } } index = id0 + iovNum; } return index; }
11,604
3,386
#define YAP_CPP_INTERFACE 1 #include <gmpxx.h> //! @{ /** * * @defgroup yap-cplus-interface An object oriented interface for YAP. * * @ingroup ChYInterface * @tableofcontents * * * C++ interface to YAP. Designed to be object oriented and to fit naturally * with the swig interface language generator. It uses ideas from the old YAP * interface and from the SWI foreign language interface. * */ #include <stdlib.h> #include <string> // Bad export from Python #include <config.h> extern "C" { #include <stddef.h> #include "Yap.h" #include "Yatom.h" #include "YapHeap.h" #include "clause.h" #include "yapio.h" #include "Foreign.h" #include "attvar.h" #include "YapText.h" #if HAVE_STDARG_H #include <stdarg.h> #endif #if HAVE_STDINT_H #include <stdint.h> #endif #if HAVE_STRING_H #include <string.h> #endif #if _MSC_VER || defined(__MINGW32__) //#include <windows.h> #endif // taken from yap_structs.h #include "iopreds.h" X_API void YAP_UserCPredicate(const char *, YAP_UserCPred, YAP_Arity arity); /* void UserCPredicateWithArgs(const char *name, int *fn(), unsigned int arity) */ X_API void YAP_UserCPredicateWithArgs(const char *, YAP_UserCPred, YAP_Arity, YAP_Term); /* void UserBackCPredicate(const char *name, int *init(), int *cont(), int arity, int extra) */ X_API void YAP_UserBackCPredicate(const char *, YAP_UserCPred, YAP_UserCPred, YAP_Arity, YAP_Arity); X_API Term Yap_StringToTerm(const char *s, size_t len, encoding_t *encp, int prio, Term *bindings_p); } class YAPEngine; class YAPAtom; class YAPFunctor; class YAPApplTerm; class YAPPairTerm; class YAPQuery; class YAPModule; class YAPError; class YAPPredicate; #include "yapa.hh" #include "yapie.hh" #include "yapt.hh" #include "yapdb.hh" #include "yapq.hh" /** * @} * */
1,802
741
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "IP_MIB.hpp" using namespace ydk; namespace cisco_ios_xe { namespace IP_MIB { IPMIB::IPMIB() : ip(std::make_shared<IPMIB::Ip>()) , iptrafficstats(std::make_shared<IPMIB::IpTrafficStats>()) , icmp(std::make_shared<IPMIB::Icmp>()) , ipaddrtable(std::make_shared<IPMIB::IpAddrTable>()) , ipnettomediatable(std::make_shared<IPMIB::IpNetToMediaTable>()) , ipv4interfacetable(std::make_shared<IPMIB::Ipv4InterfaceTable>()) , ipv6interfacetable(std::make_shared<IPMIB::Ipv6InterfaceTable>()) , ipsystemstatstable(std::make_shared<IPMIB::IpSystemStatsTable>()) , ipifstatstable(std::make_shared<IPMIB::IpIfStatsTable>()) , ipaddressprefixtable(std::make_shared<IPMIB::IpAddressPrefixTable>()) , ipaddresstable(std::make_shared<IPMIB::IpAddressTable>()) , ipnettophysicaltable(std::make_shared<IPMIB::IpNetToPhysicalTable>()) , ipv6scopezoneindextable(std::make_shared<IPMIB::Ipv6ScopeZoneIndexTable>()) , ipdefaultroutertable(std::make_shared<IPMIB::IpDefaultRouterTable>()) , ipv6routeradverttable(std::make_shared<IPMIB::Ipv6RouterAdvertTable>()) , icmpstatstable(std::make_shared<IPMIB::IcmpStatsTable>()) , icmpmsgstatstable(std::make_shared<IPMIB::IcmpMsgStatsTable>()) { ip->parent = this; iptrafficstats->parent = this; icmp->parent = this; ipaddrtable->parent = this; ipnettomediatable->parent = this; ipv4interfacetable->parent = this; ipv6interfacetable->parent = this; ipsystemstatstable->parent = this; ipifstatstable->parent = this; ipaddressprefixtable->parent = this; ipaddresstable->parent = this; ipnettophysicaltable->parent = this; ipv6scopezoneindextable->parent = this; ipdefaultroutertable->parent = this; ipv6routeradverttable->parent = this; icmpstatstable->parent = this; icmpmsgstatstable->parent = this; yang_name = "IP-MIB"; yang_parent_name = "IP-MIB"; is_top_level_class = true; has_list_ancestor = false; } IPMIB::~IPMIB() { } bool IPMIB::has_data() const { if (is_presence_container) return true; return (ip != nullptr && ip->has_data()) || (iptrafficstats != nullptr && iptrafficstats->has_data()) || (icmp != nullptr && icmp->has_data()) || (ipaddrtable != nullptr && ipaddrtable->has_data()) || (ipnettomediatable != nullptr && ipnettomediatable->has_data()) || (ipv4interfacetable != nullptr && ipv4interfacetable->has_data()) || (ipv6interfacetable != nullptr && ipv6interfacetable->has_data()) || (ipsystemstatstable != nullptr && ipsystemstatstable->has_data()) || (ipifstatstable != nullptr && ipifstatstable->has_data()) || (ipaddressprefixtable != nullptr && ipaddressprefixtable->has_data()) || (ipaddresstable != nullptr && ipaddresstable->has_data()) || (ipnettophysicaltable != nullptr && ipnettophysicaltable->has_data()) || (ipv6scopezoneindextable != nullptr && ipv6scopezoneindextable->has_data()) || (ipdefaultroutertable != nullptr && ipdefaultroutertable->has_data()) || (ipv6routeradverttable != nullptr && ipv6routeradverttable->has_data()) || (icmpstatstable != nullptr && icmpstatstable->has_data()) || (icmpmsgstatstable != nullptr && icmpmsgstatstable->has_data()); } bool IPMIB::has_operation() const { return is_set(yfilter) || (ip != nullptr && ip->has_operation()) || (iptrafficstats != nullptr && iptrafficstats->has_operation()) || (icmp != nullptr && icmp->has_operation()) || (ipaddrtable != nullptr && ipaddrtable->has_operation()) || (ipnettomediatable != nullptr && ipnettomediatable->has_operation()) || (ipv4interfacetable != nullptr && ipv4interfacetable->has_operation()) || (ipv6interfacetable != nullptr && ipv6interfacetable->has_operation()) || (ipsystemstatstable != nullptr && ipsystemstatstable->has_operation()) || (ipifstatstable != nullptr && ipifstatstable->has_operation()) || (ipaddressprefixtable != nullptr && ipaddressprefixtable->has_operation()) || (ipaddresstable != nullptr && ipaddresstable->has_operation()) || (ipnettophysicaltable != nullptr && ipnettophysicaltable->has_operation()) || (ipv6scopezoneindextable != nullptr && ipv6scopezoneindextable->has_operation()) || (ipdefaultroutertable != nullptr && ipdefaultroutertable->has_operation()) || (ipv6routeradverttable != nullptr && ipv6routeradverttable->has_operation()) || (icmpstatstable != nullptr && icmpstatstable->has_operation()) || (icmpmsgstatstable != nullptr && icmpmsgstatstable->has_operation()); } std::string IPMIB::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ip") { if(ip == nullptr) { ip = std::make_shared<IPMIB::Ip>(); } return ip; } if(child_yang_name == "ipTrafficStats") { if(iptrafficstats == nullptr) { iptrafficstats = std::make_shared<IPMIB::IpTrafficStats>(); } return iptrafficstats; } if(child_yang_name == "icmp") { if(icmp == nullptr) { icmp = std::make_shared<IPMIB::Icmp>(); } return icmp; } if(child_yang_name == "ipAddrTable") { if(ipaddrtable == nullptr) { ipaddrtable = std::make_shared<IPMIB::IpAddrTable>(); } return ipaddrtable; } if(child_yang_name == "ipNetToMediaTable") { if(ipnettomediatable == nullptr) { ipnettomediatable = std::make_shared<IPMIB::IpNetToMediaTable>(); } return ipnettomediatable; } if(child_yang_name == "ipv4InterfaceTable") { if(ipv4interfacetable == nullptr) { ipv4interfacetable = std::make_shared<IPMIB::Ipv4InterfaceTable>(); } return ipv4interfacetable; } if(child_yang_name == "ipv6InterfaceTable") { if(ipv6interfacetable == nullptr) { ipv6interfacetable = std::make_shared<IPMIB::Ipv6InterfaceTable>(); } return ipv6interfacetable; } if(child_yang_name == "ipSystemStatsTable") { if(ipsystemstatstable == nullptr) { ipsystemstatstable = std::make_shared<IPMIB::IpSystemStatsTable>(); } return ipsystemstatstable; } if(child_yang_name == "ipIfStatsTable") { if(ipifstatstable == nullptr) { ipifstatstable = std::make_shared<IPMIB::IpIfStatsTable>(); } return ipifstatstable; } if(child_yang_name == "ipAddressPrefixTable") { if(ipaddressprefixtable == nullptr) { ipaddressprefixtable = std::make_shared<IPMIB::IpAddressPrefixTable>(); } return ipaddressprefixtable; } if(child_yang_name == "ipAddressTable") { if(ipaddresstable == nullptr) { ipaddresstable = std::make_shared<IPMIB::IpAddressTable>(); } return ipaddresstable; } if(child_yang_name == "ipNetToPhysicalTable") { if(ipnettophysicaltable == nullptr) { ipnettophysicaltable = std::make_shared<IPMIB::IpNetToPhysicalTable>(); } return ipnettophysicaltable; } if(child_yang_name == "ipv6ScopeZoneIndexTable") { if(ipv6scopezoneindextable == nullptr) { ipv6scopezoneindextable = std::make_shared<IPMIB::Ipv6ScopeZoneIndexTable>(); } return ipv6scopezoneindextable; } if(child_yang_name == "ipDefaultRouterTable") { if(ipdefaultroutertable == nullptr) { ipdefaultroutertable = std::make_shared<IPMIB::IpDefaultRouterTable>(); } return ipdefaultroutertable; } if(child_yang_name == "ipv6RouterAdvertTable") { if(ipv6routeradverttable == nullptr) { ipv6routeradverttable = std::make_shared<IPMIB::Ipv6RouterAdvertTable>(); } return ipv6routeradverttable; } if(child_yang_name == "icmpStatsTable") { if(icmpstatstable == nullptr) { icmpstatstable = std::make_shared<IPMIB::IcmpStatsTable>(); } return icmpstatstable; } if(child_yang_name == "icmpMsgStatsTable") { if(icmpmsgstatstable == nullptr) { icmpmsgstatstable = std::make_shared<IPMIB::IcmpMsgStatsTable>(); } return icmpmsgstatstable; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(ip != nullptr) { _children["ip"] = ip; } if(iptrafficstats != nullptr) { _children["ipTrafficStats"] = iptrafficstats; } if(icmp != nullptr) { _children["icmp"] = icmp; } if(ipaddrtable != nullptr) { _children["ipAddrTable"] = ipaddrtable; } if(ipnettomediatable != nullptr) { _children["ipNetToMediaTable"] = ipnettomediatable; } if(ipv4interfacetable != nullptr) { _children["ipv4InterfaceTable"] = ipv4interfacetable; } if(ipv6interfacetable != nullptr) { _children["ipv6InterfaceTable"] = ipv6interfacetable; } if(ipsystemstatstable != nullptr) { _children["ipSystemStatsTable"] = ipsystemstatstable; } if(ipifstatstable != nullptr) { _children["ipIfStatsTable"] = ipifstatstable; } if(ipaddressprefixtable != nullptr) { _children["ipAddressPrefixTable"] = ipaddressprefixtable; } if(ipaddresstable != nullptr) { _children["ipAddressTable"] = ipaddresstable; } if(ipnettophysicaltable != nullptr) { _children["ipNetToPhysicalTable"] = ipnettophysicaltable; } if(ipv6scopezoneindextable != nullptr) { _children["ipv6ScopeZoneIndexTable"] = ipv6scopezoneindextable; } if(ipdefaultroutertable != nullptr) { _children["ipDefaultRouterTable"] = ipdefaultroutertable; } if(ipv6routeradverttable != nullptr) { _children["ipv6RouterAdvertTable"] = ipv6routeradverttable; } if(icmpstatstable != nullptr) { _children["icmpStatsTable"] = icmpstatstable; } if(icmpmsgstatstable != nullptr) { _children["icmpMsgStatsTable"] = icmpmsgstatstable; } return _children; } void IPMIB::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr<ydk::Entity> IPMIB::clone_ptr() const { return std::make_shared<IPMIB>(); } std::string IPMIB::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string IPMIB::get_bundle_name() const { return "cisco_ios_xe"; } augment_capabilities_function IPMIB::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> IPMIB::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool IPMIB::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ip" || name == "ipTrafficStats" || name == "icmp" || name == "ipAddrTable" || name == "ipNetToMediaTable" || name == "ipv4InterfaceTable" || name == "ipv6InterfaceTable" || name == "ipSystemStatsTable" || name == "ipIfStatsTable" || name == "ipAddressPrefixTable" || name == "ipAddressTable" || name == "ipNetToPhysicalTable" || name == "ipv6ScopeZoneIndexTable" || name == "ipDefaultRouterTable" || name == "ipv6RouterAdvertTable" || name == "icmpStatsTable" || name == "icmpMsgStatsTable") return true; return false; } IPMIB::Ip::Ip() : ipforwarding{YType::enumeration, "ipForwarding"}, ipdefaultttl{YType::int32, "ipDefaultTTL"}, ipinreceives{YType::uint32, "ipInReceives"}, ipinhdrerrors{YType::uint32, "ipInHdrErrors"}, ipinaddrerrors{YType::uint32, "ipInAddrErrors"}, ipforwdatagrams{YType::uint32, "ipForwDatagrams"}, ipinunknownprotos{YType::uint32, "ipInUnknownProtos"}, ipindiscards{YType::uint32, "ipInDiscards"}, ipindelivers{YType::uint32, "ipInDelivers"}, ipoutrequests{YType::uint32, "ipOutRequests"}, ipoutdiscards{YType::uint32, "ipOutDiscards"}, ipoutnoroutes{YType::uint32, "ipOutNoRoutes"}, ipreasmtimeout{YType::int32, "ipReasmTimeout"}, ipreasmreqds{YType::uint32, "ipReasmReqds"}, ipreasmoks{YType::uint32, "ipReasmOKs"}, ipreasmfails{YType::uint32, "ipReasmFails"}, ipfragoks{YType::uint32, "ipFragOKs"}, ipfragfails{YType::uint32, "ipFragFails"}, ipfragcreates{YType::uint32, "ipFragCreates"}, iproutingdiscards{YType::uint32, "ipRoutingDiscards"}, ipv6ipforwarding{YType::enumeration, "ipv6IpForwarding"}, ipv6ipdefaulthoplimit{YType::int32, "ipv6IpDefaultHopLimit"}, ipv4interfacetablelastchange{YType::uint32, "ipv4InterfaceTableLastChange"}, ipv6interfacetablelastchange{YType::uint32, "ipv6InterfaceTableLastChange"}, ipaddressspinlock{YType::int32, "ipAddressSpinLock"}, ipv6routeradvertspinlock{YType::int32, "ipv6RouterAdvertSpinLock"} { yang_name = "ip"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ip::~Ip() { } bool IPMIB::Ip::has_data() const { if (is_presence_container) return true; return ipforwarding.is_set || ipdefaultttl.is_set || ipinreceives.is_set || ipinhdrerrors.is_set || ipinaddrerrors.is_set || ipforwdatagrams.is_set || ipinunknownprotos.is_set || ipindiscards.is_set || ipindelivers.is_set || ipoutrequests.is_set || ipoutdiscards.is_set || ipoutnoroutes.is_set || ipreasmtimeout.is_set || ipreasmreqds.is_set || ipreasmoks.is_set || ipreasmfails.is_set || ipfragoks.is_set || ipfragfails.is_set || ipfragcreates.is_set || iproutingdiscards.is_set || ipv6ipforwarding.is_set || ipv6ipdefaulthoplimit.is_set || ipv4interfacetablelastchange.is_set || ipv6interfacetablelastchange.is_set || ipaddressspinlock.is_set || ipv6routeradvertspinlock.is_set; } bool IPMIB::Ip::has_operation() const { return is_set(yfilter) || ydk::is_set(ipforwarding.yfilter) || ydk::is_set(ipdefaultttl.yfilter) || ydk::is_set(ipinreceives.yfilter) || ydk::is_set(ipinhdrerrors.yfilter) || ydk::is_set(ipinaddrerrors.yfilter) || ydk::is_set(ipforwdatagrams.yfilter) || ydk::is_set(ipinunknownprotos.yfilter) || ydk::is_set(ipindiscards.yfilter) || ydk::is_set(ipindelivers.yfilter) || ydk::is_set(ipoutrequests.yfilter) || ydk::is_set(ipoutdiscards.yfilter) || ydk::is_set(ipoutnoroutes.yfilter) || ydk::is_set(ipreasmtimeout.yfilter) || ydk::is_set(ipreasmreqds.yfilter) || ydk::is_set(ipreasmoks.yfilter) || ydk::is_set(ipreasmfails.yfilter) || ydk::is_set(ipfragoks.yfilter) || ydk::is_set(ipfragfails.yfilter) || ydk::is_set(ipfragcreates.yfilter) || ydk::is_set(iproutingdiscards.yfilter) || ydk::is_set(ipv6ipforwarding.yfilter) || ydk::is_set(ipv6ipdefaulthoplimit.yfilter) || ydk::is_set(ipv4interfacetablelastchange.yfilter) || ydk::is_set(ipv6interfacetablelastchange.yfilter) || ydk::is_set(ipaddressspinlock.yfilter) || ydk::is_set(ipv6routeradvertspinlock.yfilter); } std::string IPMIB::Ip::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ip::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ip"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ip::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipforwarding.is_set || is_set(ipforwarding.yfilter)) leaf_name_data.push_back(ipforwarding.get_name_leafdata()); if (ipdefaultttl.is_set || is_set(ipdefaultttl.yfilter)) leaf_name_data.push_back(ipdefaultttl.get_name_leafdata()); if (ipinreceives.is_set || is_set(ipinreceives.yfilter)) leaf_name_data.push_back(ipinreceives.get_name_leafdata()); if (ipinhdrerrors.is_set || is_set(ipinhdrerrors.yfilter)) leaf_name_data.push_back(ipinhdrerrors.get_name_leafdata()); if (ipinaddrerrors.is_set || is_set(ipinaddrerrors.yfilter)) leaf_name_data.push_back(ipinaddrerrors.get_name_leafdata()); if (ipforwdatagrams.is_set || is_set(ipforwdatagrams.yfilter)) leaf_name_data.push_back(ipforwdatagrams.get_name_leafdata()); if (ipinunknownprotos.is_set || is_set(ipinunknownprotos.yfilter)) leaf_name_data.push_back(ipinunknownprotos.get_name_leafdata()); if (ipindiscards.is_set || is_set(ipindiscards.yfilter)) leaf_name_data.push_back(ipindiscards.get_name_leafdata()); if (ipindelivers.is_set || is_set(ipindelivers.yfilter)) leaf_name_data.push_back(ipindelivers.get_name_leafdata()); if (ipoutrequests.is_set || is_set(ipoutrequests.yfilter)) leaf_name_data.push_back(ipoutrequests.get_name_leafdata()); if (ipoutdiscards.is_set || is_set(ipoutdiscards.yfilter)) leaf_name_data.push_back(ipoutdiscards.get_name_leafdata()); if (ipoutnoroutes.is_set || is_set(ipoutnoroutes.yfilter)) leaf_name_data.push_back(ipoutnoroutes.get_name_leafdata()); if (ipreasmtimeout.is_set || is_set(ipreasmtimeout.yfilter)) leaf_name_data.push_back(ipreasmtimeout.get_name_leafdata()); if (ipreasmreqds.is_set || is_set(ipreasmreqds.yfilter)) leaf_name_data.push_back(ipreasmreqds.get_name_leafdata()); if (ipreasmoks.is_set || is_set(ipreasmoks.yfilter)) leaf_name_data.push_back(ipreasmoks.get_name_leafdata()); if (ipreasmfails.is_set || is_set(ipreasmfails.yfilter)) leaf_name_data.push_back(ipreasmfails.get_name_leafdata()); if (ipfragoks.is_set || is_set(ipfragoks.yfilter)) leaf_name_data.push_back(ipfragoks.get_name_leafdata()); if (ipfragfails.is_set || is_set(ipfragfails.yfilter)) leaf_name_data.push_back(ipfragfails.get_name_leafdata()); if (ipfragcreates.is_set || is_set(ipfragcreates.yfilter)) leaf_name_data.push_back(ipfragcreates.get_name_leafdata()); if (iproutingdiscards.is_set || is_set(iproutingdiscards.yfilter)) leaf_name_data.push_back(iproutingdiscards.get_name_leafdata()); if (ipv6ipforwarding.is_set || is_set(ipv6ipforwarding.yfilter)) leaf_name_data.push_back(ipv6ipforwarding.get_name_leafdata()); if (ipv6ipdefaulthoplimit.is_set || is_set(ipv6ipdefaulthoplimit.yfilter)) leaf_name_data.push_back(ipv6ipdefaulthoplimit.get_name_leafdata()); if (ipv4interfacetablelastchange.is_set || is_set(ipv4interfacetablelastchange.yfilter)) leaf_name_data.push_back(ipv4interfacetablelastchange.get_name_leafdata()); if (ipv6interfacetablelastchange.is_set || is_set(ipv6interfacetablelastchange.yfilter)) leaf_name_data.push_back(ipv6interfacetablelastchange.get_name_leafdata()); if (ipaddressspinlock.is_set || is_set(ipaddressspinlock.yfilter)) leaf_name_data.push_back(ipaddressspinlock.get_name_leafdata()); if (ipv6routeradvertspinlock.is_set || is_set(ipv6routeradvertspinlock.yfilter)) leaf_name_data.push_back(ipv6routeradvertspinlock.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ip::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ip::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Ip::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipForwarding") { ipforwarding = value; ipforwarding.value_namespace = name_space; ipforwarding.value_namespace_prefix = name_space_prefix; } if(value_path == "ipDefaultTTL") { ipdefaultttl = value; ipdefaultttl.value_namespace = name_space; ipdefaultttl.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInReceives") { ipinreceives = value; ipinreceives.value_namespace = name_space; ipinreceives.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInHdrErrors") { ipinhdrerrors = value; ipinhdrerrors.value_namespace = name_space; ipinhdrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInAddrErrors") { ipinaddrerrors = value; ipinaddrerrors.value_namespace = name_space; ipinaddrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipForwDatagrams") { ipforwdatagrams = value; ipforwdatagrams.value_namespace = name_space; ipforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInUnknownProtos") { ipinunknownprotos = value; ipinunknownprotos.value_namespace = name_space; ipinunknownprotos.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInDiscards") { ipindiscards = value; ipindiscards.value_namespace = name_space; ipindiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipInDelivers") { ipindelivers = value; ipindelivers.value_namespace = name_space; ipindelivers.value_namespace_prefix = name_space_prefix; } if(value_path == "ipOutRequests") { ipoutrequests = value; ipoutrequests.value_namespace = name_space; ipoutrequests.value_namespace_prefix = name_space_prefix; } if(value_path == "ipOutDiscards") { ipoutdiscards = value; ipoutdiscards.value_namespace = name_space; ipoutdiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipOutNoRoutes") { ipoutnoroutes = value; ipoutnoroutes.value_namespace = name_space; ipoutnoroutes.value_namespace_prefix = name_space_prefix; } if(value_path == "ipReasmTimeout") { ipreasmtimeout = value; ipreasmtimeout.value_namespace = name_space; ipreasmtimeout.value_namespace_prefix = name_space_prefix; } if(value_path == "ipReasmReqds") { ipreasmreqds = value; ipreasmreqds.value_namespace = name_space; ipreasmreqds.value_namespace_prefix = name_space_prefix; } if(value_path == "ipReasmOKs") { ipreasmoks = value; ipreasmoks.value_namespace = name_space; ipreasmoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipReasmFails") { ipreasmfails = value; ipreasmfails.value_namespace = name_space; ipreasmfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipFragOKs") { ipfragoks = value; ipfragoks.value_namespace = name_space; ipfragoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipFragFails") { ipfragfails = value; ipfragfails.value_namespace = name_space; ipfragfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipFragCreates") { ipfragcreates = value; ipfragcreates.value_namespace = name_space; ipfragcreates.value_namespace_prefix = name_space_prefix; } if(value_path == "ipRoutingDiscards") { iproutingdiscards = value; iproutingdiscards.value_namespace = name_space; iproutingdiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6IpForwarding") { ipv6ipforwarding = value; ipv6ipforwarding.value_namespace = name_space; ipv6ipforwarding.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6IpDefaultHopLimit") { ipv6ipdefaulthoplimit = value; ipv6ipdefaulthoplimit.value_namespace = name_space; ipv6ipdefaulthoplimit.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4InterfaceTableLastChange") { ipv4interfacetablelastchange = value; ipv4interfacetablelastchange.value_namespace = name_space; ipv4interfacetablelastchange.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceTableLastChange") { ipv6interfacetablelastchange = value; ipv6interfacetablelastchange.value_namespace = name_space; ipv6interfacetablelastchange.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressSpinLock") { ipaddressspinlock = value; ipaddressspinlock.value_namespace = name_space; ipaddressspinlock.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertSpinLock") { ipv6routeradvertspinlock = value; ipv6routeradvertspinlock.value_namespace = name_space; ipv6routeradvertspinlock.value_namespace_prefix = name_space_prefix; } } void IPMIB::Ip::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipForwarding") { ipforwarding.yfilter = yfilter; } if(value_path == "ipDefaultTTL") { ipdefaultttl.yfilter = yfilter; } if(value_path == "ipInReceives") { ipinreceives.yfilter = yfilter; } if(value_path == "ipInHdrErrors") { ipinhdrerrors.yfilter = yfilter; } if(value_path == "ipInAddrErrors") { ipinaddrerrors.yfilter = yfilter; } if(value_path == "ipForwDatagrams") { ipforwdatagrams.yfilter = yfilter; } if(value_path == "ipInUnknownProtos") { ipinunknownprotos.yfilter = yfilter; } if(value_path == "ipInDiscards") { ipindiscards.yfilter = yfilter; } if(value_path == "ipInDelivers") { ipindelivers.yfilter = yfilter; } if(value_path == "ipOutRequests") { ipoutrequests.yfilter = yfilter; } if(value_path == "ipOutDiscards") { ipoutdiscards.yfilter = yfilter; } if(value_path == "ipOutNoRoutes") { ipoutnoroutes.yfilter = yfilter; } if(value_path == "ipReasmTimeout") { ipreasmtimeout.yfilter = yfilter; } if(value_path == "ipReasmReqds") { ipreasmreqds.yfilter = yfilter; } if(value_path == "ipReasmOKs") { ipreasmoks.yfilter = yfilter; } if(value_path == "ipReasmFails") { ipreasmfails.yfilter = yfilter; } if(value_path == "ipFragOKs") { ipfragoks.yfilter = yfilter; } if(value_path == "ipFragFails") { ipfragfails.yfilter = yfilter; } if(value_path == "ipFragCreates") { ipfragcreates.yfilter = yfilter; } if(value_path == "ipRoutingDiscards") { iproutingdiscards.yfilter = yfilter; } if(value_path == "ipv6IpForwarding") { ipv6ipforwarding.yfilter = yfilter; } if(value_path == "ipv6IpDefaultHopLimit") { ipv6ipdefaulthoplimit.yfilter = yfilter; } if(value_path == "ipv4InterfaceTableLastChange") { ipv4interfacetablelastchange.yfilter = yfilter; } if(value_path == "ipv6InterfaceTableLastChange") { ipv6interfacetablelastchange.yfilter = yfilter; } if(value_path == "ipAddressSpinLock") { ipaddressspinlock.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertSpinLock") { ipv6routeradvertspinlock.yfilter = yfilter; } } bool IPMIB::Ip::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipForwarding" || name == "ipDefaultTTL" || name == "ipInReceives" || name == "ipInHdrErrors" || name == "ipInAddrErrors" || name == "ipForwDatagrams" || name == "ipInUnknownProtos" || name == "ipInDiscards" || name == "ipInDelivers" || name == "ipOutRequests" || name == "ipOutDiscards" || name == "ipOutNoRoutes" || name == "ipReasmTimeout" || name == "ipReasmReqds" || name == "ipReasmOKs" || name == "ipReasmFails" || name == "ipFragOKs" || name == "ipFragFails" || name == "ipFragCreates" || name == "ipRoutingDiscards" || name == "ipv6IpForwarding" || name == "ipv6IpDefaultHopLimit" || name == "ipv4InterfaceTableLastChange" || name == "ipv6InterfaceTableLastChange" || name == "ipAddressSpinLock" || name == "ipv6RouterAdvertSpinLock") return true; return false; } IPMIB::IpTrafficStats::IpTrafficStats() : ipifstatstablelastchange{YType::uint32, "ipIfStatsTableLastChange"} { yang_name = "ipTrafficStats"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpTrafficStats::~IpTrafficStats() { } bool IPMIB::IpTrafficStats::has_data() const { if (is_presence_container) return true; return ipifstatstablelastchange.is_set; } bool IPMIB::IpTrafficStats::has_operation() const { return is_set(yfilter) || ydk::is_set(ipifstatstablelastchange.yfilter); } std::string IPMIB::IpTrafficStats::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpTrafficStats::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipTrafficStats"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpTrafficStats::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipifstatstablelastchange.is_set || is_set(ipifstatstablelastchange.yfilter)) leaf_name_data.push_back(ipifstatstablelastchange.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpTrafficStats::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpTrafficStats::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpTrafficStats::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipIfStatsTableLastChange") { ipifstatstablelastchange = value; ipifstatstablelastchange.value_namespace = name_space; ipifstatstablelastchange.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpTrafficStats::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipIfStatsTableLastChange") { ipifstatstablelastchange.yfilter = yfilter; } } bool IPMIB::IpTrafficStats::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipIfStatsTableLastChange") return true; return false; } IPMIB::Icmp::Icmp() : icmpinmsgs{YType::uint32, "icmpInMsgs"}, icmpinerrors{YType::uint32, "icmpInErrors"}, icmpindestunreachs{YType::uint32, "icmpInDestUnreachs"}, icmpintimeexcds{YType::uint32, "icmpInTimeExcds"}, icmpinparmprobs{YType::uint32, "icmpInParmProbs"}, icmpinsrcquenchs{YType::uint32, "icmpInSrcQuenchs"}, icmpinredirects{YType::uint32, "icmpInRedirects"}, icmpinechos{YType::uint32, "icmpInEchos"}, icmpinechoreps{YType::uint32, "icmpInEchoReps"}, icmpintimestamps{YType::uint32, "icmpInTimestamps"}, icmpintimestampreps{YType::uint32, "icmpInTimestampReps"}, icmpinaddrmasks{YType::uint32, "icmpInAddrMasks"}, icmpinaddrmaskreps{YType::uint32, "icmpInAddrMaskReps"}, icmpoutmsgs{YType::uint32, "icmpOutMsgs"}, icmpouterrors{YType::uint32, "icmpOutErrors"}, icmpoutdestunreachs{YType::uint32, "icmpOutDestUnreachs"}, icmpouttimeexcds{YType::uint32, "icmpOutTimeExcds"}, icmpoutparmprobs{YType::uint32, "icmpOutParmProbs"}, icmpoutsrcquenchs{YType::uint32, "icmpOutSrcQuenchs"}, icmpoutredirects{YType::uint32, "icmpOutRedirects"}, icmpoutechos{YType::uint32, "icmpOutEchos"}, icmpoutechoreps{YType::uint32, "icmpOutEchoReps"}, icmpouttimestamps{YType::uint32, "icmpOutTimestamps"}, icmpouttimestampreps{YType::uint32, "icmpOutTimestampReps"}, icmpoutaddrmasks{YType::uint32, "icmpOutAddrMasks"}, icmpoutaddrmaskreps{YType::uint32, "icmpOutAddrMaskReps"} { yang_name = "icmp"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Icmp::~Icmp() { } bool IPMIB::Icmp::has_data() const { if (is_presence_container) return true; return icmpinmsgs.is_set || icmpinerrors.is_set || icmpindestunreachs.is_set || icmpintimeexcds.is_set || icmpinparmprobs.is_set || icmpinsrcquenchs.is_set || icmpinredirects.is_set || icmpinechos.is_set || icmpinechoreps.is_set || icmpintimestamps.is_set || icmpintimestampreps.is_set || icmpinaddrmasks.is_set || icmpinaddrmaskreps.is_set || icmpoutmsgs.is_set || icmpouterrors.is_set || icmpoutdestunreachs.is_set || icmpouttimeexcds.is_set || icmpoutparmprobs.is_set || icmpoutsrcquenchs.is_set || icmpoutredirects.is_set || icmpoutechos.is_set || icmpoutechoreps.is_set || icmpouttimestamps.is_set || icmpouttimestampreps.is_set || icmpoutaddrmasks.is_set || icmpoutaddrmaskreps.is_set; } bool IPMIB::Icmp::has_operation() const { return is_set(yfilter) || ydk::is_set(icmpinmsgs.yfilter) || ydk::is_set(icmpinerrors.yfilter) || ydk::is_set(icmpindestunreachs.yfilter) || ydk::is_set(icmpintimeexcds.yfilter) || ydk::is_set(icmpinparmprobs.yfilter) || ydk::is_set(icmpinsrcquenchs.yfilter) || ydk::is_set(icmpinredirects.yfilter) || ydk::is_set(icmpinechos.yfilter) || ydk::is_set(icmpinechoreps.yfilter) || ydk::is_set(icmpintimestamps.yfilter) || ydk::is_set(icmpintimestampreps.yfilter) || ydk::is_set(icmpinaddrmasks.yfilter) || ydk::is_set(icmpinaddrmaskreps.yfilter) || ydk::is_set(icmpoutmsgs.yfilter) || ydk::is_set(icmpouterrors.yfilter) || ydk::is_set(icmpoutdestunreachs.yfilter) || ydk::is_set(icmpouttimeexcds.yfilter) || ydk::is_set(icmpoutparmprobs.yfilter) || ydk::is_set(icmpoutsrcquenchs.yfilter) || ydk::is_set(icmpoutredirects.yfilter) || ydk::is_set(icmpoutechos.yfilter) || ydk::is_set(icmpoutechoreps.yfilter) || ydk::is_set(icmpouttimestamps.yfilter) || ydk::is_set(icmpouttimestampreps.yfilter) || ydk::is_set(icmpoutaddrmasks.yfilter) || ydk::is_set(icmpoutaddrmaskreps.yfilter); } std::string IPMIB::Icmp::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Icmp::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmp"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Icmp::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (icmpinmsgs.is_set || is_set(icmpinmsgs.yfilter)) leaf_name_data.push_back(icmpinmsgs.get_name_leafdata()); if (icmpinerrors.is_set || is_set(icmpinerrors.yfilter)) leaf_name_data.push_back(icmpinerrors.get_name_leafdata()); if (icmpindestunreachs.is_set || is_set(icmpindestunreachs.yfilter)) leaf_name_data.push_back(icmpindestunreachs.get_name_leafdata()); if (icmpintimeexcds.is_set || is_set(icmpintimeexcds.yfilter)) leaf_name_data.push_back(icmpintimeexcds.get_name_leafdata()); if (icmpinparmprobs.is_set || is_set(icmpinparmprobs.yfilter)) leaf_name_data.push_back(icmpinparmprobs.get_name_leafdata()); if (icmpinsrcquenchs.is_set || is_set(icmpinsrcquenchs.yfilter)) leaf_name_data.push_back(icmpinsrcquenchs.get_name_leafdata()); if (icmpinredirects.is_set || is_set(icmpinredirects.yfilter)) leaf_name_data.push_back(icmpinredirects.get_name_leafdata()); if (icmpinechos.is_set || is_set(icmpinechos.yfilter)) leaf_name_data.push_back(icmpinechos.get_name_leafdata()); if (icmpinechoreps.is_set || is_set(icmpinechoreps.yfilter)) leaf_name_data.push_back(icmpinechoreps.get_name_leafdata()); if (icmpintimestamps.is_set || is_set(icmpintimestamps.yfilter)) leaf_name_data.push_back(icmpintimestamps.get_name_leafdata()); if (icmpintimestampreps.is_set || is_set(icmpintimestampreps.yfilter)) leaf_name_data.push_back(icmpintimestampreps.get_name_leafdata()); if (icmpinaddrmasks.is_set || is_set(icmpinaddrmasks.yfilter)) leaf_name_data.push_back(icmpinaddrmasks.get_name_leafdata()); if (icmpinaddrmaskreps.is_set || is_set(icmpinaddrmaskreps.yfilter)) leaf_name_data.push_back(icmpinaddrmaskreps.get_name_leafdata()); if (icmpoutmsgs.is_set || is_set(icmpoutmsgs.yfilter)) leaf_name_data.push_back(icmpoutmsgs.get_name_leafdata()); if (icmpouterrors.is_set || is_set(icmpouterrors.yfilter)) leaf_name_data.push_back(icmpouterrors.get_name_leafdata()); if (icmpoutdestunreachs.is_set || is_set(icmpoutdestunreachs.yfilter)) leaf_name_data.push_back(icmpoutdestunreachs.get_name_leafdata()); if (icmpouttimeexcds.is_set || is_set(icmpouttimeexcds.yfilter)) leaf_name_data.push_back(icmpouttimeexcds.get_name_leafdata()); if (icmpoutparmprobs.is_set || is_set(icmpoutparmprobs.yfilter)) leaf_name_data.push_back(icmpoutparmprobs.get_name_leafdata()); if (icmpoutsrcquenchs.is_set || is_set(icmpoutsrcquenchs.yfilter)) leaf_name_data.push_back(icmpoutsrcquenchs.get_name_leafdata()); if (icmpoutredirects.is_set || is_set(icmpoutredirects.yfilter)) leaf_name_data.push_back(icmpoutredirects.get_name_leafdata()); if (icmpoutechos.is_set || is_set(icmpoutechos.yfilter)) leaf_name_data.push_back(icmpoutechos.get_name_leafdata()); if (icmpoutechoreps.is_set || is_set(icmpoutechoreps.yfilter)) leaf_name_data.push_back(icmpoutechoreps.get_name_leafdata()); if (icmpouttimestamps.is_set || is_set(icmpouttimestamps.yfilter)) leaf_name_data.push_back(icmpouttimestamps.get_name_leafdata()); if (icmpouttimestampreps.is_set || is_set(icmpouttimestampreps.yfilter)) leaf_name_data.push_back(icmpouttimestampreps.get_name_leafdata()); if (icmpoutaddrmasks.is_set || is_set(icmpoutaddrmasks.yfilter)) leaf_name_data.push_back(icmpoutaddrmasks.get_name_leafdata()); if (icmpoutaddrmaskreps.is_set || is_set(icmpoutaddrmaskreps.yfilter)) leaf_name_data.push_back(icmpoutaddrmaskreps.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Icmp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Icmp::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Icmp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "icmpInMsgs") { icmpinmsgs = value; icmpinmsgs.value_namespace = name_space; icmpinmsgs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInErrors") { icmpinerrors = value; icmpinerrors.value_namespace = name_space; icmpinerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInDestUnreachs") { icmpindestunreachs = value; icmpindestunreachs.value_namespace = name_space; icmpindestunreachs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInTimeExcds") { icmpintimeexcds = value; icmpintimeexcds.value_namespace = name_space; icmpintimeexcds.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInParmProbs") { icmpinparmprobs = value; icmpinparmprobs.value_namespace = name_space; icmpinparmprobs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInSrcQuenchs") { icmpinsrcquenchs = value; icmpinsrcquenchs.value_namespace = name_space; icmpinsrcquenchs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInRedirects") { icmpinredirects = value; icmpinredirects.value_namespace = name_space; icmpinredirects.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInEchos") { icmpinechos = value; icmpinechos.value_namespace = name_space; icmpinechos.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInEchoReps") { icmpinechoreps = value; icmpinechoreps.value_namespace = name_space; icmpinechoreps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInTimestamps") { icmpintimestamps = value; icmpintimestamps.value_namespace = name_space; icmpintimestamps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInTimestampReps") { icmpintimestampreps = value; icmpintimestampreps.value_namespace = name_space; icmpintimestampreps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInAddrMasks") { icmpinaddrmasks = value; icmpinaddrmasks.value_namespace = name_space; icmpinaddrmasks.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpInAddrMaskReps") { icmpinaddrmaskreps = value; icmpinaddrmaskreps.value_namespace = name_space; icmpinaddrmaskreps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutMsgs") { icmpoutmsgs = value; icmpoutmsgs.value_namespace = name_space; icmpoutmsgs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutErrors") { icmpouterrors = value; icmpouterrors.value_namespace = name_space; icmpouterrors.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutDestUnreachs") { icmpoutdestunreachs = value; icmpoutdestunreachs.value_namespace = name_space; icmpoutdestunreachs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutTimeExcds") { icmpouttimeexcds = value; icmpouttimeexcds.value_namespace = name_space; icmpouttimeexcds.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutParmProbs") { icmpoutparmprobs = value; icmpoutparmprobs.value_namespace = name_space; icmpoutparmprobs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutSrcQuenchs") { icmpoutsrcquenchs = value; icmpoutsrcquenchs.value_namespace = name_space; icmpoutsrcquenchs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutRedirects") { icmpoutredirects = value; icmpoutredirects.value_namespace = name_space; icmpoutredirects.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutEchos") { icmpoutechos = value; icmpoutechos.value_namespace = name_space; icmpoutechos.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutEchoReps") { icmpoutechoreps = value; icmpoutechoreps.value_namespace = name_space; icmpoutechoreps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutTimestamps") { icmpouttimestamps = value; icmpouttimestamps.value_namespace = name_space; icmpouttimestamps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutTimestampReps") { icmpouttimestampreps = value; icmpouttimestampreps.value_namespace = name_space; icmpouttimestampreps.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutAddrMasks") { icmpoutaddrmasks = value; icmpoutaddrmasks.value_namespace = name_space; icmpoutaddrmasks.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpOutAddrMaskReps") { icmpoutaddrmaskreps = value; icmpoutaddrmaskreps.value_namespace = name_space; icmpoutaddrmaskreps.value_namespace_prefix = name_space_prefix; } } void IPMIB::Icmp::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "icmpInMsgs") { icmpinmsgs.yfilter = yfilter; } if(value_path == "icmpInErrors") { icmpinerrors.yfilter = yfilter; } if(value_path == "icmpInDestUnreachs") { icmpindestunreachs.yfilter = yfilter; } if(value_path == "icmpInTimeExcds") { icmpintimeexcds.yfilter = yfilter; } if(value_path == "icmpInParmProbs") { icmpinparmprobs.yfilter = yfilter; } if(value_path == "icmpInSrcQuenchs") { icmpinsrcquenchs.yfilter = yfilter; } if(value_path == "icmpInRedirects") { icmpinredirects.yfilter = yfilter; } if(value_path == "icmpInEchos") { icmpinechos.yfilter = yfilter; } if(value_path == "icmpInEchoReps") { icmpinechoreps.yfilter = yfilter; } if(value_path == "icmpInTimestamps") { icmpintimestamps.yfilter = yfilter; } if(value_path == "icmpInTimestampReps") { icmpintimestampreps.yfilter = yfilter; } if(value_path == "icmpInAddrMasks") { icmpinaddrmasks.yfilter = yfilter; } if(value_path == "icmpInAddrMaskReps") { icmpinaddrmaskreps.yfilter = yfilter; } if(value_path == "icmpOutMsgs") { icmpoutmsgs.yfilter = yfilter; } if(value_path == "icmpOutErrors") { icmpouterrors.yfilter = yfilter; } if(value_path == "icmpOutDestUnreachs") { icmpoutdestunreachs.yfilter = yfilter; } if(value_path == "icmpOutTimeExcds") { icmpouttimeexcds.yfilter = yfilter; } if(value_path == "icmpOutParmProbs") { icmpoutparmprobs.yfilter = yfilter; } if(value_path == "icmpOutSrcQuenchs") { icmpoutsrcquenchs.yfilter = yfilter; } if(value_path == "icmpOutRedirects") { icmpoutredirects.yfilter = yfilter; } if(value_path == "icmpOutEchos") { icmpoutechos.yfilter = yfilter; } if(value_path == "icmpOutEchoReps") { icmpoutechoreps.yfilter = yfilter; } if(value_path == "icmpOutTimestamps") { icmpouttimestamps.yfilter = yfilter; } if(value_path == "icmpOutTimestampReps") { icmpouttimestampreps.yfilter = yfilter; } if(value_path == "icmpOutAddrMasks") { icmpoutaddrmasks.yfilter = yfilter; } if(value_path == "icmpOutAddrMaskReps") { icmpoutaddrmaskreps.yfilter = yfilter; } } bool IPMIB::Icmp::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmpInMsgs" || name == "icmpInErrors" || name == "icmpInDestUnreachs" || name == "icmpInTimeExcds" || name == "icmpInParmProbs" || name == "icmpInSrcQuenchs" || name == "icmpInRedirects" || name == "icmpInEchos" || name == "icmpInEchoReps" || name == "icmpInTimestamps" || name == "icmpInTimestampReps" || name == "icmpInAddrMasks" || name == "icmpInAddrMaskReps" || name == "icmpOutMsgs" || name == "icmpOutErrors" || name == "icmpOutDestUnreachs" || name == "icmpOutTimeExcds" || name == "icmpOutParmProbs" || name == "icmpOutSrcQuenchs" || name == "icmpOutRedirects" || name == "icmpOutEchos" || name == "icmpOutEchoReps" || name == "icmpOutTimestamps" || name == "icmpOutTimestampReps" || name == "icmpOutAddrMasks" || name == "icmpOutAddrMaskReps") return true; return false; } IPMIB::IpAddrTable::IpAddrTable() : ipaddrentry(this, {"ipadentaddr"}) { yang_name = "ipAddrTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddrTable::~IpAddrTable() { } bool IPMIB::IpAddrTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipaddrentry.len(); index++) { if(ipaddrentry[index]->has_data()) return true; } return false; } bool IPMIB::IpAddrTable::has_operation() const { for (std::size_t index=0; index<ipaddrentry.len(); index++) { if(ipaddrentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpAddrTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddrTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddrTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddrTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddrTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipAddrEntry") { auto ent_ = std::make_shared<IPMIB::IpAddrTable::IpAddrEntry>(); ent_->parent = this; ipaddrentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddrTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipaddrentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpAddrTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpAddrTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpAddrTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAddrEntry") return true; return false; } IPMIB::IpAddrTable::IpAddrEntry::IpAddrEntry() : ipadentaddr{YType::str, "ipAdEntAddr"}, ipadentifindex{YType::int32, "ipAdEntIfIndex"}, ipadentnetmask{YType::str, "ipAdEntNetMask"}, ipadentbcastaddr{YType::int32, "ipAdEntBcastAddr"}, ipadentreasmmaxsize{YType::int32, "ipAdEntReasmMaxSize"} { yang_name = "ipAddrEntry"; yang_parent_name = "ipAddrTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddrTable::IpAddrEntry::~IpAddrEntry() { } bool IPMIB::IpAddrTable::IpAddrEntry::has_data() const { if (is_presence_container) return true; return ipadentaddr.is_set || ipadentifindex.is_set || ipadentnetmask.is_set || ipadentbcastaddr.is_set || ipadentreasmmaxsize.is_set; } bool IPMIB::IpAddrTable::IpAddrEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipadentaddr.yfilter) || ydk::is_set(ipadentifindex.yfilter) || ydk::is_set(ipadentnetmask.yfilter) || ydk::is_set(ipadentbcastaddr.yfilter) || ydk::is_set(ipadentreasmmaxsize.yfilter); } std::string IPMIB::IpAddrTable::IpAddrEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipAddrTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddrTable::IpAddrEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddrEntry"; ADD_KEY_TOKEN(ipadentaddr, "ipAdEntAddr"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddrTable::IpAddrEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipadentaddr.is_set || is_set(ipadentaddr.yfilter)) leaf_name_data.push_back(ipadentaddr.get_name_leafdata()); if (ipadentifindex.is_set || is_set(ipadentifindex.yfilter)) leaf_name_data.push_back(ipadentifindex.get_name_leafdata()); if (ipadentnetmask.is_set || is_set(ipadentnetmask.yfilter)) leaf_name_data.push_back(ipadentnetmask.get_name_leafdata()); if (ipadentbcastaddr.is_set || is_set(ipadentbcastaddr.yfilter)) leaf_name_data.push_back(ipadentbcastaddr.get_name_leafdata()); if (ipadentreasmmaxsize.is_set || is_set(ipadentreasmmaxsize.yfilter)) leaf_name_data.push_back(ipadentreasmmaxsize.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddrTable::IpAddrEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddrTable::IpAddrEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpAddrTable::IpAddrEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipAdEntAddr") { ipadentaddr = value; ipadentaddr.value_namespace = name_space; ipadentaddr.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAdEntIfIndex") { ipadentifindex = value; ipadentifindex.value_namespace = name_space; ipadentifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAdEntNetMask") { ipadentnetmask = value; ipadentnetmask.value_namespace = name_space; ipadentnetmask.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAdEntBcastAddr") { ipadentbcastaddr = value; ipadentbcastaddr.value_namespace = name_space; ipadentbcastaddr.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAdEntReasmMaxSize") { ipadentreasmmaxsize = value; ipadentreasmmaxsize.value_namespace = name_space; ipadentreasmmaxsize.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpAddrTable::IpAddrEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipAdEntAddr") { ipadentaddr.yfilter = yfilter; } if(value_path == "ipAdEntIfIndex") { ipadentifindex.yfilter = yfilter; } if(value_path == "ipAdEntNetMask") { ipadentnetmask.yfilter = yfilter; } if(value_path == "ipAdEntBcastAddr") { ipadentbcastaddr.yfilter = yfilter; } if(value_path == "ipAdEntReasmMaxSize") { ipadentreasmmaxsize.yfilter = yfilter; } } bool IPMIB::IpAddrTable::IpAddrEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAdEntAddr" || name == "ipAdEntIfIndex" || name == "ipAdEntNetMask" || name == "ipAdEntBcastAddr" || name == "ipAdEntReasmMaxSize") return true; return false; } IPMIB::IpNetToMediaTable::IpNetToMediaTable() : ipnettomediaentry(this, {"ipnettomediaifindex", "ipnettomedianetaddress"}) { yang_name = "ipNetToMediaTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpNetToMediaTable::~IpNetToMediaTable() { } bool IPMIB::IpNetToMediaTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipnettomediaentry.len(); index++) { if(ipnettomediaentry[index]->has_data()) return true; } return false; } bool IPMIB::IpNetToMediaTable::has_operation() const { for (std::size_t index=0; index<ipnettomediaentry.len(); index++) { if(ipnettomediaentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpNetToMediaTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpNetToMediaTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipNetToMediaTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpNetToMediaTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpNetToMediaTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipNetToMediaEntry") { auto ent_ = std::make_shared<IPMIB::IpNetToMediaTable::IpNetToMediaEntry>(); ent_->parent = this; ipnettomediaentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpNetToMediaTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipnettomediaentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpNetToMediaTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpNetToMediaTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpNetToMediaTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipNetToMediaEntry") return true; return false; } IPMIB::IpNetToMediaTable::IpNetToMediaEntry::IpNetToMediaEntry() : ipnettomediaifindex{YType::int32, "ipNetToMediaIfIndex"}, ipnettomedianetaddress{YType::str, "ipNetToMediaNetAddress"}, ipnettomediaphysaddress{YType::str, "ipNetToMediaPhysAddress"}, ipnettomediatype{YType::enumeration, "ipNetToMediaType"} { yang_name = "ipNetToMediaEntry"; yang_parent_name = "ipNetToMediaTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpNetToMediaTable::IpNetToMediaEntry::~IpNetToMediaEntry() { } bool IPMIB::IpNetToMediaTable::IpNetToMediaEntry::has_data() const { if (is_presence_container) return true; return ipnettomediaifindex.is_set || ipnettomedianetaddress.is_set || ipnettomediaphysaddress.is_set || ipnettomediatype.is_set; } bool IPMIB::IpNetToMediaTable::IpNetToMediaEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipnettomediaifindex.yfilter) || ydk::is_set(ipnettomedianetaddress.yfilter) || ydk::is_set(ipnettomediaphysaddress.yfilter) || ydk::is_set(ipnettomediatype.yfilter); } std::string IPMIB::IpNetToMediaTable::IpNetToMediaEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipNetToMediaTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpNetToMediaTable::IpNetToMediaEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipNetToMediaEntry"; ADD_KEY_TOKEN(ipnettomediaifindex, "ipNetToMediaIfIndex"); ADD_KEY_TOKEN(ipnettomedianetaddress, "ipNetToMediaNetAddress"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpNetToMediaTable::IpNetToMediaEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipnettomediaifindex.is_set || is_set(ipnettomediaifindex.yfilter)) leaf_name_data.push_back(ipnettomediaifindex.get_name_leafdata()); if (ipnettomedianetaddress.is_set || is_set(ipnettomedianetaddress.yfilter)) leaf_name_data.push_back(ipnettomedianetaddress.get_name_leafdata()); if (ipnettomediaphysaddress.is_set || is_set(ipnettomediaphysaddress.yfilter)) leaf_name_data.push_back(ipnettomediaphysaddress.get_name_leafdata()); if (ipnettomediatype.is_set || is_set(ipnettomediatype.yfilter)) leaf_name_data.push_back(ipnettomediatype.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpNetToMediaTable::IpNetToMediaEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpNetToMediaTable::IpNetToMediaEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpNetToMediaTable::IpNetToMediaEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipNetToMediaIfIndex") { ipnettomediaifindex = value; ipnettomediaifindex.value_namespace = name_space; ipnettomediaifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToMediaNetAddress") { ipnettomedianetaddress = value; ipnettomedianetaddress.value_namespace = name_space; ipnettomedianetaddress.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToMediaPhysAddress") { ipnettomediaphysaddress = value; ipnettomediaphysaddress.value_namespace = name_space; ipnettomediaphysaddress.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToMediaType") { ipnettomediatype = value; ipnettomediatype.value_namespace = name_space; ipnettomediatype.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpNetToMediaTable::IpNetToMediaEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipNetToMediaIfIndex") { ipnettomediaifindex.yfilter = yfilter; } if(value_path == "ipNetToMediaNetAddress") { ipnettomedianetaddress.yfilter = yfilter; } if(value_path == "ipNetToMediaPhysAddress") { ipnettomediaphysaddress.yfilter = yfilter; } if(value_path == "ipNetToMediaType") { ipnettomediatype.yfilter = yfilter; } } bool IPMIB::IpNetToMediaTable::IpNetToMediaEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipNetToMediaIfIndex" || name == "ipNetToMediaNetAddress" || name == "ipNetToMediaPhysAddress" || name == "ipNetToMediaType") return true; return false; } IPMIB::Ipv4InterfaceTable::Ipv4InterfaceTable() : ipv4interfaceentry(this, {"ipv4interfaceifindex"}) { yang_name = "ipv4InterfaceTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv4InterfaceTable::~Ipv4InterfaceTable() { } bool IPMIB::Ipv4InterfaceTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv4interfaceentry.len(); index++) { if(ipv4interfaceentry[index]->has_data()) return true; } return false; } bool IPMIB::Ipv4InterfaceTable::has_operation() const { for (std::size_t index=0; index<ipv4interfaceentry.len(); index++) { if(ipv4interfaceentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::Ipv4InterfaceTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv4InterfaceTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4InterfaceTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv4InterfaceTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv4InterfaceTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv4InterfaceEntry") { auto ent_ = std::make_shared<IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry>(); ent_->parent = this; ipv4interfaceentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv4InterfaceTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv4interfaceentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::Ipv4InterfaceTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::Ipv4InterfaceTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::Ipv4InterfaceTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4InterfaceEntry") return true; return false; } IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::Ipv4InterfaceEntry() : ipv4interfaceifindex{YType::int32, "ipv4InterfaceIfIndex"}, ipv4interfacereasmmaxsize{YType::int32, "ipv4InterfaceReasmMaxSize"}, ipv4interfaceenablestatus{YType::enumeration, "ipv4InterfaceEnableStatus"}, ipv4interfaceretransmittime{YType::uint32, "ipv4InterfaceRetransmitTime"} { yang_name = "ipv4InterfaceEntry"; yang_parent_name = "ipv4InterfaceTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::~Ipv4InterfaceEntry() { } bool IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::has_data() const { if (is_presence_container) return true; return ipv4interfaceifindex.is_set || ipv4interfacereasmmaxsize.is_set || ipv4interfaceenablestatus.is_set || ipv4interfaceretransmittime.is_set; } bool IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipv4interfaceifindex.yfilter) || ydk::is_set(ipv4interfacereasmmaxsize.yfilter) || ydk::is_set(ipv4interfaceenablestatus.yfilter) || ydk::is_set(ipv4interfaceretransmittime.yfilter); } std::string IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipv4InterfaceTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv4InterfaceEntry"; ADD_KEY_TOKEN(ipv4interfaceifindex, "ipv4InterfaceIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipv4interfaceifindex.is_set || is_set(ipv4interfaceifindex.yfilter)) leaf_name_data.push_back(ipv4interfaceifindex.get_name_leafdata()); if (ipv4interfacereasmmaxsize.is_set || is_set(ipv4interfacereasmmaxsize.yfilter)) leaf_name_data.push_back(ipv4interfacereasmmaxsize.get_name_leafdata()); if (ipv4interfaceenablestatus.is_set || is_set(ipv4interfaceenablestatus.yfilter)) leaf_name_data.push_back(ipv4interfaceenablestatus.get_name_leafdata()); if (ipv4interfaceretransmittime.is_set || is_set(ipv4interfaceretransmittime.yfilter)) leaf_name_data.push_back(ipv4interfaceretransmittime.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipv4InterfaceIfIndex") { ipv4interfaceifindex = value; ipv4interfaceifindex.value_namespace = name_space; ipv4interfaceifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4InterfaceReasmMaxSize") { ipv4interfacereasmmaxsize = value; ipv4interfacereasmmaxsize.value_namespace = name_space; ipv4interfacereasmmaxsize.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4InterfaceEnableStatus") { ipv4interfaceenablestatus = value; ipv4interfaceenablestatus.value_namespace = name_space; ipv4interfaceenablestatus.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv4InterfaceRetransmitTime") { ipv4interfaceretransmittime = value; ipv4interfaceretransmittime.value_namespace = name_space; ipv4interfaceretransmittime.value_namespace_prefix = name_space_prefix; } } void IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipv4InterfaceIfIndex") { ipv4interfaceifindex.yfilter = yfilter; } if(value_path == "ipv4InterfaceReasmMaxSize") { ipv4interfacereasmmaxsize.yfilter = yfilter; } if(value_path == "ipv4InterfaceEnableStatus") { ipv4interfaceenablestatus.yfilter = yfilter; } if(value_path == "ipv4InterfaceRetransmitTime") { ipv4interfaceretransmittime.yfilter = yfilter; } } bool IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv4InterfaceIfIndex" || name == "ipv4InterfaceReasmMaxSize" || name == "ipv4InterfaceEnableStatus" || name == "ipv4InterfaceRetransmitTime") return true; return false; } IPMIB::Ipv6InterfaceTable::Ipv6InterfaceTable() : ipv6interfaceentry(this, {"ipv6interfaceifindex"}) { yang_name = "ipv6InterfaceTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6InterfaceTable::~Ipv6InterfaceTable() { } bool IPMIB::Ipv6InterfaceTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv6interfaceentry.len(); index++) { if(ipv6interfaceentry[index]->has_data()) return true; } return false; } bool IPMIB::Ipv6InterfaceTable::has_operation() const { for (std::size_t index=0; index<ipv6interfaceentry.len(); index++) { if(ipv6interfaceentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::Ipv6InterfaceTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6InterfaceTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6InterfaceTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6InterfaceTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6InterfaceTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv6InterfaceEntry") { auto ent_ = std::make_shared<IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry>(); ent_->parent = this; ipv6interfaceentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6InterfaceTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv6interfaceentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::Ipv6InterfaceTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::Ipv6InterfaceTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::Ipv6InterfaceTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6InterfaceEntry") return true; return false; } IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::Ipv6InterfaceEntry() : ipv6interfaceifindex{YType::int32, "ipv6InterfaceIfIndex"}, ipv6interfacereasmmaxsize{YType::uint32, "ipv6InterfaceReasmMaxSize"}, ipv6interfaceidentifier{YType::str, "ipv6InterfaceIdentifier"}, ipv6interfaceenablestatus{YType::enumeration, "ipv6InterfaceEnableStatus"}, ipv6interfacereachabletime{YType::uint32, "ipv6InterfaceReachableTime"}, ipv6interfaceretransmittime{YType::uint32, "ipv6InterfaceRetransmitTime"}, ipv6interfaceforwarding{YType::enumeration, "ipv6InterfaceForwarding"} { yang_name = "ipv6InterfaceEntry"; yang_parent_name = "ipv6InterfaceTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::~Ipv6InterfaceEntry() { } bool IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::has_data() const { if (is_presence_container) return true; return ipv6interfaceifindex.is_set || ipv6interfacereasmmaxsize.is_set || ipv6interfaceidentifier.is_set || ipv6interfaceenablestatus.is_set || ipv6interfacereachabletime.is_set || ipv6interfaceretransmittime.is_set || ipv6interfaceforwarding.is_set; } bool IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipv6interfaceifindex.yfilter) || ydk::is_set(ipv6interfacereasmmaxsize.yfilter) || ydk::is_set(ipv6interfaceidentifier.yfilter) || ydk::is_set(ipv6interfaceenablestatus.yfilter) || ydk::is_set(ipv6interfacereachabletime.yfilter) || ydk::is_set(ipv6interfaceretransmittime.yfilter) || ydk::is_set(ipv6interfaceforwarding.yfilter); } std::string IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipv6InterfaceTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6InterfaceEntry"; ADD_KEY_TOKEN(ipv6interfaceifindex, "ipv6InterfaceIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipv6interfaceifindex.is_set || is_set(ipv6interfaceifindex.yfilter)) leaf_name_data.push_back(ipv6interfaceifindex.get_name_leafdata()); if (ipv6interfacereasmmaxsize.is_set || is_set(ipv6interfacereasmmaxsize.yfilter)) leaf_name_data.push_back(ipv6interfacereasmmaxsize.get_name_leafdata()); if (ipv6interfaceidentifier.is_set || is_set(ipv6interfaceidentifier.yfilter)) leaf_name_data.push_back(ipv6interfaceidentifier.get_name_leafdata()); if (ipv6interfaceenablestatus.is_set || is_set(ipv6interfaceenablestatus.yfilter)) leaf_name_data.push_back(ipv6interfaceenablestatus.get_name_leafdata()); if (ipv6interfacereachabletime.is_set || is_set(ipv6interfacereachabletime.yfilter)) leaf_name_data.push_back(ipv6interfacereachabletime.get_name_leafdata()); if (ipv6interfaceretransmittime.is_set || is_set(ipv6interfaceretransmittime.yfilter)) leaf_name_data.push_back(ipv6interfaceretransmittime.get_name_leafdata()); if (ipv6interfaceforwarding.is_set || is_set(ipv6interfaceforwarding.yfilter)) leaf_name_data.push_back(ipv6interfaceforwarding.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipv6InterfaceIfIndex") { ipv6interfaceifindex = value; ipv6interfaceifindex.value_namespace = name_space; ipv6interfaceifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceReasmMaxSize") { ipv6interfacereasmmaxsize = value; ipv6interfacereasmmaxsize.value_namespace = name_space; ipv6interfacereasmmaxsize.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceIdentifier") { ipv6interfaceidentifier = value; ipv6interfaceidentifier.value_namespace = name_space; ipv6interfaceidentifier.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceEnableStatus") { ipv6interfaceenablestatus = value; ipv6interfaceenablestatus.value_namespace = name_space; ipv6interfaceenablestatus.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceReachableTime") { ipv6interfacereachabletime = value; ipv6interfacereachabletime.value_namespace = name_space; ipv6interfacereachabletime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceRetransmitTime") { ipv6interfaceretransmittime = value; ipv6interfaceretransmittime.value_namespace = name_space; ipv6interfaceretransmittime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6InterfaceForwarding") { ipv6interfaceforwarding = value; ipv6interfaceforwarding.value_namespace = name_space; ipv6interfaceforwarding.value_namespace_prefix = name_space_prefix; } } void IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipv6InterfaceIfIndex") { ipv6interfaceifindex.yfilter = yfilter; } if(value_path == "ipv6InterfaceReasmMaxSize") { ipv6interfacereasmmaxsize.yfilter = yfilter; } if(value_path == "ipv6InterfaceIdentifier") { ipv6interfaceidentifier.yfilter = yfilter; } if(value_path == "ipv6InterfaceEnableStatus") { ipv6interfaceenablestatus.yfilter = yfilter; } if(value_path == "ipv6InterfaceReachableTime") { ipv6interfacereachabletime.yfilter = yfilter; } if(value_path == "ipv6InterfaceRetransmitTime") { ipv6interfaceretransmittime.yfilter = yfilter; } if(value_path == "ipv6InterfaceForwarding") { ipv6interfaceforwarding.yfilter = yfilter; } } bool IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6InterfaceIfIndex" || name == "ipv6InterfaceReasmMaxSize" || name == "ipv6InterfaceIdentifier" || name == "ipv6InterfaceEnableStatus" || name == "ipv6InterfaceReachableTime" || name == "ipv6InterfaceRetransmitTime" || name == "ipv6InterfaceForwarding") return true; return false; } IPMIB::IpSystemStatsTable::IpSystemStatsTable() : ipsystemstatsentry(this, {"ipsystemstatsipversion"}) { yang_name = "ipSystemStatsTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpSystemStatsTable::~IpSystemStatsTable() { } bool IPMIB::IpSystemStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipsystemstatsentry.len(); index++) { if(ipsystemstatsentry[index]->has_data()) return true; } return false; } bool IPMIB::IpSystemStatsTable::has_operation() const { for (std::size_t index=0; index<ipsystemstatsentry.len(); index++) { if(ipsystemstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpSystemStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpSystemStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipSystemStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpSystemStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpSystemStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipSystemStatsEntry") { auto ent_ = std::make_shared<IPMIB::IpSystemStatsTable::IpSystemStatsEntry>(); ent_->parent = this; ipsystemstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpSystemStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipsystemstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpSystemStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpSystemStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpSystemStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipSystemStatsEntry") return true; return false; } IPMIB::IpSystemStatsTable::IpSystemStatsEntry::IpSystemStatsEntry() : ipsystemstatsipversion{YType::enumeration, "ipSystemStatsIPVersion"}, ipsystemstatsinreceives{YType::uint32, "ipSystemStatsInReceives"}, ipsystemstatshcinreceives{YType::uint64, "ipSystemStatsHCInReceives"}, ipsystemstatsinoctets{YType::uint32, "ipSystemStatsInOctets"}, ipsystemstatshcinoctets{YType::uint64, "ipSystemStatsHCInOctets"}, ipsystemstatsinhdrerrors{YType::uint32, "ipSystemStatsInHdrErrors"}, ipsystemstatsinnoroutes{YType::uint32, "ipSystemStatsInNoRoutes"}, ipsystemstatsinaddrerrors{YType::uint32, "ipSystemStatsInAddrErrors"}, ipsystemstatsinunknownprotos{YType::uint32, "ipSystemStatsInUnknownProtos"}, ipsystemstatsintruncatedpkts{YType::uint32, "ipSystemStatsInTruncatedPkts"}, ipsystemstatsinforwdatagrams{YType::uint32, "ipSystemStatsInForwDatagrams"}, ipsystemstatshcinforwdatagrams{YType::uint64, "ipSystemStatsHCInForwDatagrams"}, ipsystemstatsreasmreqds{YType::uint32, "ipSystemStatsReasmReqds"}, ipsystemstatsreasmoks{YType::uint32, "ipSystemStatsReasmOKs"}, ipsystemstatsreasmfails{YType::uint32, "ipSystemStatsReasmFails"}, ipsystemstatsindiscards{YType::uint32, "ipSystemStatsInDiscards"}, ipsystemstatsindelivers{YType::uint32, "ipSystemStatsInDelivers"}, ipsystemstatshcindelivers{YType::uint64, "ipSystemStatsHCInDelivers"}, ipsystemstatsoutrequests{YType::uint32, "ipSystemStatsOutRequests"}, ipsystemstatshcoutrequests{YType::uint64, "ipSystemStatsHCOutRequests"}, ipsystemstatsoutnoroutes{YType::uint32, "ipSystemStatsOutNoRoutes"}, ipsystemstatsoutforwdatagrams{YType::uint32, "ipSystemStatsOutForwDatagrams"}, ipsystemstatshcoutforwdatagrams{YType::uint64, "ipSystemStatsHCOutForwDatagrams"}, ipsystemstatsoutdiscards{YType::uint32, "ipSystemStatsOutDiscards"}, ipsystemstatsoutfragreqds{YType::uint32, "ipSystemStatsOutFragReqds"}, ipsystemstatsoutfragoks{YType::uint32, "ipSystemStatsOutFragOKs"}, ipsystemstatsoutfragfails{YType::uint32, "ipSystemStatsOutFragFails"}, ipsystemstatsoutfragcreates{YType::uint32, "ipSystemStatsOutFragCreates"}, ipsystemstatsouttransmits{YType::uint32, "ipSystemStatsOutTransmits"}, ipsystemstatshcouttransmits{YType::uint64, "ipSystemStatsHCOutTransmits"}, ipsystemstatsoutoctets{YType::uint32, "ipSystemStatsOutOctets"}, ipsystemstatshcoutoctets{YType::uint64, "ipSystemStatsHCOutOctets"}, ipsystemstatsinmcastpkts{YType::uint32, "ipSystemStatsInMcastPkts"}, ipsystemstatshcinmcastpkts{YType::uint64, "ipSystemStatsHCInMcastPkts"}, ipsystemstatsinmcastoctets{YType::uint32, "ipSystemStatsInMcastOctets"}, ipsystemstatshcinmcastoctets{YType::uint64, "ipSystemStatsHCInMcastOctets"}, ipsystemstatsoutmcastpkts{YType::uint32, "ipSystemStatsOutMcastPkts"}, ipsystemstatshcoutmcastpkts{YType::uint64, "ipSystemStatsHCOutMcastPkts"}, ipsystemstatsoutmcastoctets{YType::uint32, "ipSystemStatsOutMcastOctets"}, ipsystemstatshcoutmcastoctets{YType::uint64, "ipSystemStatsHCOutMcastOctets"}, ipsystemstatsinbcastpkts{YType::uint32, "ipSystemStatsInBcastPkts"}, ipsystemstatshcinbcastpkts{YType::uint64, "ipSystemStatsHCInBcastPkts"}, ipsystemstatsoutbcastpkts{YType::uint32, "ipSystemStatsOutBcastPkts"}, ipsystemstatshcoutbcastpkts{YType::uint64, "ipSystemStatsHCOutBcastPkts"}, ipsystemstatsdiscontinuitytime{YType::uint32, "ipSystemStatsDiscontinuityTime"}, ipsystemstatsrefreshrate{YType::uint32, "ipSystemStatsRefreshRate"} { yang_name = "ipSystemStatsEntry"; yang_parent_name = "ipSystemStatsTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpSystemStatsTable::IpSystemStatsEntry::~IpSystemStatsEntry() { } bool IPMIB::IpSystemStatsTable::IpSystemStatsEntry::has_data() const { if (is_presence_container) return true; return ipsystemstatsipversion.is_set || ipsystemstatsinreceives.is_set || ipsystemstatshcinreceives.is_set || ipsystemstatsinoctets.is_set || ipsystemstatshcinoctets.is_set || ipsystemstatsinhdrerrors.is_set || ipsystemstatsinnoroutes.is_set || ipsystemstatsinaddrerrors.is_set || ipsystemstatsinunknownprotos.is_set || ipsystemstatsintruncatedpkts.is_set || ipsystemstatsinforwdatagrams.is_set || ipsystemstatshcinforwdatagrams.is_set || ipsystemstatsreasmreqds.is_set || ipsystemstatsreasmoks.is_set || ipsystemstatsreasmfails.is_set || ipsystemstatsindiscards.is_set || ipsystemstatsindelivers.is_set || ipsystemstatshcindelivers.is_set || ipsystemstatsoutrequests.is_set || ipsystemstatshcoutrequests.is_set || ipsystemstatsoutnoroutes.is_set || ipsystemstatsoutforwdatagrams.is_set || ipsystemstatshcoutforwdatagrams.is_set || ipsystemstatsoutdiscards.is_set || ipsystemstatsoutfragreqds.is_set || ipsystemstatsoutfragoks.is_set || ipsystemstatsoutfragfails.is_set || ipsystemstatsoutfragcreates.is_set || ipsystemstatsouttransmits.is_set || ipsystemstatshcouttransmits.is_set || ipsystemstatsoutoctets.is_set || ipsystemstatshcoutoctets.is_set || ipsystemstatsinmcastpkts.is_set || ipsystemstatshcinmcastpkts.is_set || ipsystemstatsinmcastoctets.is_set || ipsystemstatshcinmcastoctets.is_set || ipsystemstatsoutmcastpkts.is_set || ipsystemstatshcoutmcastpkts.is_set || ipsystemstatsoutmcastoctets.is_set || ipsystemstatshcoutmcastoctets.is_set || ipsystemstatsinbcastpkts.is_set || ipsystemstatshcinbcastpkts.is_set || ipsystemstatsoutbcastpkts.is_set || ipsystemstatshcoutbcastpkts.is_set || ipsystemstatsdiscontinuitytime.is_set || ipsystemstatsrefreshrate.is_set; } bool IPMIB::IpSystemStatsTable::IpSystemStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipsystemstatsipversion.yfilter) || ydk::is_set(ipsystemstatsinreceives.yfilter) || ydk::is_set(ipsystemstatshcinreceives.yfilter) || ydk::is_set(ipsystemstatsinoctets.yfilter) || ydk::is_set(ipsystemstatshcinoctets.yfilter) || ydk::is_set(ipsystemstatsinhdrerrors.yfilter) || ydk::is_set(ipsystemstatsinnoroutes.yfilter) || ydk::is_set(ipsystemstatsinaddrerrors.yfilter) || ydk::is_set(ipsystemstatsinunknownprotos.yfilter) || ydk::is_set(ipsystemstatsintruncatedpkts.yfilter) || ydk::is_set(ipsystemstatsinforwdatagrams.yfilter) || ydk::is_set(ipsystemstatshcinforwdatagrams.yfilter) || ydk::is_set(ipsystemstatsreasmreqds.yfilter) || ydk::is_set(ipsystemstatsreasmoks.yfilter) || ydk::is_set(ipsystemstatsreasmfails.yfilter) || ydk::is_set(ipsystemstatsindiscards.yfilter) || ydk::is_set(ipsystemstatsindelivers.yfilter) || ydk::is_set(ipsystemstatshcindelivers.yfilter) || ydk::is_set(ipsystemstatsoutrequests.yfilter) || ydk::is_set(ipsystemstatshcoutrequests.yfilter) || ydk::is_set(ipsystemstatsoutnoroutes.yfilter) || ydk::is_set(ipsystemstatsoutforwdatagrams.yfilter) || ydk::is_set(ipsystemstatshcoutforwdatagrams.yfilter) || ydk::is_set(ipsystemstatsoutdiscards.yfilter) || ydk::is_set(ipsystemstatsoutfragreqds.yfilter) || ydk::is_set(ipsystemstatsoutfragoks.yfilter) || ydk::is_set(ipsystemstatsoutfragfails.yfilter) || ydk::is_set(ipsystemstatsoutfragcreates.yfilter) || ydk::is_set(ipsystemstatsouttransmits.yfilter) || ydk::is_set(ipsystemstatshcouttransmits.yfilter) || ydk::is_set(ipsystemstatsoutoctets.yfilter) || ydk::is_set(ipsystemstatshcoutoctets.yfilter) || ydk::is_set(ipsystemstatsinmcastpkts.yfilter) || ydk::is_set(ipsystemstatshcinmcastpkts.yfilter) || ydk::is_set(ipsystemstatsinmcastoctets.yfilter) || ydk::is_set(ipsystemstatshcinmcastoctets.yfilter) || ydk::is_set(ipsystemstatsoutmcastpkts.yfilter) || ydk::is_set(ipsystemstatshcoutmcastpkts.yfilter) || ydk::is_set(ipsystemstatsoutmcastoctets.yfilter) || ydk::is_set(ipsystemstatshcoutmcastoctets.yfilter) || ydk::is_set(ipsystemstatsinbcastpkts.yfilter) || ydk::is_set(ipsystemstatshcinbcastpkts.yfilter) || ydk::is_set(ipsystemstatsoutbcastpkts.yfilter) || ydk::is_set(ipsystemstatshcoutbcastpkts.yfilter) || ydk::is_set(ipsystemstatsdiscontinuitytime.yfilter) || ydk::is_set(ipsystemstatsrefreshrate.yfilter); } std::string IPMIB::IpSystemStatsTable::IpSystemStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipSystemStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpSystemStatsTable::IpSystemStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipSystemStatsEntry"; ADD_KEY_TOKEN(ipsystemstatsipversion, "ipSystemStatsIPVersion"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpSystemStatsTable::IpSystemStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipsystemstatsipversion.is_set || is_set(ipsystemstatsipversion.yfilter)) leaf_name_data.push_back(ipsystemstatsipversion.get_name_leafdata()); if (ipsystemstatsinreceives.is_set || is_set(ipsystemstatsinreceives.yfilter)) leaf_name_data.push_back(ipsystemstatsinreceives.get_name_leafdata()); if (ipsystemstatshcinreceives.is_set || is_set(ipsystemstatshcinreceives.yfilter)) leaf_name_data.push_back(ipsystemstatshcinreceives.get_name_leafdata()); if (ipsystemstatsinoctets.is_set || is_set(ipsystemstatsinoctets.yfilter)) leaf_name_data.push_back(ipsystemstatsinoctets.get_name_leafdata()); if (ipsystemstatshcinoctets.is_set || is_set(ipsystemstatshcinoctets.yfilter)) leaf_name_data.push_back(ipsystemstatshcinoctets.get_name_leafdata()); if (ipsystemstatsinhdrerrors.is_set || is_set(ipsystemstatsinhdrerrors.yfilter)) leaf_name_data.push_back(ipsystemstatsinhdrerrors.get_name_leafdata()); if (ipsystemstatsinnoroutes.is_set || is_set(ipsystemstatsinnoroutes.yfilter)) leaf_name_data.push_back(ipsystemstatsinnoroutes.get_name_leafdata()); if (ipsystemstatsinaddrerrors.is_set || is_set(ipsystemstatsinaddrerrors.yfilter)) leaf_name_data.push_back(ipsystemstatsinaddrerrors.get_name_leafdata()); if (ipsystemstatsinunknownprotos.is_set || is_set(ipsystemstatsinunknownprotos.yfilter)) leaf_name_data.push_back(ipsystemstatsinunknownprotos.get_name_leafdata()); if (ipsystemstatsintruncatedpkts.is_set || is_set(ipsystemstatsintruncatedpkts.yfilter)) leaf_name_data.push_back(ipsystemstatsintruncatedpkts.get_name_leafdata()); if (ipsystemstatsinforwdatagrams.is_set || is_set(ipsystemstatsinforwdatagrams.yfilter)) leaf_name_data.push_back(ipsystemstatsinforwdatagrams.get_name_leafdata()); if (ipsystemstatshcinforwdatagrams.is_set || is_set(ipsystemstatshcinforwdatagrams.yfilter)) leaf_name_data.push_back(ipsystemstatshcinforwdatagrams.get_name_leafdata()); if (ipsystemstatsreasmreqds.is_set || is_set(ipsystemstatsreasmreqds.yfilter)) leaf_name_data.push_back(ipsystemstatsreasmreqds.get_name_leafdata()); if (ipsystemstatsreasmoks.is_set || is_set(ipsystemstatsreasmoks.yfilter)) leaf_name_data.push_back(ipsystemstatsreasmoks.get_name_leafdata()); if (ipsystemstatsreasmfails.is_set || is_set(ipsystemstatsreasmfails.yfilter)) leaf_name_data.push_back(ipsystemstatsreasmfails.get_name_leafdata()); if (ipsystemstatsindiscards.is_set || is_set(ipsystemstatsindiscards.yfilter)) leaf_name_data.push_back(ipsystemstatsindiscards.get_name_leafdata()); if (ipsystemstatsindelivers.is_set || is_set(ipsystemstatsindelivers.yfilter)) leaf_name_data.push_back(ipsystemstatsindelivers.get_name_leafdata()); if (ipsystemstatshcindelivers.is_set || is_set(ipsystemstatshcindelivers.yfilter)) leaf_name_data.push_back(ipsystemstatshcindelivers.get_name_leafdata()); if (ipsystemstatsoutrequests.is_set || is_set(ipsystemstatsoutrequests.yfilter)) leaf_name_data.push_back(ipsystemstatsoutrequests.get_name_leafdata()); if (ipsystemstatshcoutrequests.is_set || is_set(ipsystemstatshcoutrequests.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutrequests.get_name_leafdata()); if (ipsystemstatsoutnoroutes.is_set || is_set(ipsystemstatsoutnoroutes.yfilter)) leaf_name_data.push_back(ipsystemstatsoutnoroutes.get_name_leafdata()); if (ipsystemstatsoutforwdatagrams.is_set || is_set(ipsystemstatsoutforwdatagrams.yfilter)) leaf_name_data.push_back(ipsystemstatsoutforwdatagrams.get_name_leafdata()); if (ipsystemstatshcoutforwdatagrams.is_set || is_set(ipsystemstatshcoutforwdatagrams.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutforwdatagrams.get_name_leafdata()); if (ipsystemstatsoutdiscards.is_set || is_set(ipsystemstatsoutdiscards.yfilter)) leaf_name_data.push_back(ipsystemstatsoutdiscards.get_name_leafdata()); if (ipsystemstatsoutfragreqds.is_set || is_set(ipsystemstatsoutfragreqds.yfilter)) leaf_name_data.push_back(ipsystemstatsoutfragreqds.get_name_leafdata()); if (ipsystemstatsoutfragoks.is_set || is_set(ipsystemstatsoutfragoks.yfilter)) leaf_name_data.push_back(ipsystemstatsoutfragoks.get_name_leafdata()); if (ipsystemstatsoutfragfails.is_set || is_set(ipsystemstatsoutfragfails.yfilter)) leaf_name_data.push_back(ipsystemstatsoutfragfails.get_name_leafdata()); if (ipsystemstatsoutfragcreates.is_set || is_set(ipsystemstatsoutfragcreates.yfilter)) leaf_name_data.push_back(ipsystemstatsoutfragcreates.get_name_leafdata()); if (ipsystemstatsouttransmits.is_set || is_set(ipsystemstatsouttransmits.yfilter)) leaf_name_data.push_back(ipsystemstatsouttransmits.get_name_leafdata()); if (ipsystemstatshcouttransmits.is_set || is_set(ipsystemstatshcouttransmits.yfilter)) leaf_name_data.push_back(ipsystemstatshcouttransmits.get_name_leafdata()); if (ipsystemstatsoutoctets.is_set || is_set(ipsystemstatsoutoctets.yfilter)) leaf_name_data.push_back(ipsystemstatsoutoctets.get_name_leafdata()); if (ipsystemstatshcoutoctets.is_set || is_set(ipsystemstatshcoutoctets.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutoctets.get_name_leafdata()); if (ipsystemstatsinmcastpkts.is_set || is_set(ipsystemstatsinmcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatsinmcastpkts.get_name_leafdata()); if (ipsystemstatshcinmcastpkts.is_set || is_set(ipsystemstatshcinmcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatshcinmcastpkts.get_name_leafdata()); if (ipsystemstatsinmcastoctets.is_set || is_set(ipsystemstatsinmcastoctets.yfilter)) leaf_name_data.push_back(ipsystemstatsinmcastoctets.get_name_leafdata()); if (ipsystemstatshcinmcastoctets.is_set || is_set(ipsystemstatshcinmcastoctets.yfilter)) leaf_name_data.push_back(ipsystemstatshcinmcastoctets.get_name_leafdata()); if (ipsystemstatsoutmcastpkts.is_set || is_set(ipsystemstatsoutmcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatsoutmcastpkts.get_name_leafdata()); if (ipsystemstatshcoutmcastpkts.is_set || is_set(ipsystemstatshcoutmcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutmcastpkts.get_name_leafdata()); if (ipsystemstatsoutmcastoctets.is_set || is_set(ipsystemstatsoutmcastoctets.yfilter)) leaf_name_data.push_back(ipsystemstatsoutmcastoctets.get_name_leafdata()); if (ipsystemstatshcoutmcastoctets.is_set || is_set(ipsystemstatshcoutmcastoctets.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutmcastoctets.get_name_leafdata()); if (ipsystemstatsinbcastpkts.is_set || is_set(ipsystemstatsinbcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatsinbcastpkts.get_name_leafdata()); if (ipsystemstatshcinbcastpkts.is_set || is_set(ipsystemstatshcinbcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatshcinbcastpkts.get_name_leafdata()); if (ipsystemstatsoutbcastpkts.is_set || is_set(ipsystemstatsoutbcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatsoutbcastpkts.get_name_leafdata()); if (ipsystemstatshcoutbcastpkts.is_set || is_set(ipsystemstatshcoutbcastpkts.yfilter)) leaf_name_data.push_back(ipsystemstatshcoutbcastpkts.get_name_leafdata()); if (ipsystemstatsdiscontinuitytime.is_set || is_set(ipsystemstatsdiscontinuitytime.yfilter)) leaf_name_data.push_back(ipsystemstatsdiscontinuitytime.get_name_leafdata()); if (ipsystemstatsrefreshrate.is_set || is_set(ipsystemstatsrefreshrate.yfilter)) leaf_name_data.push_back(ipsystemstatsrefreshrate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpSystemStatsTable::IpSystemStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpSystemStatsTable::IpSystemStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpSystemStatsTable::IpSystemStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipSystemStatsIPVersion") { ipsystemstatsipversion = value; ipsystemstatsipversion.value_namespace = name_space; ipsystemstatsipversion.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInReceives") { ipsystemstatsinreceives = value; ipsystemstatsinreceives.value_namespace = name_space; ipsystemstatsinreceives.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInReceives") { ipsystemstatshcinreceives = value; ipsystemstatshcinreceives.value_namespace = name_space; ipsystemstatshcinreceives.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInOctets") { ipsystemstatsinoctets = value; ipsystemstatsinoctets.value_namespace = name_space; ipsystemstatsinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInOctets") { ipsystemstatshcinoctets = value; ipsystemstatshcinoctets.value_namespace = name_space; ipsystemstatshcinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInHdrErrors") { ipsystemstatsinhdrerrors = value; ipsystemstatsinhdrerrors.value_namespace = name_space; ipsystemstatsinhdrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInNoRoutes") { ipsystemstatsinnoroutes = value; ipsystemstatsinnoroutes.value_namespace = name_space; ipsystemstatsinnoroutes.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInAddrErrors") { ipsystemstatsinaddrerrors = value; ipsystemstatsinaddrerrors.value_namespace = name_space; ipsystemstatsinaddrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInUnknownProtos") { ipsystemstatsinunknownprotos = value; ipsystemstatsinunknownprotos.value_namespace = name_space; ipsystemstatsinunknownprotos.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInTruncatedPkts") { ipsystemstatsintruncatedpkts = value; ipsystemstatsintruncatedpkts.value_namespace = name_space; ipsystemstatsintruncatedpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInForwDatagrams") { ipsystemstatsinforwdatagrams = value; ipsystemstatsinforwdatagrams.value_namespace = name_space; ipsystemstatsinforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInForwDatagrams") { ipsystemstatshcinforwdatagrams = value; ipsystemstatshcinforwdatagrams.value_namespace = name_space; ipsystemstatshcinforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsReasmReqds") { ipsystemstatsreasmreqds = value; ipsystemstatsreasmreqds.value_namespace = name_space; ipsystemstatsreasmreqds.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsReasmOKs") { ipsystemstatsreasmoks = value; ipsystemstatsreasmoks.value_namespace = name_space; ipsystemstatsreasmoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsReasmFails") { ipsystemstatsreasmfails = value; ipsystemstatsreasmfails.value_namespace = name_space; ipsystemstatsreasmfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInDiscards") { ipsystemstatsindiscards = value; ipsystemstatsindiscards.value_namespace = name_space; ipsystemstatsindiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInDelivers") { ipsystemstatsindelivers = value; ipsystemstatsindelivers.value_namespace = name_space; ipsystemstatsindelivers.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInDelivers") { ipsystemstatshcindelivers = value; ipsystemstatshcindelivers.value_namespace = name_space; ipsystemstatshcindelivers.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutRequests") { ipsystemstatsoutrequests = value; ipsystemstatsoutrequests.value_namespace = name_space; ipsystemstatsoutrequests.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutRequests") { ipsystemstatshcoutrequests = value; ipsystemstatshcoutrequests.value_namespace = name_space; ipsystemstatshcoutrequests.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutNoRoutes") { ipsystemstatsoutnoroutes = value; ipsystemstatsoutnoroutes.value_namespace = name_space; ipsystemstatsoutnoroutes.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutForwDatagrams") { ipsystemstatsoutforwdatagrams = value; ipsystemstatsoutforwdatagrams.value_namespace = name_space; ipsystemstatsoutforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutForwDatagrams") { ipsystemstatshcoutforwdatagrams = value; ipsystemstatshcoutforwdatagrams.value_namespace = name_space; ipsystemstatshcoutforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutDiscards") { ipsystemstatsoutdiscards = value; ipsystemstatsoutdiscards.value_namespace = name_space; ipsystemstatsoutdiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutFragReqds") { ipsystemstatsoutfragreqds = value; ipsystemstatsoutfragreqds.value_namespace = name_space; ipsystemstatsoutfragreqds.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutFragOKs") { ipsystemstatsoutfragoks = value; ipsystemstatsoutfragoks.value_namespace = name_space; ipsystemstatsoutfragoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutFragFails") { ipsystemstatsoutfragfails = value; ipsystemstatsoutfragfails.value_namespace = name_space; ipsystemstatsoutfragfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutFragCreates") { ipsystemstatsoutfragcreates = value; ipsystemstatsoutfragcreates.value_namespace = name_space; ipsystemstatsoutfragcreates.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutTransmits") { ipsystemstatsouttransmits = value; ipsystemstatsouttransmits.value_namespace = name_space; ipsystemstatsouttransmits.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutTransmits") { ipsystemstatshcouttransmits = value; ipsystemstatshcouttransmits.value_namespace = name_space; ipsystemstatshcouttransmits.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutOctets") { ipsystemstatsoutoctets = value; ipsystemstatsoutoctets.value_namespace = name_space; ipsystemstatsoutoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutOctets") { ipsystemstatshcoutoctets = value; ipsystemstatshcoutoctets.value_namespace = name_space; ipsystemstatshcoutoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInMcastPkts") { ipsystemstatsinmcastpkts = value; ipsystemstatsinmcastpkts.value_namespace = name_space; ipsystemstatsinmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInMcastPkts") { ipsystemstatshcinmcastpkts = value; ipsystemstatshcinmcastpkts.value_namespace = name_space; ipsystemstatshcinmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInMcastOctets") { ipsystemstatsinmcastoctets = value; ipsystemstatsinmcastoctets.value_namespace = name_space; ipsystemstatsinmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInMcastOctets") { ipsystemstatshcinmcastoctets = value; ipsystemstatshcinmcastoctets.value_namespace = name_space; ipsystemstatshcinmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutMcastPkts") { ipsystemstatsoutmcastpkts = value; ipsystemstatsoutmcastpkts.value_namespace = name_space; ipsystemstatsoutmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutMcastPkts") { ipsystemstatshcoutmcastpkts = value; ipsystemstatshcoutmcastpkts.value_namespace = name_space; ipsystemstatshcoutmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutMcastOctets") { ipsystemstatsoutmcastoctets = value; ipsystemstatsoutmcastoctets.value_namespace = name_space; ipsystemstatsoutmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutMcastOctets") { ipsystemstatshcoutmcastoctets = value; ipsystemstatshcoutmcastoctets.value_namespace = name_space; ipsystemstatshcoutmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsInBcastPkts") { ipsystemstatsinbcastpkts = value; ipsystemstatsinbcastpkts.value_namespace = name_space; ipsystemstatsinbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCInBcastPkts") { ipsystemstatshcinbcastpkts = value; ipsystemstatshcinbcastpkts.value_namespace = name_space; ipsystemstatshcinbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsOutBcastPkts") { ipsystemstatsoutbcastpkts = value; ipsystemstatsoutbcastpkts.value_namespace = name_space; ipsystemstatsoutbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsHCOutBcastPkts") { ipsystemstatshcoutbcastpkts = value; ipsystemstatshcoutbcastpkts.value_namespace = name_space; ipsystemstatshcoutbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsDiscontinuityTime") { ipsystemstatsdiscontinuitytime = value; ipsystemstatsdiscontinuitytime.value_namespace = name_space; ipsystemstatsdiscontinuitytime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipSystemStatsRefreshRate") { ipsystemstatsrefreshrate = value; ipsystemstatsrefreshrate.value_namespace = name_space; ipsystemstatsrefreshrate.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpSystemStatsTable::IpSystemStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipSystemStatsIPVersion") { ipsystemstatsipversion.yfilter = yfilter; } if(value_path == "ipSystemStatsInReceives") { ipsystemstatsinreceives.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInReceives") { ipsystemstatshcinreceives.yfilter = yfilter; } if(value_path == "ipSystemStatsInOctets") { ipsystemstatsinoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInOctets") { ipsystemstatshcinoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsInHdrErrors") { ipsystemstatsinhdrerrors.yfilter = yfilter; } if(value_path == "ipSystemStatsInNoRoutes") { ipsystemstatsinnoroutes.yfilter = yfilter; } if(value_path == "ipSystemStatsInAddrErrors") { ipsystemstatsinaddrerrors.yfilter = yfilter; } if(value_path == "ipSystemStatsInUnknownProtos") { ipsystemstatsinunknownprotos.yfilter = yfilter; } if(value_path == "ipSystemStatsInTruncatedPkts") { ipsystemstatsintruncatedpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsInForwDatagrams") { ipsystemstatsinforwdatagrams.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInForwDatagrams") { ipsystemstatshcinforwdatagrams.yfilter = yfilter; } if(value_path == "ipSystemStatsReasmReqds") { ipsystemstatsreasmreqds.yfilter = yfilter; } if(value_path == "ipSystemStatsReasmOKs") { ipsystemstatsreasmoks.yfilter = yfilter; } if(value_path == "ipSystemStatsReasmFails") { ipsystemstatsreasmfails.yfilter = yfilter; } if(value_path == "ipSystemStatsInDiscards") { ipsystemstatsindiscards.yfilter = yfilter; } if(value_path == "ipSystemStatsInDelivers") { ipsystemstatsindelivers.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInDelivers") { ipsystemstatshcindelivers.yfilter = yfilter; } if(value_path == "ipSystemStatsOutRequests") { ipsystemstatsoutrequests.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutRequests") { ipsystemstatshcoutrequests.yfilter = yfilter; } if(value_path == "ipSystemStatsOutNoRoutes") { ipsystemstatsoutnoroutes.yfilter = yfilter; } if(value_path == "ipSystemStatsOutForwDatagrams") { ipsystemstatsoutforwdatagrams.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutForwDatagrams") { ipsystemstatshcoutforwdatagrams.yfilter = yfilter; } if(value_path == "ipSystemStatsOutDiscards") { ipsystemstatsoutdiscards.yfilter = yfilter; } if(value_path == "ipSystemStatsOutFragReqds") { ipsystemstatsoutfragreqds.yfilter = yfilter; } if(value_path == "ipSystemStatsOutFragOKs") { ipsystemstatsoutfragoks.yfilter = yfilter; } if(value_path == "ipSystemStatsOutFragFails") { ipsystemstatsoutfragfails.yfilter = yfilter; } if(value_path == "ipSystemStatsOutFragCreates") { ipsystemstatsoutfragcreates.yfilter = yfilter; } if(value_path == "ipSystemStatsOutTransmits") { ipsystemstatsouttransmits.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutTransmits") { ipsystemstatshcouttransmits.yfilter = yfilter; } if(value_path == "ipSystemStatsOutOctets") { ipsystemstatsoutoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutOctets") { ipsystemstatshcoutoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsInMcastPkts") { ipsystemstatsinmcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInMcastPkts") { ipsystemstatshcinmcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsInMcastOctets") { ipsystemstatsinmcastoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInMcastOctets") { ipsystemstatshcinmcastoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsOutMcastPkts") { ipsystemstatsoutmcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutMcastPkts") { ipsystemstatshcoutmcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsOutMcastOctets") { ipsystemstatsoutmcastoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutMcastOctets") { ipsystemstatshcoutmcastoctets.yfilter = yfilter; } if(value_path == "ipSystemStatsInBcastPkts") { ipsystemstatsinbcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsHCInBcastPkts") { ipsystemstatshcinbcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsOutBcastPkts") { ipsystemstatsoutbcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsHCOutBcastPkts") { ipsystemstatshcoutbcastpkts.yfilter = yfilter; } if(value_path == "ipSystemStatsDiscontinuityTime") { ipsystemstatsdiscontinuitytime.yfilter = yfilter; } if(value_path == "ipSystemStatsRefreshRate") { ipsystemstatsrefreshrate.yfilter = yfilter; } } bool IPMIB::IpSystemStatsTable::IpSystemStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipSystemStatsIPVersion" || name == "ipSystemStatsInReceives" || name == "ipSystemStatsHCInReceives" || name == "ipSystemStatsInOctets" || name == "ipSystemStatsHCInOctets" || name == "ipSystemStatsInHdrErrors" || name == "ipSystemStatsInNoRoutes" || name == "ipSystemStatsInAddrErrors" || name == "ipSystemStatsInUnknownProtos" || name == "ipSystemStatsInTruncatedPkts" || name == "ipSystemStatsInForwDatagrams" || name == "ipSystemStatsHCInForwDatagrams" || name == "ipSystemStatsReasmReqds" || name == "ipSystemStatsReasmOKs" || name == "ipSystemStatsReasmFails" || name == "ipSystemStatsInDiscards" || name == "ipSystemStatsInDelivers" || name == "ipSystemStatsHCInDelivers" || name == "ipSystemStatsOutRequests" || name == "ipSystemStatsHCOutRequests" || name == "ipSystemStatsOutNoRoutes" || name == "ipSystemStatsOutForwDatagrams" || name == "ipSystemStatsHCOutForwDatagrams" || name == "ipSystemStatsOutDiscards" || name == "ipSystemStatsOutFragReqds" || name == "ipSystemStatsOutFragOKs" || name == "ipSystemStatsOutFragFails" || name == "ipSystemStatsOutFragCreates" || name == "ipSystemStatsOutTransmits" || name == "ipSystemStatsHCOutTransmits" || name == "ipSystemStatsOutOctets" || name == "ipSystemStatsHCOutOctets" || name == "ipSystemStatsInMcastPkts" || name == "ipSystemStatsHCInMcastPkts" || name == "ipSystemStatsInMcastOctets" || name == "ipSystemStatsHCInMcastOctets" || name == "ipSystemStatsOutMcastPkts" || name == "ipSystemStatsHCOutMcastPkts" || name == "ipSystemStatsOutMcastOctets" || name == "ipSystemStatsHCOutMcastOctets" || name == "ipSystemStatsInBcastPkts" || name == "ipSystemStatsHCInBcastPkts" || name == "ipSystemStatsOutBcastPkts" || name == "ipSystemStatsHCOutBcastPkts" || name == "ipSystemStatsDiscontinuityTime" || name == "ipSystemStatsRefreshRate") return true; return false; } IPMIB::IpIfStatsTable::IpIfStatsTable() : ipifstatsentry(this, {"ipifstatsipversion", "ipifstatsifindex"}) { yang_name = "ipIfStatsTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpIfStatsTable::~IpIfStatsTable() { } bool IPMIB::IpIfStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipifstatsentry.len(); index++) { if(ipifstatsentry[index]->has_data()) return true; } return false; } bool IPMIB::IpIfStatsTable::has_operation() const { for (std::size_t index=0; index<ipifstatsentry.len(); index++) { if(ipifstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpIfStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpIfStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipIfStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpIfStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpIfStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipIfStatsEntry") { auto ent_ = std::make_shared<IPMIB::IpIfStatsTable::IpIfStatsEntry>(); ent_->parent = this; ipifstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpIfStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipifstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpIfStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpIfStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpIfStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipIfStatsEntry") return true; return false; } IPMIB::IpIfStatsTable::IpIfStatsEntry::IpIfStatsEntry() : ipifstatsipversion{YType::enumeration, "ipIfStatsIPVersion"}, ipifstatsifindex{YType::int32, "ipIfStatsIfIndex"}, ipifstatsinreceives{YType::uint32, "ipIfStatsInReceives"}, ipifstatshcinreceives{YType::uint64, "ipIfStatsHCInReceives"}, ipifstatsinoctets{YType::uint32, "ipIfStatsInOctets"}, ipifstatshcinoctets{YType::uint64, "ipIfStatsHCInOctets"}, ipifstatsinhdrerrors{YType::uint32, "ipIfStatsInHdrErrors"}, ipifstatsinnoroutes{YType::uint32, "ipIfStatsInNoRoutes"}, ipifstatsinaddrerrors{YType::uint32, "ipIfStatsInAddrErrors"}, ipifstatsinunknownprotos{YType::uint32, "ipIfStatsInUnknownProtos"}, ipifstatsintruncatedpkts{YType::uint32, "ipIfStatsInTruncatedPkts"}, ipifstatsinforwdatagrams{YType::uint32, "ipIfStatsInForwDatagrams"}, ipifstatshcinforwdatagrams{YType::uint64, "ipIfStatsHCInForwDatagrams"}, ipifstatsreasmreqds{YType::uint32, "ipIfStatsReasmReqds"}, ipifstatsreasmoks{YType::uint32, "ipIfStatsReasmOKs"}, ipifstatsreasmfails{YType::uint32, "ipIfStatsReasmFails"}, ipifstatsindiscards{YType::uint32, "ipIfStatsInDiscards"}, ipifstatsindelivers{YType::uint32, "ipIfStatsInDelivers"}, ipifstatshcindelivers{YType::uint64, "ipIfStatsHCInDelivers"}, ipifstatsoutrequests{YType::uint32, "ipIfStatsOutRequests"}, ipifstatshcoutrequests{YType::uint64, "ipIfStatsHCOutRequests"}, ipifstatsoutforwdatagrams{YType::uint32, "ipIfStatsOutForwDatagrams"}, ipifstatshcoutforwdatagrams{YType::uint64, "ipIfStatsHCOutForwDatagrams"}, ipifstatsoutdiscards{YType::uint32, "ipIfStatsOutDiscards"}, ipifstatsoutfragreqds{YType::uint32, "ipIfStatsOutFragReqds"}, ipifstatsoutfragoks{YType::uint32, "ipIfStatsOutFragOKs"}, ipifstatsoutfragfails{YType::uint32, "ipIfStatsOutFragFails"}, ipifstatsoutfragcreates{YType::uint32, "ipIfStatsOutFragCreates"}, ipifstatsouttransmits{YType::uint32, "ipIfStatsOutTransmits"}, ipifstatshcouttransmits{YType::uint64, "ipIfStatsHCOutTransmits"}, ipifstatsoutoctets{YType::uint32, "ipIfStatsOutOctets"}, ipifstatshcoutoctets{YType::uint64, "ipIfStatsHCOutOctets"}, ipifstatsinmcastpkts{YType::uint32, "ipIfStatsInMcastPkts"}, ipifstatshcinmcastpkts{YType::uint64, "ipIfStatsHCInMcastPkts"}, ipifstatsinmcastoctets{YType::uint32, "ipIfStatsInMcastOctets"}, ipifstatshcinmcastoctets{YType::uint64, "ipIfStatsHCInMcastOctets"}, ipifstatsoutmcastpkts{YType::uint32, "ipIfStatsOutMcastPkts"}, ipifstatshcoutmcastpkts{YType::uint64, "ipIfStatsHCOutMcastPkts"}, ipifstatsoutmcastoctets{YType::uint32, "ipIfStatsOutMcastOctets"}, ipifstatshcoutmcastoctets{YType::uint64, "ipIfStatsHCOutMcastOctets"}, ipifstatsinbcastpkts{YType::uint32, "ipIfStatsInBcastPkts"}, ipifstatshcinbcastpkts{YType::uint64, "ipIfStatsHCInBcastPkts"}, ipifstatsoutbcastpkts{YType::uint32, "ipIfStatsOutBcastPkts"}, ipifstatshcoutbcastpkts{YType::uint64, "ipIfStatsHCOutBcastPkts"}, ipifstatsdiscontinuitytime{YType::uint32, "ipIfStatsDiscontinuityTime"}, ipifstatsrefreshrate{YType::uint32, "ipIfStatsRefreshRate"} { yang_name = "ipIfStatsEntry"; yang_parent_name = "ipIfStatsTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpIfStatsTable::IpIfStatsEntry::~IpIfStatsEntry() { } bool IPMIB::IpIfStatsTable::IpIfStatsEntry::has_data() const { if (is_presence_container) return true; return ipifstatsipversion.is_set || ipifstatsifindex.is_set || ipifstatsinreceives.is_set || ipifstatshcinreceives.is_set || ipifstatsinoctets.is_set || ipifstatshcinoctets.is_set || ipifstatsinhdrerrors.is_set || ipifstatsinnoroutes.is_set || ipifstatsinaddrerrors.is_set || ipifstatsinunknownprotos.is_set || ipifstatsintruncatedpkts.is_set || ipifstatsinforwdatagrams.is_set || ipifstatshcinforwdatagrams.is_set || ipifstatsreasmreqds.is_set || ipifstatsreasmoks.is_set || ipifstatsreasmfails.is_set || ipifstatsindiscards.is_set || ipifstatsindelivers.is_set || ipifstatshcindelivers.is_set || ipifstatsoutrequests.is_set || ipifstatshcoutrequests.is_set || ipifstatsoutforwdatagrams.is_set || ipifstatshcoutforwdatagrams.is_set || ipifstatsoutdiscards.is_set || ipifstatsoutfragreqds.is_set || ipifstatsoutfragoks.is_set || ipifstatsoutfragfails.is_set || ipifstatsoutfragcreates.is_set || ipifstatsouttransmits.is_set || ipifstatshcouttransmits.is_set || ipifstatsoutoctets.is_set || ipifstatshcoutoctets.is_set || ipifstatsinmcastpkts.is_set || ipifstatshcinmcastpkts.is_set || ipifstatsinmcastoctets.is_set || ipifstatshcinmcastoctets.is_set || ipifstatsoutmcastpkts.is_set || ipifstatshcoutmcastpkts.is_set || ipifstatsoutmcastoctets.is_set || ipifstatshcoutmcastoctets.is_set || ipifstatsinbcastpkts.is_set || ipifstatshcinbcastpkts.is_set || ipifstatsoutbcastpkts.is_set || ipifstatshcoutbcastpkts.is_set || ipifstatsdiscontinuitytime.is_set || ipifstatsrefreshrate.is_set; } bool IPMIB::IpIfStatsTable::IpIfStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipifstatsipversion.yfilter) || ydk::is_set(ipifstatsifindex.yfilter) || ydk::is_set(ipifstatsinreceives.yfilter) || ydk::is_set(ipifstatshcinreceives.yfilter) || ydk::is_set(ipifstatsinoctets.yfilter) || ydk::is_set(ipifstatshcinoctets.yfilter) || ydk::is_set(ipifstatsinhdrerrors.yfilter) || ydk::is_set(ipifstatsinnoroutes.yfilter) || ydk::is_set(ipifstatsinaddrerrors.yfilter) || ydk::is_set(ipifstatsinunknownprotos.yfilter) || ydk::is_set(ipifstatsintruncatedpkts.yfilter) || ydk::is_set(ipifstatsinforwdatagrams.yfilter) || ydk::is_set(ipifstatshcinforwdatagrams.yfilter) || ydk::is_set(ipifstatsreasmreqds.yfilter) || ydk::is_set(ipifstatsreasmoks.yfilter) || ydk::is_set(ipifstatsreasmfails.yfilter) || ydk::is_set(ipifstatsindiscards.yfilter) || ydk::is_set(ipifstatsindelivers.yfilter) || ydk::is_set(ipifstatshcindelivers.yfilter) || ydk::is_set(ipifstatsoutrequests.yfilter) || ydk::is_set(ipifstatshcoutrequests.yfilter) || ydk::is_set(ipifstatsoutforwdatagrams.yfilter) || ydk::is_set(ipifstatshcoutforwdatagrams.yfilter) || ydk::is_set(ipifstatsoutdiscards.yfilter) || ydk::is_set(ipifstatsoutfragreqds.yfilter) || ydk::is_set(ipifstatsoutfragoks.yfilter) || ydk::is_set(ipifstatsoutfragfails.yfilter) || ydk::is_set(ipifstatsoutfragcreates.yfilter) || ydk::is_set(ipifstatsouttransmits.yfilter) || ydk::is_set(ipifstatshcouttransmits.yfilter) || ydk::is_set(ipifstatsoutoctets.yfilter) || ydk::is_set(ipifstatshcoutoctets.yfilter) || ydk::is_set(ipifstatsinmcastpkts.yfilter) || ydk::is_set(ipifstatshcinmcastpkts.yfilter) || ydk::is_set(ipifstatsinmcastoctets.yfilter) || ydk::is_set(ipifstatshcinmcastoctets.yfilter) || ydk::is_set(ipifstatsoutmcastpkts.yfilter) || ydk::is_set(ipifstatshcoutmcastpkts.yfilter) || ydk::is_set(ipifstatsoutmcastoctets.yfilter) || ydk::is_set(ipifstatshcoutmcastoctets.yfilter) || ydk::is_set(ipifstatsinbcastpkts.yfilter) || ydk::is_set(ipifstatshcinbcastpkts.yfilter) || ydk::is_set(ipifstatsoutbcastpkts.yfilter) || ydk::is_set(ipifstatshcoutbcastpkts.yfilter) || ydk::is_set(ipifstatsdiscontinuitytime.yfilter) || ydk::is_set(ipifstatsrefreshrate.yfilter); } std::string IPMIB::IpIfStatsTable::IpIfStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipIfStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpIfStatsTable::IpIfStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipIfStatsEntry"; ADD_KEY_TOKEN(ipifstatsipversion, "ipIfStatsIPVersion"); ADD_KEY_TOKEN(ipifstatsifindex, "ipIfStatsIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpIfStatsTable::IpIfStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipifstatsipversion.is_set || is_set(ipifstatsipversion.yfilter)) leaf_name_data.push_back(ipifstatsipversion.get_name_leafdata()); if (ipifstatsifindex.is_set || is_set(ipifstatsifindex.yfilter)) leaf_name_data.push_back(ipifstatsifindex.get_name_leafdata()); if (ipifstatsinreceives.is_set || is_set(ipifstatsinreceives.yfilter)) leaf_name_data.push_back(ipifstatsinreceives.get_name_leafdata()); if (ipifstatshcinreceives.is_set || is_set(ipifstatshcinreceives.yfilter)) leaf_name_data.push_back(ipifstatshcinreceives.get_name_leafdata()); if (ipifstatsinoctets.is_set || is_set(ipifstatsinoctets.yfilter)) leaf_name_data.push_back(ipifstatsinoctets.get_name_leafdata()); if (ipifstatshcinoctets.is_set || is_set(ipifstatshcinoctets.yfilter)) leaf_name_data.push_back(ipifstatshcinoctets.get_name_leafdata()); if (ipifstatsinhdrerrors.is_set || is_set(ipifstatsinhdrerrors.yfilter)) leaf_name_data.push_back(ipifstatsinhdrerrors.get_name_leafdata()); if (ipifstatsinnoroutes.is_set || is_set(ipifstatsinnoroutes.yfilter)) leaf_name_data.push_back(ipifstatsinnoroutes.get_name_leafdata()); if (ipifstatsinaddrerrors.is_set || is_set(ipifstatsinaddrerrors.yfilter)) leaf_name_data.push_back(ipifstatsinaddrerrors.get_name_leafdata()); if (ipifstatsinunknownprotos.is_set || is_set(ipifstatsinunknownprotos.yfilter)) leaf_name_data.push_back(ipifstatsinunknownprotos.get_name_leafdata()); if (ipifstatsintruncatedpkts.is_set || is_set(ipifstatsintruncatedpkts.yfilter)) leaf_name_data.push_back(ipifstatsintruncatedpkts.get_name_leafdata()); if (ipifstatsinforwdatagrams.is_set || is_set(ipifstatsinforwdatagrams.yfilter)) leaf_name_data.push_back(ipifstatsinforwdatagrams.get_name_leafdata()); if (ipifstatshcinforwdatagrams.is_set || is_set(ipifstatshcinforwdatagrams.yfilter)) leaf_name_data.push_back(ipifstatshcinforwdatagrams.get_name_leafdata()); if (ipifstatsreasmreqds.is_set || is_set(ipifstatsreasmreqds.yfilter)) leaf_name_data.push_back(ipifstatsreasmreqds.get_name_leafdata()); if (ipifstatsreasmoks.is_set || is_set(ipifstatsreasmoks.yfilter)) leaf_name_data.push_back(ipifstatsreasmoks.get_name_leafdata()); if (ipifstatsreasmfails.is_set || is_set(ipifstatsreasmfails.yfilter)) leaf_name_data.push_back(ipifstatsreasmfails.get_name_leafdata()); if (ipifstatsindiscards.is_set || is_set(ipifstatsindiscards.yfilter)) leaf_name_data.push_back(ipifstatsindiscards.get_name_leafdata()); if (ipifstatsindelivers.is_set || is_set(ipifstatsindelivers.yfilter)) leaf_name_data.push_back(ipifstatsindelivers.get_name_leafdata()); if (ipifstatshcindelivers.is_set || is_set(ipifstatshcindelivers.yfilter)) leaf_name_data.push_back(ipifstatshcindelivers.get_name_leafdata()); if (ipifstatsoutrequests.is_set || is_set(ipifstatsoutrequests.yfilter)) leaf_name_data.push_back(ipifstatsoutrequests.get_name_leafdata()); if (ipifstatshcoutrequests.is_set || is_set(ipifstatshcoutrequests.yfilter)) leaf_name_data.push_back(ipifstatshcoutrequests.get_name_leafdata()); if (ipifstatsoutforwdatagrams.is_set || is_set(ipifstatsoutforwdatagrams.yfilter)) leaf_name_data.push_back(ipifstatsoutforwdatagrams.get_name_leafdata()); if (ipifstatshcoutforwdatagrams.is_set || is_set(ipifstatshcoutforwdatagrams.yfilter)) leaf_name_data.push_back(ipifstatshcoutforwdatagrams.get_name_leafdata()); if (ipifstatsoutdiscards.is_set || is_set(ipifstatsoutdiscards.yfilter)) leaf_name_data.push_back(ipifstatsoutdiscards.get_name_leafdata()); if (ipifstatsoutfragreqds.is_set || is_set(ipifstatsoutfragreqds.yfilter)) leaf_name_data.push_back(ipifstatsoutfragreqds.get_name_leafdata()); if (ipifstatsoutfragoks.is_set || is_set(ipifstatsoutfragoks.yfilter)) leaf_name_data.push_back(ipifstatsoutfragoks.get_name_leafdata()); if (ipifstatsoutfragfails.is_set || is_set(ipifstatsoutfragfails.yfilter)) leaf_name_data.push_back(ipifstatsoutfragfails.get_name_leafdata()); if (ipifstatsoutfragcreates.is_set || is_set(ipifstatsoutfragcreates.yfilter)) leaf_name_data.push_back(ipifstatsoutfragcreates.get_name_leafdata()); if (ipifstatsouttransmits.is_set || is_set(ipifstatsouttransmits.yfilter)) leaf_name_data.push_back(ipifstatsouttransmits.get_name_leafdata()); if (ipifstatshcouttransmits.is_set || is_set(ipifstatshcouttransmits.yfilter)) leaf_name_data.push_back(ipifstatshcouttransmits.get_name_leafdata()); if (ipifstatsoutoctets.is_set || is_set(ipifstatsoutoctets.yfilter)) leaf_name_data.push_back(ipifstatsoutoctets.get_name_leafdata()); if (ipifstatshcoutoctets.is_set || is_set(ipifstatshcoutoctets.yfilter)) leaf_name_data.push_back(ipifstatshcoutoctets.get_name_leafdata()); if (ipifstatsinmcastpkts.is_set || is_set(ipifstatsinmcastpkts.yfilter)) leaf_name_data.push_back(ipifstatsinmcastpkts.get_name_leafdata()); if (ipifstatshcinmcastpkts.is_set || is_set(ipifstatshcinmcastpkts.yfilter)) leaf_name_data.push_back(ipifstatshcinmcastpkts.get_name_leafdata()); if (ipifstatsinmcastoctets.is_set || is_set(ipifstatsinmcastoctets.yfilter)) leaf_name_data.push_back(ipifstatsinmcastoctets.get_name_leafdata()); if (ipifstatshcinmcastoctets.is_set || is_set(ipifstatshcinmcastoctets.yfilter)) leaf_name_data.push_back(ipifstatshcinmcastoctets.get_name_leafdata()); if (ipifstatsoutmcastpkts.is_set || is_set(ipifstatsoutmcastpkts.yfilter)) leaf_name_data.push_back(ipifstatsoutmcastpkts.get_name_leafdata()); if (ipifstatshcoutmcastpkts.is_set || is_set(ipifstatshcoutmcastpkts.yfilter)) leaf_name_data.push_back(ipifstatshcoutmcastpkts.get_name_leafdata()); if (ipifstatsoutmcastoctets.is_set || is_set(ipifstatsoutmcastoctets.yfilter)) leaf_name_data.push_back(ipifstatsoutmcastoctets.get_name_leafdata()); if (ipifstatshcoutmcastoctets.is_set || is_set(ipifstatshcoutmcastoctets.yfilter)) leaf_name_data.push_back(ipifstatshcoutmcastoctets.get_name_leafdata()); if (ipifstatsinbcastpkts.is_set || is_set(ipifstatsinbcastpkts.yfilter)) leaf_name_data.push_back(ipifstatsinbcastpkts.get_name_leafdata()); if (ipifstatshcinbcastpkts.is_set || is_set(ipifstatshcinbcastpkts.yfilter)) leaf_name_data.push_back(ipifstatshcinbcastpkts.get_name_leafdata()); if (ipifstatsoutbcastpkts.is_set || is_set(ipifstatsoutbcastpkts.yfilter)) leaf_name_data.push_back(ipifstatsoutbcastpkts.get_name_leafdata()); if (ipifstatshcoutbcastpkts.is_set || is_set(ipifstatshcoutbcastpkts.yfilter)) leaf_name_data.push_back(ipifstatshcoutbcastpkts.get_name_leafdata()); if (ipifstatsdiscontinuitytime.is_set || is_set(ipifstatsdiscontinuitytime.yfilter)) leaf_name_data.push_back(ipifstatsdiscontinuitytime.get_name_leafdata()); if (ipifstatsrefreshrate.is_set || is_set(ipifstatsrefreshrate.yfilter)) leaf_name_data.push_back(ipifstatsrefreshrate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpIfStatsTable::IpIfStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpIfStatsTable::IpIfStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpIfStatsTable::IpIfStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipIfStatsIPVersion") { ipifstatsipversion = value; ipifstatsipversion.value_namespace = name_space; ipifstatsipversion.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsIfIndex") { ipifstatsifindex = value; ipifstatsifindex.value_namespace = name_space; ipifstatsifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInReceives") { ipifstatsinreceives = value; ipifstatsinreceives.value_namespace = name_space; ipifstatsinreceives.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInReceives") { ipifstatshcinreceives = value; ipifstatshcinreceives.value_namespace = name_space; ipifstatshcinreceives.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInOctets") { ipifstatsinoctets = value; ipifstatsinoctets.value_namespace = name_space; ipifstatsinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInOctets") { ipifstatshcinoctets = value; ipifstatshcinoctets.value_namespace = name_space; ipifstatshcinoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInHdrErrors") { ipifstatsinhdrerrors = value; ipifstatsinhdrerrors.value_namespace = name_space; ipifstatsinhdrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInNoRoutes") { ipifstatsinnoroutes = value; ipifstatsinnoroutes.value_namespace = name_space; ipifstatsinnoroutes.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInAddrErrors") { ipifstatsinaddrerrors = value; ipifstatsinaddrerrors.value_namespace = name_space; ipifstatsinaddrerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInUnknownProtos") { ipifstatsinunknownprotos = value; ipifstatsinunknownprotos.value_namespace = name_space; ipifstatsinunknownprotos.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInTruncatedPkts") { ipifstatsintruncatedpkts = value; ipifstatsintruncatedpkts.value_namespace = name_space; ipifstatsintruncatedpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInForwDatagrams") { ipifstatsinforwdatagrams = value; ipifstatsinforwdatagrams.value_namespace = name_space; ipifstatsinforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInForwDatagrams") { ipifstatshcinforwdatagrams = value; ipifstatshcinforwdatagrams.value_namespace = name_space; ipifstatshcinforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsReasmReqds") { ipifstatsreasmreqds = value; ipifstatsreasmreqds.value_namespace = name_space; ipifstatsreasmreqds.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsReasmOKs") { ipifstatsreasmoks = value; ipifstatsreasmoks.value_namespace = name_space; ipifstatsreasmoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsReasmFails") { ipifstatsreasmfails = value; ipifstatsreasmfails.value_namespace = name_space; ipifstatsreasmfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInDiscards") { ipifstatsindiscards = value; ipifstatsindiscards.value_namespace = name_space; ipifstatsindiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInDelivers") { ipifstatsindelivers = value; ipifstatsindelivers.value_namespace = name_space; ipifstatsindelivers.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInDelivers") { ipifstatshcindelivers = value; ipifstatshcindelivers.value_namespace = name_space; ipifstatshcindelivers.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutRequests") { ipifstatsoutrequests = value; ipifstatsoutrequests.value_namespace = name_space; ipifstatsoutrequests.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutRequests") { ipifstatshcoutrequests = value; ipifstatshcoutrequests.value_namespace = name_space; ipifstatshcoutrequests.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutForwDatagrams") { ipifstatsoutforwdatagrams = value; ipifstatsoutforwdatagrams.value_namespace = name_space; ipifstatsoutforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutForwDatagrams") { ipifstatshcoutforwdatagrams = value; ipifstatshcoutforwdatagrams.value_namespace = name_space; ipifstatshcoutforwdatagrams.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutDiscards") { ipifstatsoutdiscards = value; ipifstatsoutdiscards.value_namespace = name_space; ipifstatsoutdiscards.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutFragReqds") { ipifstatsoutfragreqds = value; ipifstatsoutfragreqds.value_namespace = name_space; ipifstatsoutfragreqds.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutFragOKs") { ipifstatsoutfragoks = value; ipifstatsoutfragoks.value_namespace = name_space; ipifstatsoutfragoks.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutFragFails") { ipifstatsoutfragfails = value; ipifstatsoutfragfails.value_namespace = name_space; ipifstatsoutfragfails.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutFragCreates") { ipifstatsoutfragcreates = value; ipifstatsoutfragcreates.value_namespace = name_space; ipifstatsoutfragcreates.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutTransmits") { ipifstatsouttransmits = value; ipifstatsouttransmits.value_namespace = name_space; ipifstatsouttransmits.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutTransmits") { ipifstatshcouttransmits = value; ipifstatshcouttransmits.value_namespace = name_space; ipifstatshcouttransmits.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutOctets") { ipifstatsoutoctets = value; ipifstatsoutoctets.value_namespace = name_space; ipifstatsoutoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutOctets") { ipifstatshcoutoctets = value; ipifstatshcoutoctets.value_namespace = name_space; ipifstatshcoutoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInMcastPkts") { ipifstatsinmcastpkts = value; ipifstatsinmcastpkts.value_namespace = name_space; ipifstatsinmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInMcastPkts") { ipifstatshcinmcastpkts = value; ipifstatshcinmcastpkts.value_namespace = name_space; ipifstatshcinmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInMcastOctets") { ipifstatsinmcastoctets = value; ipifstatsinmcastoctets.value_namespace = name_space; ipifstatsinmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInMcastOctets") { ipifstatshcinmcastoctets = value; ipifstatshcinmcastoctets.value_namespace = name_space; ipifstatshcinmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutMcastPkts") { ipifstatsoutmcastpkts = value; ipifstatsoutmcastpkts.value_namespace = name_space; ipifstatsoutmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutMcastPkts") { ipifstatshcoutmcastpkts = value; ipifstatshcoutmcastpkts.value_namespace = name_space; ipifstatshcoutmcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutMcastOctets") { ipifstatsoutmcastoctets = value; ipifstatsoutmcastoctets.value_namespace = name_space; ipifstatsoutmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutMcastOctets") { ipifstatshcoutmcastoctets = value; ipifstatshcoutmcastoctets.value_namespace = name_space; ipifstatshcoutmcastoctets.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsInBcastPkts") { ipifstatsinbcastpkts = value; ipifstatsinbcastpkts.value_namespace = name_space; ipifstatsinbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCInBcastPkts") { ipifstatshcinbcastpkts = value; ipifstatshcinbcastpkts.value_namespace = name_space; ipifstatshcinbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsOutBcastPkts") { ipifstatsoutbcastpkts = value; ipifstatsoutbcastpkts.value_namespace = name_space; ipifstatsoutbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsHCOutBcastPkts") { ipifstatshcoutbcastpkts = value; ipifstatshcoutbcastpkts.value_namespace = name_space; ipifstatshcoutbcastpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsDiscontinuityTime") { ipifstatsdiscontinuitytime = value; ipifstatsdiscontinuitytime.value_namespace = name_space; ipifstatsdiscontinuitytime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipIfStatsRefreshRate") { ipifstatsrefreshrate = value; ipifstatsrefreshrate.value_namespace = name_space; ipifstatsrefreshrate.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpIfStatsTable::IpIfStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipIfStatsIPVersion") { ipifstatsipversion.yfilter = yfilter; } if(value_path == "ipIfStatsIfIndex") { ipifstatsifindex.yfilter = yfilter; } if(value_path == "ipIfStatsInReceives") { ipifstatsinreceives.yfilter = yfilter; } if(value_path == "ipIfStatsHCInReceives") { ipifstatshcinreceives.yfilter = yfilter; } if(value_path == "ipIfStatsInOctets") { ipifstatsinoctets.yfilter = yfilter; } if(value_path == "ipIfStatsHCInOctets") { ipifstatshcinoctets.yfilter = yfilter; } if(value_path == "ipIfStatsInHdrErrors") { ipifstatsinhdrerrors.yfilter = yfilter; } if(value_path == "ipIfStatsInNoRoutes") { ipifstatsinnoroutes.yfilter = yfilter; } if(value_path == "ipIfStatsInAddrErrors") { ipifstatsinaddrerrors.yfilter = yfilter; } if(value_path == "ipIfStatsInUnknownProtos") { ipifstatsinunknownprotos.yfilter = yfilter; } if(value_path == "ipIfStatsInTruncatedPkts") { ipifstatsintruncatedpkts.yfilter = yfilter; } if(value_path == "ipIfStatsInForwDatagrams") { ipifstatsinforwdatagrams.yfilter = yfilter; } if(value_path == "ipIfStatsHCInForwDatagrams") { ipifstatshcinforwdatagrams.yfilter = yfilter; } if(value_path == "ipIfStatsReasmReqds") { ipifstatsreasmreqds.yfilter = yfilter; } if(value_path == "ipIfStatsReasmOKs") { ipifstatsreasmoks.yfilter = yfilter; } if(value_path == "ipIfStatsReasmFails") { ipifstatsreasmfails.yfilter = yfilter; } if(value_path == "ipIfStatsInDiscards") { ipifstatsindiscards.yfilter = yfilter; } if(value_path == "ipIfStatsInDelivers") { ipifstatsindelivers.yfilter = yfilter; } if(value_path == "ipIfStatsHCInDelivers") { ipifstatshcindelivers.yfilter = yfilter; } if(value_path == "ipIfStatsOutRequests") { ipifstatsoutrequests.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutRequests") { ipifstatshcoutrequests.yfilter = yfilter; } if(value_path == "ipIfStatsOutForwDatagrams") { ipifstatsoutforwdatagrams.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutForwDatagrams") { ipifstatshcoutforwdatagrams.yfilter = yfilter; } if(value_path == "ipIfStatsOutDiscards") { ipifstatsoutdiscards.yfilter = yfilter; } if(value_path == "ipIfStatsOutFragReqds") { ipifstatsoutfragreqds.yfilter = yfilter; } if(value_path == "ipIfStatsOutFragOKs") { ipifstatsoutfragoks.yfilter = yfilter; } if(value_path == "ipIfStatsOutFragFails") { ipifstatsoutfragfails.yfilter = yfilter; } if(value_path == "ipIfStatsOutFragCreates") { ipifstatsoutfragcreates.yfilter = yfilter; } if(value_path == "ipIfStatsOutTransmits") { ipifstatsouttransmits.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutTransmits") { ipifstatshcouttransmits.yfilter = yfilter; } if(value_path == "ipIfStatsOutOctets") { ipifstatsoutoctets.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutOctets") { ipifstatshcoutoctets.yfilter = yfilter; } if(value_path == "ipIfStatsInMcastPkts") { ipifstatsinmcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsHCInMcastPkts") { ipifstatshcinmcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsInMcastOctets") { ipifstatsinmcastoctets.yfilter = yfilter; } if(value_path == "ipIfStatsHCInMcastOctets") { ipifstatshcinmcastoctets.yfilter = yfilter; } if(value_path == "ipIfStatsOutMcastPkts") { ipifstatsoutmcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutMcastPkts") { ipifstatshcoutmcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsOutMcastOctets") { ipifstatsoutmcastoctets.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutMcastOctets") { ipifstatshcoutmcastoctets.yfilter = yfilter; } if(value_path == "ipIfStatsInBcastPkts") { ipifstatsinbcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsHCInBcastPkts") { ipifstatshcinbcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsOutBcastPkts") { ipifstatsoutbcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsHCOutBcastPkts") { ipifstatshcoutbcastpkts.yfilter = yfilter; } if(value_path == "ipIfStatsDiscontinuityTime") { ipifstatsdiscontinuitytime.yfilter = yfilter; } if(value_path == "ipIfStatsRefreshRate") { ipifstatsrefreshrate.yfilter = yfilter; } } bool IPMIB::IpIfStatsTable::IpIfStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipIfStatsIPVersion" || name == "ipIfStatsIfIndex" || name == "ipIfStatsInReceives" || name == "ipIfStatsHCInReceives" || name == "ipIfStatsInOctets" || name == "ipIfStatsHCInOctets" || name == "ipIfStatsInHdrErrors" || name == "ipIfStatsInNoRoutes" || name == "ipIfStatsInAddrErrors" || name == "ipIfStatsInUnknownProtos" || name == "ipIfStatsInTruncatedPkts" || name == "ipIfStatsInForwDatagrams" || name == "ipIfStatsHCInForwDatagrams" || name == "ipIfStatsReasmReqds" || name == "ipIfStatsReasmOKs" || name == "ipIfStatsReasmFails" || name == "ipIfStatsInDiscards" || name == "ipIfStatsInDelivers" || name == "ipIfStatsHCInDelivers" || name == "ipIfStatsOutRequests" || name == "ipIfStatsHCOutRequests" || name == "ipIfStatsOutForwDatagrams" || name == "ipIfStatsHCOutForwDatagrams" || name == "ipIfStatsOutDiscards" || name == "ipIfStatsOutFragReqds" || name == "ipIfStatsOutFragOKs" || name == "ipIfStatsOutFragFails" || name == "ipIfStatsOutFragCreates" || name == "ipIfStatsOutTransmits" || name == "ipIfStatsHCOutTransmits" || name == "ipIfStatsOutOctets" || name == "ipIfStatsHCOutOctets" || name == "ipIfStatsInMcastPkts" || name == "ipIfStatsHCInMcastPkts" || name == "ipIfStatsInMcastOctets" || name == "ipIfStatsHCInMcastOctets" || name == "ipIfStatsOutMcastPkts" || name == "ipIfStatsHCOutMcastPkts" || name == "ipIfStatsOutMcastOctets" || name == "ipIfStatsHCOutMcastOctets" || name == "ipIfStatsInBcastPkts" || name == "ipIfStatsHCInBcastPkts" || name == "ipIfStatsOutBcastPkts" || name == "ipIfStatsHCOutBcastPkts" || name == "ipIfStatsDiscontinuityTime" || name == "ipIfStatsRefreshRate") return true; return false; } IPMIB::IpAddressPrefixTable::IpAddressPrefixTable() : ipaddressprefixentry(this, {"ipaddressprefixifindex", "ipaddressprefixtype", "ipaddressprefixprefix", "ipaddressprefixlength"}) { yang_name = "ipAddressPrefixTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddressPrefixTable::~IpAddressPrefixTable() { } bool IPMIB::IpAddressPrefixTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipaddressprefixentry.len(); index++) { if(ipaddressprefixentry[index]->has_data()) return true; } return false; } bool IPMIB::IpAddressPrefixTable::has_operation() const { for (std::size_t index=0; index<ipaddressprefixentry.len(); index++) { if(ipaddressprefixentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpAddressPrefixTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddressPrefixTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddressPrefixTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddressPrefixTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddressPrefixTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipAddressPrefixEntry") { auto ent_ = std::make_shared<IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry>(); ent_->parent = this; ipaddressprefixentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddressPrefixTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipaddressprefixentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpAddressPrefixTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpAddressPrefixTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpAddressPrefixTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAddressPrefixEntry") return true; return false; } IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::IpAddressPrefixEntry() : ipaddressprefixifindex{YType::int32, "ipAddressPrefixIfIndex"}, ipaddressprefixtype{YType::enumeration, "ipAddressPrefixType"}, ipaddressprefixprefix{YType::str, "ipAddressPrefixPrefix"}, ipaddressprefixlength{YType::uint32, "ipAddressPrefixLength"}, ipaddressprefixorigin{YType::enumeration, "ipAddressPrefixOrigin"}, ipaddressprefixonlinkflag{YType::boolean, "ipAddressPrefixOnLinkFlag"}, ipaddressprefixautonomousflag{YType::boolean, "ipAddressPrefixAutonomousFlag"}, ipaddressprefixadvpreferredlifetime{YType::uint32, "ipAddressPrefixAdvPreferredLifetime"}, ipaddressprefixadvvalidlifetime{YType::uint32, "ipAddressPrefixAdvValidLifetime"} { yang_name = "ipAddressPrefixEntry"; yang_parent_name = "ipAddressPrefixTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::~IpAddressPrefixEntry() { } bool IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::has_data() const { if (is_presence_container) return true; return ipaddressprefixifindex.is_set || ipaddressprefixtype.is_set || ipaddressprefixprefix.is_set || ipaddressprefixlength.is_set || ipaddressprefixorigin.is_set || ipaddressprefixonlinkflag.is_set || ipaddressprefixautonomousflag.is_set || ipaddressprefixadvpreferredlifetime.is_set || ipaddressprefixadvvalidlifetime.is_set; } bool IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipaddressprefixifindex.yfilter) || ydk::is_set(ipaddressprefixtype.yfilter) || ydk::is_set(ipaddressprefixprefix.yfilter) || ydk::is_set(ipaddressprefixlength.yfilter) || ydk::is_set(ipaddressprefixorigin.yfilter) || ydk::is_set(ipaddressprefixonlinkflag.yfilter) || ydk::is_set(ipaddressprefixautonomousflag.yfilter) || ydk::is_set(ipaddressprefixadvpreferredlifetime.yfilter) || ydk::is_set(ipaddressprefixadvvalidlifetime.yfilter); } std::string IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipAddressPrefixTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddressPrefixEntry"; ADD_KEY_TOKEN(ipaddressprefixifindex, "ipAddressPrefixIfIndex"); ADD_KEY_TOKEN(ipaddressprefixtype, "ipAddressPrefixType"); ADD_KEY_TOKEN(ipaddressprefixprefix, "ipAddressPrefixPrefix"); ADD_KEY_TOKEN(ipaddressprefixlength, "ipAddressPrefixLength"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipaddressprefixifindex.is_set || is_set(ipaddressprefixifindex.yfilter)) leaf_name_data.push_back(ipaddressprefixifindex.get_name_leafdata()); if (ipaddressprefixtype.is_set || is_set(ipaddressprefixtype.yfilter)) leaf_name_data.push_back(ipaddressprefixtype.get_name_leafdata()); if (ipaddressprefixprefix.is_set || is_set(ipaddressprefixprefix.yfilter)) leaf_name_data.push_back(ipaddressprefixprefix.get_name_leafdata()); if (ipaddressprefixlength.is_set || is_set(ipaddressprefixlength.yfilter)) leaf_name_data.push_back(ipaddressprefixlength.get_name_leafdata()); if (ipaddressprefixorigin.is_set || is_set(ipaddressprefixorigin.yfilter)) leaf_name_data.push_back(ipaddressprefixorigin.get_name_leafdata()); if (ipaddressprefixonlinkflag.is_set || is_set(ipaddressprefixonlinkflag.yfilter)) leaf_name_data.push_back(ipaddressprefixonlinkflag.get_name_leafdata()); if (ipaddressprefixautonomousflag.is_set || is_set(ipaddressprefixautonomousflag.yfilter)) leaf_name_data.push_back(ipaddressprefixautonomousflag.get_name_leafdata()); if (ipaddressprefixadvpreferredlifetime.is_set || is_set(ipaddressprefixadvpreferredlifetime.yfilter)) leaf_name_data.push_back(ipaddressprefixadvpreferredlifetime.get_name_leafdata()); if (ipaddressprefixadvvalidlifetime.is_set || is_set(ipaddressprefixadvvalidlifetime.yfilter)) leaf_name_data.push_back(ipaddressprefixadvvalidlifetime.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipAddressPrefixIfIndex") { ipaddressprefixifindex = value; ipaddressprefixifindex.value_namespace = name_space; ipaddressprefixifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixType") { ipaddressprefixtype = value; ipaddressprefixtype.value_namespace = name_space; ipaddressprefixtype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixPrefix") { ipaddressprefixprefix = value; ipaddressprefixprefix.value_namespace = name_space; ipaddressprefixprefix.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixLength") { ipaddressprefixlength = value; ipaddressprefixlength.value_namespace = name_space; ipaddressprefixlength.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixOrigin") { ipaddressprefixorigin = value; ipaddressprefixorigin.value_namespace = name_space; ipaddressprefixorigin.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixOnLinkFlag") { ipaddressprefixonlinkflag = value; ipaddressprefixonlinkflag.value_namespace = name_space; ipaddressprefixonlinkflag.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixAutonomousFlag") { ipaddressprefixautonomousflag = value; ipaddressprefixautonomousflag.value_namespace = name_space; ipaddressprefixautonomousflag.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixAdvPreferredLifetime") { ipaddressprefixadvpreferredlifetime = value; ipaddressprefixadvpreferredlifetime.value_namespace = name_space; ipaddressprefixadvpreferredlifetime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefixAdvValidLifetime") { ipaddressprefixadvvalidlifetime = value; ipaddressprefixadvvalidlifetime.value_namespace = name_space; ipaddressprefixadvvalidlifetime.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipAddressPrefixIfIndex") { ipaddressprefixifindex.yfilter = yfilter; } if(value_path == "ipAddressPrefixType") { ipaddressprefixtype.yfilter = yfilter; } if(value_path == "ipAddressPrefixPrefix") { ipaddressprefixprefix.yfilter = yfilter; } if(value_path == "ipAddressPrefixLength") { ipaddressprefixlength.yfilter = yfilter; } if(value_path == "ipAddressPrefixOrigin") { ipaddressprefixorigin.yfilter = yfilter; } if(value_path == "ipAddressPrefixOnLinkFlag") { ipaddressprefixonlinkflag.yfilter = yfilter; } if(value_path == "ipAddressPrefixAutonomousFlag") { ipaddressprefixautonomousflag.yfilter = yfilter; } if(value_path == "ipAddressPrefixAdvPreferredLifetime") { ipaddressprefixadvpreferredlifetime.yfilter = yfilter; } if(value_path == "ipAddressPrefixAdvValidLifetime") { ipaddressprefixadvvalidlifetime.yfilter = yfilter; } } bool IPMIB::IpAddressPrefixTable::IpAddressPrefixEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAddressPrefixIfIndex" || name == "ipAddressPrefixType" || name == "ipAddressPrefixPrefix" || name == "ipAddressPrefixLength" || name == "ipAddressPrefixOrigin" || name == "ipAddressPrefixOnLinkFlag" || name == "ipAddressPrefixAutonomousFlag" || name == "ipAddressPrefixAdvPreferredLifetime" || name == "ipAddressPrefixAdvValidLifetime") return true; return false; } IPMIB::IpAddressTable::IpAddressTable() : ipaddressentry(this, {"ipaddressaddrtype", "ipaddressaddr"}) { yang_name = "ipAddressTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddressTable::~IpAddressTable() { } bool IPMIB::IpAddressTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipaddressentry.len(); index++) { if(ipaddressentry[index]->has_data()) return true; } return false; } bool IPMIB::IpAddressTable::has_operation() const { for (std::size_t index=0; index<ipaddressentry.len(); index++) { if(ipaddressentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpAddressTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddressTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddressTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddressTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddressTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipAddressEntry") { auto ent_ = std::make_shared<IPMIB::IpAddressTable::IpAddressEntry>(); ent_->parent = this; ipaddressentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddressTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipaddressentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpAddressTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpAddressTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpAddressTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAddressEntry") return true; return false; } IPMIB::IpAddressTable::IpAddressEntry::IpAddressEntry() : ipaddressaddrtype{YType::enumeration, "ipAddressAddrType"}, ipaddressaddr{YType::str, "ipAddressAddr"}, ipaddressifindex{YType::int32, "ipAddressIfIndex"}, ipaddresstype{YType::enumeration, "ipAddressType"}, ipaddressprefix{YType::str, "ipAddressPrefix"}, ipaddressorigin{YType::enumeration, "ipAddressOrigin"}, ipaddressstatus{YType::enumeration, "ipAddressStatus"}, ipaddresscreated{YType::uint32, "ipAddressCreated"}, ipaddresslastchanged{YType::uint32, "ipAddressLastChanged"}, ipaddressrowstatus{YType::enumeration, "ipAddressRowStatus"}, ipaddressstoragetype{YType::enumeration, "ipAddressStorageType"} { yang_name = "ipAddressEntry"; yang_parent_name = "ipAddressTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpAddressTable::IpAddressEntry::~IpAddressEntry() { } bool IPMIB::IpAddressTable::IpAddressEntry::has_data() const { if (is_presence_container) return true; return ipaddressaddrtype.is_set || ipaddressaddr.is_set || ipaddressifindex.is_set || ipaddresstype.is_set || ipaddressprefix.is_set || ipaddressorigin.is_set || ipaddressstatus.is_set || ipaddresscreated.is_set || ipaddresslastchanged.is_set || ipaddressrowstatus.is_set || ipaddressstoragetype.is_set; } bool IPMIB::IpAddressTable::IpAddressEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipaddressaddrtype.yfilter) || ydk::is_set(ipaddressaddr.yfilter) || ydk::is_set(ipaddressifindex.yfilter) || ydk::is_set(ipaddresstype.yfilter) || ydk::is_set(ipaddressprefix.yfilter) || ydk::is_set(ipaddressorigin.yfilter) || ydk::is_set(ipaddressstatus.yfilter) || ydk::is_set(ipaddresscreated.yfilter) || ydk::is_set(ipaddresslastchanged.yfilter) || ydk::is_set(ipaddressrowstatus.yfilter) || ydk::is_set(ipaddressstoragetype.yfilter); } std::string IPMIB::IpAddressTable::IpAddressEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipAddressTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpAddressTable::IpAddressEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipAddressEntry"; ADD_KEY_TOKEN(ipaddressaddrtype, "ipAddressAddrType"); ADD_KEY_TOKEN(ipaddressaddr, "ipAddressAddr"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpAddressTable::IpAddressEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipaddressaddrtype.is_set || is_set(ipaddressaddrtype.yfilter)) leaf_name_data.push_back(ipaddressaddrtype.get_name_leafdata()); if (ipaddressaddr.is_set || is_set(ipaddressaddr.yfilter)) leaf_name_data.push_back(ipaddressaddr.get_name_leafdata()); if (ipaddressifindex.is_set || is_set(ipaddressifindex.yfilter)) leaf_name_data.push_back(ipaddressifindex.get_name_leafdata()); if (ipaddresstype.is_set || is_set(ipaddresstype.yfilter)) leaf_name_data.push_back(ipaddresstype.get_name_leafdata()); if (ipaddressprefix.is_set || is_set(ipaddressprefix.yfilter)) leaf_name_data.push_back(ipaddressprefix.get_name_leafdata()); if (ipaddressorigin.is_set || is_set(ipaddressorigin.yfilter)) leaf_name_data.push_back(ipaddressorigin.get_name_leafdata()); if (ipaddressstatus.is_set || is_set(ipaddressstatus.yfilter)) leaf_name_data.push_back(ipaddressstatus.get_name_leafdata()); if (ipaddresscreated.is_set || is_set(ipaddresscreated.yfilter)) leaf_name_data.push_back(ipaddresscreated.get_name_leafdata()); if (ipaddresslastchanged.is_set || is_set(ipaddresslastchanged.yfilter)) leaf_name_data.push_back(ipaddresslastchanged.get_name_leafdata()); if (ipaddressrowstatus.is_set || is_set(ipaddressrowstatus.yfilter)) leaf_name_data.push_back(ipaddressrowstatus.get_name_leafdata()); if (ipaddressstoragetype.is_set || is_set(ipaddressstoragetype.yfilter)) leaf_name_data.push_back(ipaddressstoragetype.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpAddressTable::IpAddressEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpAddressTable::IpAddressEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpAddressTable::IpAddressEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipAddressAddrType") { ipaddressaddrtype = value; ipaddressaddrtype.value_namespace = name_space; ipaddressaddrtype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressAddr") { ipaddressaddr = value; ipaddressaddr.value_namespace = name_space; ipaddressaddr.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressIfIndex") { ipaddressifindex = value; ipaddressifindex.value_namespace = name_space; ipaddressifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressType") { ipaddresstype = value; ipaddresstype.value_namespace = name_space; ipaddresstype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressPrefix") { ipaddressprefix = value; ipaddressprefix.value_namespace = name_space; ipaddressprefix.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressOrigin") { ipaddressorigin = value; ipaddressorigin.value_namespace = name_space; ipaddressorigin.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressStatus") { ipaddressstatus = value; ipaddressstatus.value_namespace = name_space; ipaddressstatus.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressCreated") { ipaddresscreated = value; ipaddresscreated.value_namespace = name_space; ipaddresscreated.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressLastChanged") { ipaddresslastchanged = value; ipaddresslastchanged.value_namespace = name_space; ipaddresslastchanged.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressRowStatus") { ipaddressrowstatus = value; ipaddressrowstatus.value_namespace = name_space; ipaddressrowstatus.value_namespace_prefix = name_space_prefix; } if(value_path == "ipAddressStorageType") { ipaddressstoragetype = value; ipaddressstoragetype.value_namespace = name_space; ipaddressstoragetype.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpAddressTable::IpAddressEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipAddressAddrType") { ipaddressaddrtype.yfilter = yfilter; } if(value_path == "ipAddressAddr") { ipaddressaddr.yfilter = yfilter; } if(value_path == "ipAddressIfIndex") { ipaddressifindex.yfilter = yfilter; } if(value_path == "ipAddressType") { ipaddresstype.yfilter = yfilter; } if(value_path == "ipAddressPrefix") { ipaddressprefix.yfilter = yfilter; } if(value_path == "ipAddressOrigin") { ipaddressorigin.yfilter = yfilter; } if(value_path == "ipAddressStatus") { ipaddressstatus.yfilter = yfilter; } if(value_path == "ipAddressCreated") { ipaddresscreated.yfilter = yfilter; } if(value_path == "ipAddressLastChanged") { ipaddresslastchanged.yfilter = yfilter; } if(value_path == "ipAddressRowStatus") { ipaddressrowstatus.yfilter = yfilter; } if(value_path == "ipAddressStorageType") { ipaddressstoragetype.yfilter = yfilter; } } bool IPMIB::IpAddressTable::IpAddressEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipAddressAddrType" || name == "ipAddressAddr" || name == "ipAddressIfIndex" || name == "ipAddressType" || name == "ipAddressPrefix" || name == "ipAddressOrigin" || name == "ipAddressStatus" || name == "ipAddressCreated" || name == "ipAddressLastChanged" || name == "ipAddressRowStatus" || name == "ipAddressStorageType") return true; return false; } IPMIB::IpNetToPhysicalTable::IpNetToPhysicalTable() : ipnettophysicalentry(this, {"ipnettophysicalifindex", "ipnettophysicalnetaddresstype", "ipnettophysicalnetaddress"}) { yang_name = "ipNetToPhysicalTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpNetToPhysicalTable::~IpNetToPhysicalTable() { } bool IPMIB::IpNetToPhysicalTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipnettophysicalentry.len(); index++) { if(ipnettophysicalentry[index]->has_data()) return true; } return false; } bool IPMIB::IpNetToPhysicalTable::has_operation() const { for (std::size_t index=0; index<ipnettophysicalentry.len(); index++) { if(ipnettophysicalentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpNetToPhysicalTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpNetToPhysicalTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipNetToPhysicalTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpNetToPhysicalTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpNetToPhysicalTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipNetToPhysicalEntry") { auto ent_ = std::make_shared<IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry>(); ent_->parent = this; ipnettophysicalentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpNetToPhysicalTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipnettophysicalentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpNetToPhysicalTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpNetToPhysicalTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpNetToPhysicalTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipNetToPhysicalEntry") return true; return false; } IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalEntry() : ipnettophysicalifindex{YType::int32, "ipNetToPhysicalIfIndex"}, ipnettophysicalnetaddresstype{YType::enumeration, "ipNetToPhysicalNetAddressType"}, ipnettophysicalnetaddress{YType::str, "ipNetToPhysicalNetAddress"}, ipnettophysicalphysaddress{YType::str, "ipNetToPhysicalPhysAddress"}, ipnettophysicallastupdated{YType::uint32, "ipNetToPhysicalLastUpdated"}, ipnettophysicaltype{YType::enumeration, "ipNetToPhysicalType"}, ipnettophysicalstate{YType::enumeration, "ipNetToPhysicalState"}, ipnettophysicalrowstatus{YType::enumeration, "ipNetToPhysicalRowStatus"} { yang_name = "ipNetToPhysicalEntry"; yang_parent_name = "ipNetToPhysicalTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::~IpNetToPhysicalEntry() { } bool IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::has_data() const { if (is_presence_container) return true; return ipnettophysicalifindex.is_set || ipnettophysicalnetaddresstype.is_set || ipnettophysicalnetaddress.is_set || ipnettophysicalphysaddress.is_set || ipnettophysicallastupdated.is_set || ipnettophysicaltype.is_set || ipnettophysicalstate.is_set || ipnettophysicalrowstatus.is_set; } bool IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipnettophysicalifindex.yfilter) || ydk::is_set(ipnettophysicalnetaddresstype.yfilter) || ydk::is_set(ipnettophysicalnetaddress.yfilter) || ydk::is_set(ipnettophysicalphysaddress.yfilter) || ydk::is_set(ipnettophysicallastupdated.yfilter) || ydk::is_set(ipnettophysicaltype.yfilter) || ydk::is_set(ipnettophysicalstate.yfilter) || ydk::is_set(ipnettophysicalrowstatus.yfilter); } std::string IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipNetToPhysicalTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipNetToPhysicalEntry"; ADD_KEY_TOKEN(ipnettophysicalifindex, "ipNetToPhysicalIfIndex"); ADD_KEY_TOKEN(ipnettophysicalnetaddresstype, "ipNetToPhysicalNetAddressType"); ADD_KEY_TOKEN(ipnettophysicalnetaddress, "ipNetToPhysicalNetAddress"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipnettophysicalifindex.is_set || is_set(ipnettophysicalifindex.yfilter)) leaf_name_data.push_back(ipnettophysicalifindex.get_name_leafdata()); if (ipnettophysicalnetaddresstype.is_set || is_set(ipnettophysicalnetaddresstype.yfilter)) leaf_name_data.push_back(ipnettophysicalnetaddresstype.get_name_leafdata()); if (ipnettophysicalnetaddress.is_set || is_set(ipnettophysicalnetaddress.yfilter)) leaf_name_data.push_back(ipnettophysicalnetaddress.get_name_leafdata()); if (ipnettophysicalphysaddress.is_set || is_set(ipnettophysicalphysaddress.yfilter)) leaf_name_data.push_back(ipnettophysicalphysaddress.get_name_leafdata()); if (ipnettophysicallastupdated.is_set || is_set(ipnettophysicallastupdated.yfilter)) leaf_name_data.push_back(ipnettophysicallastupdated.get_name_leafdata()); if (ipnettophysicaltype.is_set || is_set(ipnettophysicaltype.yfilter)) leaf_name_data.push_back(ipnettophysicaltype.get_name_leafdata()); if (ipnettophysicalstate.is_set || is_set(ipnettophysicalstate.yfilter)) leaf_name_data.push_back(ipnettophysicalstate.get_name_leafdata()); if (ipnettophysicalrowstatus.is_set || is_set(ipnettophysicalrowstatus.yfilter)) leaf_name_data.push_back(ipnettophysicalrowstatus.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipNetToPhysicalIfIndex") { ipnettophysicalifindex = value; ipnettophysicalifindex.value_namespace = name_space; ipnettophysicalifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalNetAddressType") { ipnettophysicalnetaddresstype = value; ipnettophysicalnetaddresstype.value_namespace = name_space; ipnettophysicalnetaddresstype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalNetAddress") { ipnettophysicalnetaddress = value; ipnettophysicalnetaddress.value_namespace = name_space; ipnettophysicalnetaddress.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalPhysAddress") { ipnettophysicalphysaddress = value; ipnettophysicalphysaddress.value_namespace = name_space; ipnettophysicalphysaddress.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalLastUpdated") { ipnettophysicallastupdated = value; ipnettophysicallastupdated.value_namespace = name_space; ipnettophysicallastupdated.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalType") { ipnettophysicaltype = value; ipnettophysicaltype.value_namespace = name_space; ipnettophysicaltype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalState") { ipnettophysicalstate = value; ipnettophysicalstate.value_namespace = name_space; ipnettophysicalstate.value_namespace_prefix = name_space_prefix; } if(value_path == "ipNetToPhysicalRowStatus") { ipnettophysicalrowstatus = value; ipnettophysicalrowstatus.value_namespace = name_space; ipnettophysicalrowstatus.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipNetToPhysicalIfIndex") { ipnettophysicalifindex.yfilter = yfilter; } if(value_path == "ipNetToPhysicalNetAddressType") { ipnettophysicalnetaddresstype.yfilter = yfilter; } if(value_path == "ipNetToPhysicalNetAddress") { ipnettophysicalnetaddress.yfilter = yfilter; } if(value_path == "ipNetToPhysicalPhysAddress") { ipnettophysicalphysaddress.yfilter = yfilter; } if(value_path == "ipNetToPhysicalLastUpdated") { ipnettophysicallastupdated.yfilter = yfilter; } if(value_path == "ipNetToPhysicalType") { ipnettophysicaltype.yfilter = yfilter; } if(value_path == "ipNetToPhysicalState") { ipnettophysicalstate.yfilter = yfilter; } if(value_path == "ipNetToPhysicalRowStatus") { ipnettophysicalrowstatus.yfilter = yfilter; } } bool IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipNetToPhysicalIfIndex" || name == "ipNetToPhysicalNetAddressType" || name == "ipNetToPhysicalNetAddress" || name == "ipNetToPhysicalPhysAddress" || name == "ipNetToPhysicalLastUpdated" || name == "ipNetToPhysicalType" || name == "ipNetToPhysicalState" || name == "ipNetToPhysicalRowStatus") return true; return false; } IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexTable() : ipv6scopezoneindexentry(this, {"ipv6scopezoneindexifindex"}) { yang_name = "ipv6ScopeZoneIndexTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6ScopeZoneIndexTable::~Ipv6ScopeZoneIndexTable() { } bool IPMIB::Ipv6ScopeZoneIndexTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv6scopezoneindexentry.len(); index++) { if(ipv6scopezoneindexentry[index]->has_data()) return true; } return false; } bool IPMIB::Ipv6ScopeZoneIndexTable::has_operation() const { for (std::size_t index=0; index<ipv6scopezoneindexentry.len(); index++) { if(ipv6scopezoneindexentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::Ipv6ScopeZoneIndexTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6ScopeZoneIndexTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6ScopeZoneIndexTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6ScopeZoneIndexTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6ScopeZoneIndexTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv6ScopeZoneIndexEntry") { auto ent_ = std::make_shared<IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry>(); ent_->parent = this; ipv6scopezoneindexentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6ScopeZoneIndexTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv6scopezoneindexentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::Ipv6ScopeZoneIndexTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::Ipv6ScopeZoneIndexTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::Ipv6ScopeZoneIndexTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6ScopeZoneIndexEntry") return true; return false; } IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::Ipv6ScopeZoneIndexEntry() : ipv6scopezoneindexifindex{YType::int32, "ipv6ScopeZoneIndexIfIndex"}, ipv6scopezoneindexlinklocal{YType::uint32, "ipv6ScopeZoneIndexLinkLocal"}, ipv6scopezoneindex3{YType::uint32, "ipv6ScopeZoneIndex3"}, ipv6scopezoneindexadminlocal{YType::uint32, "ipv6ScopeZoneIndexAdminLocal"}, ipv6scopezoneindexsitelocal{YType::uint32, "ipv6ScopeZoneIndexSiteLocal"}, ipv6scopezoneindex6{YType::uint32, "ipv6ScopeZoneIndex6"}, ipv6scopezoneindex7{YType::uint32, "ipv6ScopeZoneIndex7"}, ipv6scopezoneindexorganizationlocal{YType::uint32, "ipv6ScopeZoneIndexOrganizationLocal"}, ipv6scopezoneindex9{YType::uint32, "ipv6ScopeZoneIndex9"}, ipv6scopezoneindexa{YType::uint32, "ipv6ScopeZoneIndexA"}, ipv6scopezoneindexb{YType::uint32, "ipv6ScopeZoneIndexB"}, ipv6scopezoneindexc{YType::uint32, "ipv6ScopeZoneIndexC"}, ipv6scopezoneindexd{YType::uint32, "ipv6ScopeZoneIndexD"} { yang_name = "ipv6ScopeZoneIndexEntry"; yang_parent_name = "ipv6ScopeZoneIndexTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::~Ipv6ScopeZoneIndexEntry() { } bool IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::has_data() const { if (is_presence_container) return true; return ipv6scopezoneindexifindex.is_set || ipv6scopezoneindexlinklocal.is_set || ipv6scopezoneindex3.is_set || ipv6scopezoneindexadminlocal.is_set || ipv6scopezoneindexsitelocal.is_set || ipv6scopezoneindex6.is_set || ipv6scopezoneindex7.is_set || ipv6scopezoneindexorganizationlocal.is_set || ipv6scopezoneindex9.is_set || ipv6scopezoneindexa.is_set || ipv6scopezoneindexb.is_set || ipv6scopezoneindexc.is_set || ipv6scopezoneindexd.is_set; } bool IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipv6scopezoneindexifindex.yfilter) || ydk::is_set(ipv6scopezoneindexlinklocal.yfilter) || ydk::is_set(ipv6scopezoneindex3.yfilter) || ydk::is_set(ipv6scopezoneindexadminlocal.yfilter) || ydk::is_set(ipv6scopezoneindexsitelocal.yfilter) || ydk::is_set(ipv6scopezoneindex6.yfilter) || ydk::is_set(ipv6scopezoneindex7.yfilter) || ydk::is_set(ipv6scopezoneindexorganizationlocal.yfilter) || ydk::is_set(ipv6scopezoneindex9.yfilter) || ydk::is_set(ipv6scopezoneindexa.yfilter) || ydk::is_set(ipv6scopezoneindexb.yfilter) || ydk::is_set(ipv6scopezoneindexc.yfilter) || ydk::is_set(ipv6scopezoneindexd.yfilter); } std::string IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipv6ScopeZoneIndexTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6ScopeZoneIndexEntry"; ADD_KEY_TOKEN(ipv6scopezoneindexifindex, "ipv6ScopeZoneIndexIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipv6scopezoneindexifindex.is_set || is_set(ipv6scopezoneindexifindex.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexifindex.get_name_leafdata()); if (ipv6scopezoneindexlinklocal.is_set || is_set(ipv6scopezoneindexlinklocal.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexlinklocal.get_name_leafdata()); if (ipv6scopezoneindex3.is_set || is_set(ipv6scopezoneindex3.yfilter)) leaf_name_data.push_back(ipv6scopezoneindex3.get_name_leafdata()); if (ipv6scopezoneindexadminlocal.is_set || is_set(ipv6scopezoneindexadminlocal.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexadminlocal.get_name_leafdata()); if (ipv6scopezoneindexsitelocal.is_set || is_set(ipv6scopezoneindexsitelocal.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexsitelocal.get_name_leafdata()); if (ipv6scopezoneindex6.is_set || is_set(ipv6scopezoneindex6.yfilter)) leaf_name_data.push_back(ipv6scopezoneindex6.get_name_leafdata()); if (ipv6scopezoneindex7.is_set || is_set(ipv6scopezoneindex7.yfilter)) leaf_name_data.push_back(ipv6scopezoneindex7.get_name_leafdata()); if (ipv6scopezoneindexorganizationlocal.is_set || is_set(ipv6scopezoneindexorganizationlocal.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexorganizationlocal.get_name_leafdata()); if (ipv6scopezoneindex9.is_set || is_set(ipv6scopezoneindex9.yfilter)) leaf_name_data.push_back(ipv6scopezoneindex9.get_name_leafdata()); if (ipv6scopezoneindexa.is_set || is_set(ipv6scopezoneindexa.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexa.get_name_leafdata()); if (ipv6scopezoneindexb.is_set || is_set(ipv6scopezoneindexb.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexb.get_name_leafdata()); if (ipv6scopezoneindexc.is_set || is_set(ipv6scopezoneindexc.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexc.get_name_leafdata()); if (ipv6scopezoneindexd.is_set || is_set(ipv6scopezoneindexd.yfilter)) leaf_name_data.push_back(ipv6scopezoneindexd.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipv6ScopeZoneIndexIfIndex") { ipv6scopezoneindexifindex = value; ipv6scopezoneindexifindex.value_namespace = name_space; ipv6scopezoneindexifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexLinkLocal") { ipv6scopezoneindexlinklocal = value; ipv6scopezoneindexlinklocal.value_namespace = name_space; ipv6scopezoneindexlinklocal.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndex3") { ipv6scopezoneindex3 = value; ipv6scopezoneindex3.value_namespace = name_space; ipv6scopezoneindex3.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexAdminLocal") { ipv6scopezoneindexadminlocal = value; ipv6scopezoneindexadminlocal.value_namespace = name_space; ipv6scopezoneindexadminlocal.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexSiteLocal") { ipv6scopezoneindexsitelocal = value; ipv6scopezoneindexsitelocal.value_namespace = name_space; ipv6scopezoneindexsitelocal.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndex6") { ipv6scopezoneindex6 = value; ipv6scopezoneindex6.value_namespace = name_space; ipv6scopezoneindex6.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndex7") { ipv6scopezoneindex7 = value; ipv6scopezoneindex7.value_namespace = name_space; ipv6scopezoneindex7.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexOrganizationLocal") { ipv6scopezoneindexorganizationlocal = value; ipv6scopezoneindexorganizationlocal.value_namespace = name_space; ipv6scopezoneindexorganizationlocal.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndex9") { ipv6scopezoneindex9 = value; ipv6scopezoneindex9.value_namespace = name_space; ipv6scopezoneindex9.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexA") { ipv6scopezoneindexa = value; ipv6scopezoneindexa.value_namespace = name_space; ipv6scopezoneindexa.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexB") { ipv6scopezoneindexb = value; ipv6scopezoneindexb.value_namespace = name_space; ipv6scopezoneindexb.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexC") { ipv6scopezoneindexc = value; ipv6scopezoneindexc.value_namespace = name_space; ipv6scopezoneindexc.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6ScopeZoneIndexD") { ipv6scopezoneindexd = value; ipv6scopezoneindexd.value_namespace = name_space; ipv6scopezoneindexd.value_namespace_prefix = name_space_prefix; } } void IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipv6ScopeZoneIndexIfIndex") { ipv6scopezoneindexifindex.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexLinkLocal") { ipv6scopezoneindexlinklocal.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndex3") { ipv6scopezoneindex3.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexAdminLocal") { ipv6scopezoneindexadminlocal.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexSiteLocal") { ipv6scopezoneindexsitelocal.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndex6") { ipv6scopezoneindex6.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndex7") { ipv6scopezoneindex7.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexOrganizationLocal") { ipv6scopezoneindexorganizationlocal.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndex9") { ipv6scopezoneindex9.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexA") { ipv6scopezoneindexa.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexB") { ipv6scopezoneindexb.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexC") { ipv6scopezoneindexc.yfilter = yfilter; } if(value_path == "ipv6ScopeZoneIndexD") { ipv6scopezoneindexd.yfilter = yfilter; } } bool IPMIB::Ipv6ScopeZoneIndexTable::Ipv6ScopeZoneIndexEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6ScopeZoneIndexIfIndex" || name == "ipv6ScopeZoneIndexLinkLocal" || name == "ipv6ScopeZoneIndex3" || name == "ipv6ScopeZoneIndexAdminLocal" || name == "ipv6ScopeZoneIndexSiteLocal" || name == "ipv6ScopeZoneIndex6" || name == "ipv6ScopeZoneIndex7" || name == "ipv6ScopeZoneIndexOrganizationLocal" || name == "ipv6ScopeZoneIndex9" || name == "ipv6ScopeZoneIndexA" || name == "ipv6ScopeZoneIndexB" || name == "ipv6ScopeZoneIndexC" || name == "ipv6ScopeZoneIndexD") return true; return false; } IPMIB::IpDefaultRouterTable::IpDefaultRouterTable() : ipdefaultrouterentry(this, {"ipdefaultrouteraddresstype", "ipdefaultrouteraddress", "ipdefaultrouterifindex"}) { yang_name = "ipDefaultRouterTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpDefaultRouterTable::~IpDefaultRouterTable() { } bool IPMIB::IpDefaultRouterTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipdefaultrouterentry.len(); index++) { if(ipdefaultrouterentry[index]->has_data()) return true; } return false; } bool IPMIB::IpDefaultRouterTable::has_operation() const { for (std::size_t index=0; index<ipdefaultrouterentry.len(); index++) { if(ipdefaultrouterentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IpDefaultRouterTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpDefaultRouterTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipDefaultRouterTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpDefaultRouterTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpDefaultRouterTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipDefaultRouterEntry") { auto ent_ = std::make_shared<IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry>(); ent_->parent = this; ipdefaultrouterentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpDefaultRouterTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipdefaultrouterentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IpDefaultRouterTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IpDefaultRouterTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IpDefaultRouterTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipDefaultRouterEntry") return true; return false; } IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::IpDefaultRouterEntry() : ipdefaultrouteraddresstype{YType::enumeration, "ipDefaultRouterAddressType"}, ipdefaultrouteraddress{YType::str, "ipDefaultRouterAddress"}, ipdefaultrouterifindex{YType::int32, "ipDefaultRouterIfIndex"}, ipdefaultrouterlifetime{YType::uint32, "ipDefaultRouterLifetime"}, ipdefaultrouterpreference{YType::enumeration, "ipDefaultRouterPreference"} { yang_name = "ipDefaultRouterEntry"; yang_parent_name = "ipDefaultRouterTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::~IpDefaultRouterEntry() { } bool IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::has_data() const { if (is_presence_container) return true; return ipdefaultrouteraddresstype.is_set || ipdefaultrouteraddress.is_set || ipdefaultrouterifindex.is_set || ipdefaultrouterlifetime.is_set || ipdefaultrouterpreference.is_set; } bool IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipdefaultrouteraddresstype.yfilter) || ydk::is_set(ipdefaultrouteraddress.yfilter) || ydk::is_set(ipdefaultrouterifindex.yfilter) || ydk::is_set(ipdefaultrouterlifetime.yfilter) || ydk::is_set(ipdefaultrouterpreference.yfilter); } std::string IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipDefaultRouterTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipDefaultRouterEntry"; ADD_KEY_TOKEN(ipdefaultrouteraddresstype, "ipDefaultRouterAddressType"); ADD_KEY_TOKEN(ipdefaultrouteraddress, "ipDefaultRouterAddress"); ADD_KEY_TOKEN(ipdefaultrouterifindex, "ipDefaultRouterIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipdefaultrouteraddresstype.is_set || is_set(ipdefaultrouteraddresstype.yfilter)) leaf_name_data.push_back(ipdefaultrouteraddresstype.get_name_leafdata()); if (ipdefaultrouteraddress.is_set || is_set(ipdefaultrouteraddress.yfilter)) leaf_name_data.push_back(ipdefaultrouteraddress.get_name_leafdata()); if (ipdefaultrouterifindex.is_set || is_set(ipdefaultrouterifindex.yfilter)) leaf_name_data.push_back(ipdefaultrouterifindex.get_name_leafdata()); if (ipdefaultrouterlifetime.is_set || is_set(ipdefaultrouterlifetime.yfilter)) leaf_name_data.push_back(ipdefaultrouterlifetime.get_name_leafdata()); if (ipdefaultrouterpreference.is_set || is_set(ipdefaultrouterpreference.yfilter)) leaf_name_data.push_back(ipdefaultrouterpreference.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipDefaultRouterAddressType") { ipdefaultrouteraddresstype = value; ipdefaultrouteraddresstype.value_namespace = name_space; ipdefaultrouteraddresstype.value_namespace_prefix = name_space_prefix; } if(value_path == "ipDefaultRouterAddress") { ipdefaultrouteraddress = value; ipdefaultrouteraddress.value_namespace = name_space; ipdefaultrouteraddress.value_namespace_prefix = name_space_prefix; } if(value_path == "ipDefaultRouterIfIndex") { ipdefaultrouterifindex = value; ipdefaultrouterifindex.value_namespace = name_space; ipdefaultrouterifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipDefaultRouterLifetime") { ipdefaultrouterlifetime = value; ipdefaultrouterlifetime.value_namespace = name_space; ipdefaultrouterlifetime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipDefaultRouterPreference") { ipdefaultrouterpreference = value; ipdefaultrouterpreference.value_namespace = name_space; ipdefaultrouterpreference.value_namespace_prefix = name_space_prefix; } } void IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipDefaultRouterAddressType") { ipdefaultrouteraddresstype.yfilter = yfilter; } if(value_path == "ipDefaultRouterAddress") { ipdefaultrouteraddress.yfilter = yfilter; } if(value_path == "ipDefaultRouterIfIndex") { ipdefaultrouterifindex.yfilter = yfilter; } if(value_path == "ipDefaultRouterLifetime") { ipdefaultrouterlifetime.yfilter = yfilter; } if(value_path == "ipDefaultRouterPreference") { ipdefaultrouterpreference.yfilter = yfilter; } } bool IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipDefaultRouterAddressType" || name == "ipDefaultRouterAddress" || name == "ipDefaultRouterIfIndex" || name == "ipDefaultRouterLifetime" || name == "ipDefaultRouterPreference") return true; return false; } IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertTable() : ipv6routeradvertentry(this, {"ipv6routeradvertifindex"}) { yang_name = "ipv6RouterAdvertTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6RouterAdvertTable::~Ipv6RouterAdvertTable() { } bool IPMIB::Ipv6RouterAdvertTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<ipv6routeradvertentry.len(); index++) { if(ipv6routeradvertentry[index]->has_data()) return true; } return false; } bool IPMIB::Ipv6RouterAdvertTable::has_operation() const { for (std::size_t index=0; index<ipv6routeradvertentry.len(); index++) { if(ipv6routeradvertentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::Ipv6RouterAdvertTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6RouterAdvertTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6RouterAdvertTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6RouterAdvertTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6RouterAdvertTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "ipv6RouterAdvertEntry") { auto ent_ = std::make_shared<IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry>(); ent_->parent = this; ipv6routeradvertentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6RouterAdvertTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : ipv6routeradvertentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::Ipv6RouterAdvertTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::Ipv6RouterAdvertTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::Ipv6RouterAdvertTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6RouterAdvertEntry") return true; return false; } IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::Ipv6RouterAdvertEntry() : ipv6routeradvertifindex{YType::int32, "ipv6RouterAdvertIfIndex"}, ipv6routeradvertsendadverts{YType::boolean, "ipv6RouterAdvertSendAdverts"}, ipv6routeradvertmaxinterval{YType::uint32, "ipv6RouterAdvertMaxInterval"}, ipv6routeradvertmininterval{YType::uint32, "ipv6RouterAdvertMinInterval"}, ipv6routeradvertmanagedflag{YType::boolean, "ipv6RouterAdvertManagedFlag"}, ipv6routeradvertotherconfigflag{YType::boolean, "ipv6RouterAdvertOtherConfigFlag"}, ipv6routeradvertlinkmtu{YType::uint32, "ipv6RouterAdvertLinkMTU"}, ipv6routeradvertreachabletime{YType::uint32, "ipv6RouterAdvertReachableTime"}, ipv6routeradvertretransmittime{YType::uint32, "ipv6RouterAdvertRetransmitTime"}, ipv6routeradvertcurhoplimit{YType::uint32, "ipv6RouterAdvertCurHopLimit"}, ipv6routeradvertdefaultlifetime{YType::uint32, "ipv6RouterAdvertDefaultLifetime"}, ipv6routeradvertrowstatus{YType::enumeration, "ipv6RouterAdvertRowStatus"} { yang_name = "ipv6RouterAdvertEntry"; yang_parent_name = "ipv6RouterAdvertTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::~Ipv6RouterAdvertEntry() { } bool IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::has_data() const { if (is_presence_container) return true; return ipv6routeradvertifindex.is_set || ipv6routeradvertsendadverts.is_set || ipv6routeradvertmaxinterval.is_set || ipv6routeradvertmininterval.is_set || ipv6routeradvertmanagedflag.is_set || ipv6routeradvertotherconfigflag.is_set || ipv6routeradvertlinkmtu.is_set || ipv6routeradvertreachabletime.is_set || ipv6routeradvertretransmittime.is_set || ipv6routeradvertcurhoplimit.is_set || ipv6routeradvertdefaultlifetime.is_set || ipv6routeradvertrowstatus.is_set; } bool IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(ipv6routeradvertifindex.yfilter) || ydk::is_set(ipv6routeradvertsendadverts.yfilter) || ydk::is_set(ipv6routeradvertmaxinterval.yfilter) || ydk::is_set(ipv6routeradvertmininterval.yfilter) || ydk::is_set(ipv6routeradvertmanagedflag.yfilter) || ydk::is_set(ipv6routeradvertotherconfigflag.yfilter) || ydk::is_set(ipv6routeradvertlinkmtu.yfilter) || ydk::is_set(ipv6routeradvertreachabletime.yfilter) || ydk::is_set(ipv6routeradvertretransmittime.yfilter) || ydk::is_set(ipv6routeradvertcurhoplimit.yfilter) || ydk::is_set(ipv6routeradvertdefaultlifetime.yfilter) || ydk::is_set(ipv6routeradvertrowstatus.yfilter); } std::string IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/ipv6RouterAdvertTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "ipv6RouterAdvertEntry"; ADD_KEY_TOKEN(ipv6routeradvertifindex, "ipv6RouterAdvertIfIndex"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ipv6routeradvertifindex.is_set || is_set(ipv6routeradvertifindex.yfilter)) leaf_name_data.push_back(ipv6routeradvertifindex.get_name_leafdata()); if (ipv6routeradvertsendadverts.is_set || is_set(ipv6routeradvertsendadverts.yfilter)) leaf_name_data.push_back(ipv6routeradvertsendadverts.get_name_leafdata()); if (ipv6routeradvertmaxinterval.is_set || is_set(ipv6routeradvertmaxinterval.yfilter)) leaf_name_data.push_back(ipv6routeradvertmaxinterval.get_name_leafdata()); if (ipv6routeradvertmininterval.is_set || is_set(ipv6routeradvertmininterval.yfilter)) leaf_name_data.push_back(ipv6routeradvertmininterval.get_name_leafdata()); if (ipv6routeradvertmanagedflag.is_set || is_set(ipv6routeradvertmanagedflag.yfilter)) leaf_name_data.push_back(ipv6routeradvertmanagedflag.get_name_leafdata()); if (ipv6routeradvertotherconfigflag.is_set || is_set(ipv6routeradvertotherconfigflag.yfilter)) leaf_name_data.push_back(ipv6routeradvertotherconfigflag.get_name_leafdata()); if (ipv6routeradvertlinkmtu.is_set || is_set(ipv6routeradvertlinkmtu.yfilter)) leaf_name_data.push_back(ipv6routeradvertlinkmtu.get_name_leafdata()); if (ipv6routeradvertreachabletime.is_set || is_set(ipv6routeradvertreachabletime.yfilter)) leaf_name_data.push_back(ipv6routeradvertreachabletime.get_name_leafdata()); if (ipv6routeradvertretransmittime.is_set || is_set(ipv6routeradvertretransmittime.yfilter)) leaf_name_data.push_back(ipv6routeradvertretransmittime.get_name_leafdata()); if (ipv6routeradvertcurhoplimit.is_set || is_set(ipv6routeradvertcurhoplimit.yfilter)) leaf_name_data.push_back(ipv6routeradvertcurhoplimit.get_name_leafdata()); if (ipv6routeradvertdefaultlifetime.is_set || is_set(ipv6routeradvertdefaultlifetime.yfilter)) leaf_name_data.push_back(ipv6routeradvertdefaultlifetime.get_name_leafdata()); if (ipv6routeradvertrowstatus.is_set || is_set(ipv6routeradvertrowstatus.yfilter)) leaf_name_data.push_back(ipv6routeradvertrowstatus.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ipv6RouterAdvertIfIndex") { ipv6routeradvertifindex = value; ipv6routeradvertifindex.value_namespace = name_space; ipv6routeradvertifindex.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertSendAdverts") { ipv6routeradvertsendadverts = value; ipv6routeradvertsendadverts.value_namespace = name_space; ipv6routeradvertsendadverts.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertMaxInterval") { ipv6routeradvertmaxinterval = value; ipv6routeradvertmaxinterval.value_namespace = name_space; ipv6routeradvertmaxinterval.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertMinInterval") { ipv6routeradvertmininterval = value; ipv6routeradvertmininterval.value_namespace = name_space; ipv6routeradvertmininterval.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertManagedFlag") { ipv6routeradvertmanagedflag = value; ipv6routeradvertmanagedflag.value_namespace = name_space; ipv6routeradvertmanagedflag.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertOtherConfigFlag") { ipv6routeradvertotherconfigflag = value; ipv6routeradvertotherconfigflag.value_namespace = name_space; ipv6routeradvertotherconfigflag.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertLinkMTU") { ipv6routeradvertlinkmtu = value; ipv6routeradvertlinkmtu.value_namespace = name_space; ipv6routeradvertlinkmtu.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertReachableTime") { ipv6routeradvertreachabletime = value; ipv6routeradvertreachabletime.value_namespace = name_space; ipv6routeradvertreachabletime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertRetransmitTime") { ipv6routeradvertretransmittime = value; ipv6routeradvertretransmittime.value_namespace = name_space; ipv6routeradvertretransmittime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertCurHopLimit") { ipv6routeradvertcurhoplimit = value; ipv6routeradvertcurhoplimit.value_namespace = name_space; ipv6routeradvertcurhoplimit.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertDefaultLifetime") { ipv6routeradvertdefaultlifetime = value; ipv6routeradvertdefaultlifetime.value_namespace = name_space; ipv6routeradvertdefaultlifetime.value_namespace_prefix = name_space_prefix; } if(value_path == "ipv6RouterAdvertRowStatus") { ipv6routeradvertrowstatus = value; ipv6routeradvertrowstatus.value_namespace = name_space; ipv6routeradvertrowstatus.value_namespace_prefix = name_space_prefix; } } void IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ipv6RouterAdvertIfIndex") { ipv6routeradvertifindex.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertSendAdverts") { ipv6routeradvertsendadverts.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertMaxInterval") { ipv6routeradvertmaxinterval.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertMinInterval") { ipv6routeradvertmininterval.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertManagedFlag") { ipv6routeradvertmanagedflag.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertOtherConfigFlag") { ipv6routeradvertotherconfigflag.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertLinkMTU") { ipv6routeradvertlinkmtu.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertReachableTime") { ipv6routeradvertreachabletime.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertRetransmitTime") { ipv6routeradvertretransmittime.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertCurHopLimit") { ipv6routeradvertcurhoplimit.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertDefaultLifetime") { ipv6routeradvertdefaultlifetime.yfilter = yfilter; } if(value_path == "ipv6RouterAdvertRowStatus") { ipv6routeradvertrowstatus.yfilter = yfilter; } } bool IPMIB::Ipv6RouterAdvertTable::Ipv6RouterAdvertEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ipv6RouterAdvertIfIndex" || name == "ipv6RouterAdvertSendAdverts" || name == "ipv6RouterAdvertMaxInterval" || name == "ipv6RouterAdvertMinInterval" || name == "ipv6RouterAdvertManagedFlag" || name == "ipv6RouterAdvertOtherConfigFlag" || name == "ipv6RouterAdvertLinkMTU" || name == "ipv6RouterAdvertReachableTime" || name == "ipv6RouterAdvertRetransmitTime" || name == "ipv6RouterAdvertCurHopLimit" || name == "ipv6RouterAdvertDefaultLifetime" || name == "ipv6RouterAdvertRowStatus") return true; return false; } IPMIB::IcmpStatsTable::IcmpStatsTable() : icmpstatsentry(this, {"icmpstatsipversion"}) { yang_name = "icmpStatsTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IcmpStatsTable::~IcmpStatsTable() { } bool IPMIB::IcmpStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<icmpstatsentry.len(); index++) { if(icmpstatsentry[index]->has_data()) return true; } return false; } bool IPMIB::IcmpStatsTable::has_operation() const { for (std::size_t index=0; index<icmpstatsentry.len(); index++) { if(icmpstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IcmpStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IcmpStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmpStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IcmpStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IcmpStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "icmpStatsEntry") { auto ent_ = std::make_shared<IPMIB::IcmpStatsTable::IcmpStatsEntry>(); ent_->parent = this; icmpstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IcmpStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : icmpstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IcmpStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IcmpStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IcmpStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmpStatsEntry") return true; return false; } IPMIB::IcmpStatsTable::IcmpStatsEntry::IcmpStatsEntry() : icmpstatsipversion{YType::enumeration, "icmpStatsIPVersion"}, icmpstatsinmsgs{YType::uint32, "icmpStatsInMsgs"}, icmpstatsinerrors{YType::uint32, "icmpStatsInErrors"}, icmpstatsoutmsgs{YType::uint32, "icmpStatsOutMsgs"}, icmpstatsouterrors{YType::uint32, "icmpStatsOutErrors"} { yang_name = "icmpStatsEntry"; yang_parent_name = "icmpStatsTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IcmpStatsTable::IcmpStatsEntry::~IcmpStatsEntry() { } bool IPMIB::IcmpStatsTable::IcmpStatsEntry::has_data() const { if (is_presence_container) return true; return icmpstatsipversion.is_set || icmpstatsinmsgs.is_set || icmpstatsinerrors.is_set || icmpstatsoutmsgs.is_set || icmpstatsouterrors.is_set; } bool IPMIB::IcmpStatsTable::IcmpStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(icmpstatsipversion.yfilter) || ydk::is_set(icmpstatsinmsgs.yfilter) || ydk::is_set(icmpstatsinerrors.yfilter) || ydk::is_set(icmpstatsoutmsgs.yfilter) || ydk::is_set(icmpstatsouterrors.yfilter); } std::string IPMIB::IcmpStatsTable::IcmpStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/icmpStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IcmpStatsTable::IcmpStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmpStatsEntry"; ADD_KEY_TOKEN(icmpstatsipversion, "icmpStatsIPVersion"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IcmpStatsTable::IcmpStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (icmpstatsipversion.is_set || is_set(icmpstatsipversion.yfilter)) leaf_name_data.push_back(icmpstatsipversion.get_name_leafdata()); if (icmpstatsinmsgs.is_set || is_set(icmpstatsinmsgs.yfilter)) leaf_name_data.push_back(icmpstatsinmsgs.get_name_leafdata()); if (icmpstatsinerrors.is_set || is_set(icmpstatsinerrors.yfilter)) leaf_name_data.push_back(icmpstatsinerrors.get_name_leafdata()); if (icmpstatsoutmsgs.is_set || is_set(icmpstatsoutmsgs.yfilter)) leaf_name_data.push_back(icmpstatsoutmsgs.get_name_leafdata()); if (icmpstatsouterrors.is_set || is_set(icmpstatsouterrors.yfilter)) leaf_name_data.push_back(icmpstatsouterrors.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IcmpStatsTable::IcmpStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IcmpStatsTable::IcmpStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IcmpStatsTable::IcmpStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "icmpStatsIPVersion") { icmpstatsipversion = value; icmpstatsipversion.value_namespace = name_space; icmpstatsipversion.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpStatsInMsgs") { icmpstatsinmsgs = value; icmpstatsinmsgs.value_namespace = name_space; icmpstatsinmsgs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpStatsInErrors") { icmpstatsinerrors = value; icmpstatsinerrors.value_namespace = name_space; icmpstatsinerrors.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpStatsOutMsgs") { icmpstatsoutmsgs = value; icmpstatsoutmsgs.value_namespace = name_space; icmpstatsoutmsgs.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpStatsOutErrors") { icmpstatsouterrors = value; icmpstatsouterrors.value_namespace = name_space; icmpstatsouterrors.value_namespace_prefix = name_space_prefix; } } void IPMIB::IcmpStatsTable::IcmpStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "icmpStatsIPVersion") { icmpstatsipversion.yfilter = yfilter; } if(value_path == "icmpStatsInMsgs") { icmpstatsinmsgs.yfilter = yfilter; } if(value_path == "icmpStatsInErrors") { icmpstatsinerrors.yfilter = yfilter; } if(value_path == "icmpStatsOutMsgs") { icmpstatsoutmsgs.yfilter = yfilter; } if(value_path == "icmpStatsOutErrors") { icmpstatsouterrors.yfilter = yfilter; } } bool IPMIB::IcmpStatsTable::IcmpStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmpStatsIPVersion" || name == "icmpStatsInMsgs" || name == "icmpStatsInErrors" || name == "icmpStatsOutMsgs" || name == "icmpStatsOutErrors") return true; return false; } IPMIB::IcmpMsgStatsTable::IcmpMsgStatsTable() : icmpmsgstatsentry(this, {"icmpmsgstatsipversion", "icmpmsgstatstype"}) { yang_name = "icmpMsgStatsTable"; yang_parent_name = "IP-MIB"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IcmpMsgStatsTable::~IcmpMsgStatsTable() { } bool IPMIB::IcmpMsgStatsTable::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<icmpmsgstatsentry.len(); index++) { if(icmpmsgstatsentry[index]->has_data()) return true; } return false; } bool IPMIB::IcmpMsgStatsTable::has_operation() const { for (std::size_t index=0; index<icmpmsgstatsentry.len(); index++) { if(icmpmsgstatsentry[index]->has_operation()) return true; } return is_set(yfilter); } std::string IPMIB::IcmpMsgStatsTable::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IcmpMsgStatsTable::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmpMsgStatsTable"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IcmpMsgStatsTable::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IcmpMsgStatsTable::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "icmpMsgStatsEntry") { auto ent_ = std::make_shared<IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry>(); ent_->parent = this; icmpmsgstatsentry.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IcmpMsgStatsTable::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : icmpmsgstatsentry.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void IPMIB::IcmpMsgStatsTable::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void IPMIB::IcmpMsgStatsTable::set_filter(const std::string & value_path, YFilter yfilter) { } bool IPMIB::IcmpMsgStatsTable::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmpMsgStatsEntry") return true; return false; } IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::IcmpMsgStatsEntry() : icmpmsgstatsipversion{YType::enumeration, "icmpMsgStatsIPVersion"}, icmpmsgstatstype{YType::int32, "icmpMsgStatsType"}, icmpmsgstatsinpkts{YType::uint32, "icmpMsgStatsInPkts"}, icmpmsgstatsoutpkts{YType::uint32, "icmpMsgStatsOutPkts"} { yang_name = "icmpMsgStatsEntry"; yang_parent_name = "icmpMsgStatsTable"; is_top_level_class = false; has_list_ancestor = false; } IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::~IcmpMsgStatsEntry() { } bool IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::has_data() const { if (is_presence_container) return true; return icmpmsgstatsipversion.is_set || icmpmsgstatstype.is_set || icmpmsgstatsinpkts.is_set || icmpmsgstatsoutpkts.is_set; } bool IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::has_operation() const { return is_set(yfilter) || ydk::is_set(icmpmsgstatsipversion.yfilter) || ydk::is_set(icmpmsgstatstype.yfilter) || ydk::is_set(icmpmsgstatsinpkts.yfilter) || ydk::is_set(icmpmsgstatsoutpkts.yfilter); } std::string IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "IP-MIB:IP-MIB/icmpMsgStatsTable/" << get_segment_path(); return path_buffer.str(); } std::string IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "icmpMsgStatsEntry"; ADD_KEY_TOKEN(icmpmsgstatsipversion, "icmpMsgStatsIPVersion"); ADD_KEY_TOKEN(icmpmsgstatstype, "icmpMsgStatsType"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (icmpmsgstatsipversion.is_set || is_set(icmpmsgstatsipversion.yfilter)) leaf_name_data.push_back(icmpmsgstatsipversion.get_name_leafdata()); if (icmpmsgstatstype.is_set || is_set(icmpmsgstatstype.yfilter)) leaf_name_data.push_back(icmpmsgstatstype.get_name_leafdata()); if (icmpmsgstatsinpkts.is_set || is_set(icmpmsgstatsinpkts.yfilter)) leaf_name_data.push_back(icmpmsgstatsinpkts.get_name_leafdata()); if (icmpmsgstatsoutpkts.is_set || is_set(icmpmsgstatsoutpkts.yfilter)) leaf_name_data.push_back(icmpmsgstatsoutpkts.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "icmpMsgStatsIPVersion") { icmpmsgstatsipversion = value; icmpmsgstatsipversion.value_namespace = name_space; icmpmsgstatsipversion.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpMsgStatsType") { icmpmsgstatstype = value; icmpmsgstatstype.value_namespace = name_space; icmpmsgstatstype.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpMsgStatsInPkts") { icmpmsgstatsinpkts = value; icmpmsgstatsinpkts.value_namespace = name_space; icmpmsgstatsinpkts.value_namespace_prefix = name_space_prefix; } if(value_path == "icmpMsgStatsOutPkts") { icmpmsgstatsoutpkts = value; icmpmsgstatsoutpkts.value_namespace = name_space; icmpmsgstatsoutpkts.value_namespace_prefix = name_space_prefix; } } void IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "icmpMsgStatsIPVersion") { icmpmsgstatsipversion.yfilter = yfilter; } if(value_path == "icmpMsgStatsType") { icmpmsgstatstype.yfilter = yfilter; } if(value_path == "icmpMsgStatsInPkts") { icmpmsgstatsinpkts.yfilter = yfilter; } if(value_path == "icmpMsgStatsOutPkts") { icmpmsgstatsoutpkts.yfilter = yfilter; } } bool IPMIB::IcmpMsgStatsTable::IcmpMsgStatsEntry::has_leaf_or_child_of_name(const std::string & name) const { if(name == "icmpMsgStatsIPVersion" || name == "icmpMsgStatsType" || name == "icmpMsgStatsInPkts" || name == "icmpMsgStatsOutPkts") return true; return false; } const Enum::YLeaf IpAddressPrefixOriginTC::other {1, "other"}; const Enum::YLeaf IpAddressPrefixOriginTC::manual {2, "manual"}; const Enum::YLeaf IpAddressPrefixOriginTC::wellknown {3, "wellknown"}; const Enum::YLeaf IpAddressPrefixOriginTC::dhcp {4, "dhcp"}; const Enum::YLeaf IpAddressPrefixOriginTC::routeradv {5, "routeradv"}; const Enum::YLeaf IpAddressOriginTC::other {1, "other"}; const Enum::YLeaf IpAddressOriginTC::manual {2, "manual"}; const Enum::YLeaf IpAddressOriginTC::dhcp {4, "dhcp"}; const Enum::YLeaf IpAddressOriginTC::linklayer {5, "linklayer"}; const Enum::YLeaf IpAddressOriginTC::random {6, "random"}; const Enum::YLeaf IpAddressStatusTC::preferred {1, "preferred"}; const Enum::YLeaf IpAddressStatusTC::deprecated {2, "deprecated"}; const Enum::YLeaf IpAddressStatusTC::invalid {3, "invalid"}; const Enum::YLeaf IpAddressStatusTC::inaccessible {4, "inaccessible"}; const Enum::YLeaf IpAddressStatusTC::unknown {5, "unknown"}; const Enum::YLeaf IpAddressStatusTC::tentative {6, "tentative"}; const Enum::YLeaf IpAddressStatusTC::duplicate {7, "duplicate"}; const Enum::YLeaf IpAddressStatusTC::optimistic {8, "optimistic"}; const Enum::YLeaf IPMIB::Ip::IpForwarding::forwarding {1, "forwarding"}; const Enum::YLeaf IPMIB::Ip::IpForwarding::notForwarding {2, "notForwarding"}; const Enum::YLeaf IPMIB::Ip::Ipv6IpForwarding::forwarding {1, "forwarding"}; const Enum::YLeaf IPMIB::Ip::Ipv6IpForwarding::notForwarding {2, "notForwarding"}; const Enum::YLeaf IPMIB::IpNetToMediaTable::IpNetToMediaEntry::IpNetToMediaType::other {1, "other"}; const Enum::YLeaf IPMIB::IpNetToMediaTable::IpNetToMediaEntry::IpNetToMediaType::invalid {2, "invalid"}; const Enum::YLeaf IPMIB::IpNetToMediaTable::IpNetToMediaEntry::IpNetToMediaType::dynamic {3, "dynamic"}; const Enum::YLeaf IPMIB::IpNetToMediaTable::IpNetToMediaEntry::IpNetToMediaType::static_ {4, "static"}; const Enum::YLeaf IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::Ipv4InterfaceEnableStatus::up {1, "up"}; const Enum::YLeaf IPMIB::Ipv4InterfaceTable::Ipv4InterfaceEntry::Ipv4InterfaceEnableStatus::down {2, "down"}; const Enum::YLeaf IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::Ipv6InterfaceEnableStatus::up {1, "up"}; const Enum::YLeaf IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::Ipv6InterfaceEnableStatus::down {2, "down"}; const Enum::YLeaf IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::Ipv6InterfaceForwarding::forwarding {1, "forwarding"}; const Enum::YLeaf IPMIB::Ipv6InterfaceTable::Ipv6InterfaceEntry::Ipv6InterfaceForwarding::notForwarding {2, "notForwarding"}; const Enum::YLeaf IPMIB::IpAddressTable::IpAddressEntry::IpAddressType::unicast {1, "unicast"}; const Enum::YLeaf IPMIB::IpAddressTable::IpAddressEntry::IpAddressType::anycast {2, "anycast"}; const Enum::YLeaf IPMIB::IpAddressTable::IpAddressEntry::IpAddressType::broadcast {3, "broadcast"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalType::other {1, "other"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalType::invalid {2, "invalid"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalType::dynamic {3, "dynamic"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalType::static_ {4, "static"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalType::local {5, "local"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::reachable {1, "reachable"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::stale {2, "stale"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::delay {3, "delay"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::probe {4, "probe"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::invalid {5, "invalid"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::unknown {6, "unknown"}; const Enum::YLeaf IPMIB::IpNetToPhysicalTable::IpNetToPhysicalEntry::IpNetToPhysicalState::incomplete {7, "incomplete"}; const Enum::YLeaf IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::IpDefaultRouterPreference::reserved {-2, "reserved"}; const Enum::YLeaf IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::IpDefaultRouterPreference::low {-1, "low"}; const Enum::YLeaf IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::IpDefaultRouterPreference::medium {0, "medium"}; const Enum::YLeaf IPMIB::IpDefaultRouterTable::IpDefaultRouterEntry::IpDefaultRouterPreference::high {1, "high"}; } }
245,899
89,359
/** * @file 1.cpp * @author Jack * @mail chengjunjie.jack@gmail.com * @date 2021-12-28 * @version 0.1 * * @copyright Copyright (c) 2021 */ #include <algorithm> #include <cstdio> #include <iostream> #include <string> #include <type_traits> #include <vector> class B; class A { public: A(int a, int b = 1, int c = 1) { printf("a: %d, b: %d\n", a, b); } friend class B; protected: int prot_mem = 1; private: int private_mem = 2; }; class B : private A { public: B(int a) : A(a) {} using A::private_mem; using A::prot_mem; }; void fn(const A &arg){}; void fn() { static int count = -1; ++count; std::cout << "fn count: " << count << std::endl; }; // 64位系统 #include <stdio.h> struct { int x; char y; } s; int main() { int a = 1; int *b = &a; if (std::is_same<decltype(*b), int &>::value) { std::printf("decltype(*b) is same as int&\n"); } if (std::is_same<decltype((a)), int &>::value) { std::printf("decltype((a)) is same as int&\n"); } std::string s = "A"; for (auto &c : s) { if (std::is_same<decltype(c), char &>::value) { std::printf("decltype(c) is same as char&\n"); } } std::vector<int> is; if (std::is_same<decltype(is.begin() - is.end()), std::vector<int>::difference_type>::value) { std::printf( "decltype(is.begin() - is.end()) is same as " "std::vector<int>::difference_type\n"); } int arr1[] = {1, 2, 3, 4}; decltype(std::begin(arr1)) b_ptr; std::vector<int> vi(std::begin(arr1), std::end(arr1)); fn(1); A a1 = {1, 2}; B b1{1}; std::cout << "b1.prot_mem: " << b1.prot_mem << std::endl; std::cout << "b1.private_mem: " << b1.private_mem << std::endl; for (int i = 0; i < 10; ++i) fn(); printf("%d\n", sizeof(s)); // 输出24 return 0; }
1,794
787
#ifndef HTCW_GFX_DRAW_HELPERS_HPP #define HTCW_GFX_DRAW_HELPERS_HPP #include "gfx_positioning.hpp" namespace gfx { namespace helpers { template<typename Destination,typename Source,bool HasAlpha> struct blender { static gfx_result point(Destination& destination,point16 pt,Source& source,point16 spt, typename Source::pixel_type pixel) { typename Destination::pixel_type px; // printf("pixel.native_value = %d\r\n",(int)pixel.native_value); gfx_result r=convert_palette(destination,source,pixel,&px); //printf("px.native_value = %d\r\n",(int)px.native_value); if(gfx_result::success!=r) { return r; } return destination.point(pt,px); } }; template<typename Destination,typename Source> struct blender<Destination,Source,true> { static gfx_result point(Destination& destination,point16 pt,Source& source,point16 spt, typename Source::pixel_type pixel) { double alpha = pixel.template channelr<channel_name::A>(); if(0.0==alpha) return gfx_result::success; if(1.0==alpha) return blender<Destination,Source,false>::point(destination,pt,source,spt,pixel); typename Source::pixel_type spx; gfx_result r=source.point(spt,&spx); if(gfx_result::success!=r) { return r; } rgb_pixel<HTCW_MAX_WORD> bg; r=convert_palette_to(source,spx,&bg); if(gfx_result::success!=r) { return r; } rgb_pixel<HTCW_MAX_WORD> fg; r=convert_palette_to(source,pixel,&fg); if(gfx_result::success!=r) { return r; } r=fg.blend(bg,alpha,&fg); if(gfx_result::success!=r) { return r; } typename Destination::pixel_type px; r=convert_palette_from(destination,fg,&px); if(gfx_result::success!=r) { return r; } return destination.point(pt,px); } }; template<typename Destination,bool Batch,bool Async> struct batcher { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { return gfx_result::success; } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { return destination.point(location,pixel); } inline static gfx_result commit_batch(Destination& destination,bool async) { return gfx_result::success; } }; template<typename Destination> struct batcher<Destination,false,true> { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { return gfx_result::success; } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { if(async) { return destination.point_async(location,pixel); } else { return destination.point(location,pixel); } } inline static gfx_result commit_batch(Destination& destination,bool async) { return gfx_result::success; } }; template<typename Destination,bool Batch,bool Async, bool Read> struct alpha_batcher { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { return batcher<Destination,Batch,Async>::begin_batch(destination,bounds,async); } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { return batcher<Destination,Batch,Async>::write_batch(destination,location,pixel,async); } inline static gfx_result commit_batch(Destination& destination,bool async) { return batcher<Destination,Batch,Async>::commit_batch(destination,async); } }; template<typename Destination,bool Batch,bool Async> struct alpha_batcher<Destination,Batch,Async,true> { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { return batcher<Destination,false,Async>::begin_batch(destination,bounds,async); } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { return batcher<Destination,false,Async>::write_batch(destination,location,pixel,async); } inline static gfx_result commit_batch(Destination& destination,bool async) { return batcher<Destination,false,Async>::commit_batch(destination,async); } }; template<typename Destination> struct batcher<Destination,true,false> { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { return destination.begin_batch(bounds); } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { return destination.write_batch(pixel); } inline static gfx_result commit_batch(Destination& destination,bool async) { return destination.commit_batch(); } }; template<typename Destination> struct batcher<Destination,true,true> { inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) { if(async) { return destination.begin_batch_async(bounds); } else { return destination.begin_batch(bounds); } } inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) { if(async) { return destination.write_batch_async(pixel); } else { return destination.write_batch(pixel); } } inline static gfx_result commit_batch(Destination& destination,bool async) { if(async) { return destination.commit_batch_async(); } else { return destination.commit_batch(); } } }; template<typename Destination,bool Suspend,bool Async> struct suspender { inline suspender(Destination& dest,bool async=false) { } inline suspender(const suspender& rhs) = default; inline suspender& operator=(const suspender& rhs)=default; inline ~suspender() =default; inline static gfx_result suspend(Destination& dst) { return gfx_result::success; } inline static gfx_result resume(Destination& dst,bool force=false) { return gfx_result::success; } inline static gfx_result suspend_async(Destination& dst) { return gfx_result::success; } inline static gfx_result resume_async(Destination& dst,bool force=false) { return gfx_result::success; } }; template<typename Destination> struct suspender<Destination,true,false> { Destination& destination; inline suspender(Destination& dest,bool async=false) : destination(dest) { suspend(destination); } inline suspender(const suspender& rhs) { suspend(destination); } inline suspender& operator=(const suspender& rhs) { destination = rhs.destination; suspend(destination); return *this; } inline ~suspender() { resume(destination); } inline static gfx_result suspend(Destination& dst) { return dst.suspend(); } inline static gfx_result resume(Destination& dst,bool force=false) { if(force) { return resume(dst,true); } return dst.resume(); } inline static gfx_result suspend_async(Destination& dst) { return suspend(dst); } inline static gfx_result resume_async(Destination& dst,bool force=false) { if(force) { return resume(dst,true); } return resume(dst); } }; template<typename Destination> struct suspender<Destination,true,true> { Destination& destination; const bool async; inline suspender(Destination& dest,bool async=false) : destination(dest),async(async) { if(async) { suspend_async(destination); return; } suspend(destination); } inline suspender(const suspender& rhs) { destination = rhs.destination; if(async) { suspend_async(destination); return; } suspend(destination); } inline suspender& operator=(const suspender& rhs) { destination = rhs.destination; if(async) { suspend_async(destination); return *this; } suspend(destination); return *this; } inline ~suspender() { if(async) { resume_async(destination); return; } resume(destination); } inline static gfx_result suspend(Destination& dst) { return dst.suspend(); } inline static gfx_result resume(Destination& dst,bool force=false) { if(force) { return dst.resume(true); } return dst.resume(); } inline static gfx_result suspend_async(Destination& dst) { return dst.suspend_async(); } inline static gfx_result resume_async(Destination& dst,bool force=false) { if(force) { dst.resume_async(true); } return dst.resume_async(); } }; } } #endif
11,262
2,800
/**************************************************************************** ** $Id: aobject.cpp,v 1.3 2008/11/09 21:09:11 leader Exp $ ** ** Code file of the Ananas Object of Ananas ** Designer and Engine applications ** ** Created : 20031201 ** ** Copyright (C) 2003-2004 Leader InfoTech. All rights reserved. ** Copyright (C) 2005-2006 Grigory Panov <gr1313 at mail.ru>, Yoshkar-Ola. ** ** This file is part of the Library of the Ananas ** automation accounting system. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.leaderit.ru/page=ananas or email sales@leaderit.ru ** See http://www.leaderit.ru/gpl/ for GPL licensing information. ** ** Contact org@leaderit.ru if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qobject.h> #include <q3sqlcursor.h> #include <q3sqlpropertymap.h> #include <qdialog.h> #include "adatabase.h" #include "aobject.h" #include "aform.h" #include "alog.h" /*! * \en * Craeate abstract aObject. * \param parent - parent object * \param name - name of object * \_en * \ru * Создает абстрактный не связанный с базой данных объект управления данными. * Созданный таким образом объект не использует информацию из метаданных о составе и * типах полей. То есть он не является какой-либо моделью данных. И на самом деле малопригоден * для использования. В дазе данных ни как не отражается создание этого объекта. Для того, * что бы зарегистрировать вновь созданный абстрактный объект в базе данных, необходимо * сначала проинициализировать его с использованием метаданных, а затем вызвать метод New(). * \_ru */ aObject::aObject( QObject *parent, const char *name ) :QObject( parent, name ) { db = 0; vInited = false; filtred = false; selectFlag = false; } /*! * \en * Create aObject, inited by md object. * md object finding by name * \param oname - md name of object, name contens prefix * Document. for documents, * InfoRegister. for information registers, * Catalogue. for catalogues, * AccumulationRegister. for Accumulation registers, * DocJournal. for journals * \param adb - link on object aDataBase used for work * \param parent - parent object * \param name - name of object * \_en * \ru * Создает объект как модель данных, описанную в метаданных. На описание в метаданных * указывает один из передаваемых при вызове параметров - имя элемента метаданных. * После успешного создания объекта с ним можно работать как с объектом данных со структурой, * описанной в метаданных, и индентифицируемой именем, переданным в параметрах вызова. * * \_ru */ aObject::aObject( const QString &oname, aDatabase *adb, QObject *parent, const char *name ) :QObject( parent, name ) { vInited = false; filtred = false; selectFlag = false; db = adb; if ( adb ) { obj = adb->cfg.find( oname ); setObject( obj ); } } /*! * Create aObject, inited by md object. * \param context - hi leve md object * \param adb - link on object aDataBase used for work * \param parent - parent object * \param name - name of object */ aObject::aObject( aCfgItem context, aDatabase *adb, QObject *parent, const char *name ) :QObject( parent, name ) { filtred = false; vInited = false; db = adb; if ( adb ) { setObject( context ); } } /*! * virtual destructor. */ aObject::~aObject() { } /*! * Tune on metadata object and it's database tables. * \param adb - link on database object * \return error code */ ERR_Code aObject::init() { if ( isInited() ) return err_noerror; return initObject(); } /*! * Set new object type after create * /param newobject - new md object * \return error code */ ERR_Code aObject::setObject( aCfgItem newobject ) { setInited( false ); obj = newobject; return init(); } /*! * Init object after create. * Need setObject( id ), where id - if of the metadata object of the adb->cfg loaded Configuration. * \return error code */ ERR_Code aObject::initObject() { aCfgItem fg, f; QString tname; setInited( true ); // db = adb; md = 0; if ( db ) md = &db->cfg; else { aLog::print(aLog::Error, tr("aObject have no database!")); return err_nodatabase; } if ( obj.isNull() ) { aLog::print(aLog::Error, tr("aObject md object not found")); return err_objnotfound; } return err_noerror; } /*! * */ bool aObject::checkStructure() { return false; } /*! * Return the table of object by it's name. * /param name - name of table for main table use name="" or empty parametr * /return link on aDataTable or 0 if table not found */ aDataTable * aObject::table( const QString &name ) { if ( !dbtables[ name ] ) { if (name!="" && !name.isEmpty()) { aLog::print(aLog::Error, tr("aObject table with name %1 not found").arg(name)); cfg_message(1, tr("Table `%s' not found.\n").utf8(),(const char*) name); } // else // { // cfg_message(1, tr("Table name is empty.\n").utf8()); // } return 0; } return dbtables[ name ]; } /*! * Insert table name and it link into internal buffer. * used for finding table by it's md name or some default name * /param dbname - database name of table * /param obj - md object, used for aDataTable initing * /param name - name of table, used for finding table in buffer * /return error code */ ERR_Code aObject::tableInsert( const QString &dbname, aCfgItem obj, const QString &name ) { if ( db ) { aDataTable *t = db->table( dbname ); if ( !t ) return err_notable; t->setObject( obj ); dbtables.insert( name, t ); return err_noerror; } aLog::print(aLog::Error, tr("aObject have no database!")); return err_nodatabase; } /*! * Insert table name and it link into internal buffer. * used for finding table by it's md name or some default name * table not inited by md object * /param dbname - database name of table * /param name - name of table, used for finding table in buffer * /return error code */ ERR_Code aObject::tableInsert( const QString &dbname, const QString &name ) { if ( db ) { aDataTable *t = db->table( dbname ); if ( !t ) return err_notable; dbtables.insert( name, t ); return err_noerror; } aLog::print(aLog::Error, tr("aObject have no database!")); return err_nodatabase; } /*! * Remove table from buffer. * /param name - table name * /return err_notable if table not found */ ERR_Code aObject::tableRemove( const QString &name ) { if ( !dbtables[name] ) { aLog::print(aLog::Error, tr("aObject table with name %1 not found").arg(name)); return err_notable; } dbtables.remove( name ); return err_noerror; } /*! * */ QString aObject::trSysName( const QString & ) { return ""; } /*! * Gets system field value. * \param name (in) - field name. * \return field value or QVariant::Invalid if field no exist. */ QVariant aObject::sysValue( const QString & name, const QString &tableName ) { aDataTable *t = table( tableName ); if ( t && t->sysFieldExists( name ) ) { return t->sysValue(name); } else return QVariant::Invalid; } /*! * Sets system field value. * \param name (in) - field name. * \param value (in) - sets value. */ int aObject::setSysValue( const QString & name, QVariant value, const QString &tableName ) { aDataTable *t = table( tableName ); if ( t ) { t->setSysValue( name, value ); return err_noerror; } return err_notable; } /*! * Return field value of the primary object database table. */ QVariant aObject::Value( const QString & name, const QString &tableName ) { aDataTable *t = table( tableName ); QString trName = trSysName(name); if ( trName != "" ) return sysValue( trName ); else { if ( t ) return t->value( name ); } return QVariant(""); } /*! * Set field value of the primary object database table. */ int aObject::SetValue( const QString & name, const QVariant &value, const QString &tableName ) { aDataTable *t = table( tableName ); QString trName = trSysName(name); if ( trName != "" ) return setSysValue( trName, value ); else { if ( t ) { t->setValue( name, value ); return err_noerror; } } return err_notable; // return setTValue( "", name, value ); } /*! * Check object selecting. * \return true if object record selected in database. */ bool aObject::IsSelected() { return selected(); } /*! * */ bool aObject::IsMarkDeleted(const QString & tname) { aDataTable *t = table( tname ); if ( t && t->sysFieldExists( "df" ) ) return t->sysValue( "df" ).toInt() == 1; return false; } /*! * */ bool aObject::IsMarked() { aDataTable *t = table(); if ( t && t->sysFieldExists( "mf" ) ) return t->sysValue( "mf" ).toInt() == 1; return false; } /*! * */ /* int aObject::TableSetMarkDeleted( bool Deleted, const QString & tname ) { aDataTable *t = table( tname ); if ( t && t->sysFieldExists( "df" ) ) { QString v = "0"; if ( Deleted ) v = "1"; t->setSysValue( "df", QVariant( v ) ); return err_noerror; } return err_incorrecttype; // Object can not be mark deleted } */ /*! * */ int aObject::SetMarkDeleted( bool Deleted, const QString & tname ) { aDataTable *t = table( tname ); if ( t && t->sysFieldExists( "df" ) ) { QString v = "0"; if ( Deleted ) v = "1"; t->setSysValue( "df", QVariant( v ) ); return err_noerror; } else { aLog::print(aLog::Error, tr("aObject have no system field %1").arg("df")); return err_incorrecttype; // Object can not be mark deleted } } /*! * */ int aObject::SetMarked( bool Marked ) { aDataTable *t = table(); if ( t && t->sysFieldExists( "mf" ) ) { QString v = ""; if ( Marked ) v = "1"; t->setSysValue( "mf", QVariant( v ) ); // t->printRecord(); return err_noerror; } aLog::print(aLog::Error, tr("aObject have no system field %1").arg("mf")); return err_incorrecttype; // Object can not be marked } /*! * Add new object record in database. */ int aObject::New() { aDataTable *t = table(); if ( !t ) return err_notable; setSelected ( t->New() ); /* Q_ULLONG Uid = t->primeInsert()->value("id").toULongLong(); if ( t->insert() ) { if ( t->select(QString("id=%1").arg(Uid), false) ) if ( t->first() ) { setSelected(true); return err_noerror; } return err_selecterror; } */ if ( selected() ) return err_noerror; return err_inserterror; } /*! * Copy current selected object data in database. */ /*Q_ULLONG aObject::copy( const QString & tablename ) { aDataTable * t = table( tablename ); if ( !t ) return 0; if ( !selected(tablename) ) return 0; QSqlRecord * r = t->primeUpdate(); Q_ULLONG Uid = db->uid( t->id ); r->setValue("id",Uid); if ( t->insert() ) return Uid; else return 0; } */ /*! * */ int aObject::Copy() { // QSqlRecord r; // Q_ULLONG Uid = copy(); // if ( !Uid ) return err_copyerror; aDataTable *t = table(); if ( t->Copy() ) return err_noerror; // if ( t->select(QString("id=%1").arg(Uid)) ) // if ( t->first() ) // return err_noerror; return err_copyerror; } /*! * Delete curent selected object record from database. */ int aObject::Delete() { aDataTable * t = table(); if ( !t ) return err_notable; db->markDeleted(getUid()); t->Delete(); // if ( !selected() ) return err_notselected; // t->primeDelete(); // t->del(); setSelected (false); return err_noerror; } /*! *\~english * Update curent selected object record to database. *\~russian *\~ */ int aObject::Update() { aDataTable *t = table(); QSqlRecord *r; int i; if ( !t ) return err_notable; t->Update(); /* r = t->primeUpdate(); t->printRecord(); for ( i=0;i<r->count();i++ ) r->setValue( i, t->value( i ) ); t->update(); */ if ( t->lastError().type() ) { //debug_message("update error %i %s\n",t->lastError().type(), ( const char *)t->lastError().text()); aLog::print(aLog::Error, tr("aObject update error. Driver message: %1").arg(t->lastError().text())); return err_updateerror; } else { return err_noerror; } } /*! *\~english * Update object attributes from curent selected object database record. *\~russian *\~ *//* void aObject::updateAttributes( const QString & tname ) { aDataTable *t = table(); } */ /*! *\~english * Conduct document. * Do nothing. Added for wDocument compatibility. *\~russian * Проводит документ. * Ничего не делает. Предназначена для совместимости и работы в wDocument. *\~ *\return \~english error code - abstract object.\~russian код ошибки - абстрактный обект.\~ */ int aObject::Conduct() { return err_abstractobj; } /*! *\~english * UnConduct document. * Do nothing. Added for wDocument compatibility. *\~russian * Распроводит документ. * Ничего не делает. Предназначена для совместимости и работы в wDocument. *\~ *\return \~english error code - abstract object.\~russian код ошибки - абстрактный обект.\~ */ int aObject::UnConduct() { return err_abstractobj; } bool aObject::IsConducted() { return 0; } /*! *\~english * Return document database id. * always return 0. Added for wJournal compatibility. *\~russian * Возвращает id документа в базе данных. * Всегда возвращает 0. Предназначена для совместимости и работы в wJournal. *\~ *\return \~english 0.\~russian 0.\~ */ qulonglong aObject::docId() { return 0; } /*! * \ru * Позиционирует указатель в БД на запись, соотвествующую объекту * с указанным идентификатором. * \param id - Идентификатор объекта. * \return возвращает код ошибки или 0 в случае успеха. * \_ru */ ERR_Code aObject::select( qulonglong id ) { aDataTable * t = table(); if ( !t ) return err_notable; setSelected (false); long otype = db->uidType( id ); // debug_message("otype=%li\n",otype); if ( !otype ) return err_objnotfound; if ( concrete && ( otype != t->getMdObjId() ) ) return err_incorrecttype; if ( !concrete ) { aCfgItem tmpObj = md->find( otype ); if ( tmpObj.isNull() ) return err_objnotfound; setObject ( tmpObj ); } if ( t->select( QString("id=%1").arg(id), false ) ) if ( t->first() ) { // t->primeUpdate(); setSelected (true); // t->printRecord(); return err_noerror; } else return err_notselected; return err_selecterror; } /*! * */ ERR_Code aObject::select(const QString & query, const QString &tableName) { aDataTable * t = table(tableName); if ( !t ) return err_notable; if (t->select(query)) if( t->first() ) { setSelected (true); return err_noerror; } else return err_notselected; return err_selecterror; } /*! * Return field value of the secondary object database table. */ QVariant aObject::tValue( const QString & tablename, const QString & name ) { aDataTable *t = table( tablename ); //CHECK_POINT if ( t ) return t->value( name ); return QVariant(""); } /*! * Set field value of the secondary object database table. */ ERR_Code aObject::setTValue( const QString & tablename, const QString & name, const QVariant &value ) { aDataTable *t = table( tablename ); if ( t ) { t->setValue( name, value ); return err_noerror; } return err_notable; } /*! * */ ERR_Code aObject::decodeDocNum( QString nm, QString & pref, int & num) { aLog::print(aLog::Debug, tr("aObject decode doc number %1").arg(nm)); int pos = -1; for ( uint i = nm.length(); i > 0; i-- ) { if ( ( nm.at(i-1) >='0' ) && ( nm.at(i-1) <= '9' ) ) continue; else { pos = i; break; } } if ( pos == -1 ) { //CHECK_POINT pref = ""; num = nm.toInt(); return err_incorrectname; } if ( pos == ( int ) nm.length() ) { //CHECK_POINT pref = nm; num = -1; return err_incorrectname; } //CHECK_POINT pref = nm.left( pos ); num = nm.mid(pos).toInt(); aLog::print(aLog::Debug, tr("aObject decode doc number ok, pref=%1 num=%2").arg(pref).arg(num)); return err_noerror; } /*! * */ /* bool aObject::Next() { return table()->next(); // return dbtables[""]->next(); } */ /*! * */ /* bool aObject::Prev() { // return dbtables[""]->prev(); return table()->prev(); } */ /*! * */ /* bool aObject::First() { // return dbtables[""]->first(); return table()->first(); } */ /*! * */ /* bool aObject::Last() { // return dbtables[""]->last(); return table()->last(); } */ /*! * */ bool aObject::Next( const QString& tableName ) { return table(tableName)->next(); } /*! * */ bool aObject::Prev( const QString& tableName ) { return table(tableName)->prev(); } /*! * */ bool aObject::First( const QString& tableName ) { return table(tableName)->first(); } /*! * */ bool aObject::Last( const QString& tableName ) { return table(tableName)->last(); } /*! * \ru * Возвращает уникальный идентификатор объекта из базы данных. * В качестве объекта например может выступать "Приходная накладная" от такого-то числа за таким то номером. * Каждый вновь созданный в системе документ или элемент справочника, включая группы справочника имеет свой уникальный * неповторяющийся идентификатор. Если какое-либо поле, какого-либо объекта имеет тип Объект (например Document.Накладная), * то в качестве значения ему нужно задавать уникальный идентификатор объекта, возвращаемый функцией Uid(). * Не существует возможности изменить существующий идентификатор какого-либо объекта. Созданием и управлением * идентификаторами объектов занимается система. * \return строка со значением уникального идентификатора. * \_ru */ QString aObject::Uid() { return QString::number(getUid()); } /*! * */ qulonglong aObject::getUid() { qulonglong Uid = 0; if ( selected() ) Uid = table()->sysValue("id").toULongLong(); return Uid; } /*! * */ void aObject::setSelected( bool sel, const QString & tablename ) { if ( tablename == "" ) selectFlag = sel; else table(tablename)->selected = sel; } /*! * */ bool aObject::selected( const QString & tablename ) { if ( tablename == "" ) return selectFlag; else return table(tablename)->selected; } /*! * */ ERR_Code aObject::setTFilter( const QString & tname, const QString & valname, const QVariant & value ) { aDataTable * t = dbtables[tname]; if ( !t ) return err_notable; if ( t->setFilter( valname, value ) ) return err_noerror; else return err_fieldnotfound; } /*! * */ ERR_Code aObject::clearTFilter( const QString & tname ) { aDataTable * t = dbtables[tname]; if ( !t ) return err_notable; t->clearFilter(); return err_noerror; } /*! * */ int aObject::SetFilter( const QString & valname, const QVariant & value ) { int err = setTFilter( "", valname, value ); filtred = !err; return err; } /*! * */ int aObject::ClearFilter() { filtred = false; return clearTFilter(""); } /*! * */ int aObject::TableSetFilter( const QString & tname, const QString & valname, const QVariant & value ) { return setTFilter( tname, valname, value ); } /*! * */ int aObject::TableClearFilter( const QString & tname ) { return clearTFilter(tname); } /*! * \ru * Обновляет базу данных данными табличной части объекта. Обычно вызывается * после метода TableSetValue. * \param tablename - имя таблицы. Необходим для указания имени, так как * в объекте возможно наличие нескольких табличных частей. * \return возвращает код ошибки или 0 в случае успеха. * \_ru */ int aObject::TableUpdate( const QString & tablename ) { aDataTable *t = table( tablename ); if ( !t ) { aLog::print(aLog::Error, tr("aObject table update: no table found with name %1").arg(tablename)); return err_notable; } // t->primeUpdate(); t->Update(); if (t->lastError().type()) { aLog::print(aLog::Error, tr("aObject update error. Driver message: %1").arg(t->lastError().text())); return err_updateerror; } return err_noerror; } /*! * */ QString aObject::displayString() { QString res="***"; int stdfc = 0, fid; aCfgItem sw, f; sw = displayStringContext(); // if ( md->objClass( obj ) == md_catalogue ) { // sw = md->find( md->find( obj, md_element ), md_string_view ); // } else { // sw = md->find( obj, md_string_view ); // } if ( !sw.isNull() ) { stdfc = md->attr( sw, mda_stdf ).toInt(); switch ( stdfc ) { case 0: fid = md->sText( sw, md_fieldid ).toInt(); res = table()->sysValue( QString( "uf%1" ).arg( fid ) ).toString(); //printf("fid=%i res=%s\n",fid, ( const char *) res ); break; case 1: break; case 2: break; } } else { aLog::print(aLog::Debug, tr("aObject display string context is null")); } // res = return res; } aCfgItem aObject::displayStringContext() { return md->find( obj, md_string_view ); } /** * \ru * Вид объекта, так как он описан в метаданных. * \_ru */ QString aObject::Kind( const QString & name ) { QString wasKind = md->objClass( obj ); if ( !name.isEmpty() ) { // Set new kind. } return wasKind; }
21,455
8,233
/*********************************************************************************************/ /* Problem: Stack Min (CtCi 3.2) ********/ /*********************************************************************************************/ /* --Problem statement: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum elements? Push, pop and min should all operate in O(1) time. --Reasoning: Use two stacks, one to store all the elements and one to keep track of the min values. --Time complexity: O(1), operations do not depend on the size of the stack. --Space complexity: O(n), in the worst case scenario where the input is made of elements sorted in descending order, we'd have to store all elements in the second stack. */ #include <iostream> #include <vector> #include <climits> #include "stack/stack.h" class StackMin { private: Stack<int> st_values, st_min; public: void push(int value) { st_values.push(value); if (min() >= value) { st_min.push(value); } } void pop(void) { if (min() == st_values.peek()) { st_min.pop(); } st_values.pop(); } int peek(void) { return st_values.peek(); } int min(void) { if (st_min.isEmpty()) { return INT_MAX; } return st_min.peek(); } StackMin() {} ~StackMin() = default; }; // driver code: int main() { StackMin st; std::vector<int> values{11, 5, 3, 9, 23, -2, 47, 1}; for (auto v : values) { st.push(v); } std::cout << "Min element in the stack: " << st.min() << "\n"; std::cout << "Top element in the stack: " << st.peek() << "\n"; st.pop(); std::cout << "Min element in the stack: " << st.min() << "\n"; std::cout << "Top element in the stack: " << st.peek() << "\n"; st.pop(); st.pop(); std::cout << "Min element in the stack: " << st.min() << "\n"; std::cout << "Top element in the stack: " << st.peek() << "\n"; return 0; }
1,993
697
#include <iostream> #include <cmath> using namespace std; int main() { float Ax, Ay, Ar, Bx, By, Br; cout << "Enter first circle [x y r]:" << endl; cin >> Ax >> Ay >> Ar; cout << "Enter second circle [x y r]:" << endl; cin >> Bx >> By >> Br; float d = sqrt(pow((Ax - Bx), 2) + pow((Ay - By), 2)); float a = (pow(Ar, 2) - pow(Br, 2) + pow(d, 2)) / (2 * d); float h= sqrt(pow(Ar, 2) - pow(a, 2)); float x = Ax + a * (Bx - Ax) / d; float y = Ay + a * (By - Ay) / d; float Cx = x + (By - Ay) * h / d; float Cy = y - (Bx - Ax) * h / d; float Dx = x - (By - Ay) * h / d; float Dy = y + (Bx - Ax) * h / d; if (Ar + Br < d) cout << "No interception points."; else if (Ar + Br == d) { cout << "One interception point." << endl; cout << "x = " << x << ", y = " << y << endl; } else if (Ar + Br > d) { cout << "Two interception points." << endl; cout << "Cx = " << Cx << ", Cy = " << Cy << endl; cout << "Dx = " << Dx << ", Dy = " << Dy << endl; } return 0; }
1,080
445
void bind_DoubleJumpComponentWrapper([[maybe_unused]] v8::Isolate* isolate, v8pp::module& module) { v8pp::class_<DoubleJumpComponentWrapper> cl_DoubleJumpComponentWrapper(isolate); cl_DoubleJumpComponentWrapper.inherit<CarComponentWrapper>(); cl_DoubleJumpComponentWrapper.ctor<uintptr_t>(); cl_DoubleJumpComponentWrapper.set<void(DoubleJumpComponentWrapper::*)(float)>("SetJumpImpulse", &DoubleJumpComponentWrapper::SetJumpImpulse); cl_DoubleJumpComponentWrapper.set<float(DoubleJumpComponentWrapper::*)()>("GetImpulseScale", &DoubleJumpComponentWrapper::GetImpulseScale); cl_DoubleJumpComponentWrapper.set<void(DoubleJumpComponentWrapper::*)(float)>("SetImpulseScale", &DoubleJumpComponentWrapper::SetImpulseScale); cl_DoubleJumpComponentWrapper.set<void(DoubleJumpComponentWrapper::*)(float)>("ApplyForces", &DoubleJumpComponentWrapper::ApplyForces); cl_DoubleJumpComponentWrapper.set<void(DoubleJumpComponentWrapper::*)()>("OnCreated", &DoubleJumpComponentWrapper::OnCreated); module.set("DoubleJumpComponentWrapper", cl_DoubleJumpComponentWrapper); }
1,067
327
#include <stdint.h> #include "settings_eeprom.h" #include "state_expresslrs.h" #include "ui.h" #include "temperature.h" #include "touchpad.h" #include "comm_espnow.h" #include "protocol_ExpressLRS.h" void StateMachine::ExLRSStateHandler::onEnter() { //onUpdateDraw(false); } void StateMachine::ExLRSStateHandler::onUpdate() { onUpdateDraw(TouchPad::touchData.buttonPrimary); } void StateMachine::ExLRSStateHandler::onUpdateDraw(uint8_t tapAction) { uint32_t off_x = 20, off_x2 = off_x + 17 * Ui::CHAR_W, off_y = 20; int16_t cursor_x = TouchPad::touchData.cursorX, cursor_y = TouchPad::touchData.cursorY; uint8_t region = expresslrs_params_get_region(); if (drawHeader()) return; // Mode Ui::display.setCursor(off_x, off_y); Ui::display.print("Mode (Hz):"); Ui::display.setCursor(off_x2, off_y); if (region == 3) Ui::display.print("50 125 250"); else Ui::display.print("50 100 200"); off_y += 20; // RF Power Ui::display.setCursor(off_x, off_y); Ui::display.print("Power (mW):"); Ui::display.setCursor(off_x2, off_y); Ui::display.print("25 50 100"); off_y += 20; // TLM Rate Ui::display.setCursor(off_x, off_y); Ui::display.print("Telemetry:"); Ui::display.setCursor(off_x2, off_y); Ui::display.print("On Off"); off_y += 20; // Set VTX channel Ui::display.setCursor(off_x, off_y); Ui::display.print("VTX channel:"); Ui::display.setCursor(off_x2, off_y); Ui::display.print("SEND"); off_y += 20; /*************************************/ // Print current settings off_y += 20; Ui::display.setCursor(off_x, off_y); Ui::display.print("== Current settings =="); off_y += 12; off_x = 40; off_x2 = off_x + 100; Ui::display.setCursor(off_x, off_y); Ui::display.print("Frequency:"); Ui::display.setCursor(off_x2, off_y); switch (expresslrs_params_get_region()) { case 0: Ui::display.print("915MHz"); break; case 1: Ui::display.print("868MHz"); break; case 2: Ui::display.print("433MHz"); break; case 3: Ui::display.print("2.4GHz"); break; default: Ui::display.print("---"); break; }; off_y += 10; Ui::display.setCursor(off_x, off_y); Ui::display.print("Rate:"); Ui::display.setCursor(off_x2, off_y); switch (expresslrs_params_get_rate()) { case 0: Ui::display.print((region == 3) ? "250Hz" : "200Hz"); break; case 1: Ui::display.print((region == 3) ? "125Hz" : "100Hz"); break; case 2: Ui::display.print("50Hz"); break; default: Ui::display.print("---"); break; }; off_y += 10; Ui::display.setCursor(off_x, off_y); Ui::display.print("Power:"); Ui::display.setCursor(off_x2, off_y); switch (expresslrs_params_get_power()) { case 0: Ui::display.print("dynamic"); break; case 1: Ui::display.print("10mW"); break; case 2: Ui::display.print("25mW"); break; case 3: Ui::display.print("50mW"); break; case 4: Ui::display.print("100mW"); break; case 5: Ui::display.print("250mW"); break; case 6: Ui::display.print("500mW"); break; case 7: Ui::display.print("1000mW"); break; case 8: Ui::display.print("2000mW"); break; default: Ui::display.print("---"); break; }; off_y += 10; Ui::display.setCursor(off_x, off_y); Ui::display.print("Telemetry:"); Ui::display.setCursor(off_x2, off_y); switch (expresslrs_params_get_tlm()) { case 0: Ui::display.print("OFF"); break; case 1: Ui::display.print("1/128"); break; case 2: Ui::display.print("1/64"); break; case 3: Ui::display.print("1/32"); break; case 4: Ui::display.print("1/16"); break; case 5: Ui::display.print("1/8"); break; case 6: Ui::display.print("1/4"); break; case 7: Ui::display.print("1/2"); break; default: Ui::display.print("---"); break; }; // Draw Mode box if (cursor_y > 16 && cursor_y < 31) { if ( // 50 cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3)) { Ui::display.rect(20 + 17 * 8 - 4, 16, 23, 15, 100); if (tapAction) expresslrs_rate_send(ExLRS_50Hz); } else if ( // 100 cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 26 * 8 + 3)) { Ui::display.rect(20 + 23 * 8 - 4, 16, 31, 15, 100); if (tapAction) expresslrs_rate_send(ExLRS_100Hz); } else if ( // 200 cursor_x > (20 + 30 * 8 - 4) && cursor_x < (20 + 33 * 8 + 3)) { Ui::display.rect(20 + 30 * 8 - 4, 16, 31, 15, 100); if (tapAction) expresslrs_rate_send(ExLRS_200Hz); } } // Draw RF Power box else if (cursor_y > 36 && cursor_y < 51) { if ( // 25mW cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3)) { Ui::display.rect(20 + 17 * 8 - 4, 36, 23, 15, 100); if (tapAction) expresslrs_power_send(ExLRS_PWR_25mW); } else if ( // 50mW cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 25 * 8 + 3)) { Ui::display.rect(20 + 23 * 8 - 4, 36, 23, 15, 100); if (tapAction) expresslrs_power_send(ExLRS_PWR_50mW); } else if ( // 100mW cursor_x > (20 + 30 * 8 - 4) && cursor_x < (20 + 33 * 8 + 3)) { Ui::display.rect(20 + 30 * 8 - 4, 36, 31, 15, 100); if (tapAction) expresslrs_power_send(ExLRS_PWR_100mW); } } // Draw TLM box else if (cursor_y > 56 && cursor_y < 71) { if ( // On cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3)) { Ui::display.rect(20 + 17 * 8 - 4, 56, 23, 15, 100); if (tapAction) expresslrs_tlm_send(ExLRS_TLM_ON); } else if ( // Off cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 26 * 8 + 3)) { Ui::display.rect(20 + 23 * 8 - 4, 56, 31, 15, 100); if (tapAction) expresslrs_tlm_send(ExLRS_TLM_OFF); } } // Draw VTX SEND box else if (cursor_y > 76 && cursor_y < 91) { if (cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 21 * 8 + 3)) { Ui::display.rect((20 + 17 * 8 - 4), 76, (4 + 4 * 8 + 3), 15, 100); if (tapAction) expresslrs_vtx_freq_send(Channels::getFrequency(Receiver::activeChannel)); } } }
7,388
2,974
// Copyright 2018 Zeyu Zhong // Lincese(MIT) // Author: Zeyu Zhong // Date: 2018.5.7 #include "../src/basicSfM.h" int main(int argc, char *argv[]) { basicSfM sfm; sfm.algorithm_sparse3d(); return 0; }
215
103
#include "StdAfx.h" #include "Grabber.h" using namespace WebinariaApplication::WebinariaLogical; ////////////////////////////////////////////////////////////////////////// // Public methods // ////////////////////////////////////////////////////////////////////////// // Default constructor CGrabber::CGrabber(HWND hWnd): AllocateBytes(0), IsCapturing(false), File(NULL), hMainWnd(hWnd), pME(NULL), pDF(NULL), pVW(NULL), pRender(NULL), pSink(NULL), ////////////////////// ghDevNotify(0), gpUnregisterDeviceNotification(0), gpRegisterDeviceNotification(0), g_dwGraphRegister(0) ////////////////////// { /*File = new wchar_t[10]; WIN32_FIND_DATA fd; HANDLE hr = FindFirstFile("tmp",&fd); FindClose(hr); if (hr == INVALID_HANDLE_VALUE) CreateDirectory("tmp",NULL); else { hr = FindFirstFile("tmp\\~.avi",&fd); if ( hr != INVALID_HANDLE_VALUE) DeleteFile("tmp\\~.avi"); FindClose(hr); } wcscpy(File, L"tmp\\~.avi");*/ //\\tmp // Register for device add/remove notifications DEV_BROADCAST_DEVICEINTERFACE filterData; ZeroMemory(&filterData, sizeof(DEV_BROADCAST_DEVICEINTERFACE)); filterData.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); filterData.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; filterData.dbcc_classguid = AM_KSCATEGORY_CAPTURE; gpUnregisterDeviceNotification = NULL; gpRegisterDeviceNotification = NULL; // dynload device removal APIs { HMODULE hmodUser = GetModuleHandle(TEXT("user32.dll")); //ASSERT(hmodUser); // we link to user32 gpUnregisterDeviceNotification = (PUnregisterDeviceNotification) GetProcAddress(hmodUser, "UnregisterDeviceNotification"); // m_pRegisterDeviceNotification is prototyped differently in unicode gpRegisterDeviceNotification = (PRegisterDeviceNotification) GetProcAddress(hmodUser, #ifdef UNICODE "RegisterDeviceNotificationW" #else "RegisterDeviceNotificationA" #endif ); // failures expected on older platforms. /*ASSERT(gpRegisterDeviceNotification && gpUnregisterDeviceNotification || !gpRegisterDeviceNotification && !gpUnregisterDeviceNotification);*/ } ghDevNotify = NULL; if(gpRegisterDeviceNotification) { ghDevNotify = gpRegisterDeviceNotification(hMainWnd, &filterData, DEVICE_NOTIFY_WINDOW_HANDLE); //ASSERT(ghDevNotify != NULL); } } // Virtual destructor CGrabber::~CGrabber(void) { if (File != NULL) delete[] File; IsCapturing = false; AllocateBytes = 0; SAFE_RELEASE(pSink); SAFE_RELEASE(pME); SAFE_RELEASE(pDF); SAFE_RELEASE(pVW); SAFE_RELEASE(pRender); } // Get interface for provide media events IMediaEventEx * CGrabber::GetMediaEventInterface() { return pME; } // Return full path to current file for captured data wchar_t * CGrabber::GetSelectFile() const { wchar_t * tmp = new wchar_t[wcslen(File)+1]; wcscpy(tmp,File); return tmp; } // Update and retrive current capturing file size unsigned long long CGrabber::GetCapFileSize() { HANDLE hFile = CreateFileW( File, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ); if(hFile == INVALID_HANDLE_VALUE) { return 0; } unsigned long SizeHigh; unsigned long SizeLow = GetFileSize(hFile, &SizeHigh); CapFileSize = SizeLow + ((unsigned long long)SizeHigh << 32); if(!CloseHandle(hFile)) { CapFileSize = 0; } return CapFileSize; } // Function to Measure Available Disk Space unsigned long long CGrabber::GetFreeDiskSpaceInBytes() { DWORD dwFreeClusters, dwBytesPerSector, dwSectorsPerCluster, dwClusters; wchar_t RootName[MAX_PATH]; LPWSTR ptmp=0; // Required argument ULARGE_INTEGER ulA, ulB, ulFreeBytes; // Need to find path for root directory on drive containing this file. GetFullPathNameW( File, NUMELMS(RootName), RootName, &ptmp); // Truncate this to the name of the root directory if(RootName[0] == '\\' && RootName[1] == '\\') { // Path begins with \\server\share\path so skip the first three backslashes ptmp = &RootName[2]; while(*ptmp && (*ptmp != '\\')) { ptmp++; } if(*ptmp) { // Advance past the third backslash ptmp++; } } else { // Path must be drv:\path ptmp = RootName; } // Find next backslash and put a null after it while(*ptmp && (*ptmp != '\\')) { ptmp++; } // Found a backslash ? if(*ptmp) { // Skip it and insert null ptmp++; *ptmp = '\0'; } // The only real way of finding out free disk space is calling // GetDiskFreeSpaceExA, but it doesn't exist on Win95 HINSTANCE h = LoadLibrary(TEXT("kernel32.dll\0")); if(h) { typedef BOOL(WINAPI *ExtFunc)(LPCWSTR RootName, PULARGE_INTEGER pulA, PULARGE_INTEGER pulB, PULARGE_INTEGER pulFreeBytes); ExtFunc pfnGetDiskFreeSpaceExW = (ExtFunc)GetProcAddress(h, "GetDiskFreeSpaceExW"); FreeLibrary(h); if(pfnGetDiskFreeSpaceExW) { if(!pfnGetDiskFreeSpaceExW(RootName, &ulA, &ulB, &ulFreeBytes)) return -1; else return (ulFreeBytes.QuadPart); } } if(!GetDiskFreeSpaceW(RootName, &dwSectorsPerCluster, &dwBytesPerSector, &dwFreeClusters, &dwClusters)) return (-1); else return(dwSectorsPerCluster * dwBytesPerSector * dwFreeClusters); } // Function for select file for saving captured information bool CGrabber::SelectFile() { USES_CONVERSION; if(OpenFileDialog()) { OFSTRUCT os; // We have a capture file name // If this is a new file, then invite the user to allocate some space if(OpenFile(W2A(File), &os, OF_EXIST) == HFILE_ERROR) { //nothing } } else return false; if(pSink) { HRESULT hr = pSink->SetFileName(File, NULL); } return true; }
5,703
2,335
/* Copyright 2018, OpenSoft Inc. * 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 OpenSoft Inc. 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 "proofnetwork/user.h" #include "proofnetwork/user_p.h" using namespace Proof; User::User(const QString &userName) : User(*new UserPrivate(userName)) {} User::User(Proof::UserPrivate &dd) : NetworkDataEntity(dd) {} QString User::userName() const { Q_D_CONST(User); return d->userName; } QString User::fullName() const { Q_D_CONST(User); return d->fullName; } QString User::email() const { Q_D_CONST(User); return d->email; } UserQmlWrapper *User::toQmlWrapper(QObject *parent) const { UserSP castedSelf = castedSelfPtr<User>(); Q_ASSERT(castedSelf); return new UserQmlWrapper(castedSelf, parent); } UserSP User::create(const QString &userName) { UserSP result(new User(userName)); initSelfWeakPtr(result); return result; } UserPrivate::UserPrivate(const QString &userName) : userName(userName) { setDirty(!userName.isEmpty()); } void User::updateSelf(const NetworkDataEntitySP &other) { Q_D(User); UserSP castedOther = qSharedPointerCast<User>(other); d->setUserName(castedOther->userName()); d->setFullName(castedOther->fullName()); d->setEmail(castedOther->email()); NetworkDataEntity::updateSelf(other); } void UserPrivate::setUserName(const QString &arg) { Q_Q(User); if (userName != arg) { userName = arg; emit q->userNameChanged(arg); } } void UserPrivate::setFullName(const QString &arg) { Q_Q(User); if (fullName != arg) { fullName = arg; emit q->fullNameChanged(arg); } } void UserPrivate::setEmail(const QString &arg) { Q_Q(User); if (email != arg) { email = arg; emit q->emailChanged(arg); } }
3,236
1,115
#pragma once #include "type_safe/strong_typedef.hpp" #include <cstddef> namespace kernel { struct StackSize_t : type_safe::strong_typedef<StackSize_t, std::size_t> , type_safe::strong_typedef_op::addition<StackSize_t> , type_safe::strong_typedef_op::subtraction<StackSize_t> { using type_safe::strong_typedef<StackSize_t, std::size_t>::strong_typedef; }; }
416
157
/*********************************************************************** * AUTHOR: <Doublecross> * FILE: GLOpenAssetImportMesh.cpp * DATE: Mon Jun 11 16:21:07 2018 * DESCR: ***********************************************************************/ #include "OpenGL/Shapes/GLOpenAssetImportMesh.h" #include <assert.h> #include "gl/include/glew.h" #include "gl/gl.h" #include <windows.h> GLOpenAssetImportMesh::MeshEntry::MeshEntry() { vbo = INVALID_OGL_VALUE; ibo = INVALID_OGL_VALUE; NumIndices = 0; MaterialIndex = INVALID_MATERIAL; }; GLOpenAssetImportMesh::MeshEntry::~MeshEntry() { if (vbo != INVALID_OGL_VALUE) glDeleteBuffers(1, &vbo); if (ibo != INVALID_OGL_VALUE) glDeleteBuffers(1, &ibo); } void GLOpenAssetImportMesh::MeshEntry::Init(const std::vector<Vertex>& Vertices, const std::vector<unsigned int>& Indices) { NumIndices = Indices.size(); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * NumIndices, &Indices[0], GL_STATIC_DRAW); } /* * Method: GLOpenAssetImportMesh::Load * Params: const std::string &Filename * Returns: bool * Effects: */ bool GLOpenAssetImportMesh::Load(const std::string &Filename) { // Release the previously loaded mesh (if it exists) Release(); bool Ret = false; Assimp::Importer Importer; const aiScene* pScene = Importer.ReadFile(Filename.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (pScene) { Ret = InitFromScene(pScene, Filename); } else { MessageBox(NULL, Importer.GetErrorString(), "Error loading mesh model", MB_ICONHAND); } return Ret; } std::shared_ptr<ITexture> GLOpenAssetImportMesh::GetTexture() { if (1 < m_Textures.size() && m_Textures[1]) return m_Textures[1]; return nullptr; } void GLOpenAssetImportMesh::Clear() { //for (unsigned int i = 0 ; i < m_Textures.size() ; i++) { // SAFE_DELETE(m_Textures[i]); //} glDeleteVertexArrays(1, &m_vao); m_Entries.clear(); m_Textures.clear(); } /* * Method: GLOpenAssetImportMesh::Create * Params: * Returns: void * Effects: */ void GLOpenAssetImportMesh::Create() { } /* * Method: GLOpenAssetImportMesh::Render * Params: * Returns: void * Effects: */ void GLOpenAssetImportMesh::Render() { glBindVertexArray(m_vao); for (unsigned int i = 0 ; i < m_Entries.size() ; i++) { glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, m_Entries[i].vbo); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)32); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Entries[i].ibo); glDrawElements(GL_TRIANGLES, m_Entries[i].NumIndices, GL_UNSIGNED_INT, 0); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); } } /* * Method: GLOpenAssetImportMesh::Release * Params: * Returns: void * Effects: */ void GLOpenAssetImportMesh::Release() { if( m_vao != 0) { glDeleteVertexArrays(1, &m_vao); m_vao = 0; } } bool GLOpenAssetImportMesh::InitFromScene(const aiScene* pScene, const std::string& Filename) { m_Entries.resize(pScene->mNumMeshes); m_Textures.resize(pScene->mNumMaterials); glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); // Initialize the meshes in the scene one by one for (unsigned int i = 0 ; i < m_Entries.size() ; i++) { const aiMesh* paiMesh = pScene->mMeshes[i]; InitMesh(i, paiMesh); } return InitMaterials(pScene, Filename); } void GLOpenAssetImportMesh::InitMesh(unsigned int Index, const aiMesh* paiMesh) { m_Entries[Index].MaterialIndex = paiMesh->mMaterialIndex; std::vector<Vertex> Vertices; std::vector<unsigned int> Indices; const aiVector3D Zero3D(0.0f, 0.0f, 0.0f); for (unsigned int i = 0 ; i < paiMesh->mNumVertices ; i++) { const aiVector3D* pPos = &(paiMesh->mVertices[i]); const aiVector3D* pNormal = &(paiMesh->mNormals[i]); const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D; const aiVector3D* pTangent = paiMesh->HasTangentsAndBitangents() ? &(paiMesh->mTangents[i]) : &Zero3D; Vertex v(glm::vec3(pPos->x, pPos->y, pPos->z), glm::vec2(pTexCoord->x, 1.0f-pTexCoord->y), glm::vec3(pNormal->x, pNormal->y, pNormal->z), glm::vec3(pTangent->x, pTangent->y, pTangent->z) ); Vertices.push_back(v); } for (unsigned int i = 0 ; i < paiMesh->mNumFaces ; i++) { const aiFace& Face = paiMesh->mFaces[i]; assert(Face.mNumIndices == 3); Indices.push_back(Face.mIndices[0]); Indices.push_back(Face.mIndices[1]); Indices.push_back(Face.mIndices[2]); } m_Entries[Index].Init(Vertices, Indices); } bool GLOpenAssetImportMesh::InitMaterials(const aiScene* pScene, const std::string& Filename) { // Extract the directory part from the file name std::string::size_type SlashIndex = Filename.find_last_of("\\"); std::string Dir; if (SlashIndex == std::string::npos) { Dir = "."; } else if (SlashIndex == 0) { Dir = "\\"; } else { Dir = Filename.substr(0, SlashIndex); } bool Ret = true; // Initialize the materials for (unsigned int i = 0 ; i < pScene->mNumMaterials ; i++) { const aiMaterial* pMaterial = pScene->mMaterials[i]; m_Textures[i] = NULL; if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString Path; if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) { std::string FullPath = Dir + "\\" + Path.data; m_Textures[i] = std::make_shared<GLTexture>(); if (!m_Textures[i]->Load(FullPath, true)) { MessageBox(NULL, FullPath.c_str(), "Error loading mesh texture", MB_ICONHAND); // delete m_Textures[i]; m_Textures[i] = NULL; Ret = false; } else { printf("Loaded texture '%s'\n", FullPath.c_str()); } } } // Load a single colour texture matching the diffuse colour if no texture added if (!m_Textures[i]) { aiColor3D color (0.f,0.f,0.f); pMaterial->Get(AI_MATKEY_COLOR_DIFFUSE,color); m_Textures[i] = std::make_shared<GLTexture>(); char data[3]; data[0] = (char) (color[2]*255); data[1] = (char) (color[1]*255); data[2] = (char) (color[0]*255); m_Textures[i]->CreateFromData(data, 1, 1, 24, false); } } return Ret; }
7,228
2,829
/** * project DESCARTES * * @file LaplacianMatrixDefinition.hxx * * @author Laurent PLAGNE * @date june 2004 - january 2005 * * @par Modifications * - author date object * * (c) Copyright EDF R&D - CEA 2001-2005 */ #ifndef __LEGOLAS_LAPLACIANMATRIXDEFINITION_HXX__ #define __LEGOLAS_LAPLACIANMATRIXDEFINITION_HXX__ #include "Legolas/Matrix/MatrixStructures/MatrixStructureTags.hxx" #include "Legolas/Matrix/Helper/DefaultMatrixDefinition.hxx" class LaplacianMatrixDefinition : public Legolas::DefaultMatrixDefinition<double> { public: // Types that must be defined to model the MATRIX_DEFINITION concept typedef Legolas::TriDiagonal MatrixStructure; typedef double RealType; typedef double GetElement; typedef Legolas::MatrixShape<1> Data; // 3 static functions to be defined to model the TRIDIAGONAL_MATRIX_DEFINITION concept static inline GetElement diagonalGetElement( int i , const Data & data) { return -2.0;} static inline GetElement upperDiagonalGetElement( int i , const Data & data) { return 1.0;} static inline GetElement lowerDiagonalGetElement( int i , const Data & data) { return 1.0;} }; #endif
1,229
425
const int kN = 10000 + 5; const int kM = 100000 + 5; int dfn[kN],low[kN],head[kN],etot,btot,n,m,nq,belong[kN]; bool is_cut[kN],visited[kN]; std::stack<int> stack; struct Edge { int v,next,belong; bool visited,is_cut; }g[kM<<1]; std::vector<int> graph[kN+kM]; void add_edge(int u,int v) { g[etot].belong = -1; g[etot].visited = g[etot].is_cut = false; g[etot].v = v; g[etot].next = head[u]; head[u] = etot ++; } void tarjan(int u,int root,int tim) { dfn[u] = low[u] = tim; visited[u] = true; int child_count = 0; for (int i = head[u]; i != -1; i = g[i].next) { Edge &e = g[i]; if (e.visited) continue; stack.push(i); g[i].visited = g[i^1].visited = true; if (visited[e.v]) { low[u] = std::min(low[u],dfn[e.v]); continue; } tarjan(e.v,root,tim+1); g[i].is_cut = g[i^1].is_cut = (low[e.v]>dfn[u] || g[i].is_cut); if (u!=root) is_cut[u] |= (low[e.v]>=dfn[u]); if (low[e.v]>=dfn[u] || u==root) { while (true) { int id = stack.top(); stack.pop(); g[id].belong = g[id^1].belong = btot; if (id==i) break; } btot ++; } low[u] = std::min(low[e.v],low[u]); child_count ++; } if (u==root && child_count>1) is_cut[u] = true; } void bcc() { for (int i = 0; i < n; ++ i) { dfn[i] = 0; is_cut[i] = false; visited[i] = false; } btot = 0; for (int i = 0; i < n; ++ i) { if (!visited[i]) { tarjan(i,i,1); } } } void build() { std::fill(graph,graph+n+m,std::vector<int>()); for (int u = 0; u < n; ++ u) { if (is_cut[u] || head[u]==-1) { int id = btot ++; belong[u] = id; for (int i = head[u]; i != -1; i = g[i].next) { Edge &e = g[i]; int v = e.belong; graph[id].push_back(v); graph[v].push_back(id); } } } for (int u = 0; u < btot; ++ u) { std::sort(graph[u].begin(),graph[u].end()); graph[u].erase(std::unique(graph[u].begin(),graph[u].end()),graph[u].end()); } for (int i = 0; i < m; ++ i) { int u = g[i<<1].v; int v = g[i<<1|1].v; if (!is_cut[u]) belong[u] = g[i<<1].belong; if (!is_cut[v]) belong[v] = g[i<<1].belong; } } int main() { while (scanf("%d%d",&n,&m)==2) { std::fill(head,head+n,-1); etot = 0; for (int i = 0; i < m; ++ i) { int a,b; scanf("%d%d",&a,&b); a --; b --; add_edge(a,b); add_edge(b,a); } bcc(); build(); } return 0; }
2,446
1,196
// Copyright 2018 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 "chromeos/dbus/cryptohome/account_identifier_operators.h" namespace cryptohome { bool operator<(const AccountIdentifier& l, const AccountIdentifier& r) { return l.account_id() < r.account_id(); } bool operator==(const AccountIdentifier& l, const AccountIdentifier& r) { return l.account_id() == r.account_id(); } } // namespace cryptohome
523
167
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2016 Mark Samman <mark.samman@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "rsa.h" RSA::RSA() { mpz_init(n); mpz_init2(d, 1024); } RSA::~RSA() { mpz_clear(n); mpz_clear(d); } void RSA::setKey(const char* pString, const char* qString) { mpz_t p, q, e; mpz_init2(p, 1024); mpz_init2(q, 1024); mpz_init(e); mpz_set_str(p, pString, 10); mpz_set_str(q, qString, 10); // e = 65537 mpz_set_ui(e, 65537); // n = p * q mpz_mul(n, p, q); mpz_t p_1, q_1, pq_1; mpz_init2(p_1, 1024); mpz_init2(q_1, 1024); mpz_init2(pq_1, 1024); mpz_sub_ui(p_1, p, 1); mpz_sub_ui(q_1, q, 1); // pq_1 = (p -1)(q - 1) mpz_mul(pq_1, p_1, q_1); // d = e^-1 mod (p - 1)(q - 1) mpz_invert(d, e, pq_1); mpz_clear(p_1); mpz_clear(q_1); mpz_clear(pq_1); mpz_clear(p); mpz_clear(q); mpz_clear(e); } void RSA::decrypt(char* msg) const { mpz_t c, m; mpz_init2(c, 1024); mpz_init2(m, 1024); mpz_import(c, 128, 1, 1, 0, 0, msg); // m = c^d mod n mpz_powm(m, c, d, n); size_t count = (mpz_sizeinbase(m, 2) + 7) / 8; memset(msg, 0, 128 - count); mpz_export(msg + (128 - count), nullptr, 1, 1, 0, 0, m); mpz_clear(c); mpz_clear(m); }
1,962
981
/* $Id: time-posix.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */ /** @file * IPRT - Time, POSIX. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #define LOG_GROUP RTLOGGROUP_TIME #define RTTIME_INCL_TIMEVAL #include <sys/time.h> #include <time.h> #include <iprt/time.h> #include "internal/time.h" DECLINLINE(uint64_t) rtTimeGetSystemNanoTS(void) { #if defined(CLOCK_MONOTONIC) && !defined(RT_OS_L4) && !defined(RT_OS_OS2) /* check monotonic clock first. */ static bool s_fMonoClock = true; if (s_fMonoClock) { struct timespec ts; if (!clock_gettime(CLOCK_MONOTONIC, &ts)) return (uint64_t)ts.tv_sec * RT_NS_1SEC_64 + ts.tv_nsec; s_fMonoClock = false; } #endif /* fallback to gettimeofday(). */ struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * RT_NS_1SEC_64 + (uint64_t)(tv.tv_usec * RT_NS_1US); } /** * Gets the current nanosecond timestamp. * * This differs from RTTimeNanoTS in that it will use system APIs and not do any * resolution or performance optimizations. * * @returns nanosecond timestamp. */ RTDECL(uint64_t) RTTimeSystemNanoTS(void) { return rtTimeGetSystemNanoTS(); } /** * Gets the current millisecond timestamp. * * This differs from RTTimeNanoTS in that it will use system APIs and not do any * resolution or performance optimizations. * * @returns millisecond timestamp. */ RTDECL(uint64_t) RTTimeSystemMilliTS(void) { return rtTimeGetSystemNanoTS() / RT_NS_1MS; }
2,886
911
#include "StdAfx.h" namespace ui { ListBox::ListBox(Layout* pLayout) : ScrollableBox(pLayout), m_bScrollSelect(false), m_iCurSel(-1), m_pCompareFunc(nullptr), m_pCompareData(NULL), m_bSelNextWhenRemoveActive(true) { } void ListBox::SetAttribute(LPCTSTR szName, LPCTSTR szValue) { CUiString strName(szName); CUiString strValue(szValue); if( strName == _T("scrollselect") ) { SetScrollSelect(strValue == _T("true")); } else { ScrollableBox::SetAttribute(szName, szValue); } } void ListBox::HandleMessage(EventArgs& event) { if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) { if (m_pParent != NULL) m_pParent->HandleMessageTemplate(event); else ScrollableBox::HandleMessage(event); return; } switch (event.Type) { case kEventMouseButtonDown: case kEventMouseButtonUp: return; case kEventKeyDown: switch (event.chKey) { case VK_UP: SelectItem(FindSelectable(m_iCurSel - 1, false), true); return; case VK_DOWN: SelectItem(FindSelectable(m_iCurSel + 1, true), true); return; case VK_HOME: SelectItem(FindSelectable(0, false), true); return; case VK_END: SelectItem(FindSelectable(GetCount() - 1, true), true); return; } break; case kEventMouseScrollWheel: { int detaValue = event.wParam; if (detaValue > 0) { if (m_bScrollSelect) { SelectItem(FindSelectable(m_iCurSel - 1, false), true); return; } break; } else { if (m_bScrollSelect) { SelectItem(FindSelectable(m_iCurSel + 1, true), true); return; } break; } } break; } ScrollableBox::HandleMessage(event); } void ListBox::HandleMessageTemplate(EventArgs& event) { ScrollableBox::HandleMessageTemplate(event); } int ListBox::GetCurSel() const { return m_iCurSel; } void ListBox::SelectNextWhenActiveRemoved(bool bSelectNextItem) { m_bSelNextWhenRemoveActive = bSelectNextItem; } bool ListBox::SelectItem(int iIndex, bool bTakeFocus, bool bTrigger) { //if( iIndex == m_iCurSel ) return true; int iOldSel = m_iCurSel; // We should first unselect the currently selected item if (m_iCurSel >= 0) { Control* pControl = GetItemAt(m_iCurSel); if (pControl != NULL) { ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if (pListItem != NULL) pListItem->OptionTemplate<Box>::Selected(false, bTrigger); } m_iCurSel = -1; } if (iIndex < 0) return false; Control* pControl = GetItemAt(iIndex); if (pControl == NULL) return false; if (!pControl->IsVisible()) return false; if (!pControl->IsEnabled()) return false; ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if (pListItem == NULL) return false; m_iCurSel = iIndex; pListItem->OptionTemplate<Box>::Selected(true, bTrigger); if (GetItemAt(m_iCurSel)) { CUiRect rcItem = GetItemAt(m_iCurSel)->GetPos(); EnsureVisible(rcItem); } if (bTakeFocus) pControl->SetFocus(); if (m_pWindow != NULL && bTrigger) { m_pWindow->SendNotify(this, kEventSelect, m_iCurSel, iOldSel); } return true; } void ListBox::EnsureVisible(const CUiRect& rcItem) { CUiRect rcNewItem = rcItem; rcNewItem.Offset(-GetScrollPos().cx, -GetScrollPos().cy); CUiRect rcList = GetPos(); CUiRect rcListInset = m_pLayout->GetPadding(); rcList.left += rcListInset.left; rcList.top += rcListInset.top; rcList.right -= rcListInset.right; rcList.bottom -= rcListInset.bottom; ScrollBar* pHorizontalScrollBar = GetHorizontalScrollBar(); if (pHorizontalScrollBar && pHorizontalScrollBar->IsVisible()) rcList.bottom -= pHorizontalScrollBar->GetFixedHeight(); if (rcNewItem.left >= rcList.left && rcNewItem.top >= rcList.top && rcNewItem.right <= rcList.right && rcNewItem.bottom <= rcList.bottom) { if (m_pParent && dynamic_cast<ListContainerElement*>(m_pParent) != NULL) { dynamic_cast<ListContainerElement*>(m_pParent)->GetOwner()->EnsureVisible(rcNewItem); } return; } int dx = 0; if (rcNewItem.left < rcList.left) dx = rcNewItem.left - rcList.left; if (rcNewItem.right > rcList.right) dx = rcNewItem.right - rcList.right; int dy = 0; if (rcNewItem.top < rcList.top) dy = rcNewItem.top - rcList.top; if (rcNewItem.bottom > rcList.bottom) dy = rcNewItem.bottom - rcList.bottom; CUiSize sz = GetScrollPos(); SetScrollPos(CUiSize(sz.cx + dx, sz.cy + dy)); } void ListBox::StopScroll() { m_scrollAnimation.Reset(); } bool ListBox::ButtonDown(EventArgs& msg) { bool ret = __super::ButtonDown(msg); StopScroll(); return ret; } bool ListBox::ScrollItemToTop(LPCTSTR strItemName) { for (auto it = m_items.begin(); it != m_items.end(); it++) { if ((*it)->GetName() == strItemName) { if (GetScrollRange().cy != 0) { CUiSize scrollPos = GetScrollPos(); scrollPos.cy = (*it)->GetPos().top - m_pLayout->GetInternalPos().top; if (scrollPos.cy >= 0) { SetScrollPos(scrollPos); return true; } else { return false; } } else { return false; } } } return false; } Control* ListBox::GetTopItem() { int listTop = GetPos().top + m_pLayout->GetPadding().top + GetScrollPos().cy; for (auto it = m_items.begin(); it != m_items.end(); it++) { if ((*it)->IsVisible() && !(*it)->IsFloat() && (*it)->GetPos().bottom >= listTop) { return (*it); } } return nullptr; } bool ListBox::SetItemIndex(Control* pControl, std::size_t iIndex) { int iOrginIndex = GetItemIndex(pControl); if( iOrginIndex == -1 ) return false; if( iOrginIndex == (int)iIndex ) return true; ListContainerElement* pSelectedListItem = NULL; if( m_iCurSel >= 0 ) pSelectedListItem = dynamic_cast<ListContainerElement*>(GetItemAt(m_iCurSel)); if( !ScrollableBox::SetItemIndex(pControl, iIndex) ) return false; std::size_t iMinIndex = min((std::size_t)iOrginIndex, iIndex); std::size_t iMaxIndex = max((std::size_t)iOrginIndex, iIndex); for(std::size_t i = iMinIndex; i < iMaxIndex + 1; ++i) { Control* pItemControl = GetItemAt(i); ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pItemControl); if( pListItem != NULL ) { pListItem->SetIndex((int)i); } } if( m_iCurSel >= 0 && pSelectedListItem != NULL ) m_iCurSel = pSelectedListItem->GetIndex(); return true; } void ListBox::Previous() { if (m_iCurSel > 0) { SelectItem(m_iCurSel - 1); } } void ListBox::Next() { int count = GetCount(); if (m_iCurSel < count - 1) { SelectItem(m_iCurSel + 1); } } void ListBox::ActiveItem() { if (m_iCurSel >= 0) { ListContainerElement* item = dynamic_cast<ListContainerElement*>( GetItemAt(m_iCurSel) ); item->InvokeDoubleClickEvent(); } } bool ListBox::Add(Control* pControl) { // Override the Add() method so we can add items specifically to // the intended widgets. Headers are assumed to be // answer the correct interface so we can add multiple list headers. // The list items should know about us ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if( pListItem != NULL ) { pListItem->SetOwner(this); pListItem->SetIndex(GetCount()); } return ScrollableBox::Add(pControl); } bool ListBox::AddAt(Control* pControl, int iIndex) { // Override the AddAt() method so we can add items specifically to // the intended widgets. Headers and are assumed to be // answer the correct interface so we can add multiple list headers. if (!ScrollableBox::AddAt(pControl, iIndex)) return false; // The list items should know about us ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl); if( pListItem != NULL ) { pListItem->SetOwner(this); pListItem->SetIndex(iIndex); } for(int i = iIndex + 1; i < GetCount(); ++i) { Control* p = GetItemAt(i); pListItem = dynamic_cast<ListContainerElement*>(p); if( pListItem != NULL ) { pListItem->SetIndex(i); } } if( m_iCurSel >= iIndex ) m_iCurSel += 1; return true; } bool ListBox::Remove(Control* pControl) { int iIndex = GetItemIndex(pControl); if (iIndex == -1) return false; return RemoveAt(iIndex); } bool ListBox::RemoveAt(int iIndex) { if (!ScrollableBox::RemoveAt(iIndex)) return false; for(int i = iIndex; i < GetCount(); ++i) { Control* p = GetItemAt(i); ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(p); if( pListItem != NULL ) pListItem->SetIndex(i); } if( iIndex == m_iCurSel && m_iCurSel >= 0 ) { if (m_bSelNextWhenRemoveActive) SelectItem(FindSelectable(m_iCurSel--, false)); else m_iCurSel = -1; } else if( iIndex < m_iCurSel ) m_iCurSel -= 1; return true; } void ListBox::RemoveAll() { m_iCurSel = -1; ScrollableBox::RemoveAll(); } bool ListBox::SortItems(PULVCompareFunc pfnCompare, UINT_PTR dwData) { if (!pfnCompare) return false; if (m_items.size() == 0) { return true; } m_pCompareFunc = pfnCompare; m_pCompareData = dwData; qsort_s(&(*m_items.begin()), m_items.size(), sizeof(Control*), ListBox::ItemComareFunc, this); ListContainerElement *pItem = NULL; for (int i = 0; i < (int)m_items.size(); ++i) { pItem = dynamic_cast<ListContainerElement*>(static_cast<Control*>(m_items[i])); if (pItem) { pItem->SetIndex(i); pItem->Selected(false, true); } } SelectItem(-1); SetPos(GetPos()); Invalidate(); return true; } int __cdecl ListBox::ItemComareFunc(void *pvlocale, const void *item1, const void *item2) { ListBox *pThis = (ListBox*)pvlocale; if (!pThis || !item1 || !item2) return 0; return pThis->ItemComareFunc(item1, item2); } int __cdecl ListBox::ItemComareFunc(const void *item1, const void *item2) { Control *pControl1 = *(Control**)item1; Control *pControl2 = *(Control**)item2; return m_pCompareFunc((UINT_PTR)pControl1, (UINT_PTR)pControl2, m_pCompareData); } bool ListBox::GetScrollSelect() { return m_bScrollSelect; } void ListBox::SetScrollSelect(bool bScrollSelect) { m_bScrollSelect = bScrollSelect; } ///////////////////////////////////////////////////////////////////////////////////// // // ListContainerElement::ListContainerElement() : m_iIndex(-1), m_pOwner(nullptr) { m_uTextStyle = DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS | DT_NOCLIP | DT_SINGLELINE; SetReceivePointerMsg(false); } void ListContainerElement::SetVisible(bool bVisible) { __super::SetVisible(bVisible); if (!IsVisible() && m_bSelected) { m_bSelected = false; if (m_pOwner != NULL) m_pOwner->SelectItem(-1); } } void ListContainerElement::Selected(bool bSelected, bool trigger) { if (!IsEnabled()) return; if (bSelected && m_pOwner != NULL) m_pOwner->SelectItem(m_iIndex, false, trigger); } void ListContainerElement::HandleMessage(EventArgs& event) { if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) { if (m_pOwner != NULL) m_pOwner->HandleMessageTemplate(event); else Box::HandleMessage(event); return; } else if (event.Type == kEventInternalDoubleClick) { if (IsActivatable()) { InvokeDoubleClickEvent(); } return; } else if (event.Type == kEventKeyDown && IsEnabled()) { if (event.chKey == VK_RETURN) { if (IsActivatable()) { if (m_pWindow != NULL) m_pWindow->SendNotify(this, kEventReturn); } return; } } else if (event.Type == kEventInternalMenu && IsEnabled()) { Selected(true, true); m_pWindow->SendNotify(this, kEventMouseMenu); Invalidate(); return; } __super::HandleMessage(event); // An important twist: The list-item will send the event not to its immediate // parent but to the "attached" list. A list may actually embed several components // in its path to the item, but key-presses etc. needs to go to the actual list. //if( m_pOwner != NULL ) m_pOwner->HandleMessage(event); else Control::HandleMessage(event); } IListOwner* ListContainerElement::GetOwner() { return m_pOwner; } void ListContainerElement::SetOwner(IListOwner* pOwner) { m_pOwner = pOwner; } int ListContainerElement::GetIndex() const { return m_iIndex; } void ListContainerElement::SetIndex(int iIndex) { m_iIndex = iIndex; } void ListContainerElement::InvokeDoubleClickEvent() { if( m_pWindow != NULL ) m_pWindow->SendNotify(this, kEventMouseDoubleClick); } } // namespace ui
12,547
4,806
#include <iostream> #include <stack> #include <list> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; TreeNode *convertBiNode(TreeNode *root); void reversion(TreeNode *root); int main() { return 0; } TreeNode *ans = new TreeNode(-1); TreeNode *cur = ans; /** * * @param root * @return */ TreeNode *convertBiNode(TreeNode *root) { reversion(root); return ans->right; } /** * 遍历树结构 * @param root */ void reversion(TreeNode *root) { if (root == NULL) { return; } dfs(root->left); root->left = NULL; cur->right = root; cur = root; dfs(root->right); }
714
273
#include "multiobjects.h" int main(int argc,char** argv){ bool debug=false; MultiImageSampler* pMultiImageSampler=new MultiImageSampler(debug); pMultiImageSampler->initVulkan(); pMultiImageSampler->initWindow(); pMultiImageSampler->prepare(); pMultiImageSampler->renderLoop(); delete pMultiImageSampler; return 1; }
348
115
#include "barcode.h" #include <algorithm> constexpr uchar Barcode::black_color; constexpr uchar Barcode::white_color; constexpr int Barcode::left_guards_size; constexpr int Barcode::middle_guards_size; constexpr int Barcode::right_guards_size; constexpr int Barcode::left_code_size; constexpr int Barcode::right_code_size; constexpr int Barcode::barcode_number_size; constexpr int Barcode::check_sum_coeffs[]; Barcode::Barcode (const cv::Mat * const gray_im) : image (gray_im), max_image_index (gray_im->cols) { if (image->channels () > 1) { barcode_exceptions::not_gray_image_exception notgray_im_ex; throw notgray_im_ex; } decode (); } void Barcode::decode () { for (int row_i = 0; row_i < image->rows; row_i++) { const uchar *test_row = image->ptr (row_i); decode_row (test_row); if (is_correct) return; clear_data (); } return; } void Barcode::decode_row (const uchar * const test_row) { constract_row_structure (test_row); identify_barcode_number (); check_control_number (); } void Barcode::clear_data () { memset (left_guards, 0, sizeof (int) * left_guards_size); memset (left_code, 0, sizeof (int) * left_code_size); memset (middle_guards, 0, sizeof (int) * middle_guards_size); memset (right_code, 0, sizeof (int) * right_code_size); memset (right_guards, 0, sizeof (int) * right_guards_size); memset (barcode_number, 0, sizeof (int) * barcode_number_size); } void Barcode::print_barcode () const { if (!is_correct) return; std::cout << barcode_number[0] << " "; for (int i = 0; i < 6; i++) std::cout << barcode_number[1 + i]; std::cout << " "; for (int i = 0; i < 6; i++) std::cout << barcode_number[7 + i]; std::cout << std::endl; } long long Barcode::get_barcode_number () const { long long ans = 0; long long decimals = 1; for (int i = 0; i < barcode_number_size; i++) { ans += barcode_number[barcode_number_size - 1 - i] * decimals; decimals *= 10; } return ans; } void Barcode::constract_row_structure (const uchar * const test_row) { bool is_left_guards_filled = false; bool is_middle_guards_filled = false; bool is_right_guards_filled = false; bool is_left_code_filled = false; bool is_right_code_filled = false; int left_guards_beg = find_row_structure_part_beg (test_row, 0, black_color); int left_code_beg = constract_row_structure_part (test_row, left_guards_beg, black_color, left_guards_size, left_guards, is_left_guards_filled); int middle_guards_beg = constract_row_structure_part (test_row, left_code_beg, white_color, left_code_size, left_code, is_left_code_filled); int right_code_beg = constract_row_structure_part (test_row, middle_guards_beg, white_color, middle_guards_size, middle_guards, is_middle_guards_filled); int right_guards_beg = constract_row_structure_part (test_row, right_code_beg, black_color, right_code_size, right_code, is_right_code_filled); int right_guards_end = constract_row_structure_part (test_row, right_guards_beg , black_color, right_guards_size, right_guards, is_right_guards_filled); if (is_left_guards_filled && is_left_code_filled && is_middle_guards_filled && is_right_code_filled && is_right_guards_filled) { has_barcode_structure = true; } return; } int Barcode::find_row_structure_part_beg (const uchar * const test_row, const int beg_index, const int part_color) { for (int index = beg_index; index < max_image_index; index++) if (test_row[index] == part_color) return index; return max_image_index; } int Barcode::constract_row_structure_part (const uchar * const test_row, const int beg_index, const uchar first_color, const int part_size, int *part, bool &part_filled) { int index, part_index; for (part_index = 0; part_index < part_size; part_index++) part[part_index] = 0; uchar curr_color = first_color; uchar prev_color = (first_color == black_color) ? white_color : black_color; for (index = beg_index, part_index = 0; index < max_image_index && part_index < part_size; index++) { if (test_row[index] == prev_color) { std::swap (curr_color, prev_color); part_index++; } part[part_index]++; } if (part_index != part_size) index = max_image_index; if (index < max_image_index) part_filled = true; return index; } void Barcode::identify_barcode_number () { if (!has_barcode_structure) return; std::string EAN_13; // guard length float h = 0.f; for (int i = 0; i < left_guards_size; i++) h += left_guards[i]; for (int i = 0; i < middle_guards_size; i++) h += middle_guards[i]; for (int i = 0; i < right_guards_size; i++) h += right_guards[i]; h /= left_guards_size + middle_guards_size + right_guards_size; // std::cout << "decode left code" << std::endl; for (int i = 0; i < left_code_size; i += 4) { int n = decode_single_number (h, left_code[i], left_code[i + 1], left_code[i + 2], left_code[i + 3]); auto got = LG_EAN_map.find (n); if (got == LG_EAN_map.end ()) { // std::cout << "Can`t decode number " << i / 4 + 1 << " in L-code." << std::endl; return; } else { barcode_number[i / 4 + 1] = (got->second).first; EAN_13 += (got->second).second; } } // std::cout << "decode right code" << std::endl; for (int i = 0; i < right_code_size; i += 4) { int n = decode_single_number (h, right_code[i], right_code[i + 1], right_code[i + 2], right_code[i + 3]); auto got = R_EAN_map.find (n); if (got == R_EAN_map.end ()) { // std::cout << "Can`t decode number " << i / 4 + 1 << " in R-code." << std::endl; return; } else barcode_number[i / 4 + 7] = (got->second).first; } // std::cout << "decode 13-th number" << std::endl; auto got = EAN_13_map.find (EAN_13); if (got == EAN_13_map.end ()) { // std::cout << "Can`t decode 13-th number!" << std::endl; return; } else barcode_number[0] = got->second; is_identified = true; } int Barcode::decode_single_number (const float h, const int l_0, const int l_1, const int l_2, const int l_3) { int max_bit_num = 7; float hl_0 = l_0 / h; float hl_1 = l_1 / h; float hl_2 = l_2 / h; float hl_3 = l_3 / h; // std::cout << hl_0 << " " << hl_1 << " " << hl_2 << " " << hl_3 << " " << std::endl; float hl_0_1 = hl_0 + hl_1; float hl_2_3 = hl_2 + hl_3; if (hl_0 < 1.f || hl_1 < 1.f) { if (hl_0 < 1.f) { hl_0 = 1.f; hl_1 = hl_0_1 - 1; hl_1 = (int) hl_1; } else if (hl_1 < 1.f) { hl_1 = 1.f; hl_0 = hl_0_1 - 1; hl_0 = (int) hl_0; } } else if ((int) hl_0_1 > (int) hl_0 + (int) hl_1) { if (hl_0 - (int) hl_0 > hl_1 - (int) hl_1) hl_0 = (int) hl_0 + 1, hl_1 = (int) hl_1; else if (hl_0 - (int) hl_0 < hl_1 - (int) hl_1) hl_1 = (int) hl_1 + 1, hl_0 = (int) hl_0; else { if ((int) (hl_1 + hl_2) > (int) hl_1 + (int) hl_2) hl_0 = (int) hl_0 + 1, hl_1 = (int) hl_1; else hl_1 = (int) hl_1 + 1, hl_0 = (int) hl_0; } } if (hl_2 < 1.f || hl_3 < 1.f) { if (hl_2 < 1.f) { hl_2 = 1.f; hl_3 = hl_2_3 - 1; hl_3 = (int) hl_3; } else if (hl_3 < 1.f) { hl_3 = 1.f; hl_2 = hl_2_3 - 1; hl_2 = (int) hl_2; } } else if ((int) hl_2_3 > (int) hl_2 + (int) hl_3) { if (hl_2 - (int) hl_2 > hl_3 - (int) hl_3) hl_2 = (int) hl_2 + 1, hl_3 = (int) hl_3; else hl_3 = (int) hl_3 + 1, hl_2 = (int) hl_2; } hl_0 = std::min (4.f, hl_0); hl_1 = std::min (4.f, hl_1); hl_2 = std::min (4.f, hl_2); hl_3 = std::min (4.f, hl_3); return (int) hl_0 * 1000 + (int) hl_1 * 100 + (int) hl_2 * 10 + (int) hl_3; } void Barcode::check_control_number () { if (!is_identified) return; int check_sum = 0; for (int i = 0; i < 13; i++) check_sum += barcode_number[i] * check_sum_coeffs[i]; if (check_sum % 10 == 0) is_correct = true; }
8,688
3,533
/* Author: Robert F. Rau II Copyright (C) 2017 Robert F. Rau II */ #include "comm/serialport.h" #include "comm/commexception.h" #include <iostream> #include <unistd.h> namespace PiFly { namespace Comm { SerialPort::SerialPort(string devPath, Baudrate baud, bool blocking) : mBlocking(blocking) { if(mBlocking) { serialFd = open(devPath.c_str(), O_RDWR); } else { serialFd = open(devPath.c_str(), O_RDWR | O_NONBLOCK | O_NDELAY); } if(serialFd < 0) { throw CommFdException(errno); } memset(&serialTTY, 0, sizeof(termios)); if(tcgetattr(serialFd, &serialTTY) != 0) { throw CommFdException(errno); } if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } // make a raw serial port cfmakeraw(&serialTTY); if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) { throw CommFdException(errno); } } SerialPort::~SerialPort() { if(serialFd >= 0) { close(serialFd); } } size_t SerialPort::read(SerialBuffer::iterator first, size_t readBytes) { if(!mBlocking) { int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes); if(resp > 0) { return resp; } else if((resp < 0) && (errno != EAGAIN)) { throw CommFdException(errno); } else { return 0; } } else { int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes); if(resp > 0) { return resp; } else if(resp == 0) { throw CommFdException(errno); } else { throw CommFdException(resp); } } } void SerialPort::write(const SerialBuffer& buffer) { size_t bytesWritten = 0; ssize_t resp; do { resp = ::write(serialFd, static_cast<const void*>(buffer.data()), buffer.size()); if(resp > 0) { bytesWritten += resp; } else if(resp == 0) { throw CommFdException(errno); } else { throw CommFdException(resp); } } while(bytesWritten < buffer.size()); } void SerialPort::setBaudrate(Baudrate baud) { if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) { throw CommFdException(errno); } if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) { throw CommFdException(errno); } } SerialPort::Baudrate SerialPort::getBaudrate() { speed_t currentBaud = cfgetispeed(&serialTTY); return linuxBaudrateMap(currentBaud); } void SerialPort::flush() { tcflush(serialFd, TCIOFLUSH); } SerialPort::Baudrate SerialPort::linuxBaudrateMap(speed_t baud) { switch(baud) { case B0: return Baudrate_0; case B50: return Baudrate_50; case B75: return Baudrate_75; case B110: return Baudrate_110; case B134: return Baudrate_134; case B150: return Baudrate_150; case B200: return Baudrate_200; case B300: return Baudrate_300; case B600: return Baudrate_600; case B1200: return Baudrate_1200; case B1800: return Baudrate_1800; case B2400: return Baudrate_2400; case B4800: return Baudrate_4800; case B9600: return Baudrate_9600; case B19200: return Baudrate_19200; case B38400: return Baudrate_38400; case B57600: return Baudrate_57600; case B115200: return Baudrate_115200; case B230400: return Baudrate_230400; default: std::cout << "linuxBaudrateMap speed_t Input baud: " << baud << "\n"; throw CommException("Unsupported baudrate"); } } speed_t SerialPort::linuxBaudrateMap(Baudrate baud) { switch(baud) { case Baudrate_0: return B0; case Baudrate_50: return B50; case Baudrate_75: return B75; case Baudrate_110: return B110; case Baudrate_134: return B134; case Baudrate_150: return B150; case Baudrate_200: return B200; case Baudrate_300: return B300; case Baudrate_600: return B600; case Baudrate_1200: return B1200; case Baudrate_1800: return B1800; case Baudrate_2400: return B2400; case Baudrate_4800: return B4800; case Baudrate_9600: return B9600; case Baudrate_19200: return B19200; case Baudrate_38400: return B38400; case Baudrate_57600: return B57600; case Baudrate_115200: return B115200; case Baudrate_230400: return B230400; default: std::cout << "linuxBaudrateMap Baudrate Input baud: " << baud << "\n"; throw CommException("Unsupported baudrate"); } } string SerialPort::baudrateString(Baudrate baud) { switch(baud) { case Baudrate_0: return "0"; case Baudrate_50: return "50"; case Baudrate_75: return "75"; case Baudrate_110: return "110"; case Baudrate_134: return "134"; case Baudrate_150: return "150"; case Baudrate_200: return "200"; case Baudrate_300: return "300"; case Baudrate_600: return "600"; case Baudrate_1200: return "1200"; case Baudrate_1800: return "1800"; case Baudrate_2400: return "2400"; case Baudrate_4800: return "4800"; case Baudrate_9600: return "9600"; case Baudrate_19200: return "19200"; case Baudrate_38400: return "38400"; case Baudrate_57600: return "57600"; case Baudrate_115200: return "115200"; case Baudrate_230400: return "230400"; default: return "unsupported"; } } } }
5,671
3,027
#pragma once import atma.types; namespace atma { struct hasher_t; template <typename T> struct hash_t { auto operator()(T const& x) const -> size_t; auto operator()(hasher_t& hsh, T const& x) const -> void; }; struct hasher_t { hasher_t(uint64 seed = 0); template <typename T> auto operator ()(T const& t) -> hasher_t&; auto operator ()(void const* datav, size_t size) -> hasher_t&; auto result() -> uint64; private: auto mmix(uint64& h, uint64 k) const -> void { k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; } void mix_tail(const uchar*& data, size_t& size) { while (size && (size < 8 || count_)) { tail_ |= *data << (count_ * 8); ++data; ++count_; --size; if (count_ == 8) { mmix(hash_, tail_); tail_ = 0; count_ = 0; } } } private: static const uint64 m = 0xc6a4a7935bd1e995ull; static const int r = 47; uint64 hash_; uint64 tail_; uint64 count_; size_t size_; }; inline auto hash(void const* key, size_t size, uint seed) -> uint64 { return hasher_t(seed)(key, size).result(); } template <typename T> inline auto hash(T const& t) -> uint64 { auto hasher = hasher_t{}; hash_t<T>{}(hasher, t); return hasher.result(); } struct std_hash_functor_adaptor_t { template <typename T> auto operator ()(T const& x) const -> size_t { return hasher_t()(&x, sizeof(T)).result(); } }; template <typename T> inline auto hash_t<T>::operator()(T const& x) const -> size_t { return hasher_t{}(x).result(); } template <typename T> inline auto hash_t<T>::operator()(hasher_t& hsh, T const& x) const -> void { hsh(&x, sizeof(T)); } inline hasher_t::hasher_t(uint64 seed) : hash_(seed) , tail_() , count_() , size_() { } inline auto hasher_t::operator ()(void const* datav, size_t size) -> hasher_t& { auto data = reinterpret_cast<uchar const*>(datav); size_ += size; mix_tail(data, size); while (size >= 8) { uint64 k = *(uint64*)data; mmix(hash_, k); data += 8; size -= 8; } mix_tail(data, size); return *this; } inline auto hasher_t::result() -> uint64 { mmix(hash_, tail_); mmix(hash_, size_); hash_ ^= hash_ >> r; hash_ *= m; hash_ ^= hash_ >> r; return hash_; } template <typename T> inline auto hasher_t::operator ()(T const& t) -> hasher_t& { hash_t<T>()(*this, t); return *this; } }
2,578
1,228
#include <iostream> //#define USING_MLOGD #include "utility/tool.h" #include <Eigen/Core> //#include <Eigen/Geometry> // Eigen 几何模块 /** * @brief 使用Gramy-Schmidt方法实现向量正交化,并单位化 * @param [in] a 向量a * @param [in] b 向量b * @param [in] c 向量c * @param [out] An 标准化后的向量A * @param [out] Bn 标准化后的向量B * @param [out] Cn 标准化后的向量C * @retval * @note a,b,c必须为线性无关组 */ static void schmidtOrthogonalV3D( Eigen::Vector3d a, Eigen::Vector3d b, Eigen::Vector3d c, Eigen::Vector3d* An, Eigen::Vector3d* Bn, Eigen::Vector3d* Cn ){ Eigen::Vector3d A,B,C; //A直接赋值为a A = a; //MLOGD("vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() ); //求B double xab = A.dot(b) / A.dot( A ); B = b - xab * A; //MLOGD("vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() ); //求C double xac = A.dot( c ) / A.dot( A ); double xbc = B.dot( c ) / B.dot( B ); C = c - ( xac * A ) - ( xbc * B ); //MLOGD("vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() ); //单位化并输出 *An = A.normalized(); *Bn = B.normalized(); *Cn = C.normalized(); //MLOGD("normalized vector A: %.3lf %.3f %.3f", An->x(), An->y(), An->z() ); //MLOGD("normalized vector B: %.3lf %.3f %.3f", Bn->x(), Bn->y(), Bn->z() ); //MLOGD("normalized vector C: %.3lf %.3f %.3f", Cn->x(), Cn->y(), Cn->z() ); } //--------------------测试函数---------------------------- static void schmidtOrthogonalTest( void ) { //线性无关组1 Eigen::Vector3d a(1,1.2,0); Eigen::Vector3d b(1,2,0); Eigen::Vector3d c(0,1,1); //线性无关组2 Eigen::Vector3d v1(9,1.2,2.4); Eigen::Vector3d v2(1,2,6.7); Eigen::Vector3d v3(5,1.5,1); Eigen::Vector3d A,B,C; schmidtOrthogonalV3D( a, b, c, &A, &B, &C ); //schmidtOrthogonalV3D( v1, v2, v3, &A, &B, &C ); TPLOGI("normalized vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() ); TPLOGI("normalized vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() ); TPLOGI("normalized vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() ); }
2,178
1,043
/******************************************************************************* * Copyright (c) 2019 by Rubedos * Kaunas, Lithuania, www.rubedos.com * All rights reserved. *******************************************************************************/ #include "FollowArucoWindow.h" #include <ros/spinner.h> #include <QApplication> using cvm_follow_aruco_sample::FollowArucoWindow; int main(int argc, char *argv[]) { // Initialize ROS ros::init(argc, argv, "FollowArucoSample"); // Start a spinner with 4 threads ros::AsyncSpinner spinner(4); spinner.start(); // Init QT application QApplication a(argc, argv); FollowArucoWindow w; w.init("DEFAULT"); // VIPER prefix w.show(); return a.exec(); }
727
240
/* * BSD 3-Clause License * * Copyright (c) 2021, Dexai Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ // @file dexai/log_dexai.cc #include "utils/dexai_log.h" #include <iostream> #include "utils/utils.h" namespace { // static drake::never_destroyed<std::shared_ptr<slogger>> s_logger = nullptr; static std::shared_ptr<slogger> s_logger = nullptr; static slogger* d_logger = nullptr; } // namespace unsigned DexaiLogger::log_id_size(spdlog::level::level_enum ll_enum) { switch (ll_enum) { case spdlog::level::warn: return log_id_error_size_ + 2; case spdlog::level::info: return log_id_error_size_ - 1; // case spdlog::level::debug: // case spdlog::level::err: // NOTE spdlog::level::error does not // exist. case spdlog::level::trace: default: return log_id_error_size_; } } namespace dexai { // Returns true IFF the logger object is NULL, // meaning that either is has not yet been created, or it was nullified. bool is_log_null() { return s_logger == nullptr; } spdlog::logger* log(int warn_if_null) { if (is_log_null()) { if (warn_if_null) { std::cerr << "WARNING: Call to uninitialized dexai::logging::logger log()" << std::endl; std::cerr << "WARNING: Using all defaults in dexai::logging::logger log()" << std::endl; } create_log(); } assert(s_logger && "FATAL: s_logger still not set after calling dexai::create_log()"); return s_logger.get(); } /// Convenience function to get the "current" logger's log directory. @see /// log_dexai.h std::string log_dir() { try { DexaiLogger* dexai_logger = dynamic_cast<DexaiLogger*>(dexai::log()); return dexai_logger == nullptr ? "" : dexai_logger->log_dir(); } catch (const std::exception& ex) { dexai::log()->warn("Error in dexai::log_dir: {}", ex.what()); } return ""; } // Convenience function to get the "current" logger's log message ID size. @see // log_dexai.h Example usage: log()->error("This is a test of // dexai::DexaiLogger::log_id_size:\n{:>{}}" // "This line shall line up with the line up one line.", // "", dexai::log_id_size() // ); unsigned log_id_size(spdlog::level::level_enum ll_enum) { try { DexaiLogger* dexai_logger = dynamic_cast<DexaiLogger*>(dexai::log(ll_enum)); return dexai_logger == nullptr ? 42 : dexai_logger->log_id_size(); } catch (const std::exception& ex) { dexai::log()->debug("Error in dexai::log_id_size({}): {}", (unsigned)ll_enum, ex.what()); } return 42; } bool create_log(const std::string& program_in, const std::string& base_path, const std::string& prefix_in, bool use_stdout, bool create_once) { if (s_logger != nullptr && create_once) { s_logger->warn("dexai::create_log: s_logger already created!"); return false; } std::string program = program_in; if (program.empty()) { program = "dexai"; } std::string base_dir = base_path; if (base_dir.empty()) { base_dir = utils::get_home_dir() + "/log_robot"; } std::string prefix = prefix_in; if (prefix.empty()) { prefix = program; } std::string log_dir; bool got_base = utils::sub_dir_path(log_dir, base_dir, program); //$ append extra date and datetime subfolders to log output path std::string date_string = utils::get_date_string(); std::string date_time_string = utils::date_time_string(); got_base = utils::sub_dir_path(log_dir, log_dir, date_string); got_base = utils::sub_dir_path(log_dir, log_dir, date_time_string); // NOTE: We cannot call drake::log or dexai::log here; they're uninitialized. if (got_base) { // NOTE: Caution: Calling log here may stackoverflow. } else { drake::log()->error( "::::::::::: dexai::create_log: fatal error -- no base directory for " "logs!"); return false; } std::vector<spdlog::sink_ptr> sinks; if (use_stdout) { sinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>()); } else { sinks.push_back(std::make_shared<spdlog::sinks::stderr_color_sink_mt>()); } std::string log_file_name = utils::date_time_string() + "_" + program + ".log"; std::string log_file_path = log_dir + "/" + log_file_name; sinks.push_back( std::make_shared<spdlog::sinks::basic_file_sink_mt>(log_file_path)); // NOTE: We don't necessarily need a DexaiLogger; we could just use one // spd::logger. std::shared_ptr<DexaiLogger> logger = std::make_shared<DexaiLogger>(prefix, log_dir, begin(sinks), end(sinks)); spdlog::register_logger( logger); // register it if you need to access it globally logger->set_level(spdlog::level::info); s_logger = logger; return true; } } // namespace dexai #if OVERRIDE_DRAKE_LOG namespace drake { logging::logger* log() { #ifdef ASSERT_TRUE // To be compiled only in a test context. std::cerr << "\t<<<< Call to drake::log() got the override log() >>>>" << std::endl << std::endl; #endif // TODO: Would prefer to assert rather than conpensate for failing // to initialize the logger, but then every executable that includes // log_dexai.h with OVERRIDE_DRAKE_LOG defined as truthy must either call // dexai::create_log or work around it. // assert(s_logger && "s_logger not set; call dexai::create_log() first!"); if (dexai::is_log_null()) { std::cerr << "WARNING: Call to uninitialized drake::logging::logger log()" << std::endl; dexai::create_log(); std::cerr << "WARNING: Used all defaults for drake::logging::logger log()" << std::endl; } assert(s_logger && "FATAL: s_logger still not set after calling dexai::create_log()"); return s_logger.get(); } } // namespace drake // TODO: If possible and worthwhile, provide access to the original result of // drake::log() that we overrode. drake::logging::logger* original_drake_log() { if (d_logger == nullptr) { d_logger = drake::log(); } return d_logger; } #endif // OVERRIDE_DRAKE_LOG
7,579
2,652
// // Created by 平地浩一 on 2021/03/23. // #include "comms.h" DigitalIn a(PA_7); DigitalIn b(PA_6); DigitalOut RA(PB_0); DigitalOut RB(PA_12); DigitalOut LA(PB_3); // PB_7 許さん!!! DigitalOut LB(PB_6); BufferedSerial pc(USBTX, USBRX); void comms_init() { RA.write(0); RB.write(0); LA.write(0); LB.write(0); } void comms_read() { bool A = a.read(); bool B = b.read(); static bool AA; static bool BB; if (A != AA || B != BB) { if (A && !B) { // 左超信地 RA.write(0); RB.write(1); LA.write(1); LB.write(0); } else if (!A && B) { // 右超信地 RA.write(1); RB.write(0); LA.write(0); LB.write(1); } else if (!A && !B) { // 停止 RA.write(1); RB.write(1); LA.write(1); LB.write(1); } else if (A && B) { // 前進 RA.write(0); RB.write(1); LA.write(0); LB.write(1); } } AA = A; BB = B; }
927
457
#ifndef TESTER_HPP #define TESTER_HPP #include <string> #include <iostream> #include <sstream> #include <vector> #include <time.h> class Tester { private: struct StrTime { std::string str; clock_t time; /** Skip output when put_all_time */ bool skip; }; /** Number of hours that can be saved in time measurement */ static const size_t TIME_BUF = 1000; /** Stream when outputting in batches */ std::stringstream _ss; /** Saved time vector */ std::vector<StrTime> _time_vec; /** * @brief Calculate the elapsed time from the last save time * @param i Index of _time_vec * @return double Elapsed time */ double _calc_elapsed_time(size_t i); public: Tester(); /** * @brief The output will look like this: str/n * @param str */ void print(std::string str); /** * @brief The output will look like this: str v/n * @tparam T Classes that can flow directly to stream * @param str * @param v */ template <typename T> void print(std::string str, T v) { std::cout << str << " " << v << std::endl; } /** * @brief The output will look like this: str v1 v2/n * @tparam T Classes that can flow directly to stream * @param str * @param v1 * @param v2 */ template <typename T1, typename T2> void print(std::string str, T1 v1, T2 v2) { std::cout << str << " " << v1 << " " << v2 << std::endl; } /** * @brief Change the output depending on the authenticity of tf. * The output will look like this: str true_str/n or str false_str/n * @param str * @param tf * @param true_str * @param false_str */ void if_print(std::string str, bool tf, std::string true_str = "true", std::string false_str = "false"); /** * @brief Filling a stream with data * @param data */ template <typename T> void set_stream(T data) { _ss << data << " "; } /** * @brief Output the data put in by set_stream */ void put_all_stream(); /** * @brief Save description and time * @param str */ void set_time(std::string str, bool skip = false); /** * @brief Outputs the most recent measurement time * @param verbose 0: Time only, 1: Output with str */ void put_recent_time(int verbose = 1); /** * @brief Output all measurement results * @param verbose 0: Time only, 1: Output with str */ void put_all_time(int verbose = 1); /** * @brief Return the elapsed time from the last save time * @param index Index of _time_vec * @return double Elapsed time */ double get_elapsed_time(size_t index); /** * @brief Returns the size of the stored time * @return size_t */ size_t get_saved_time_size(); }; #endif
2,933
973
#include <boost/python.hpp> #include <boost/format.hpp> #include "viewport/render/task.h" #include "viewport/render/instance.h" #include "fab/types/shape.h" #include "fab/util/region.h" #include "fab/tree/render.h" RenderTask::RenderTask(RenderInstance* parent, PyObject* s, QMatrix4x4 M, QVector2D clip, int refinement) : shape(s), M(M), clip(clip), refinement(refinement) { Py_INCREF(shape); future = QtConcurrent::run(this, &RenderTask::async); watcher.setFuture(future); connect(&watcher, &decltype(watcher)::finished, parent, &RenderInstance::onTaskFinished); } RenderTask::~RenderTask() { Py_DECREF(shape); } void RenderTask::halt() { halt_flag = 1; } RenderTask* RenderTask::getNext(RenderInstance* parent) const { return refinement > 1 ? new RenderTask(parent, shape, M, clip, refinement - 1) : NULL; } void RenderTask::async() { QTime timer; timer.start(); boost::python::extract<const Shape&> get_shape(shape); Q_ASSERT(get_shape.check()); const Shape& s = get_shape(); if (!std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax) && !std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax)) { if (std::isinf(s.bounds.zmin) || std::isinf(s.bounds.zmax)) { render2d(s); } else { render3d(s); } } // Set color from shape or to white color = (s.r != -1 && s.g != -1 && s.g != -1) ? QColor(s.r, s.g, s.b) : QColor(255, 255, 255); // Compensate for screen scale float scale = sqrt(pow(M(0, 0), 2) + pow(M(0, 1), 2) + pow(M(0, 2), 2)); size /= scale; render_time = timer.elapsed(); } void RenderTask::render3d(const Shape& s) { Transform T = getTransform(M); Shape transformed = s.map(T); Bounds b = render(&transformed, transformed.bounds, 1.0 / refinement); { // Apply a transform-less mapping to the bounds auto m = M; m.setColumn(3, {0, 0, 0, m(3,3)}); pos = m.inverted() * QVector3D( (b.xmin + b.xmax)/2, (b.ymin + b.ymax)/2, (b.zmin + b.zmax)/2); } size = {b.xmax - b.xmin, b.ymax - b.ymin, b.zmax - b.zmin}; flat = false; } void RenderTask::render2d(const Shape& s) { QMatrix4x4 matrix_flat = M; matrix_flat(0, 2) = 0; matrix_flat(1, 2) = 0; matrix_flat(2, 0) = 0; matrix_flat(2, 1) = 0; matrix_flat(2, 2) = 1; Shape s_flat(s.math, Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0)); Transform T_flat = getTransform(matrix_flat); Shape transformed = s_flat.map(T_flat); // Render the flattened shape, but with bounds equivalent to the shape's // position in a 3D bounding box. Bounds b3d_ = Bounds(s.bounds.xmin, s.bounds.ymin, 0, s.bounds.xmax, s.bounds.ymax, 0.0001). map(getTransform(M)); Bounds b3d = render(&transformed, b3d_, 1.0 / refinement); { // Apply a transform-less mapping to the bounds auto m = M; m.setColumn(3, {0, 0, 0, m(3, 3)}); pos = m.inverted() * QVector3D((b3d.xmin + b3d.xmax)/2, (b3d.ymin + b3d.ymax)/2, (b3d.zmin + b3d.zmax)/2); } size = {b3d.xmax - b3d.xmin, b3d.ymax - b3d.ymin, b3d.zmax - b3d.zmin}; // Apply a gradient to the depth-map based on tilt if (M(1,2)) { bool direction = M(2,2) > 0; for (int j=0; j < depth.height(); ++j) { for (int i=0; i < depth.width(); ++i) { uint8_t pix = depth.pixel(i, j) & 0xff; if (pix) { if (direction) pix *= j / float(depth.height()); else pix *= 1 - j / float(depth.height()); depth.setPixel(i, j, pix | (pix << 8) | (pix << 16)); } } } } { // Set normals to a flat value (rather than derivatives) float xy = sqrt(pow(M(0,2),2) + pow(M(1,2),2)); float z = fabs(M(2,2)); float len = sqrt(pow(xy, 2) + pow(z, 2)); xy /= len; z /= len; shaded.fill((int(z * 255) << 16) | int(xy * 255)); } flat = true; } Transform RenderTask::getTransform(QMatrix4x4 m) { QMatrix4x4 mf = m.inverted(); QMatrix4x4 mi = mf.inverted(); Transform T = Transform( (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(0,0) % mf(0,1) % mf(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(1,0) % mf(1,1) % mf(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mf(2,0) % mf(2,1) % mf(2,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(0,0) % mi(0,1) % mi(0,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(1,0) % mi(1,1) % mi(1,2)).str(), (boost::format("++*Xf%g*Yf%g*Zf%g") % mi(2,0) % mi(2,1) % mi(2,2)).str()); return T; } //////////////////////////////////////////////////////////////////////////////// Bounds RenderTask::render(Shape* shape, Bounds b_, float scale) { // Screen-space clipping: // x and y are clipped to the window; // z is clipped assuming a voxel depth of max(width, height) const float xmin = -M(0,3) - clip.x() / 2; const float xmax = -M(0,3) + clip.x() / 2; const float ymin = -M(1,3) - clip.y() / 2; const float ymax = -M(1,3) + clip.y() / 2; const float zmin = -M(2,3) - fmax(clip.x(), clip.y()) / 2; const float zmax = -M(2,3) + fmax(clip.x(), clip.y()) / 2; Bounds b(fmax(xmin, b_.xmin), fmax(ymin, b_.ymin), fmax(zmin, b_.zmin), fmin(xmax, b_.xmax), fmin(ymax, b_.ymax), fmin(zmax, b_.zmax)); depth = QImage((b.xmax - b.xmin) * scale, (b.ymax - b.ymin) * scale, QImage::Format_RGB32); shaded = QImage(depth.width(), depth.height(), depth.format()); depth.fill(0x000000); uint16_t* d16(new uint16_t[depth.width() * depth.height()]); uint16_t** d16_rows(new uint16_t*[depth.height()]); uint8_t (*s8)[3] = new uint8_t[depth.width() * depth.height()][3]; uint8_t (**s8_rows)[3] = new decltype(s8)[depth.height()]; for (int i=0; i < depth.height(); ++i) { d16_rows[i] = &d16[depth.width() * i]; s8_rows[i] = &s8[depth.width() * i]; } memset(d16, 0, depth.width() * depth.height() * 2); memset(s8, 0, depth.width() * depth.height() * 3); Region r = (Region) { .imin=0, .jmin=0, .kmin=0, .ni=(uint32_t)depth.width(), .nj=(uint32_t)depth.height(), .nk=uint32_t(fmax(1, (b.zmax - b.zmin) * scale)) }; build_arrays(&r, b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax); render16(shape->tree.get(), r, d16_rows, &halt_flag, nullptr); shaded8(shape->tree.get(), r, d16_rows, s8_rows, &halt_flag, nullptr); free_arrays(&r); // Copy from bitmap arrays into a QImage for (int j=0; j < depth.height(); ++j) { for (int i=0; i < depth.width(); ++i) { uint16_t pix16 = d16_rows[j][i]; uint8_t pix8 = pix16 >> 8; uint8_t* norm = s8_rows[j][i]; if (pix8) { depth.setPixel(i, j, pix8 | (pix8 << 8) | (pix8 << 16)); if (pix16 < UINT16_MAX) { shaded.setPixel(i, j, norm[0] | (norm[1] << 8) | (norm[2] << 16)); } else { shaded.setPixel(i, j, 0 | (0 << 8) | (255 << 16)); } } } } delete [] s8; delete [] s8_rows; delete [] d16; delete [] d16_rows; return b; }
8,170
3,252
#include <wayfire/plugin.hpp> #include <wayfire/output.hpp> #include <wayfire/core.hpp> #include <linux/input.h> #include <linux/input-event-codes.h> #include <wayfire/signal-definitions.hpp> #include <wayfire/util/log.hpp> static bool begins_with(std::string word, std::string prefix) { if (word.length() < prefix.length()) return false; return word.substr(0, prefix.length()) == prefix; } /* Initial repeat delay passed */ static int repeat_delay_timeout_handler(void *callback) { (*reinterpret_cast<std::function<void()>*> (callback)) (); return 1; // disconnect }; /* Between each repeat */ static int repeat_once_handler(void *callback) { (*reinterpret_cast<std::function<void()>*> (callback)) (); return 1; // continue timer } /* Provides a way to bind specific commands to activator bindings. * * It supports 2 modes: * * 1. Regular bindings * 2. Repeatable bindings - for example, if the user binds a keybinding, then * after a specific delay the command begins to be executed repeatedly, until * the user released the key. In the config file, repeatable bindings have the * prefix repeatable_ * 3. Always bindings - bindings that can be executed even if a plugin is already * active, or if the screen is locked. They have a prefix always_ * */ class wayfire_command : public wf::plugin_interface_t { std::vector<wf::activator_callback> bindings; struct { uint32_t pressed_button = 0; uint32_t pressed_key = 0; std::string repeat_command; } repeat; wl_event_source *repeat_source = NULL, *repeat_delay_source = NULL; enum binding_mode { BINDING_NORMAL, BINDING_REPEAT, BINDING_ALWAYS, }; bool on_binding(std::string command, binding_mode mode, wf::activator_source_t source, uint32_t value) { /* We already have a repeatable command, do not accept further bindings */ if (repeat.pressed_key || repeat.pressed_button) return false; uint32_t act_flags = 0; if (mode == BINDING_ALWAYS) act_flags |= wf::PLUGIN_ACTIVATION_IGNORE_INHIBIT; if (!output->activate_plugin(grab_interface, act_flags)) return false; wf::get_core().run(command.c_str()); /* No repeat necessary in any of those cases */ if (mode != BINDING_REPEAT || source == wf::ACTIVATOR_SOURCE_GESTURE || value == 0) { output->deactivate_plugin(grab_interface); return true; } repeat.repeat_command = command; if (source == wf::ACTIVATOR_SOURCE_KEYBINDING) { repeat.pressed_key = value; } else { repeat.pressed_button = value; } repeat_delay_source = wl_event_loop_add_timer(wf::get_core().ev_loop, repeat_delay_timeout_handler, &on_repeat_delay_timeout); wl_event_source_timer_update(repeat_delay_source, wf::option_wrapper_t<int>("input/kb_repeat_delay")); wf::get_core().connect_signal("pointer_button", &on_button_event); wf::get_core().connect_signal("keyboard_key", &on_key_event); return true; } std::function<void()> on_repeat_delay_timeout = [=] () { repeat_delay_source = NULL; repeat_source = wl_event_loop_add_timer(wf::get_core().ev_loop, repeat_once_handler, &on_repeat_once); on_repeat_once(); }; std::function<void()> on_repeat_once = [=] () { uint32_t repeat_rate = wf::option_wrapper_t<int> ("input/kb_repeat_rate"); if (repeat_rate <= 0 || repeat_rate > 1000) return reset_repeat(); wl_event_source_timer_update(repeat_source, 1000 / repeat_rate); wf::get_core().run(repeat.repeat_command.c_str()); }; void reset_repeat() { if (repeat_delay_source) { wl_event_source_remove(repeat_delay_source); repeat_delay_source = NULL; } if (repeat_source) { wl_event_source_remove(repeat_source); repeat_source = NULL; } repeat.pressed_key = repeat.pressed_button = 0; output->deactivate_plugin(grab_interface); wf::get_core().disconnect_signal("pointer_button", &on_button_event); wf::get_core().disconnect_signal("keyboard_key", &on_key_event); } wf::signal_callback_t on_button_event = [=] (wf::signal_data_t *data) { auto ev = static_cast< wf::input_event_signal<wlr_event_pointer_button>*>(data); if (ev->event->button == repeat.pressed_button && ev->event->state == WLR_BUTTON_RELEASED) { reset_repeat(); } }; wf::signal_callback_t on_key_event = [=] (wf::signal_data_t *data) { auto ev = static_cast< wf::input_event_signal<wlr_event_keyboard_key>*>(data); if (ev->event->keycode == repeat.pressed_key && ev->event->state == WLR_KEY_RELEASED) { reset_repeat(); } }; public: void setup_bindings_from_config() { auto section = wf::get_core().config.get_section("command"); std::vector<std::string> command_names; const std::string exec_prefix = "command_"; for (auto command : section->get_registered_options()) { if (begins_with(command->get_name(), exec_prefix)) { command_names.push_back( command->get_name().substr(exec_prefix.length())); } } bindings.resize(command_names.size()); const std::string norepeat = "...norepeat..."; const std::string noalways = "...noalways..."; for (size_t i = 0; i < command_names.size(); i++) { auto command = exec_prefix + command_names[i]; auto regular_binding_name = "binding_" + command_names[i]; auto repeat_binding_name = "repeatable_binding_" + command_names[i]; auto always_binding_name = "always_binding_" + command_names[i]; auto check_activator = [&] (const std::string& name) { auto opt = section->get_option_or(name); if (opt) { auto value = wf::option_type::from_string< wf::activatorbinding_t> (opt->get_value_str()); if (value) return wf::create_option(value.value()); } return wf::option_sptr_t<wf::activatorbinding_t>{}; }; auto executable = section->get_option(command)->get_value_str(); auto repeatable_opt = check_activator(repeat_binding_name); auto regular_opt = check_activator(regular_binding_name); auto always_opt = check_activator(always_binding_name); using namespace std::placeholders; if (repeatable_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_REPEAT, _1, _2); output->add_activator(repeatable_opt, &bindings[i]); } else if (always_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_ALWAYS, _1, _2); output->add_activator(always_opt, &bindings[i]); } else if (regular_opt) { bindings[i] = std::bind(std::mem_fn(&wayfire_command::on_binding), this, executable, BINDING_NORMAL, _1, _2); output->add_activator(regular_opt, &bindings[i]); } } } void clear_bindings() { for (auto& binding : bindings) output->rem_binding(&binding); bindings.clear(); } wf::signal_callback_t reload_config; void init() { grab_interface->name = "command"; grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT; using namespace std::placeholders; setup_bindings_from_config(); reload_config = [=] (wf::signal_data_t*) { clear_bindings(); setup_bindings_from_config(); }; wf::get_core().connect_signal("reload-config", &reload_config); } void fini() { wf::get_core().disconnect_signal("reload-config", &reload_config); clear_bindings(); } }; DECLARE_WAYFIRE_PLUGIN(wayfire_command);
8,579
2,681
#include "stdafx.h" #include "SocketMgr.h" bool SocketMgr::s_bRunningCleanupThread = true; std::recursive_mutex SocketMgr::s_disconnectionQueueLock; std::queue<Socket *> SocketMgr::s_disconnectionQueue; Thread SocketMgr::s_cleanupThread; Atomic<uint32_t> SocketMgr::s_refCounter; uint32_t THREADCALL SocketCleanupThread(void * lpParam) { while (SocketMgr::s_bRunningCleanupThread) { SocketMgr::s_disconnectionQueueLock.lock(); while (!SocketMgr::s_disconnectionQueue.empty()) { Socket *pSock = SocketMgr::s_disconnectionQueue.front(); if (pSock->GetSocketMgr()) pSock->GetSocketMgr()->DisconnectCallback(pSock); SocketMgr::s_disconnectionQueue.pop(); } SocketMgr::s_disconnectionQueueLock.unlock(); sleep(100); } return 0; } SocketMgr::SocketMgr() : m_threadCount(0), m_bWorkerThreadsActive(false), m_bShutdown(false) { static bool bRefCounterInitialised = false; if (!bRefCounterInitialised) { s_refCounter = 0; bRefCounterInitialised = true; } IncRef(); Initialise(); } void SocketMgr::SpawnWorkerThreads() { if (m_bWorkerThreadsActive) return; m_bWorkerThreadsActive = true; m_thread = new Thread(SocketWorkerThread, this); if (!s_cleanupThread.isStarted()) s_cleanupThread.start(SocketCleanupThread); } uint32_t THREADCALL SocketMgr::SocketWorkerThread(void * lpParam) { SocketMgr *socketMgr = (SocketMgr *)lpParam; HANDLE cp = socketMgr->GetCompletionPort(); DWORD len; Socket * s = nullptr; OverlappedStruct * ov = nullptr; LPOVERLAPPED ol_ptr; while (socketMgr->m_bWorkerThreadsActive) { if (!GetQueuedCompletionStatus(cp, &len, (PULONG_PTR)&s, &ol_ptr, INFINITE)) { if (s != nullptr) s->Disconnect(); continue; } ov = CONTAINING_RECORD(ol_ptr, OverlappedStruct, m_overlap); if (ov->m_event == SOCKET_IO_THREAD_SHUTDOWN) { delete ov; return 0; } if (ov->m_event < NUM_SOCKET_IO_EVENTS) ophandlers[ov->m_event](s, len); } return 0; } void SocketMgr::Initialise() { m_completionPort = nullptr; } void SocketMgr::CreateCompletionPort() { SetCompletionPort(CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, (ULONG_PTR)0, 0)); } void SocketMgr::SetupWinsock() { WSADATA wsaData; WSAStartup(MAKEWORD(2,0), &wsaData); } void HandleReadComplete(Socket * s, uint32_t len) { if (s->IsDeleted()) return; s->m_readEvent.Unmark(); if (len) { s->GetReadBuffer().IncrementWritten(len); s->OnRead(); s->SetupReadEvent(); } else { // s->Delete(); // Queue deletion. s->Disconnect(); } } void HandleWriteComplete(Socket * s, uint32_t len) { if (s->IsDeleted()) return; s->m_writeEvent.Unmark(); s->BurstBegin(); // Lock s->GetWriteBuffer().Remove(len); if( s->GetWriteBuffer().GetContiguousBytes() > 0 ) s->WriteCallback(); else s->DecSendLock(); s->BurstEnd(); // Unlock } void HandleShutdown(Socket * s, uint32_t len) {} void SocketMgr::OnConnect(Socket *pSock) {} void SocketMgr::DisconnectCallback(Socket *pSock) {} void SocketMgr::OnDisconnect(Socket *pSock) { Guard lock(s_disconnectionQueueLock); s_disconnectionQueue.push(pSock); } void SocketMgr::ShutdownThreads() { OverlappedStruct * ov = new OverlappedStruct(SOCKET_IO_THREAD_SHUTDOWN); PostQueuedCompletionStatus(m_completionPort, 0, (ULONG_PTR)0, &ov->m_overlap); m_bWorkerThreadsActive = false; m_thread->waitForExit(); delete m_thread; } void SocketMgr::Shutdown() { if (m_bShutdown) return; ShutdownThreads(); DecRef(); m_bShutdown = true; } void SocketMgr::SetupSockets() { SetupWinsock(); } void SocketMgr::CleanupSockets() { if (s_cleanupThread.isStarted()) { s_bRunningCleanupThread = false; s_cleanupThread.waitForExit(); } WSACleanup(); } SocketMgr::~SocketMgr() { Shutdown(); }
3,749
1,602
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtNetwork> class ClientServer : public QUdpSocket { Q_OBJECT public: enum Type { ConnectedClient, UnconnectedClient, Server }; ClientServer(Type type, const QString &host, quint16 port) : type(type) { switch (type) { case Server: if (bind(0, ShareAddress | ReuseAddressHint)) { printf("%d\n", localPort()); } else { printf("XXX\n"); } break; case ConnectedClient: connectToHost(host, port); startTimer(250); printf("ok\n"); break; case UnconnectedClient: peerAddress = host; peerPort = port; if (bind(QHostAddress::Any, port + 1, ShareAddress | ReuseAddressHint)) { startTimer(250); printf("ok\n"); } else { printf("XXX\n"); } break; } fflush(stdout); connect(this, SIGNAL(readyRead()), this, SLOT(readTestData())); } protected: void timerEvent(QTimerEvent *event) { static int n = 0; switch (type) { case ConnectedClient: write(QByteArray::number(n++)); break; case UnconnectedClient: writeDatagram(QByteArray::number(n++), peerAddress, peerPort); break; default: break; } QUdpSocket::timerEvent(event); } private slots: void readTestData() { printf("readData()\n"); switch (type) { case ConnectedClient: { while (bytesAvailable() || hasPendingDatagrams()) { QByteArray data = readAll(); printf("got %d\n", data.toInt()); } break; } case UnconnectedClient: { while (hasPendingDatagrams()) { QByteArray data; data.resize(pendingDatagramSize()); readDatagram(data.data(), data.size()); printf("got %d\n", data.toInt()); } break; } case Server: { while (hasPendingDatagrams()) { QHostAddress sender; quint16 senderPort; QByteArray data; data.resize(pendingDatagramSize()); readDatagram(data.data(), data.size(), &sender, &senderPort); printf("got %d\n", data.toInt()); printf("sending %d\n", data.toInt() * 2); writeDatagram(QByteArray::number(data.toInt() * 2), sender, senderPort); } break; } } fflush(stdout); } private: Type type; QHostAddress peerAddress; quint16 peerPort; }; int main(int argc, char **argv) { QCoreApplication app(argc, argv); ClientServer::Type type; if (app.arguments().size() < 4) { qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]); return 1; } QString arg = app.arguments().at(1).trimmed().toLower(); if (arg == "connectedclient") { type = ClientServer::ConnectedClient; } else if (arg == "unconnectedclient") { type = ClientServer::UnconnectedClient; } else if (arg == "server") { type = ClientServer::Server; } else { qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]); return 1; } ClientServer clientServer(type, app.arguments().at(2), app.arguments().at(3).toInt()); return app.exec(); } #include "main.moc"
5,303
1,501
#include "step_crawling.h" #include <RobotUtilities/utilities.h> #include <ati_netft/ati_netft.h> #include <abb_egm/abb_egm.h> #include <ur_socket/ur_socket.h> using namespace std; using namespace RUT; int main(int argc, char* argv[]) { ROS_INFO_STREAM("Step crawling task server node starting"); ros::init(argc, argv, "step_crawling_node"); ros::NodeHandle hd; Clock::time_point time0 = std::chrono::high_resolution_clock::now(); ATINetft ati; cout << "[test] initializing ft sensor:\n"; ati.init(hd, time0); cout << "[test] initializing robot:\n"; URSocket *robot = URSocket::Instance(); robot->init(hd, time0); StepCrawlingTaskServer task_server; task_server.init(&hd, time0, &ati, robot); task_server.initStepCrawlingTaskServer(); task_server.hostServices(); ROS_INFO_STREAM(endl << "[MAIN] Rest in Peace." << endl); return 0; }
872
337
#include "stats/analyzer.hpp" #include "writers/r_writer.hpp" using namespace Anaquin; // Defined in main.cpp extern Path __output__; // Defined in resources.cpp extern Scripts PlotLinear(); // Defined in resources.cpp extern Scripts PlotFold(); // Defined in resources.cpp extern Scripts PlotLogistic(); Scripts RWriter::createLogistic(const FileName &file, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, bool showLOQ) { return (boost::format(PlotLogistic()) % date() % __full_command__ % __output__ % file % title % xlab % ylab % ("log2(data$" + expected + ")") % ("data$" + measured) % (showLOQ ? "TRUE" : "FALSE")).str(); } Scripts RWriter::createFold(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, bool shouldLog, const std::string &extra) { const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected); const auto obs = shouldLog ? ("log2(data$" + measured + ")") : ("data$" + measured); return (boost::format(PlotFold()) % date() % __full_command__ % path % file % title % xlab % ylab % exp % obs % "TRUE" % extra).str(); } Scripts RWriter::createMultiLinear(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, const std::string &xname, bool showLOQ, bool shouldLog, const std::string &extra) { const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected); const auto obs = shouldLog ? ("log2(data[,3:ncol(data)])") : ("data[,3:ncol(data)]"); return (boost::format(PlotLinear()) % date() % __full_command__ % path % file % title % xlab % ylab % exp % obs % xname % (showLOQ ? "TRUE" : "FALSE") % extra).str(); } Scripts RWriter::createRConjoint(const FileName &file, const Scripts &script, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &x, const std::string &y) { return (boost::format(script) % date() % __full_command__ % path % file % title % xlab % ylab % x % y).str(); } Scripts RWriter::createRLinear(const FileName &file, const Path &path, const std::string &title, const std::string &xlab, const std::string &ylab, const std::string &expected, const std::string &measured, const std::string &xname, bool showLOQ, const std::string &script) { return (boost::format(script.empty() ? PlotLinear() : script) % date() % __full_command__ % path % file % title % xlab % ylab % expected % measured % xname % (showLOQ ? "TRUE" : "FALSE")).str(); } Scripts RWriter::createScript(const FileName &file, const Scripts &script) { return (boost::format(script) % date() % __full_command__ % __output__ % file).str(); } Scripts RWriter::createScript(const FileName &file, const Scripts &script, const std::string &x) { return (boost::format(script) % date() % __full_command__ % __output__ % file % x).str(); }
6,543
1,376
#include "advent.h" inline void reverse(std::vector<int>& vect, int from, int length) { int const vsize = vect.size(); if (length > vsize) return; for (int i = 0; i < length / 2; ++i) std::swap(vect[(from + i) % vsize], vect[(from + length - i - 1) % vsize]); } inline std::string knotHash(std::string const& input) { int const numRounds = 64; int const seqLength = 256; int const xorLength = 16; std::vector<int> sequence; std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); }); std::vector<int> lengths; std::transform(input.begin(), input.end(), std::back_inserter(lengths), [](char symbol) { return static_cast<int>(symbol); }); for (int n : { 17, 31, 73, 47, 23 }) lengths.push_back(n); int curInd = 0; int skipSize = 0; for (int r = 0; r < numRounds; ++r) { for (int length : lengths) { if (length > static_cast<int>(sequence.size())) continue; reverse(sequence, curInd, length); curInd += (length + skipSize) % seqLength; skipSize = (skipSize + 1) % seqLength; } } std::string xored(2 * seqLength / xorLength, 0); for (int i = 0; i < seqLength / xorLength; ++i) { int xorResult = 0; for (int j = 0; j < xorLength; ++j) { xorResult ^= sequence[i * xorLength + j]; } char hex1 = (xorResult / 16) % 16; char hex0 = xorResult % 16; if (hex1 < 10) xored[i * 2] = hex1 + '0'; else xored[i * 2] = hex1 - 10 + 'a'; if (hex0 < 10) xored[i * 2 + 1] = hex0 + '0'; else xored[i * 2 + 1] = hex0 - 10 + 'a'; } return xored; } void BugFix<10>::solve1st() { int const seqLength = 256; std::vector<int> sequence; std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); }); std::string word; int curInd = 0; int skipSize = 0; while (std::getline(*mIn, word, ',')) { int const length = std::stoi(word); if (length > static_cast<int>(sequence.size())) continue; reverse(sequence, curInd, length); curInd += (length + skipSize) % seqLength; ++skipSize; } *mOut << sequence[0] * sequence[1] << std::endl; } void BugFix<10>::solve2nd() { std::string input; *mIn >> input; *mOut << knotHash(input) << std::endl; }
2,209
989
#include "yexception.h" static inline void Throw1DontMove() { ythrow yexception() << "blabla"; //dont move this line } static inline void Throw2DontMove() { ythrow yexception() << 1 << " qw " << 12.1; //dont move this line } #include <library/unittest/registar.h> #include <util/stream/ios.h> #include "yexception_ut.h" #if defined (_MSC_VER) # pragma warning(disable:4702) /*unreachable code*/ #endif static void CallbackFun(int i) { throw i; } static TOutputStream* OUTS = 0; class TExceptionTest: public TTestBase { UNIT_TEST_SUITE(TExceptionTest); UNIT_TEST_EXCEPTION(TestException, yexception) UNIT_TEST_EXCEPTION(TestLineInfo, yexception) UNIT_TEST(TestFormat1) UNIT_TEST(TestRaise1) UNIT_TEST(TestVirtuality) UNIT_TEST(TestVirtualInheritance) UNIT_TEST(TestMixedCode) UNIT_TEST_SUITE_END(); private: inline void TestVirtualInheritance() { TStringStream ss; OUTS = &ss; class TA { public: inline TA() { *OUTS << "A"; } }; class TB { public: inline TB() { *OUTS << "B"; } }; class TC: public virtual TB, public virtual TA { public: inline TC() { *OUTS << "C"; } }; class TD: public virtual TA { public: inline TD() { *OUTS << "D"; } }; class TE: public TC, public TD { public: inline TE() { *OUTS << "E"; } }; TE e; UNIT_ASSERT_EQUAL(ss.Str(), "BACDE"); } inline void TestVirtuality() { try { ythrow TFileError() << "1"; UNIT_ASSERT(false); } catch (const TIoException&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << 1; UNIT_ASSERT(false); } catch (const TSystemError&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << '1'; UNIT_ASSERT(false); } catch (const yexception&) { } catch (...) { UNIT_ASSERT(false); } try { ythrow TFileError() << 1.0; UNIT_ASSERT(false); } catch (const TFileError&) { } catch (...) { UNIT_ASSERT(false); } } inline void TestFormat1() { try { throw yexception() << 1 << " qw " << 12.1; UNIT_ASSERT(false); } catch (...) { const Stroka err = CurrentExceptionMessage(); UNIT_ASSERT_VALUES_EQUAL(err, "1 qw 12.1"); } } inline void TestRaise1() { try { Throw2DontMove(); UNIT_ASSERT(false); } catch (...) { Stroka err = CurrentExceptionMessage(); char *ptr = err.begin(); while ((ptr = strchr(ptr, '\\')) != 0) *ptr = '/'; UNIT_ASSERT_VALUES_EQUAL(err, "util/generic/yexception_ut.cpp:8: 1 qw 12.1"); } } inline void TestException() { ythrow yexception() << "blablabla"; } inline void TestLineInfo() { try { Throw1DontMove(); } catch (...) { UNIT_ASSERT_VALUES_EQUAL(CurrentExceptionMessage(), "yexception_ut.cpp:4: blabla"); throw; } } //! tests propagation of an exception through C code //! @note on some platforms, for example GCC on 32-bit Linux without -fexceptions option, //! throwing an exception from a C++ callback through C code aborts program inline void TestMixedCode() { const int N = 26082009; try { TestCallback(&CallbackFun, N); UNIT_ASSERT(false); } catch (int i) { UNIT_ASSERT_VALUES_EQUAL(i, N); } } }; UNIT_TEST_SUITE_REGISTRATION(TExceptionTest);
4,626
1,342
#include "Scene.hpp" #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/config.h> #include <numeric> #include <execution> #include "Util.hpp" #include "stb/stb_image.h" Scene::Scene(const std::filesystem::path& filename) { const auto path = util::resourcesPath / filename; const auto pathString = path.string(); Assimp::Importer importer; std::cout << "Loading model from " << filename.string() << std::endl; // aiComponent_TANGENTS_AND_BITANGENTS flips the winding order (assimp-internal bug) const aiScene * assimpScene = importer.ReadFile(pathString.c_str(), aiProcess_GenSmoothNormals | aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_JoinIdenticalVertices | aiProcess_RemoveComponent | aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS | aiComponent_CAMERAS | aiComponent_LIGHTS /*| aiComponent_TANGENTS_AND_BITANGENTS*/ | aiComponent_COLORS | aiProcess_SplitLargeMeshes | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_OptimizeMeshes | aiProcess_SortByPType | aiProcess_FindDegenerates | aiProcess_FindInvalidData); if (!assimpScene || assimpScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) { const std::string err = importer.GetErrorString(); throw std::runtime_error("Assimp import failed: " + err); } std::cout << "Assimp import complete. Processing Model..." << std::endl; // - - - M E S H E S - - - if (assimpScene->HasMeshes()) { const auto numMeshes = assimpScene->mNumMeshes; m_meshes.resize(numMeshes); for (int i = 0; i < static_cast<int>(numMeshes); ++i) { m_meshes[i] = std::shared_ptr<Mesh>(new Mesh(assimpScene->mMeshes[i], assimpScene->mMaterials[assimpScene->mMeshes[i]->mMaterialIndex], path)); } } // - - - M O D E L M A T R I C E S - - - static_assert(sizeof(aiMatrix4x4) == sizeof(glm::mat4)); std::function<void(aiNode* node, glm::mat4 trans)> traverseChildren = [this, &traverseChildren](aiNode* node, glm::mat4 trans) { // check if transformation exists if (std::none_of(&node->mTransformation.a1, (&node->mTransformation.d4) + 1, [](float f) { return std::isnan(f) || std::isinf(f); })) { // accumulate transform const glm::mat4 transform = reinterpret_cast<glm::mat4&>(node->mTransformation); trans *= transform; } // assign transformation to meshes #pragma omp parallel for for (int i = 0; i < static_cast<int>(node->mNumMeshes); ++i) { m_meshes[node->mMeshes[i]]->modelMatrix = trans; } // recursively work on the child nodes #pragma omp parallel for for (int i = 0; i < static_cast<int>(node->mNumChildren); ++i) { traverseChildren(node->mChildren[i], trans); } }; const auto root = assimpScene->mRootNode; std::thread modelMatThread([&]() { traverseChildren(root, glm::mat4(1.0f)); calculateBoundingBox(); }); { // running in parallel --> no model-matrices available in this scope! updateMultiDrawBuffers(); updateMaterialBuffer(); m_cullingProgram.attachNew(GL_COMPUTE_SHADER, ShaderFile::load("compute/viewFrustumCulling.comp")); m_lightIndexBuffer.resize(1, GL_DYNAMIC_STORAGE_BIT); } modelMatThread.join(); updateModelMatrices(); updateBoundingBoxBuffer(); std::cout << "Loading complete: " << filename.string() << std::endl; importer.FreeScene(); } void Scene::render(const Program& program, bool overwriteCameraBuffer) const { // BINDINGS m_indirectDrawBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::indirectDraw); m_bBoxBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::boundingBoxes); m_modelMatBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::modelMatrices); m_materialBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::materials); m_lightBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::lights); if (overwriteCameraBuffer) m_camera->uploadToGpu(); // CULLING m_cullingProgram.use(); glDispatchCompute(static_cast<GLuint>(glm::ceil(m_indirectDrawBuffer.size() / 64.0f)), 1, 1); glMemoryBarrier(GL_COMMAND_BARRIER_BIT | GL_SHADER_STORAGE_BARRIER_BIT); // DRAW program.use(); m_multiDrawVao.bind(); glBindBuffer(GL_DRAW_INDIRECT_BUFFER, *m_indirectDrawBuffer.id()); glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, nullptr, static_cast<GLsizei>(m_indirectDrawBuffer.size()), 0); } const Bounds& Scene::calculateBoundingBox() { struct Reduction { Bounds operator()(Bounds b, const std::shared_ptr<Mesh>& x) const { return b + Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f)); } Bounds operator()(const std::shared_ptr<Mesh>& x, Bounds b) const { return b + Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f)); } Bounds operator()(const std::shared_ptr<Mesh>& a, const std::shared_ptr<Mesh>& b) const { Bounds bounds; bounds = bounds + Bounds(a->modelMatrix * glm::vec4(a->bounds.min, 1.0f), a->modelMatrix * glm::vec4(a->bounds.max, 1.0f)); return bounds + Bounds(b->modelMatrix * glm::vec4(b->bounds.min, 1.0f), b->modelMatrix * glm::vec4(b->bounds.max, 1.0f)); } Bounds operator()(Bounds b, const Bounds& x) const { return b + x; } }; bounds = std::reduce(std::execution::par_unseq, m_meshes.begin(), m_meshes.end(), Bounds(), Reduction()); if (m_camera) m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0])); return bounds; } void Scene::updateModelMatrices() { std::vector<glm::mat4> modelMatrices(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(modelMatrices.size()); ++i) modelMatrices[i] = m_meshes[i]->modelMatrix; if (modelMatrices.size() != static_cast<size_t>(m_modelMatBuffer.size())) m_modelMatBuffer.resize(modelMatrices.size(), GL_DYNAMIC_STORAGE_BIT); m_modelMatBuffer.assign(modelMatrices); } void Scene::updateBoundingBoxBuffer() { std::vector<Bounds> boundingBoxes(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(boundingBoxes.size()); ++i) boundingBoxes[i] = m_meshes[i]->bounds; if (boundingBoxes.size() != static_cast<size_t>(m_bBoxBuffer.size())) m_bBoxBuffer.resize(boundingBoxes.size(), GL_DYNAMIC_STORAGE_BIT); m_bBoxBuffer.assign(boundingBoxes); } void Scene::updateMaterialBuffer() { std::vector<Material> materials(m_meshes.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(materials.size()); ++i) materials[i] = m_meshes[i]->material; if (materials.size() != static_cast<size_t>(m_materialBuffer.size())) m_materialBuffer.resize(materials.size(), GL_DYNAMIC_STORAGE_BIT); m_materialBuffer.assign(materials); } void Scene::updateLightBuffer() { std::vector<Light> lights(m_lights.size()); #pragma omp parallel for for (int i = 0; i < static_cast<int>(lights.size()); ++i) { m_lights[i]->recalculateLightSpaceMatrix(*this); lights[i] = *m_lights[i]; } if (lights.size() != static_cast<size_t>(m_lightBuffer.size())) m_lightBuffer.resize(lights.size(), GL_DYNAMIC_STORAGE_BIT); m_lightBuffer.assign(lights); } void Scene::updateShadowMaps() { for (int i = 0; i < static_cast<int>(m_lights.size()); ++i) { m_lightIndexBuffer.assign(i); m_lightIndexBuffer.bind(GL_UNIFORM_BUFFER, BufferBinding::lightIndex); m_lights[i]->updateShadowMap(*this); } } void Scene::addMesh(const std::shared_ptr<Mesh>& mesh) { m_meshes.push_back(mesh); std::thread bBoxThread([&]() { calculateBoundingBox(); }); updateModelMatrices(); updateMultiDrawBuffers(); updateBoundingBoxBuffer(); updateMaterialBuffer(); bBoxThread.join(); } void Scene::addLight(const std::shared_ptr<Light>& light) { m_lights.push_back(light); updateLightBuffer(); updateShadowMaps(); } void Scene::setCamera(const std::shared_ptr<Camera>& camera) { m_camera = camera; m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0])); } std::shared_ptr<Camera> Scene::getCamera() const { return m_camera; } const std::deque<std::shared_ptr<Mesh>>& Scene::getMeshes() const { return m_meshes; } void Scene::reorderMeshes() { std::deque<std::shared_ptr<Mesh>> orderedMeshes; for (const auto& mesh : m_meshes) { if (mesh->isTransparent()) orderedMeshes.push_back(mesh); else orderedMeshes.push_front(mesh); } m_meshes = orderedMeshes; updateModelMatrices(); updateMultiDrawBuffers(); updateBoundingBoxBuffer(); updateMaterialBuffer(); } void Scene::updateMultiDrawBuffers() { std::vector<GLuint> allIndices; std::vector<glm::vec4> allVertices; std::vector<glm::vec4> allNormals; std::vector<glm::vec2> allUVs; std::vector<IndirectDrawCommand> indirectDrawParams; GLuint start = 0; GLuint baseVertexOffset = 0; for (const auto& mesh : m_meshes) { allIndices.insert(allIndices.end(), mesh->indices.begin(), mesh->indices.end()); allVertices.insert(allVertices.end(), mesh->vertices.begin(), mesh->vertices.end()); allNormals.insert(allNormals.end(), mesh->normals.begin(), mesh->normals.end()); allUVs.insert(allUVs.end(), mesh->uvs.begin(), mesh->uvs.end()); const auto count = static_cast<GLuint>(mesh->indices.size()); indirectDrawParams.push_back({ count, 1U, start, baseVertexOffset, 0U }); start += count; baseVertexOffset += static_cast<GLuint>(mesh->vertices.size()); } m_multiDrawIndexBuffer.resize(allIndices.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawIndexBuffer.assign(allIndices); m_multiDrawVertexBuffer.resize(allVertices.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawVertexBuffer.assign(allVertices); m_multiDrawNormalBuffer.resize(allNormals.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawNormalBuffer.assign(allNormals); m_multiDrawUVBuffer.resize(allUVs.size(), GL_DYNAMIC_STORAGE_BIT); m_multiDrawUVBuffer.assign(allUVs); m_indirectDrawBuffer.resize(indirectDrawParams.size(), GL_DYNAMIC_STORAGE_BIT); m_indirectDrawBuffer.assign(indirectDrawParams); m_multiDrawVao.format(VertexAttributeBinding::vertices, 4, GL_FLOAT, false, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawVertexBuffer, VertexAttributeBinding::vertices, 0, sizeof(glm::vec4)); m_multiDrawVao.binding(VertexAttributeBinding::vertices); m_multiDrawVao.format(VertexAttributeBinding::normals, 4, GL_FLOAT, true, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawNormalBuffer, VertexAttributeBinding::normals, 0, sizeof(glm::vec4)); m_multiDrawVao.binding(VertexAttributeBinding::normals); m_multiDrawVao.format(VertexAttributeBinding::texCoords, 2, GL_FLOAT, false, 0); m_multiDrawVao.setVertexBuffer(m_multiDrawUVBuffer, VertexAttributeBinding::texCoords, 0, sizeof(glm::vec2)); m_multiDrawVao.binding(VertexAttributeBinding::texCoords); m_multiDrawVao.setElementBuffer(m_multiDrawIndexBuffer); }
11,578
4,121
// @TODO // https://codeforces.com/contest/1243/problem/B2
58
27
/* List of all Panels * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <QFile> #include <QTextStream> #include <QMessageBox> #include "Common/Qt/StringException.h" #include "Common/Qt/QtJsonTools.h" #include "JsonSettings.h" #include "JsonProgram.h" #include "Tools/PersistentSettings.h" #include "PanelList.h" #include <iostream> using std::cout; using std::endl; namespace PokemonAutomation{ const std::vector<std::unique_ptr<ConfigSet>>& SETTINGS_LIST(){ static std::vector<std::unique_ptr<ConfigSet>> list; if (!list.empty()){ return list; } QString path = settings.path + CONFIG_FOLDER_NAME + "/SettingsList.txt"; QFile file(path); if (!file.open(QFile::ReadOnly)){ // QMessageBox box; // box.critical(nullptr, "Error", "Unable to open settings list: " + settings_path); return list; } cout << "File = " << path.toUtf8().data() << endl; QTextStream stream(&file); while (!stream.atEnd()){ QString line = stream.readLine(); if (line.isEmpty()){ continue; } cout << "Open: " << line.toUtf8().data() << endl; try{ QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json"; list.emplace_back(new Settings_JsonFile(path)); }catch (const StringException& str){ cout << "Error: " << str.message().toUtf8().data() << endl; } } file.close(); return list; } const std::map<QString, ConfigSet*>& SETTINGS_MAP(){ static std::map<QString, ConfigSet*> map; if (!map.empty()){ return map; } for (const auto& program : SETTINGS_LIST()){ auto ret = map.emplace(program->name(), program.get()); if (!ret.second){ throw StringException("Duplicate program name: " + program->name()); } } return map; } const std::vector<std::unique_ptr<Program>>& PROGRAM_LIST(){ static std::vector<std::unique_ptr<Program>> list; if (!list.empty()){ return list; } QString path = settings.path + CONFIG_FOLDER_NAME + "/ProgramList.txt"; QFile file(path); if (!file.open(QFile::ReadOnly)){ // QMessageBox box; // box.critical(nullptr, "Error", "Unable to open programs list: " + settings_path); return list; } cout << "File = " << path.toUtf8().data() << endl; QTextStream stream(&file); while (!stream.atEnd()){ QString line = stream.readLine(); if (line.isEmpty()){ continue; } cout << "Open: " << line.toUtf8().data() << endl; try{ QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json"; list.emplace_back(new Program_JsonFile(path)); }catch (const StringException& str){ cout << "Error: " << str.message().toUtf8().data() << endl; } } file.close(); return list; } const std::map<QString, Program*>& PROGRAM_MAP(){ static std::map<QString, Program*> map; if (map.empty()){ for (const auto& program : PROGRAM_LIST()){ auto ret = map.emplace(program->name(), program.get()); if (!ret.second){ throw StringException("Duplicate program name: " + program->name()); } } } return map; } }
3,485
1,138
#include "catch.hpp" #include <boost/crc.hpp> #include <osmium/osm/crc.hpp> #include <osmium/osm/node.hpp> #include "helper.hpp" TEST_CASE("Basic_Node") { osmium::CRC<boost::crc_32_type> crc32; SECTION("node_builder") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); node.set_id(17) .set_version(3) .set_visible(true) .set_changeset(333) .set_uid(21) .set_timestamp(123); REQUIRE(osmium::item_type::node == node.type()); REQUIRE(node.type_is_in(osmium::osm_entity_bits::node)); REQUIRE(node.type_is_in(osmium::osm_entity_bits::nwr)); REQUIRE(17l == node.id()); REQUIRE(17ul == node.positive_id()); REQUIRE(3 == node.version()); REQUIRE(true == node.visible()); REQUIRE(false == node.deleted()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); REQUIRE(std::string("foo") == node.user()); REQUIRE(123 == node.timestamp()); REQUIRE(osmium::Location(3.5, 4.7) == node.location()); REQUIRE(2 == node.tags().size()); crc32.update(node); REQUIRE(crc32().checksum() == 0xc696802f); node.set_visible(false); REQUIRE(false == node.visible()); REQUIRE(true == node.deleted()); } SECTION("node_default_attributes") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); REQUIRE(0l == node.id()); REQUIRE(0ul == node.positive_id()); REQUIRE(0 == node.version()); REQUIRE(true == node.visible()); REQUIRE(0 == node.changeset()); REQUIRE(0 == node.uid()); REQUIRE(std::string("") == node.user()); REQUIRE(0 == node.timestamp()); REQUIRE(osmium::Location() == node.location()); REQUIRE(0 == node.tags().size()); } SECTION("set_node_attributes_from_string") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); node.set_id("-17") .set_version("3") .set_visible(true) .set_changeset("333") .set_uid("21"); REQUIRE(-17l == node.id()); REQUIRE(17ul == node.positive_id()); REQUIRE(3 == node.version()); REQUIRE(true == node.visible()); REQUIRE(333 == node.changeset()); REQUIRE(21 == node.uid()); } SECTION("large_id") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{}); int64_t id = 3000000000l; node.set_id(id); REQUIRE(id == node.id()); REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id()); node.set_id(-id); REQUIRE(-id == node.id()); REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id()); } SECTION("tags") { osmium::memory::Buffer buffer(10000); osmium::Node& node = buffer_add_node(buffer, "foo", {{"amenity", "pub"}, {"name", "OSM BAR"}}, {3.5, 4.7}); REQUIRE(nullptr == node.tags().get_value_by_key("fail")); REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity")); REQUIRE(std::string("pub") == node.get_value_by_key("amenity")); REQUIRE(std::string("default") == node.tags().get_value_by_key("fail", "default")); REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity", "default")); REQUIRE(std::string("pub") == node.get_value_by_key("amenity", "default")); } }
3,580
1,477
#include<bits/stdc++.h> using namespace std; const int MAXN = 2E+5 + 5; const int MAXX = 1E+9 + 7; int n, vec[MAXN],vec2[MAXN],dp[MAXN]; vector<int> fenwick(MAXN, 0); void add(int pos, int val){ for(int i = pos; i<=n; i+=i&(-i)){ fenwick[i] = max(val, fenwick[i]); } } int get(int pos){ int ans = -MAXX; for(int i = pos; i>0; i-=i&(-i)){ ans = max(ans, fenwick[i]); } return ans; } int main(){ ios::sync_with_stdio(0); cin>>n; map<int,int> comp; for(int i = 1; i<=n; i++){ cin>>vec[i]; vec2[i] = vec[i]; } sort(vec2, vec2+n+1); int counter = 1; for(int i = 1; i<=n; i++){ if(comp[vec2[i]] == 0){ comp[vec2[i]] = counter++; } } for(int i = 1; i<=n; i++) {vec[i] = comp[vec[i]];} int ans = -MAXX; for(int i = 1; i<=n; i++){ dp[i] = 1; dp[i] = max(get(vec[i]-1)+1, dp[i]); add(vec[i], dp[i]); ans = max(ans, dp[i]); } cout<<ans<<'\n'; return 0; }
1,051
494
/* * OpenCloseGraspActionServer.cpp * * Created on: Apr 19, 2013 * Author: jnicho */ /* * Software License Agreement (BSD License) * * Copyright (c) 2011, Southwest Research Institute * 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 Southwest Research Institute, 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 <ros/ros.h> #include <actionlib/server/action_server.h> #include <object_manipulation_msgs/GraspHandPostureExecutionAction.h> #include <object_manipulation_msgs/GraspHandPostureExecutionGoal.h> #include <robot_io/DigitalOutputUpdate.h> #include <soem_beckhoff_drivers/DigitalMsg.h> using namespace object_manipulation_msgs; using namespace actionlib; typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType; static const std::string OUTPUT_TOPIC = "/digital_outputs"; static const std::string INPUT_TOPIC = "/digital_inputs"; static const std::string OUTPUT_SERVICE = "/digital_output_update"; class SimpleGraspActionServer { private: typedef ActionServer<GraspHandPostureExecutionAction> GEAS; typedef GEAS::GoalHandle GoalHandle; public: SimpleGraspActionServer(ros::NodeHandle &n) : node_(n), action_server_(node_, "grasp_execution_action", boost::bind(&SimpleGraspActionServer::goalCB, this, _1), boost::bind(&SimpleGraspActionServer::cancelCB, this, _1), false), use_sensor_feedback_(false), suction_on_output_channel_(DigitalOutputType::SUCTION1_ON), suction_check_input_channel_(DigitalOutputType::SUCTION1_ON) { } ~SimpleGraspActionServer() { } void init() { ros::NodeHandle pn("/"); std::string nodeName = ros::this_node::getName(); // service client service_client_ = pn.serviceClient<robot_io::DigitalOutputUpdate>(OUTPUT_SERVICE); while(!service_client_.waitForExistence(ros::Duration(5.0f))) { ROS_INFO_STREAM(nodeName<<": Waiting for "<<OUTPUT_SERVICE<<" to start"); } if(!fetchParameters() ) { ROS_ERROR_STREAM(nodeName<<": Did not find required ros parameters, exiting"); ros::shutdown(); return; } if(!validateChannelIndices()) { ROS_ERROR_STREAM(nodeName<<": One or more parameter values are invalid"); ros::shutdown(); return; } action_server_.start(); ROS_INFO_STREAM(nodeName<<": Grasp execution action node started"); } private: void goalCB(GoalHandle gh) { std::string nodeName = ros::this_node::getName(); ROS_INFO("%s",(nodeName + ": Received grasping goal").c_str()); robot_io::DigitalOutputUpdate::Request req; robot_io::DigitalOutputUpdate::Response res; bool success; switch(gh.getGoal()->goal) { case GraspHandPostureExecutionGoal::PRE_GRASP: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = true; if(service_client_.call(req,res)) { gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command succeeded"); } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Pre-grasp command aborted"); } break; case GraspHandPostureExecutionGoal::GRASP: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Grasp command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = false; success = service_client_.call(req,res); if(success) { if(use_sensor_feedback_ && !checkSensorState()) { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Grasp command aborted"); break; } } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Grasp command aborted"); break; } gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Grasp command succeeded"); break; case GraspHandPostureExecutionGoal::RELEASE: gh.setAccepted(); ROS_INFO_STREAM(nodeName + ": Release command accepted"); req.bit_index = suction_on_output_channel_; req.output_bit_state = true; if(service_client_.call(req,res)) { gh.setSucceeded(); ROS_INFO_STREAM(nodeName + ": Release command succeeded"); } else { gh.setAborted(); ROS_INFO_STREAM(nodeName + ": Release command aborted"); } break; default: ROS_WARN_STREAM(nodeName + ": Unidentified grasp request, rejecting request"); gh.setRejected(); break; } } void cancelCB(GoalHandle gh) { std::string nodeName = ros::this_node::getName(); ROS_INFO_STREAM(nodeName + ": Canceling current grasp action"); gh.setCanceled(); ROS_INFO_STREAM(nodeName + ": Current grasp action has been canceled"); } bool fetchParameters() { ros::NodeHandle nh; bool success = true; nh.getParam("use_sensor_feedback",use_sensor_feedback_); success = success && nh.getParam("suction_on_output_channel",suction_on_output_channel_); success = success && nh.getParam("suction_check_output_channel",suction_check_input_channel_); return success; } bool validateChannelIndices() { typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType; if(suction_on_output_channel_ >= (int)DigitalOutputType::COUNT || suction_on_output_channel_ == (int)DigitalOutputType::COLLISION) { return false; } if(suction_check_input_channel_ >= int(DigitalOutputType::COUNT)) { return false; } return true; } bool checkSensorState() { ros::NodeHandle nh("/"); soem_beckhoff_drivers::DigitalMsg::ConstPtr input_msg_ = ros::topic::waitForMessage<soem_beckhoff_drivers::DigitalMsg>(INPUT_TOPIC,nh,ros::Duration(2.0f)); if(!input_msg_) { ROS_ERROR_STREAM(ros::this_node::getName()<<": Input message received invalid"); return true; } else { return ((input_msg_->values[suction_check_input_channel_] == 1) ? true : false); } } // ros comm ros::NodeHandle node_; GEAS action_server_; ros::ServiceClient service_client_; // ros parameters int suction_on_output_channel_; // index value to output channel for suction int suction_check_input_channel_; // index value to input channel for vacuum sensor bool use_sensor_feedback_; }; int main(int argc, char** argv) { ros::init(argc, argv, "grasp_execution_action_node"); ros::NodeHandle node(""); SimpleGraspActionServer ge(node); ge.init(); ros::spin(); return 0; }
7,852
2,909
#include <iostream.h> #include <conio.h> void convert (char letter); main() { int x = 2; //for the do/while char b; //to accept letter input do{ cout<<"Welcome to the Letter Converter Program. \n"; cout<<"This program will accept a letter and convert it between \n"; //introduction cout<<"uppercase and lower case. \n"; cout<<"\nEnter a letter to convert. -> "; cin>>b; convert(b); //sends b to the function convert, doesn't return. do{ cout<<"\nTo stop the program, enter 1. To rerun the program, enter 2. -> "; cin>>x; cout<<endl; // this makes it so only 1 or 2 can be entered - cannot enter 3 to quit for instance. }while((x != 1) && (x != 2)); clrscr(); }while(x==2); return 0; } void convert (char letter) { //The letter must be between 65-90 and 97-122 to be 'a to z'. //Which is why 91-96 is not allowed. if(letter >= 65 && letter <= 122) { //uppercase to lower case. if(letter >= 65 && letter <= 90) { letter = letter + 32; cout<<endl<<letter<<endl; letter = letter - 32; //without this it seems to convert it back to uppercase, but this fixes that issue. } //for 91 to 96, which are not letters. if(letter >=91 && letter <= 96) { cout<<"\nYou didn't enter a letter; try again. \n"; } //lower case to upper case. if(letter >= 97 && letter <= 122) { letter = letter - 32; cout<<endl<<letter<<endl; } } else //if the user enters something else that isn't letter (65-90 or 97-122), the program prints this. { cout<<"\nYou didn't enter a letter; try again. \n"; } }
1,651
663
#include <src/adcs/state_estimators/b_dot_estimator.h> #include <src/util/matrix.h> #include <src/util/msp_exception.h> #include <src/util/physical_constants.h> BDotEstimator::BDotEstimator(uint16_t sample_period_millis, uint16_t time_constant_millis) : smoother_x(time_constant_millis, sample_period_millis), smoother_y(time_constant_millis, sample_period_millis), smoother_z(time_constant_millis, sample_period_millis), differentiator_x(sample_period_millis), differentiator_y(sample_period_millis), differentiator_z(sample_period_millis) {} void BDotEstimator::Estimate(const Matrix &magnetometer_reading, Matrix &estimate_output) { if (!estimate_output.SameSize(magnetometer_reading) || estimate_output.GetNRows() != geomagnetic_field_vector_nrows || estimate_output.GetNColumns() != geomagnetic_field_vector_ncolumns) { throw MspException("BDotEstimator::Estimate arguments not 3x1", kBdotEstimatorArgumentFail, __FILE__, __LINE__); } estimate_output.Set(0, 0, differentiator_x.ProcessSample(smoother_x.ProcessSample( magnetometer_reading.Get(0, 0)))); estimate_output.Set(1, 0, differentiator_y.ProcessSample(smoother_y.ProcessSample( magnetometer_reading.Get(1, 0)))); estimate_output.Set(2, 0, differentiator_z.ProcessSample(smoother_z.ProcessSample( magnetometer_reading.Get(2, 0)))); }
1,617
511
// mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.cc is auto generated by mojom_bindings_generator.py, do not edit // 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #endif #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/hash/md5_constexpr.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/task/common/task_annotator.h" #include "base/trace_event/trace_event.h" #include "mojo/public/cpp/bindings/lib/generated_code_util.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "third_party/perfetto/include/perfetto/tracing/traced_value.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-params-data.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-shared-message-ids.h" #include "mojo/public/interfaces/bindings/tests/deserializer.test-mojom-blink-import-headers.h" #include "mojo/public/cpp/bindings/lib/wtf_serialization.h" #ifndef MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_DESERIALIZER_TEST_MOJOM_BLINK_JUMBO_H_ #define MOJO_PUBLIC_INTERFACES_BINDINGS_TESTS_DESERIALIZER_TEST_MOJOM_BLINK_JUMBO_H_ #endif namespace deserializer { namespace blink { TestStruct::TestStruct() : v1(), v2(), v3() {} TestStruct::TestStruct( int32_t v1_in, int32_t v2_in, int64_t v3_in) : v1(std::move(v1_in)), v2(std::move(v2_in)), v3(std::move(v3_in)) {} TestStruct::~TestStruct() = default; size_t TestStruct::Hash(size_t seed) const { seed = mojo::internal::WTFHash(seed, this->v1); seed = mojo::internal::WTFHash(seed, this->v2); seed = mojo::internal::WTFHash(seed, this->v3); return seed; } void TestStruct::WriteIntoTracedValue(perfetto::TracedValue context) const { auto dict = std::move(context).WriteDictionary(); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v1"), this->v1, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int32_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v2"), this->v2, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int32_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); perfetto::WriteIntoTracedValueWithFallback( dict.AddItem( "v3"), this->v3, #if BUILDFLAG(MOJO_TRACE_ENABLED) "<value of type int64_t>" #else "<value>" #endif // BUILDFLAG(MOJO_TRACE_ENABLED) ); } bool TestStruct::Validate( const void* data, mojo::internal::ValidationContext* validation_context) { return Data_::Validate(data, validation_context); } } // namespace blink } // namespace deserializer namespace mojo { // static bool StructTraits<::deserializer::blink::TestStruct::DataView, ::deserializer::blink::TestStructPtr>::Read( ::deserializer::blink::TestStruct::DataView input, ::deserializer::blink::TestStructPtr* output) { bool success = true; ::deserializer::blink::TestStructPtr result(::deserializer::blink::TestStruct::New()); if (success) result->v1 = input.v1(); if (success) result->v2 = input.v2(); if (success) result->v3 = input.v3(); *output = std::move(result); return success; } } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #endif
4,108
1,600
/* This file is part of the regenie software package. Copyright (c) 2020-2021 Joelle Mbatchou, Andrey Ziyatdinov & Jonathan Marchini Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Regenie.hpp" #include "Files.hpp" #include "Geno.hpp" #include "Step1_Models.hpp" #include "Pheno.hpp" #include "HLM.hpp" using namespace std; using namespace Eigen; using namespace boost; using namespace LBFGSpp; using boost::math::normal; using boost::math::chi_squared; HLM::HLM(){ } HLM::~HLM(){ } void HLM::prep_run(struct phenodt const* pheno_data, struct param const* params){ // store Vlin = (1, E) allocate_mat(Vlin, pheno_data->interaction_cov.rows(), params->ncov_interaction + 1); Vlin << MatrixXd::Ones(pheno_data->interaction_cov.rows(),1), pheno_data->interaction_cov; if(params->hlm_vquad && params->int_add_extra_term){ // set V = (1, E, E^2) [ apply QR to U = (E,E^2), center & scale, and set V = (1, U)] MatrixXd Vtmp (Vlin.rows(), params->ncov_interaction * 2); Vtmp << pheno_data->interaction_cov, pheno_data->interaction_cov.array().square().matrix(); //cerr << "pre:\n" << Vtmp.topRows(5) << "\n\n"; apply_QR(Vtmp, params, true); allocate_mat(V, Vtmp.rows(), Vtmp.cols() + 1); V << MatrixXd::Ones(Vtmp.rows(),1), Vtmp; //cerr << "post:\n" << V.topRows(5) << "\n\n"; } else { // set V = (1, E) and center & scale E allocate_mat(V, Vlin.rows(), Vlin.cols()); V = Vlin; rescale_mat(V.rightCols(params->ncov_interaction), params); } // set X = (covs, E^2?, blup) - covs may include E MatrixXd Xtmp (pheno_data->new_cov.rows(), params->ncov + (params->int_add_extra_term && !params->add_homdev ? params->ncov_interaction : 0 )); if(params->int_add_extra_term && !params->add_homdev) { //cerr << "pre:\n" << Xtmp.topRows(5) << "\n\n"; Xtmp << pheno_data->new_cov, pheno_data->interaction_cov.array().square().matrix(); apply_QR(Xtmp, params, false); } else Xtmp = pheno_data->new_cov; //cerr << "post:\n" << Xtmp.topRows(5) << "\n\n"; allocate_mat(X, Xtmp.rows(), Xtmp.cols() + (params->skip_blups ? 0 : 1) ); X.leftCols(Xtmp.cols()) = Xtmp; // for projection under null Px.resize(params->n_pheno); allocate_mat(yres, pheno_data->interaction_cov.rows(), params->n_pheno); } // For each phenotype, fit the null HLM // Y = Xa + e, where e ~ N(0, exp(Vb) ) // Have this be outside of the class so can use LBFGS solver void HLM_fitNull(HLM& nullHLM, struct ests const& m_ests, struct phenodt const& pheno_data, struct in_files const& files, struct param const& params, mstream& sout){ // if no blup predictions are given, this should only be ran once if(params.skip_blups && !nullHLM.first_fit) return; sout << " -fitting null HLMs for each trait..." << flush; auto t1 = std::chrono::high_resolution_clock::now(); double fx; VectorXd beta(nullHLM.V.cols()); allocate_mat(nullHLM.Dinv_sqrt, pheno_data.phenotypes_raw.rows(), pheno_data.phenotypes_raw.cols()); LBFGSParam<double> bfgs_param; bfgs_param.max_iterations = nullHLM.max_iter; bfgs_param.max_linesearch = nullHLM.linesearch_try; // use more lenient number LBFGSSolver<double> solver(bfgs_param); for(int i = 0; i < params.n_pheno; i++){ nullHLM.n = pheno_data.Neff(i); nullHLM.mask = pheno_data.masked_indivs.col(i); nullHLM.y = pheno_data.phenotypes_raw.col(i); if(!params.skip_blups) // add blup as a covariate nullHLM.X.rightCols(1) = m_ests.blups.col(i); beta.array() = 0; try { // get starting value for b nullHLM.get_alpha(beta); nullHLM.get_beta_approx(beta); // LBFGS solver.minimize(nullHLM, beta, fx); nullHLM.store_null_est(i); } catch(...){ // redo with higher number of line search trials try { if(params.verbose) sout << "Retrying HLM null model fitting for " << files.pheno_names[i] << endl; LBFGSParam<double> bfgs_param_retry; bfgs_param_retry.max_iterations = nullHLM.max_iter_retry; bfgs_param_retry.max_linesearch = nullHLM.linesearch_retry; bfgs_param_retry.max_step = nullHLM.max_step_retry; LBFGSSolver<double> solver_retry(bfgs_param_retry); // get starting value for b beta.array() = 0; nullHLM.get_alpha(beta); nullHLM.get_beta_approx(beta); // LBFGS solver_retry.minimize(nullHLM, beta, fx); nullHLM.store_null_est(i); } catch(...){ throw "LFBGS could not fit HLM null model for trait " + files.pheno_names[i]; } } //cerr << "\nFinal--\nalpha=\n"<<nullHLM.alpha << "\n\nbeta=\n" << beta <<"\n\nfx=" << fx << "\t" << std::boolalpha << isnan(fx); } //cerr << "\n\n" << nullHLM.yres.topRows(5)<<"\n\n"; sout << "done"; auto t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); sout << " (" << duration.count() << "ms) "<< endl; nullHLM.first_fit = false; } void HLM::get_alpha(VectorXd const& beta){ Vb = (V * beta).array(); Dinv = (-Vb).exp() * mask.cast<double>(); if( (Dinv == 0).all() ) // will cause Xd = 0 throw std::underflow_error("D=0 occurred"); MatrixXd Xd = (X.array().colwise() * Dinv).matrix().transpose(); alpha = (Xd * X).colPivHouseholderQr().solve( Xd * y ); } void HLM::get_beta_approx(VectorXd& beta){ ArrayXd esq = ((y - X * alpha).array() * mask.cast<double>()).square(); //cerr << "\nE=\n" << esq.head(10) << "\n\n"; beta = (V.transpose() * esq.matrix().asDiagonal() * V).colPivHouseholderQr().solve( V.transpose() * ((esq - 1) * mask.cast<double>()).matrix() ); //cerr << "alpha:\n" << alpha << "\n\nbeta:\n" << beta <<"\n\n"; } // get projection matrix void HLM::store_null_est(int const& ph){ Dinv_sqrt.col(ph) = Dinv.sqrt().matrix(); MatrixXd Xd = (X.array().colwise() * Dinv_sqrt.col(ph).array()).matrix(); SelfAdjointEigenSolver<MatrixXd> es(Xd.transpose() * Xd); VectorXd eigD = es.eigenvalues(); Px[ph] = ((Xd * es.eigenvectors()).array().rowwise() / eigD.transpose().array().sqrt()).matrix(); //cerr << "\nP=\n" << Px[ph].topRows(5) << "\n\n"; residualize(ph, y, yres.col(ph)); } void HLM::residualize(int const& ph, Ref<MatrixXd> mat_orig, Ref<MatrixXd> mat_res){ MatrixXd m = (mat_orig.array().colwise() * Dinv_sqrt.col(ph).array()).matrix(); //cerr << "Y" << ph+1 << "\norig:\n" << print_mat_dims(mat_orig) << // "\nm:\n" << print_mat_dims(m) << "\nPx:\n" << print_mat_dims(Px[ph]) << endl; mat_res = m - Px[ph] * (Px[ph].transpose() * m); }
7,656
3,001
#include "global.h" #include <math.h> #include <time.h> void localInitialization() { int color_pop = st_MPI_p.color_pop; int* nPop_all = st_MPI_p.nPop_all; int mpi_rank = st_MPI_p.mpi_rank; int mpi_size_subPop = st_MPI_p.mpi_size_subPop; int mpi_rank_subPop = st_MPI_p.mpi_rank_subPop; int nPop = st_global_p.nPop; int nObj = st_global_p.nObj; int nDim = st_global_p.nDim; int* each_size_subPop = st_MPI_p.each_size_subPop; int* recv_size_subPop = st_MPI_p.recv_size_subPop; int* disp_size_subPop = st_MPI_p.disp_size_subPop; int* nPop_mine = &st_global_p.nPop_mine; int* nPop_exchange = &st_global_p.nPop_exchange; int* n_weights_mine = &st_pop_comm_p.n_weights_mine; int* n_weights_left = &st_pop_comm_p.n_weights_left; int* n_weights_right = &st_pop_comm_p.n_weights_right; int* n_neighbor_left = &st_pop_comm_p.n_neighbor_left; int* n_neighbor_right = &st_pop_comm_p.n_neighbor_right; double* weights_mine = st_decomp_p.weights_mine; double* weights_all = st_decomp_p.weights_all; double* posFactor_mine = st_pop_comm_p.posFactor_mine; double* diver_var_store_all = st_grp_info_p.diver_var_store_all; double* weights_left = st_decomp_p.weights_left; double* weights_right = st_decomp_p.weights_right; double* posFactor_left = st_pop_comm_p.posFactor_left; double* posFactor_right = st_pop_comm_p.posFactor_right; // int i; int quo; int rem; quo = nPop_all[color_pop] / mpi_size_subPop; rem = nPop_all[color_pop] % mpi_size_subPop; for(i = 0; i < mpi_size_subPop; i++) { each_size_subPop[i] = quo; if(i < rem) each_size_subPop[i]++; recv_size_subPop[i] = each_size_subPop[i]; } disp_size_subPop[0] = 0; for(i = 1; i < mpi_size_subPop; i++) { disp_size_subPop[i] = disp_size_subPop[i - 1] + recv_size_subPop[i - 1]; } // (*nPop_mine) = each_size_subPop[mpi_rank_subPop]; int min_num; MPI_Allreduce(nPop_mine, &min_num, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if(min_num == 0) { if(0 == mpi_rank) printf("%s: There are too many CPUs, at least one rank has 0 individual, exiting...\n", AT); MPI_Abort(MPI_COMM_WORLD, MY_ERROR_MPI_TOOMANY); } (*nPop_exchange) = 0; (*n_weights_mine) = (*nPop_mine); if(mpi_rank_subPop) (*n_weights_left) = each_size_subPop[mpi_rank_subPop - 1]; else (*n_weights_left) = 0; if(mpi_rank_subPop < mpi_size_subPop - 1) (*n_weights_right) = each_size_subPop[mpi_rank_subPop + 1]; else (*n_weights_right) = 0; (*n_neighbor_left) = (*n_weights_left); (*n_neighbor_right) = (*n_weights_right); // load_weights();////////////////////////////////////////////////////////////////////////// // memcpy(weights_mine, &weights_all[disp_size_subPop[mpi_rank_subPop] * nObj], (*n_weights_mine) * nObj * sizeof(double)); memcpy(posFactor_mine, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop] * nDim], (*n_weights_mine) * nDim * sizeof(double)); if((*n_weights_left)) { memcpy(weights_left, &weights_all[disp_size_subPop[mpi_rank_subPop - 1] * nObj], (*n_weights_left) * nObj * sizeof(double)); memcpy(posFactor_left, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop - 1] * nDim], (*n_weights_left) * nDim * sizeof(double)); } if((*n_weights_right)) { memcpy(weights_right, &weights_all[disp_size_subPop[mpi_rank_subPop + 1] * nObj], (*n_weights_right) * nObj * sizeof(double)); memcpy(posFactor_right, &diver_var_store_all[disp_size_subPop[mpi_rank_subPop + 1] * nDim], (*n_weights_right) * nDim * sizeof(double)); } // return; } void localInitialization_ND() { int color_pop = st_MPI_p.color_pop; int* nPop_all = st_MPI_p.nPop_all; int mpi_rank = st_MPI_p.mpi_rank; int mpi_size_subPop = st_MPI_p.mpi_size_subPop; int mpi_rank_subPop = st_MPI_p.mpi_rank_subPop; int* each_size_subPop = st_MPI_p.each_size_subPop; int* recv_size_subPop = st_MPI_p.recv_size_subPop; int* disp_size_subPop = st_MPI_p.disp_size_subPop; int* nPop_mine = &st_global_p.nPop_mine; // int i; int quo; int rem; quo = nPop_all[color_pop] / mpi_size_subPop; rem = nPop_all[color_pop] % mpi_size_subPop; for(i = 0; i < mpi_size_subPop; i++) { each_size_subPop[i] = quo; if(i < rem) each_size_subPop[i]++; recv_size_subPop[i] = each_size_subPop[i]; } disp_size_subPop[0] = 0; for(i = 1; i < mpi_size_subPop; i++) { disp_size_subPop[i] = disp_size_subPop[i - 1] + recv_size_subPop[i - 1]; } // (*nPop_mine) = each_size_subPop[mpi_rank_subPop]; int min_num; MPI_Allreduce(nPop_mine, &min_num, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); if(min_num == 0) { if(0 == mpi_rank) printf("%s: There are too many CPUs, at least one rank has 0 individual, exiting...\n", AT); MPI_Abort(MPI_COMM_WORLD, MY_ERROR_MPI_TOOMANY); } return; }
5,098
2,222
/* Copyright (c) 2018 PaddlePaddle 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 <math.h> #include <algorithm> #include <string> #include <vector> #include "paddle/fluid/framework/lod_tensor.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/detection/bbox_util.h" #include "paddle/fluid/operators/detection/mask_util.h" #include "paddle/fluid/operators/gather.h" #include "paddle/fluid/operators/math/concat_and_split.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; const int kBoxDim = 4; template <typename T> void AppendMask(LoDTensor* out, int64_t offset, Tensor* to_add) { auto* out_data = out->data<T>(); auto* to_add_data = to_add->data<T>(); memcpy(out_data + offset, to_add_data, to_add->numel() * sizeof(T)); } class GenerateMaskLabelsOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("ImInfo"), "Input(ImInfo) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("GtClasses"), "Input(GtClasses) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("IsCrowd"), "Input(IsCrowd) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("GtSegms"), "Input(GtSegms) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("Rois"), "Input(Rois) shouldn't be null."); PADDLE_ENFORCE(ctx->HasInput("LabelsInt32"), "Input(LabelsInt32) shouldn't be null."); PADDLE_ENFORCE( ctx->HasOutput("MaskRois"), "Output(MaskRois) of GenerateMaskLabelsOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("RoiHasMaskInt32"), "Output(RoiHasMaskInt32) of GenerateMaskLabelsOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("MaskInt32"), "Output(MaskInt32) of GenerateMaskLabelsOp should not be null"); auto im_info_dims = ctx->GetInputDim("ImInfo"); auto gt_segms_dims = ctx->GetInputDim("GtSegms"); PADDLE_ENFORCE_EQ(im_info_dims.size(), 2, "The rank of Input(ImInfo) must be 2."); PADDLE_ENFORCE_EQ(gt_segms_dims.size(), 2, "The rank of Input(GtSegms) must be 2."); PADDLE_ENFORCE_EQ(gt_segms_dims[1], 2, "The second dim of Input(GtSegms) must be 2."); int num_classes = ctx->Attrs().Get<int>("num_classes"); int resolution = ctx->Attrs().Get<int>("resolution"); ctx->SetOutputDim("MaskRois", {-1, 4}); ctx->SetOutputDim("RoiHasMaskInt32", {-1, 1}); ctx->SetOutputDim("MaskInt32", {-1, num_classes * resolution * resolution}); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext& ctx) const override { auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Rois"); return framework::OpKernelType(data_type, platform::CPUPlace()); } }; /* * Expand masks from shape (#masks, M ** 2) to (#masks, #classes * M ** 2) * to encode class specific mask targets. */ template <typename T> static inline void ExpandMaskTarget(const platform::CPUDeviceContext& ctx, const Tensor& masks, const Tensor& mask_class_labels, const int resolution, const int num_classes, Tensor* mask_targets) { const uint8_t* masks_data = masks.data<uint8_t>(); int64_t num_mask = masks.dims()[0]; const int* mask_class_labels_data = mask_class_labels.data<int>(); const int M = resolution * resolution; const int mask_dim = M * num_classes; int* mask_targets_data = mask_targets->mutable_data<int>({num_mask, mask_dim}, ctx.GetPlace()); math::set_constant(ctx, mask_targets, -1); for (int64_t mask_id = 0; mask_id < num_mask; ++mask_id) { int cls = mask_class_labels_data[mask_id]; int start = M * cls; if (cls > 0) { for (int i = 0; i < M; ++i) { mask_targets_data[mask_id * mask_dim + start + i] = static_cast<int>(masks_data[mask_id * M + i]); } } } } template <typename T> std::vector<Tensor> SampleMaskForOneImage( const platform::CPUDeviceContext& ctx, const Tensor& im_info, const Tensor& gt_classes, const Tensor& is_crowd, const Tensor& gt_segms, const Tensor& rois, const Tensor& label_int32, const int num_classes, const int resolution, const framework::LoD& segm_length) { // Prepare the mask targets by associating one gt mask to each training roi // that has a fg (non-bg) class label. const int64_t gt_size = static_cast<int64_t>(gt_classes.dims()[0]); const int64_t roi_size = static_cast<int64_t>(rois.dims()[0]); const int* gt_classes_data = gt_classes.data<int>(); const int* is_crowd_data = is_crowd.data<int>(); const int* label_int32_data = label_int32.data<int>(); PADDLE_ENFORCE_EQ(roi_size, label_int32.dims()[0]); std::vector<int> mask_gt_inds, fg_inds; std::vector<std::vector<std::vector<T>>> gt_polys; auto polys_num = segm_length[1]; auto segm_lod_offset = framework::ConvertToOffsetBasedLoD(segm_length); auto lod1 = segm_lod_offset[1]; auto lod2 = segm_lod_offset[2]; const T* polys_data = gt_segms.data<T>(); for (int64_t i = 0; i < gt_size; ++i) { if ((gt_classes_data[i] > 0) && (is_crowd_data[i] == 0)) { mask_gt_inds.emplace_back(i); // slice fg segmentation polys int poly_num = polys_num[i]; std::vector<std::vector<T>> polys; int s_idx = lod1[i]; for (int j = 0; j < poly_num; ++j) { int s = lod2[s_idx + j]; int e = lod2[s_idx + j + 1]; PADDLE_ENFORCE_NE(s, e); std::vector<T> plts(polys_data + s * 2, polys_data + e * 2); polys.push_back(plts); } gt_polys.push_back(polys); } } for (int64_t i = 0; i < roi_size; ++i) { if (label_int32_data[i] > 0) { fg_inds.emplace_back(i); } } int gt_num = mask_gt_inds.size(); int fg_num = fg_inds.size(); Tensor boxes_from_polys; boxes_from_polys.mutable_data<T>({gt_num, 4}, platform::CPUPlace()); Poly2Boxes(gt_polys, boxes_from_polys.data<T>()); std::vector<int> roi_has_mask = std::vector<int>(fg_inds.begin(), fg_inds.end()); Tensor mask_class_labels; Tensor masks; Tensor rois_fg; auto im_scale = im_info.data<T>()[2]; if (fg_num > 0) { // Class labels for the foreground rois mask_class_labels.mutable_data<int>({fg_num, 1}, ctx.GetPlace()); Gather<int>(label_int32_data, 1, fg_inds.data(), fg_inds.size(), mask_class_labels.data<int>()); uint8_t* masks_data = masks.mutable_data<uint8_t>( {fg_num, resolution * resolution}, ctx.GetPlace()); // Find overlap between all foreground rois and the bounding boxes // enclosing each segmentation T* rois_fg_data = rois_fg.mutable_data<T>({fg_num, 4}, ctx.GetPlace()); Gather<T>(rois.data<T>(), 4, fg_inds.data(), fg_inds.size(), rois_fg.data<T>()); for (int k = 0; k < rois_fg.numel(); ++k) { rois_fg_data[k] = rois_fg_data[k] / im_scale; } Tensor overlaps_bbfg_bbpolys; overlaps_bbfg_bbpolys.mutable_data<T>({fg_num, gt_num}, ctx.GetPlace()); BboxOverlaps<T>(rois_fg, boxes_from_polys, &overlaps_bbfg_bbpolys); // Map from each fg rois to the index of the mask with highest overlap // (measured by bbox overlap) T* overlaps_bbfg_bbpolys_data = overlaps_bbfg_bbpolys.data<T>(); std::vector<int> fg_masks_inds; for (int64_t i = 0; i < fg_num; ++i) { const T* v = overlaps_bbfg_bbpolys_data + i * gt_num; T max_overlap = std::numeric_limits<T>::min(); int id = 0; for (int64_t j = 0; j < gt_num; ++j) { if (v[j] > max_overlap) { max_overlap = v[j]; id = j; } } fg_masks_inds.push_back(id); } // add fg targets for (int64_t i = 0; i < fg_num; ++i) { int fg_polys_ind = fg_masks_inds[i]; T* roi_fg = rois_fg_data + i * 4; uint8_t* mask = masks_data + i * resolution * resolution; Polys2MaskWrtBox(gt_polys[fg_polys_ind], roi_fg, resolution, mask); } } else { // The network cannot handle empty blobs, so we must provide a mask // We simply take the first bg roi, given it an all -1's mask (ignore // label), and label it with class zero (bg). int bg_num = 1; T* rois_fg_data = rois_fg.mutable_data<T>({bg_num, 4}, ctx.GetPlace()); const T* rois_data = rois.data<T>(); std::vector<int> bg_inds; for (int64_t i = 0; i < roi_size; ++i) { if (label_int32_data[i] == 0) { bg_inds.emplace_back(i); rois_fg_data[0] = rois_data[0] / im_scale; rois_fg_data[1] = rois_data[1] / im_scale; rois_fg_data[2] = rois_data[2] / im_scale; rois_fg_data[3] = rois_data[3] / im_scale; break; } } masks.mutable_data<uint8_t>({bg_num, resolution * resolution}, ctx.GetPlace()); math::set_constant(ctx, &masks, -1); int* mask_class_labels_data = mask_class_labels.mutable_data<int>({bg_num, 1}, ctx.GetPlace()); mask_class_labels_data[0] = 0; roi_has_mask = std::vector<int>(bg_inds.begin(), bg_inds.end()); } Tensor masks_expand; ExpandMaskTarget<T>(ctx, masks, mask_class_labels, resolution, num_classes, &masks_expand); T* rois_fg_data = rois_fg.data<T>(); for (int k = 0; k < rois_fg.numel(); ++k) { rois_fg_data[k] = rois_fg_data[k] * im_scale; } Tensor roi_has_mask_t; int roi_has_mask_size = roi_has_mask.size(); int* roi_has_mask_data = roi_has_mask_t.mutable_data<int>({roi_has_mask_size, 1}, ctx.GetPlace()); std::copy(roi_has_mask.begin(), roi_has_mask.end(), roi_has_mask_data); std::vector<Tensor> res; res.emplace_back(rois_fg); res.emplace_back(roi_has_mask_t); res.emplace_back(masks_expand); return res; } template <typename T> class GenerateMaskLabelsKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* im_info = ctx.Input<LoDTensor>("ImInfo"); auto* gt_classes = ctx.Input<LoDTensor>("GtClasses"); auto* is_crowd = ctx.Input<LoDTensor>("IsCrowd"); auto* gt_segms = ctx.Input<LoDTensor>("GtSegms"); auto* rois = ctx.Input<LoDTensor>("Rois"); auto* label_int32 = ctx.Input<LoDTensor>("LabelsInt32"); auto* mask_rois = ctx.Output<LoDTensor>("MaskRois"); auto* roi_has_mask_int32 = ctx.Output<LoDTensor>("RoiHasMaskInt32"); auto* mask_int32 = ctx.Output<LoDTensor>("MaskInt32"); int num_classes = ctx.Attr<int>("num_classes"); int resolution = ctx.Attr<int>("resolution"); PADDLE_ENFORCE_EQ(gt_classes->lod().size(), 1UL, "GenerateMaskLabelsOp gt_classes needs 1 level of LoD"); PADDLE_ENFORCE_EQ(is_crowd->lod().size(), 1UL, "GenerateMaskLabelsOp is_crowd needs 1 level of LoD"); PADDLE_ENFORCE_EQ(rois->lod().size(), 1UL, "GenerateMaskLabelsOp rois needs 1 level of LoD"); PADDLE_ENFORCE_EQ(label_int32->lod().size(), 1UL, "GenerateMaskLabelsOp label_int32 needs 1 level of LoD"); PADDLE_ENFORCE_EQ(gt_segms->lod().size(), 3UL); int64_t n = static_cast<int64_t>(gt_classes->lod().back().size() - 1); PADDLE_ENFORCE_EQ(gt_segms->lod()[0].size() - 1, n); int mask_dim = num_classes * resolution * resolution; int roi_num = rois->lod().back()[n]; mask_rois->mutable_data<T>({roi_num, kBoxDim}, ctx.GetPlace()); roi_has_mask_int32->mutable_data<int>({roi_num, 1}, ctx.GetPlace()); mask_int32->mutable_data<int>({roi_num, mask_dim}, ctx.GetPlace()); framework::LoD lod; std::vector<size_t> lod0(1, 0); int64_t num_mask = 0; auto& dev_ctx = ctx.device_context<platform::CPUDeviceContext>(); auto gt_classes_lod = gt_classes->lod().back(); auto is_crowd_lod = is_crowd->lod().back(); auto rois_lod = rois->lod().back(); auto label_int32_lod = label_int32->lod().back(); auto gt_segms_lod = gt_segms->lod(); for (int i = 0; i < n; ++i) { if (rois_lod[i] == rois_lod[i + 1]) { lod0.emplace_back(num_mask); continue; } Tensor im_info_slice = im_info->Slice(i, i + 1); Tensor gt_classes_slice = gt_classes->Slice(gt_classes_lod[i], gt_classes_lod[i + 1]); Tensor is_crowd_slice = is_crowd->Slice(is_crowd_lod[i], is_crowd_lod[i + 1]); Tensor label_int32_slice = label_int32->Slice(label_int32_lod[i], label_int32_lod[i + 1]); Tensor rois_slice = rois->Slice(rois_lod[i], rois_lod[i + 1]); auto sub_lod_and_offset = framework::GetSubLoDAndAbsoluteOffset(gt_segms_lod, i, i + 1, 0); auto lod_length = sub_lod_and_offset.first; size_t s = sub_lod_and_offset.second.first; size_t e = sub_lod_and_offset.second.second; Tensor gt_segms_slice = gt_segms->Slice(s, e); std::vector<Tensor> tensor_output = SampleMaskForOneImage<T>( dev_ctx, im_info_slice, gt_classes_slice, is_crowd_slice, gt_segms_slice, rois_slice, label_int32_slice, num_classes, resolution, lod_length); Tensor sampled_mask_rois = tensor_output[0]; Tensor sampled_roi_has_mask_int32 = tensor_output[1]; Tensor sampled_mask_int32 = tensor_output[2]; AppendMask<T>(mask_rois, kBoxDim * num_mask, &sampled_mask_rois); AppendMask<int>(roi_has_mask_int32, num_mask, &sampled_roi_has_mask_int32); AppendMask<int>(mask_int32, mask_dim * num_mask, &sampled_mask_int32); num_mask += sampled_mask_rois.dims()[0]; lod0.emplace_back(num_mask); } lod.emplace_back(lod0); mask_rois->set_lod(lod); roi_has_mask_int32->set_lod(lod); mask_int32->set_lod(lod); mask_rois->Resize({num_mask, kBoxDim}); roi_has_mask_int32->Resize({num_mask, 1}); mask_int32->Resize({num_mask, mask_dim}); } }; class GenerateMaskLabelsOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput("ImInfo", "(Tensor), This input is a 2D Tensor with shape [B, 3]. " "B is the number of input images, " "each element consists of im_height, im_width, im_scale."); AddInput("GtClasses", "(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. " "M is the number of groundtruth, " "each element is a class label of groundtruth."); AddInput( "IsCrowd", "(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. " "M is the number of groundtruth, " "each element is a flag indicates whether a groundtruth is crowd."); AddInput( "GtSegms", "(LoDTensor), This input is a 2D LoDTensor with shape [S, 2], it's LoD " "level is 3. The LoD[0] represents the gt objects number of each " "instance. LoD[1] represents the segmentation counts of each objects. " "LoD[2] represents the polygons number of each segmentation. S the " "total number of polygons coordinate points. Each element is (x, y) " "coordinate points."); AddInput( "Rois", "(LoDTensor), This input is a 2D LoDTensor with shape [R, 4]. " "R is the number of rois which is the output of " "generate_proposal_labels, " "each element is a bounding box with (xmin, ymin, xmax, ymax) format."); AddInput("LabelsInt32", "(LoDTensor), This intput is a 2D LoDTensor with shape [R, 1], " "each element repersents a class label of a roi"); AddOutput( "MaskRois", "(LoDTensor), This output is a 2D LoDTensor with shape [P, 4]. " "P is the number of mask, " "each element is a bounding box with [xmin, ymin, xmax, ymax] format."); AddOutput("RoiHasMaskInt32", "(LoDTensor), This output is a 2D LoDTensor with shape [P, 1], " "each element repersents the output mask rois index with regard " "to input rois"); AddOutput("MaskInt32", "(LoDTensor), This output is a 4D LoDTensor with shape [P, Q], " "Q equal to num_classes * resolution * resolution"); AddAttr<int>("num_classes", "Class number."); AddAttr<int>("resolution", "Resolution of mask."); AddComment(R"DOC( This operator can be, for given the RoIs and corresponding labels, to sample foreground RoIs. This mask branch also has a :math: `K \\times M^{2}` dimensional output targets for each foreground RoI, which encodes K binary masks of resolution M x M, one for each of the K classes. This mask targets are used to compute loss of mask branch. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR( generate_mask_labels, ops::GenerateMaskLabelsOp, ops::GenerateMaskLabelsOpMaker, paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>); REGISTER_OP_CPU_KERNEL(generate_mask_labels, ops::GenerateMaskLabelsKernel<float>);
17,960
6,720
/* git-junction * Copyright (c) 2016-2017 by Pauli Saksa * * Licensed under The MIT License, see file LICENSE.txt in this source tree. */ #include "input.hh" #include "exception.hh" #include "terminal_input.hh" #include "utils.hh" #include <iostream> #include <sstream> #include <unistd.h> // bool accept_field_functor::accept_size(std::string::size_type size, std::string::size_type min, std::string::size_type max) { if (size < min) { std::cout << "too short, " << min << '-' << max << " characters\n"; return false; } if (size > max) { std::cout << "too long, " << min << '-' << max << " characters\n"; return false; } return true; } accept_field_functor::~accept_field_functor() { } // ********************************************************* bool accept_yes_or_no::operator() (std::string &input) const { if (input.size() < 2 || input.size() > 3) { return false; } lowercase(input); return input == "yes" || input == "no"; } // ********************************************************* static std::string read_line(const std::string &prompt, bool hide) { terminal_input term_input{hide}; std::cout << prompt << std::flush; std::ostringstream oss; char inp; while (true) { const int i =read(STDIN_FILENO, &inp, 1); if (i != 1) { std::cout << '\n'; throw stdin_exception{}; } if (inp == '\n' || inp == '\r') break; if (inp >= 0 && inp < 32) continue; oss << inp; } return oss.str(); } // ********************************************************* std::string read_field(const std::string prompt, bool hide, const accept_field_functor &accept) { while (true) { std::string input =read_line(prompt, hide); if (accept(input)) // accept() may modify input return input; } }
2,036
663
/* Copyright 2020 Myles Trevino Licensed under the Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ #pragma once #include <string> #include <vector> namespace LV::Decoder { void load_track_information(const std::string& file); void initialize_resampler_and_decoder(); void load_samples(); void destroy(); // Getters. const std::vector<float>& get_data(); const int get_sample_rate(); }
432
162
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef WB_ELEVATION_GRID_HPP #define WB_ELEVATION_GRID_HPP #include "WbGeometry.hpp" #include "WbMFDouble.hpp" #include "WbSFDouble.hpp" #include "WbSFInt.hpp" #include "WbSFNode.hpp" class WbVector3; typedef struct dxHeightfieldData *dHeightfieldDataID; class WbElevationGrid : public WbGeometry { Q_OBJECT public: // constructors and destructor explicit WbElevationGrid(WbTokenizer *tokenizer = NULL); WbElevationGrid(const WbElevationGrid &other); explicit WbElevationGrid(const WbNode &other); virtual ~WbElevationGrid(); // field accessors // getters double xSpacing() const { return mXSpacing->value(); } double zSpacing() const { return mZSpacing->value(); } int xDimension() const { return mXDimension->value(); } int zDimension() const { return mZDimension->value(); } int height(int index) const { return mHeight->item(index); } double heightRange() const { return mMaxHeight - mMinHeight; } // setters void setXspacing(double x) { mXSpacing->setValue(x); } void setZspacing(double z) { mZSpacing->setValue(z); } void setHeightScaleFactor(double ratio) { mHeight->multiplyAllItems(ratio); } // reimplemented public functions int nodeType() const override { return WB_NODE_ELEVATION_GRID; } void preFinalize() override; void postFinalize() override; dGeomID createOdeGeom(dSpaceID space) override; void createWrenObjects() override; void createResizeManipulator() override; bool isAValidBoundingObject(bool checkOde = false, bool warning = true) const override; bool isSuitableForInsertionInBoundingObject(bool warning = false) const override; void rescale(const WbVector3 &scale) override; // ray tracing void recomputeBoundingSphere() const override; bool pickUVCoordinate(WbVector2 &uv, const WbRay &ray, int textureCoordSet = 0) const override; double computeDistance(const WbRay &ray) const override; // friction WbVector3 computeFrictionDirection(const WbVector3 &normal) const override; // resize manipulator void setResizeManipulatorDimensions() override; signals: void validElevationGridInserted(); protected: bool areSizeFieldsVisibleAndNotRegenerator() const override; void exportNodeFields(WbVrmlWriter &writer) const override; private: WbElevationGrid &operator=(const WbElevationGrid &); // non copyable WbNode *clone() const override { return new WbElevationGrid(*this); } void init(); // user accessible fields WbMFDouble *mHeight; WbSFInt *mXDimension; WbSFDouble *mXSpacing; WbSFInt *mZDimension; WbSFDouble *mZSpacing; WbSFDouble *mThickness; // other variables double mMinHeight; // min value in "height" field double mMaxHeight; // max value in "height" field dHeightfieldDataID mHeightfieldData; double *mData; void checkHeight(); double width() const { return mXSpacing->value() * (mXDimension->value() - 1); } double depth() const { return mZSpacing->value() * (mZDimension->value() - 1); } double height() const { return mMaxHeight - mMinHeight; } bool sanitizeFields(); // WREN void buildWrenMesh(); void updateScale(); // ODE void applyToOdeData(bool correctSolidMass = true) override; bool setOdeHeightfieldData(); double scaledWidth() const; double scaledDepth() const; double heightScaleFactor() const { return fabs(absoluteScale().y()); } // ray tracing double computeLocalCollisionPoint(const WbRay &ray, WbVector3 &localCollisionPoint) const; void computeMinMax(const WbVector3 &point, WbVector3 &min, WbVector3 &max) const; private slots: void updateHeight(); void updateXDimension(); void updateXSpacing(); void updateZDimension(); void updateZSpacing(); void updateThickness(); void updateLineScale(); }; #endif
4,337
1,438
// main.cpp // #include "Core.hpp" int main(int argc, char** argv) { if (Core.Init()) { Core.Quit(); return -1; } else { Core.MainLoop(); Core.Quit(); return 0; } return 0; }
209
102
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Casting/numeric_cast.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Serialization/IdUtils.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Settings/SettingsRegistry.h> #include <AzCore/std/parallel/scoped_lock.h> #include <AzCore/std/smart_ptr/make_shared.h> #include <AzFramework/Components/TransformComponent.h> #include <AzFramework/Entity/GameEntityContextBus.h> #include <AzFramework/Spawnable/Spawnable.h> #include <AzFramework/Spawnable/SpawnableEntitiesManager.h> namespace AzFramework { template<typename T> void SpawnableEntitiesManager::QueueRequest(EntitySpawnTicket& ticket, SpawnablePriority priority, T&& request) { request.m_ticket = &GetTicketPayload<Ticket>(ticket); Queue& queue = priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); request.m_requestId = GetTicketPayload<Ticket>(ticket).m_nextRequestId++; queue.m_pendingRequest.push(AZStd::move(request)); } } SpawnableEntitiesManager::SpawnableEntitiesManager() { AZ::ComponentApplicationBus::BroadcastResult(m_defaultSerializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); AZ_Assert( m_defaultSerializeContext, "Failed to retrieve serialization context during construction of the Spawnable Entities Manager."); if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { AZ::u64 value = aznumeric_caster(m_highPriorityThreshold); settingsRegistry->Get(value, "/O3DE/AzFramework/Spawnables/HighPriorityThreshold"); m_highPriorityThreshold = aznumeric_cast<SpawnablePriority>(AZStd::clamp(value, 0llu, 255llu)); } } SpawnableEntitiesManager::~SpawnableEntitiesManager() { AZ_Assert(m_totalTickets == 0, "Shutting down the Spawnable Entities Manager while there are still active Spawnable Tickets."); } void SpawnableEntitiesManager::SpawnAllEntities(EntitySpawnTicket& ticket, SpawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnAllEntities hasn't been initialized."); SpawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::SpawnEntities( EntitySpawnTicket& ticket, AZStd::vector<uint32_t> entityIndices, SpawnEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to SpawnEntities hasn't been initialized."); SpawnEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityIndices = AZStd::move(entityIndices); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); queueEntry.m_preInsertionCallback = AZStd::move(optionalArgs.m_preInsertionCallback); queueEntry.m_referencePreviouslySpawnedEntities = optionalArgs.m_referencePreviouslySpawnedEntities; QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::DespawnAllEntities(EntitySpawnTicket& ticket, DespawnAllEntitiesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnAllEntities hasn't been initialized."); DespawnAllEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::DespawnEntity(AZ::EntityId entityId, EntitySpawnTicket& ticket, DespawnEntityOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to DespawnEntity hasn't been initialized."); DespawnEntityCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_entityId = entityId; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::RetrieveTicket( EntitySpawnTicket::Id ticketId, RetrieveEntitySpawnTicketCallback callback, RetrieveTicketOptionalArgs optionalArgs) { if (ticketId == 0) { AZ_Assert(false, "Ticket id provided to RetrieveEntitySpawnTicket is invalid."); return; } RetrieveTicketCommand queueEntry; queueEntry.m_ticketId = ticketId; queueEntry.m_callback = AZStd::move(callback); Queue& queue = optionalArgs.m_priority <= m_highPriorityThreshold ? m_highPriorityQueue : m_regularPriorityQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); queue.m_pendingRequest.push(AZStd::move(queueEntry)); } } void SpawnableEntitiesManager::ReloadSpawnable( EntitySpawnTicket& ticket, AZ::Data::Asset<Spawnable> spawnable, ReloadSpawnableOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); ReloadSpawnableCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_spawnable = AZStd::move(spawnable); queueEntry.m_serializeContext = optionalArgs.m_serializeContext == nullptr ? m_defaultSerializeContext : optionalArgs.m_serializeContext; queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::UpdateEntityAliasTypes( EntitySpawnTicket& ticket, AZStd::vector<EntityAliasTypeChange> updatedAliases, UpdateEntityAliasTypesOptionalArgs optionalArgs) { AZ_Assert(ticket.IsValid(), "Ticket provided to ReloadSpawnable hasn't been initialized."); UpdateEntityAliasTypesCommand queueEntry; queueEntry.m_entityAliases = AZStd::move(updatedAliases); queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(optionalArgs.m_completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ListEntities( EntitySpawnTicket& ticket, ListEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ListIndicesAndEntities( EntitySpawnTicket& ticket, ListIndicesEntitiesCallback listCallback, ListEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ListEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ListEntities hasn't been initialized."); ListIndicesEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::ClaimEntities( EntitySpawnTicket& ticket, ClaimEntitiesCallback listCallback, ClaimEntitiesOptionalArgs optionalArgs) { AZ_Assert(listCallback, "ClaimEntities called on spawnable entities without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to ClaimEntities hasn't been initialized."); ClaimEntitiesCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_listCallback = AZStd::move(listCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback, BarrierOptionalArgs optionalArgs) { AZ_Assert(completionCallback, "Barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to Barrier hasn't been initialized."); BarrierCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } void SpawnableEntitiesManager::LoadBarrier( EntitySpawnTicket& ticket, BarrierCallback completionCallback, LoadBarrierOptionalArgs optionalArgs) { AZ_Assert(completionCallback, "Load barrier on spawnable entities called without a valid callback to use."); AZ_Assert(ticket.IsValid(), "Ticket provided to LoadBarrier hasn't been initialized."); LoadBarrierCommand queueEntry; queueEntry.m_ticketId = ticket.GetId(); queueEntry.m_completionCallback = AZStd::move(completionCallback); queueEntry.m_checkAliasSpawnables = optionalArgs.m_checkAliasSpawnables; QueueRequest(ticket, optionalArgs.m_priority, AZStd::move(queueEntry)); } auto SpawnableEntitiesManager::ProcessQueue(CommandQueuePriority priority) -> CommandQueueStatus { CommandQueueStatus result = CommandQueueStatus::NoCommandsLeft; if ((priority & CommandQueuePriority::High) == CommandQueuePriority::High) { if (ProcessQueue(m_highPriorityQueue) == CommandQueueStatus::HasCommandsLeft) { result = CommandQueueStatus::HasCommandsLeft; } } if ((priority & CommandQueuePriority::Regular) == CommandQueuePriority::Regular) { if (ProcessQueue(m_regularPriorityQueue) == CommandQueueStatus::HasCommandsLeft) { result = CommandQueueStatus::HasCommandsLeft; } } return result; } auto SpawnableEntitiesManager::ProcessQueue(Queue& queue) -> CommandQueueStatus { // Process delayed requests first. // Only process the requests that are currently in this queue, not the ones that could be re-added if they still can't complete. size_t delayedSize = queue.m_delayed.size(); for (size_t i = 0; i < delayedSize; ++i) { Requests& request = queue.m_delayed.front(); CommandResult result = AZStd::visit( [this](auto&& args) -> CommandResult { return ProcessRequest(args); }, request); if (result == CommandResult::Requeue) { queue.m_delayed.emplace_back(AZStd::move(request)); } queue.m_delayed.pop_front(); } // Process newly added requests. while (true) { AZStd::queue<Requests> pendingRequestQueue; { AZStd::scoped_lock queueLock(queue.m_pendingRequestMutex); queue.m_pendingRequest.swap(pendingRequestQueue); } if (!pendingRequestQueue.empty()) { while (!pendingRequestQueue.empty()) { Requests& request = pendingRequestQueue.front(); CommandResult result = AZStd::visit( [this](auto&& args) -> CommandResult { return ProcessRequest(args); }, request); if (result == CommandResult::Requeue) { queue.m_delayed.emplace_back(AZStd::move(request)); } pendingRequestQueue.pop(); } } else { break; } }; return queue.m_delayed.empty() ? CommandQueueStatus::NoCommandsLeft : CommandQueueStatus::HasCommandsLeft; } void* SpawnableEntitiesManager::CreateTicket(AZ::Data::Asset<Spawnable>&& spawnable) { static AZStd::atomic_uint32_t idCounter { 1 }; auto result = aznew Ticket(); result->m_spawnable = AZStd::move(spawnable); result->m_ticketId = idCounter++; m_totalTickets++; m_ticketsPendingRegistration++; AZ_Assert( m_ticketsPendingRegistration <= m_totalTickets, "There are less total entity spawn tickets than there are tickets pending registration in the SpawnableEntitiesManager."); RegisterTicketCommand queueEntry; queueEntry.m_ticket = result; { AZStd::scoped_lock queueLock(m_highPriorityQueue.m_pendingRequestMutex); queueEntry.m_requestId = result->m_nextRequestId++; m_highPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } return result; } void SpawnableEntitiesManager::IncrementTicketReference(void* ticket) { reinterpret_cast<Ticket*>(ticket)->m_referenceCount++; } void SpawnableEntitiesManager::DecrementTicketReference(void* ticket) { auto ticketInstance = reinterpret_cast<Ticket*>(ticket); if (ticketInstance->m_referenceCount-- == 1) { DestroyTicketCommand queueEntry; queueEntry.m_ticket = ticketInstance; { AZStd::scoped_lock queueLock(m_regularPriorityQueue.m_pendingRequestMutex); queueEntry.m_requestId = ticketInstance->m_nextRequestId++; m_regularPriorityQueue.m_pendingRequest.push(AZStd::move(queueEntry)); } } } EntitySpawnTicket::Id SpawnableEntitiesManager::GetTicketId(void* ticket) { return reinterpret_cast<Ticket*>(ticket)->m_ticketId; } const AZ::Data::Asset<Spawnable>& SpawnableEntitiesManager::GetSpawnableOnTicket(void* ticket) { return reinterpret_cast<Ticket*>(ticket)->m_spawnable; } AZ::Entity* SpawnableEntitiesManager::CloneSingleEntity(const AZ::Entity& entityPrototype, EntityIdMap& prototypeToCloneMap, AZ::SerializeContext& serializeContext) { // If the same ID gets remapped more than once, preserve the original remapping instead of overwriting it. constexpr bool allowDuplicateIds = false; return AZ::IdUtils::Remapper<AZ::EntityId, allowDuplicateIds>::CloneObjectAndGenerateNewIdsAndFixRefs( &entityPrototype, prototypeToCloneMap, &serializeContext); } AZ::Entity* SpawnableEntitiesManager::CloneSingleAliasedEntity( const AZ::Entity& entityPrototype, const Spawnable::EntityAlias& alias, EntityIdMap& prototypeToCloneMap, AZ::Entity* previouslySpawnedEntity, AZ::SerializeContext& serializeContext) { AZ::Entity* clone = nullptr; switch (alias.m_aliasType) { case Spawnable::EntityAliasType::Original: // Behave as the original version. clone = CloneSingleEntity(entityPrototype, prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Disable: // Do nothing. return nullptr; case Spawnable::EntityAliasType::Replace: clone = CloneSingleEntity(*(alias.m_spawnable->GetEntities()[alias.m_targetIndex]), prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Additional: // The asset handler will have sorted and inserted a Spawnable::EntityAliasType::Original, so the just // spawn the additional entity. clone = CloneSingleEntity(*(alias.m_spawnable->GetEntities()[alias.m_targetIndex]), prototypeToCloneMap, serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); return clone; case Spawnable::EntityAliasType::Merge: AZ_Assert(previouslySpawnedEntity != nullptr, "Merging components but there's no entity to add to yet."); AppendComponents( *previouslySpawnedEntity, alias.m_spawnable->GetEntities()[alias.m_targetIndex]->GetComponents(), prototypeToCloneMap, serializeContext); return nullptr; default: AZ_Assert(false, "Unsupported spawnable entity alias type: %i", alias.m_aliasType); return nullptr; } } void SpawnableEntitiesManager::AppendComponents( AZ::Entity& target, const AZ::Entity::ComponentArrayType& componentPrototypes, EntityIdMap& prototypeToCloneMap, AZ::SerializeContext& serializeContext) { // Only components are added and entities are looked up so no duplicate entity ids should be encountered. constexpr bool allowDuplicateIds = false; for (const AZ::Component* component : componentPrototypes) { AZ::Component* clone = AZ::IdUtils::Remapper<AZ::EntityId, allowDuplicateIds>::CloneObjectAndGenerateNewIdsAndFixRefs( component, prototypeToCloneMap, &serializeContext); AZ_Assert(clone, "Unable to clone component for entity '%s' (%zu).", target.GetName().c_str(), target.GetId()); [[maybe_unused]] bool result = target.AddComponent(clone); AZ_Assert(result, "Unable to add cloned component to entity '%s' (%zu).", target.GetName().c_str(), target.GetId()); } } void SpawnableEntitiesManager::InitializeEntityIdMappings( const Spawnable::EntityList& entities, EntityIdMap& idMap, AZStd::unordered_set<AZ::EntityId>& previouslySpawned) { // Make sure we don't have any previous data lingering around. idMap.clear(); previouslySpawned.clear(); idMap.reserve(entities.size()); previouslySpawned.reserve(entities.size()); for (auto& entity : entities) { idMap.emplace(entity->GetId(), AZ::Entity::MakeId()); } } void SpawnableEntitiesManager::RefreshEntityIdMapping( const AZ::EntityId& entityId, EntityIdMap& idMap, AZStd::unordered_set<AZ::EntityId>& previouslySpawned) { if (previouslySpawned.contains(entityId)) { // This entity has already been spawned at least once before, so we need to generate a new id for it and // preserve the new id to fix up any future entity references to this entity. idMap[entityId] = AZ::Entity::MakeId(); } else { // This entity hasn't been spawned yet, so use the first id we've already generated for this entity and mark // it as spawned so we know not to reuse this id next time. previouslySpawned.emplace(entityId); } } auto SpawnableEntitiesManager::ProcessRequest(SpawnAllEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasConstVisitor aliases = ticket.m_spawnable->TryGetAliasesConst(); aliases.IsValid() && aliases.AreAllSpawnablesReady()) { AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector<uint32_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices; // Keep track how many entities there were in the array initially size_t spawnedEntitiesInitialCount = spawnedEntities.size(); // These are 'prototype' entities we'll be cloning from const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities(); uint32_t entitiesToSpawnSize = aznumeric_caster(entitiesToSpawn.size()); // Reserve buffers spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize); spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); // Pre-generate the full set of entity-id-to-new-entity-id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // We clear out and regenerate the set of IDs on every SpawnAllEntities call, because presumably every entity reference // in every entity we're about to instantiate is intended to point to an entity in our newly-instantiated batch, regardless // of spawn order. If we didn't clear out the map, it would be possible for some entities here to have references to // previously-spawned entities from a previous SpawnEntities or SpawnAllEntities call. InitializeEntityIdMappings(entitiesToSpawn, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); auto aliasIt = aliases.begin(); auto aliasEnd = aliases.end(); if (aliasIt == aliasEnd) { for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(i); } } else { for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); if (aliasIt == aliasEnd || aliasIt->m_sourceIndex != i) { spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(i); } else { // The list of entities has already been sorted and optimized (See SpawnableEntitiesAliasList:Optimize) so can // be safely executed in order without risking an invalid state. AZ::Entity* previousEntity = nullptr; do { AZ::Entity* clone = CloneSingleAliasedEntity( *entitiesToSpawn[i], *aliasIt, ticket.m_entityIdReferenceMap, previousEntity, *request.m_serializeContext); previousEntity = clone; if (clone) { spawnedEntities.emplace_back(clone); spawnedEntityIndices.push_back(i); } ++aliasIt; } while (aliasIt != aliasEnd && aliasIt->m_sourceIndex == i); } } } // There were no initial entities then the ticket now holds exactly all entities. If there were already entities then // a new set are not added so it no longer holds exactly the number of entities. ticket.m_loadAll = spawnedEntitiesInitialCount == 0; auto newEntitiesBegin = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; auto newEntitiesEnd = ticket.m_spawnedEntities.end(); // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { request.m_preInsertionCallback(request.m_ticketId, SpawnableEntityContainerView(newEntitiesBegin, newEntitiesEnd)); } // Add to the game context, now the entities are active for (auto it = newEntitiesBegin; it != newEntitiesEnd; ++it) { AZ::Entity* clone = (*it); clone->SetEntitySpawnTicketId(request.m_ticketId); GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, clone); } // Let other systems know about newly spawned entities for any post-processing after adding to the scene/game context. if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView(newEntitiesBegin, newEntitiesEnd)); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(SpawnEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasConstVisitor aliases = ticket.m_spawnable->TryGetAliasesConst(); aliases.IsValid() && aliases.AreAllSpawnablesReady()) { AZStd::vector<AZ::Entity*>& spawnedEntities = ticket.m_spawnedEntities; AZStd::vector<uint32_t>& spawnedEntityIndices = ticket.m_spawnedEntityIndices; AZ_Assert( spawnedEntities.size() == spawnedEntityIndices.size(), "The indices for the spawned entities has gone out of sync with the entities."); // Keep track of how many entities there were in the array initially size_t spawnedEntitiesInitialCount = spawnedEntities.size(); // These are 'prototype' entities we'll be cloning from const Spawnable::EntityList& entitiesToSpawn = ticket.m_spawnable->GetEntities(); size_t entitiesToSpawnSize = request.m_entityIndices.size(); if (ticket.m_entityIdReferenceMap.empty() || !request.m_referencePreviouslySpawnedEntities) { // This map keeps track of ids from prototype (spawnable) to clone (instance) allowing patch ups of fields referring // to entityIds outside of a given entity. // We pre-generate the full set of entity id to new entity id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // By default, we only initialize this map once because it needs to persist across multiple SpawnEntities calls, so // that reference fixups work even when the entity being referenced is spawned in a different SpawnEntities // (or SpawnAllEntities) call. // However, the caller can also choose to reset the map by passing in "m_referencePreviouslySpawnedEntities = false". InitializeEntityIdMappings(entitiesToSpawn, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); } spawnedEntities.reserve(spawnedEntities.size() + entitiesToSpawnSize); spawnedEntityIndices.reserve(spawnedEntityIndices.size() + entitiesToSpawnSize); auto aliasBegin = aliases.begin(); auto aliasEnd = aliases.end(); if (aliasBegin == aliasEnd) { for (uint32_t index : request.m_entityIndices) { if (index < entitiesToSpawn.size()) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); spawnedEntities.push_back( CloneSingleEntity(*entitiesToSpawn[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(index); } } } else { for (uint32_t index : request.m_entityIndices) { if (index < entitiesToSpawn.size()) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping( entitiesToSpawn[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); auto aliasIt = AZStd::lower_bound( aliasBegin, aliasEnd, index, [](const Spawnable::EntityAlias& lhs, uint32_t rhs) { return lhs.m_sourceIndex < rhs; }); if (aliasIt == aliasEnd || aliasIt->m_sourceIndex != index) { spawnedEntities.emplace_back( CloneSingleEntity(*entitiesToSpawn[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext)); spawnedEntityIndices.push_back(index); } else { // The list of entities has already been sorted and optimized (See SpawnableEntitiesAliasList:Optimize) so // can be safely executed in order without risking an invalid state. AZ::Entity* previousEntity = nullptr; do { AZ::Entity* clone = CloneSingleAliasedEntity( *entitiesToSpawn[index], *aliasIt, ticket.m_entityIdReferenceMap, previousEntity, *request.m_serializeContext); previousEntity = clone; if (clone) { spawnedEntities.emplace_back(clone); spawnedEntityIndices.push_back(index); } ++aliasIt; } while (aliasIt != aliasEnd && aliasIt->m_sourceIndex == index); } } } } ticket.m_loadAll = false; // Let other systems know about newly spawned entities for any pre-processing before adding to the scene/game context. if (request.m_preInsertionCallback) { request.m_preInsertionCallback( request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } // Add to the game context, now the entities are active for (auto it = ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount; it != ticket.m_spawnedEntities.end(); ++it) { AZ::Entity* clone = (*it); clone->SetEntitySpawnTicketId(request.m_ticketId); GameEntityContextRequestBus::Broadcast(&GameEntityContextRequestBus::Events::AddGameEntity, *it); } if (request.m_completionCallback) { request.m_completionCallback( request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin() + spawnedEntitiesInitialCount, ticket.m_spawnedEntities.end())); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(DespawnAllEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { for (AZ::Entity* entity : ticket.m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } ticket.m_spawnedEntities.clear(); ticket.m_spawnedEntityIndices.clear(); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(DespawnEntityCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { AZStd::vector<AZ::Entity*>& spawnedEntities = request.m_ticket->m_spawnedEntities; for (auto entityIterator = spawnedEntities.begin(); entityIterator != spawnedEntities.end(); ++entityIterator) { if (*entityIterator != nullptr && (*entityIterator)->GetId() == request.m_entityId) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. (*entityIterator)->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, (*entityIterator)->GetId()); AZStd::iter_swap(entityIterator, spawnedEntities.rbegin()); spawnedEntities.pop_back(); break; } } if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ReloadSpawnableCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; AZ_Assert(ticket.m_spawnable.GetId() == request.m_spawnable.GetId(), "Spawnable is being reloaded, but the provided spawnable has a different asset id. " "This will likely result in unexpected entities being created."); if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { // Delete the original entities. for (AZ::Entity* entity : ticket.m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } // Rebuild the list of entities. ticket.m_spawnedEntities.clear(); const Spawnable::EntityList& entities = request.m_spawnable->GetEntities(); // Pre-generate the full set of entity id to new entity id mappings, so that during the clone operation below, // any entity references that point to a not-yet-cloned entity will still get their ids remapped correctly. // This map is intentionally cleared out and regenerated here to ensure that we're starting fresh with mappings that // match the new set of prototype entities getting spawned. InitializeEntityIdMappings(entities, ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); if (ticket.m_loadAll) { // The new spawnable may have a different number of entities and since the intent of the user was // to spawn every entity, simply start over. ticket.m_spawnedEntityIndices.clear(); size_t entitiesToSpawnSize = entities.size(); for (uint32_t i = 0; i < entitiesToSpawnSize; ++i) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping(entities[i].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); AZ::Entity* clone = CloneSingleEntity(*entities[i], ticket.m_entityIdReferenceMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); ticket.m_spawnedEntities.push_back(clone); ticket.m_spawnedEntityIndices.push_back(i); } } else { size_t entitiesSize = entities.size(); for (uint32_t index : ticket.m_spawnedEntityIndices) { // It's possible for the new spawnable to have a different number of entities, so guard against this. // It's also possible that the entities have moved within the spawnable to a new index. This can't be // detected and will result in the incorrect entities being spawned. if (index < entitiesSize) { // If this entity has previously been spawned, give it a new id in the reference map RefreshEntityIdMapping(entities[index].get()->GetId(), ticket.m_entityIdReferenceMap, ticket.m_previouslySpawned); AZ::Entity* clone = CloneSingleEntity(*entities[index], ticket.m_entityIdReferenceMap, *request.m_serializeContext); AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); ticket.m_spawnedEntities.push_back(clone); } } } ticket.m_spawnable = AZStd::move(request.m_spawnable); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(UpdateEntityAliasTypesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (Spawnable::EntityAliasVisitor aliases = ticket.m_spawnable->TryGetAliases(); aliases.IsValid()) { for (EntityAliasTypeChange& replacement : request.m_entityAliases) { aliases.UpdateAliasType(replacement.m_aliasIndex, replacement.m_newAliasType); } aliases.Optimize(); if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } } return CommandResult::Requeue; } auto SpawnableEntitiesManager::ProcessRequest(ListEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { request.m_listCallback(request.m_ticketId, SpawnableConstEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ListIndicesEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { AZ_Assert( ticket.m_spawnedEntities.size() == ticket.m_spawnedEntityIndices.size(), "Entities and indices on spawnable ticket have gone out of sync."); request.m_listCallback(request.m_ticketId, SpawnableConstIndexEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntityIndices.begin(), ticket.m_spawnedEntities.size())); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(ClaimEntitiesCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { request.m_listCallback(request.m_ticketId, SpawnableEntityContainerView( ticket.m_spawnedEntities.begin(), ticket.m_spawnedEntities.end())); ticket.m_spawnedEntities.clear(); ticket.m_spawnedEntityIndices.clear(); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(BarrierCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (request.m_requestId == ticket.m_currentRequestId) { if (request.m_completionCallback) { request.m_completionCallback(request.m_ticketId); } ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(LoadBarrierCommand& request) -> CommandResult { Ticket& ticket = *request.m_ticket; if (ticket.m_spawnable.IsReady() && request.m_requestId == ticket.m_currentRequestId) { if (request.m_checkAliasSpawnables) { if (Spawnable::EntityAliasConstVisitor visitor = ticket.m_spawnable->TryGetAliasesConst(); !visitor.IsValid() || !visitor.AreAllSpawnablesReady()) { return CommandResult::Requeue; } } request.m_completionCallback(request.m_ticketId); ticket.m_currentRequestId++; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(RetrieveTicketCommand& request) -> CommandResult { auto entitySpawnTicketIterator = m_entitySpawnTicketMap.find(request.m_ticketId); if (entitySpawnTicketIterator == m_entitySpawnTicketMap.end()) { if (m_ticketsPendingRegistration > 0) { // There are still tickets pending registration, which may hold the reference, so delay this request // until all tickets are registered and it's known for sure if the ticket doesn't exist anymore. return CommandResult::Requeue; } else { AZ_Assert(false, "The EntitySpawnTicket corresponding to id '%lu' cannot be found", request.m_ticketId); return CommandResult::Executed; } } // About to make a copy so increase the reference count. entitySpawnTicketIterator->second->m_referenceCount++; request.m_callback(InternalToExternalTicket(entitySpawnTicketIterator->second, this)); return CommandResult::Executed; } auto SpawnableEntitiesManager::ProcessRequest(RegisterTicketCommand& request) -> CommandResult { if (request.m_requestId == request.m_ticket->m_currentRequestId) { m_entitySpawnTicketMap.insert_or_assign(request.m_ticket->m_ticketId, request.m_ticket); request.m_ticket->m_currentRequestId++; AZ_Assert( m_ticketsPendingRegistration > 0, "Attempting to decrement the number of entity spawn tickets pending registration while there are no registrations pending " "in the SpawnableEntitiesManager."); m_ticketsPendingRegistration--; return CommandResult::Executed; } else { return CommandResult::Requeue; } } auto SpawnableEntitiesManager::ProcessRequest(DestroyTicketCommand& request) -> CommandResult { if (request.m_requestId == request.m_ticket->m_currentRequestId) { for (AZ::Entity* entity : request.m_ticket->m_spawnedEntities) { if (entity != nullptr) { // Setting it to 0 is needed to avoid the infinite loop between GameEntityContext and SpawnableEntitiesManager. entity->SetEntitySpawnTicketId(0); GameEntityContextRequestBus::Broadcast( &GameEntityContextRequestBus::Events::DestroyGameEntity, entity->GetId()); } } m_entitySpawnTicketMap.erase(request.m_ticket->m_ticketId); delete request.m_ticket; AZ_Assert( m_totalTickets > 0, "Attempting to decrement the total number of entity spawn tickets while are zero tickets in the SpawnableEntitiesManager."); m_totalTickets--; return CommandResult::Executed; } else { return CommandResult::Requeue; } } } // namespace AzFramework
49,361
13,149
/* * main.cpp * Created on: July 5, 2018 * Author: Oleksii Kulikov */ #include <iostream> #include <chrono> #include "bnl.hpp" #include "output.hpp" #include "generator.hpp" #include "old_bnl.hpp" #include "old_dnc.hpp" #include "dnc.hpp" #include "nnl.hpp" #include "parallel_dnc.hpp" static std::size_t n = 0, dimension = 0; void init(){ std::cout << "Number of tuples: \nn = "; std::cin >> n; std::cout << "Number of dimensions: \ndimensions = "; std::cin >> dimension; } // @param cp gives the variation of the algorithm ( 0: getNext | 1: consume/produce | 2: parallel consume/produce ) double test_algorithm(Output &output, int cp){ std::chrono::_V2::system_clock::time_point start = std::chrono::high_resolution_clock::now(); switch(cp){ case 0: output.getTuples(); break; case 1: output.getTuplesCP(); break; case 2: output.getTuplesParallelCP(); break; default: break; } std::chrono::_V2::system_clock::time_point finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = finish - start; output.print(); std::cout << "Elapsed time: " << elapsed.count() << "s\n\n"; return elapsed.count(); } bool check_results(const std::vector<std::vector<std::vector<double>>> &results){ static bool output = true; // check if sizes are equal for(auto r:results){ if(results[0].size() != r.size()){ std::cout << "Result sizes do not match.\n"; output = false; } } // check if results match for(std::size_t i = 1; i < results.size(); i++){ for(std::size_t j = 0; j < results[0].size(); j++){ if(std::find(results[i].begin(), results[i].end(), results[0][j]) == results[i].end()) { std::cout << "Tuple[" << j << "] in result 0 does not exist in result " << i << ".\n"; output = false; } } } return output; } int main() { init(); BNL *bnl_pointer; Output *output_pointer; // BNL iterator model Generator g(bnl_pointer, n, dimension); BNL bnl_im(output_pointer, &g); Output o1(&bnl_im); g.set_parent(&bnl_im); bnl_im.set_parent(&o1); std::cout << "Computing Skyline with iterator model BNL...\n"; double elapsed_1 = test_algorithm(o1, 0); // BNL produce/consume BNL bnl_pc(output_pointer, &g); Output o2(&bnl_pc); g.set_parent(&bnl_pc); bnl_pc.set_parent(&o2); std::cout << "Computing Skyline with produce/consume BNL...\n"; double elapsed_2 = test_algorithm(o2, 1); // NNL produce/consume NNL nnl_pc(output_pointer, &g); Output o3(&nnl_pc); g.set_parent(&nnl_pc); nnl_pc.set_parent(&o3); std::cout << "Computing Skyline with produce/consume NNL...\n"; double elapsed_3 = test_algorithm(o3, 1); // NNL produce/consume parallelized NNL nnl_parallel_pc(output_pointer, &g); Output o4(&nnl_parallel_pc); g.set_parent(&nnl_parallel_pc); nnl_parallel_pc.set_parent(&o4); std::cout << "Computing Skyline with produce/consume parallelized NNL...\n"; double elapsed_4 = test_algorithm(o4, 2); // DNC produce/consume DNC dnc(output_pointer, &g); Output o5(&dnc); g.set_parent(&dnc); dnc.set_parent(&o5); std::cout << "Computing Skyline with produce/consume DNC...\n"; double elapsed_5 = test_algorithm(o5, 1); // DNC produce/consume parallelized Parallel_DNC parallel_dnc(output_pointer, &g); Output o6(&parallel_dnc); g.set_parent(&parallel_dnc); parallel_dnc.set_parent(&o6); std::cout << "Computing Skyline with parallel produce/consume DNC...\n"; double elapsed_6 = test_algorithm(o6, 1); // OLD VERSIONS FOR TESTING // Old version of BNL // OldBNL old_bnl; // auto start = std::chrono::high_resolution_clock::now(); // std::cout << "Computing Skyline with normal BNL...\n"; // std::vector<std::vector<double>> result_bnl = old_bnl.computeSkyline(g.getTuples(), n); // auto finish = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> elapsed_7 = finish - start; // std::cout << "Resulting Skyline: \n"; // for(std::vector<std::vector<double>>::size_type i = 0; i < result_bnl.size(); i++){ // std::cout << "Tuple[" << i << "] is ("; // for(std::vector<double>::size_type j = 0; j < result_bnl[i].size(); j++){ // std::cout << result_bnl[i][j] << ' '; // } // std::cout << ")\n"; // } // std::cout << "\nElapsed time: " << elapsed_7.count() << "s\n\n"; // Old version of DNC // OldDNC old_dnc; // start = std::chrono::high_resolution_clock::now(); // std::cout << "Computing Skyline with normal DNC...\n"; // std::vector<std::vector<double>> result_old_dnc = old_dnc.computeSkyline(g.getTuples(), dimension); // finish = std::chrono::high_resolution_clock::now(); // std::chrono::duration<double> elapsed_8 = finish - start; // std::cout << "Resulting Skyline: \n"; // for(std::vector<std::vector<double>>::size_type i = 0; i < result_old_dnc.size(); i++){ // std::cout << "Tuple[" << i << "] is ("; // for(std::vector<double>::size_type j = 0; j < result_old_dnc[i].size(); j++){ // std::cout << result_old_dnc[i][j] << ' '; // } // std::cout << ")\n"; // } // std::cout << "\nElapsed time: " << elapsed_8.count() << "s\n\n"; // Total std::cout << "Input was: n = " << n << " dimension = " << dimension << "\n\n"; std::cout << "Results are: "; std::vector<std::vector<std::vector<double>>> to_check; to_check.push_back(o1.getStorage()); to_check.push_back(o2.getStorage()); to_check.push_back(o3.getStorage()); to_check.push_back(o4.getStorage()); to_check.push_back(o5.getStorage()); to_check.push_back(o6.getStorage()); // to_check.push_back(result_bnl); // to_check.push_back(result_old_dnc); if(check_results(to_check)) std::cout << "OK\n"; else std::cout << "NOT OK\n"; std::cout << "\nExecution time\n"; std::cout << "Iterator Model BNL: " << elapsed_1 << "s\n"; std::cout << "Produce/Consume BNL " << elapsed_2 << "s\n"; std::cout << "Produce/Consume NNL: " << elapsed_3 << "s\n"; std::cout << "Produce/Consume NNL Parallelized: " << elapsed_4 << "s\n"; std::cout << "Produce/Consume DNC: " << elapsed_5 << "s\n"; std::cout << "Produce/Consume DNC Parallelized: " << elapsed_6 << "s\n"; // std::cout << "Normal BNL: " << elapsed_7.count() << "s\n"; // std::cout << "Normal DNC: " << elapsed_8.count() << "s\n"; return 0; }
6,148
2,510
/* * Copyright (c) 2007, Laminar Research. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "TensorRoads.h" #include "MapDefs.h" #include "../RenderFarmUI/RF_DEMGraphics.h" #include "DEMDefs.h" #include "MapAlgs.h" #include "MapOverlay.h" #include "MapTopology.h" #include "PolyRasterUtils.h" #include "TensorUtils.h" #include "MathUtils.h" #include "ParamDefs.h" #include "GISTool_Globals.h" #include "PerfUtils.h" #include "MapCreate.h" #include "XUtils.h" #define ADVANCE_RATIO 0.0005 #define PROFILE_PERFORMANCE 1 #if PROFILE_PERFORMANCE #define TIMER(x) StElapsedTime __PerfTimer##x(#x); #else #define TIMER(x) #endif // SEt this to 1 to see the road restriction DEM - can explain why no roads showed up in a location. #define SHOW_ROAD_RESTRICT 0 // Make roads EVEN if origin code says not to. Useful for testing maybe. #define IGNORE_ORIGIN_CODES 0 // Show roads as debug mesh lines #define SHOW_GENERATED_ROADS 0 // Ignore urban density - useful for debugging #define IGNORE_DENSITY 1 /* Back before we had OSM, TensorRoads generated the "fake" road grids for urban areas where we lacked true vector data. This came from an academic paper. Here are the major ideas: - A "tensor field is a "flow field" - that is, a field of 2-d vector directions. - The idea was two-step: make a flow field that loosel corresponds to how we want the road grid to "flow", then turn the tensor field into roads. TENSOR FIELDS A tensor field is a field of 3-d rotations - its "flow" is bent by the rotations. What's cool about tensors (as opposed to a normal 2-d field of vectors indicating direction, or a 2-d field of angles) is that tensor fields are affine transforms and thus we can add them together and scale them. In other words, the same kinds of "blending" that would make an image look good produces VERY reasonable and sane results for tensor fields. Furthermore, tensor fields can be defined functionally - thus we can do a "composition of functions" (with the functions weighted. In fact, that is exactly what we do: we can build a tensor out of: - The terrain gradient, which will make the road grid follow the terrain. - Linear or circular pre-defined functions, which may have attenuation. - We can build linear gradients that scale off known edges to enforce the grid along highways. With the right blending gradients, we get a reasonably sane tensor map that seems to reflect 'local stuff'. TENSOR 2 ROADS The way we convert our tensor field is pretty easy. We create "seed" points along known highways (seed roads) and at those seed points we make a small step either along or normal to the flow. We then drop a seed for our cross-street and keep going. The result will be a sort of emergent grid that bends around the natural "flow" of the tensor field. If our tensor field is aesthetically pleasing (in otherwords, fly) then the road grid won't look that bad. There are some heuristics in this seeding to try to weed out and generally sanatize the emerging edges, as well as to keep the process fast. For example, we use a raster mask to avoid over-adding roads. (If the algorithm is allowed to run forever, it will eventually fill in an infinite number of infinitely thin lines, for certain tensors.) */ /************************************************************************************************************************************************ * ************************************************************************************************************************************************/ inline bool RoadsForThisFace(Face_handle f) { return !f->data().IsWater() && f->data().mTerrainType != terrain_Airport #if !IGNORE_ORIGIN_CODES && f->data().mParams.count(af_OriginCode) && f->data().mParams[af_OriginCode] == 2.0 #endif ; } bool CrossCheck(const Segment2& s1, const Segment2& s2, Point2& p) { if(s1.p1 == s2.p1 || s1.p1 == s2.p2 || s1.p2 == s2.p1 || s1.p2 == s2.p2) return false; if(!s1.could_intersect(s2)) return false; if(s1.p1.y() == s2.p1.y()) { DebugAssert(s1.p1.x() != s2.p2.x()); if (s1.p1.x() < s2.p1.x()) { if (s1.intersect(s2,p) && p != s1.p1 && p != s1.p2) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y); return true; } else return false; } else { if (s2.intersect(s1,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y); return true; } else return false; } } else { if (s1.p1.y() < s2.p1.y()) { if (s1.intersect(s2,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y); return true; } else return false; } else { if (s2.intersect(s1,p)) { // printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y, // s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y, // s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y); return true; } else return false; } } } Halfedge_handle InsertOneEdge(const Point_2& p1, const Point_2& p2, Pmwx& io_map, Locator& io_locator) { DebugAssert(p1 != p2); Vertex_handle v1, v2; Face_handle f; CGAL::Object obj1 = io_locator.locate(p1); CGAL::Object obj2 = io_locator.locate(p2); bool has_v1 = CGAL::assign(v1, obj1); bool has_v2 = CGAL::assign(v2, obj2); Curve_2 s(Segment_2(p1,p2)); if(has_v1 && has_v2) return io_map.insert_at_vertices(s, v1,v2); else if (has_v1) return io_map.insert_from_left_vertex(s, v1); else if (has_v2) return io_map.insert_from_right_vertex(s, v2); else if(CGAL::assign(f,obj1)) return io_map.insert_in_face_interior(s,f); else { //return CGAL::insert_curve(io_map,s); DebugAssert(!"Not disjoint!!"); return Halfedge_handle(); } } /* void SetRoadProps(Halfedge_handle e) { if (!e->data().mDominant) e = e->twin(); e->data().mSegments.push_back(GISNetworkSegment_t()); e->data().mSegments.back().mFeatType = road_LocalUnsep; } */ inline bool LessEdgesThan(Face_handle f, int c) { if(f->is_unbounded()) return false; Pmwx::Ccb_halfedge_circulator circ,stop; circ = stop = f->outer_ccb(); do { if(c-- <= 0) return false; ++circ; } while(circ != stop); for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h) { circ = stop = *h; do { if(c-- <= 0) return false; ++circ; } while(circ != stop); } return true; } void BulkZapRoads(const DEMGeo& inUrbanDensity, Pmwx& io_map) { printf("BEFORE ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2); for(Pmwx::Edge_iterator e = io_map.edges_begin(); e != io_map.edges_end(); ) { if((e->source()->degree() > 2 && e->target()->degree() > 2 && // If we have a real intersection on both sides AND e->face() != e->twin()->face() && // We divide two DIFFERENT faces (so we don't make an island) AND LessEdgesThan(e->face(), 6) && // The faces aren't too complex LessEdgesThan(e->twin()->face(), 6)) || (e->source()->degree() == 1 || e->target()->degree() == 1) // Or if we're an antenna ) { Point_2 mp(CGAL::midpoint(e->source()->point(),e->target()->point())); double d = inUrbanDensity.get(inUrbanDensity.lon_to_x(CGAL::to_double(mp.x())),inUrbanDensity.lat_to_y(CGAL::to_double(mp.y()))); if(e->source()->degree() == 1 || e->target()->degree() == 1) d = min(d,0.5); // always think of nuking antennas #if IGNORE_DENSITY d =1.0; #endif if(!RollDice(d)) { Halfedge_handle k = e; ++e; io_map.remove_edge(k); } else ++e; } else ++e; } printf("AFTER ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2); } void BulkInsertRoads(vector<Segment2> roads, Pmwx& io_map) { GIS_halfedge_data hed; hed.mSegments.push_back(GISNetworkSegment_t()); hed.mSegments.back().mFeatType = road_Local; vector<Segment_2> road_vec(roads.size()); vector<GIS_halfedge_data> data_vec(roads.size(),hed); for(int n = 0; n < roads.size(); ++n) road_vec[n] = Segment_2(ben2cgal<Point_2>(roads[n].p1),ben2cgal<Point_2>(roads[n].p2)); Map_CreateWithLineData(io_map, road_vec, data_vec); } int ThinLine(list<Point2>& pts, double max_dist_move, double max_dist_seg) { max_dist_move *= max_dist_move; max_dist_seg *= max_dist_seg; int t=0; while(1) { list<Point2>::iterator best_dead = pts.end(); double d_sq = 0.0f; for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i) { if(i != pts.begin()) { list<Point2>::iterator p(i), n(i); --p; ++n; if(n != pts.end()) { Segment2 span(*p, *n); if(span.squared_length() < max_dist_seg) { Point2 pp(span.projection(*i)); double my_dist = Segment2(pp, *i).squared_length(); if(my_dist < max_dist_move && my_dist > d_sq) { best_dead = i; d_sq = my_dist; } } } } } if(best_dead == pts.end()) break; pts.erase(best_dead); ++t; } return t; } /************************************************************************************************************************************************ * ************************************************************************************************************************************************/ RoadPrefs_t gRoadPrefs = { 10.0, 50000.0, 0.8, 1.0 }; struct TensorSeed { Point2 p; bool major; int x; int y; }; typedef list<TensorSeed> SeedQueue; struct Tensor_info { const DEMGeo * elev; const DEMGeo * grdx; const DEMGeo * grdy; const DEMGeo * uden; const DEMGeo * urad; const DEMGeo * usqr; Bbox2 bounds; }; inline int dem_get(const DEMGeo& d, int x, int y) { float e[9]; e[0] = d.get(x-1,y-1); e[1] = d.get(x ,y-1); e[2] = d.get(x+1,y-1); e[3] = d.get(x-1,y ); e[4] = d.get(x ,y ); e[5] = d.get(x+1,y ); e[6] = d.get(x-1,y+1); e[7] = d.get(x ,y+1); e[8] = d.get(x+1,y+1); if(e[4] == DEM_NO_DATA) return DEM_NO_DATA; int f = 0; bool h = false; for(int n = 0; n < 9; ++n) if(e[n] != DEM_NO_DATA) { h = true; f |= (int) e[n]; } return h ? f : DEM_NO_DATA; } static Vector2 Tensor_Func(const Point2& p, void * ref) { Tensor_info * i = (Tensor_info *) ref; double lon = interp(0,i->bounds.p1.x(),1,i->bounds.p2.x(),p.x()); double lat = interp(0,i->bounds.p1.y(),1,i->bounds.p2.y(),p.y()); double xe = i->elev->lon_to_x(lon); double ye = i->elev->lat_to_y(lat); double xr = i->urad->lon_to_x(lon); double yr = i->urad->lat_to_y(lat); double xu = i->usqr->lon_to_x(lon); double yu = i->usqr->lat_to_y(lat); double xg = i->grdx->lon_to_x(lon); double yg = i->grdx->lat_to_y(lat); double sq_w = 0.0f; double ir_w = 1.0f; float sqv = i->usqr->get(xu,yu); if (sqv == 1.0) sq_w = 1.f, ir_w = 0.0f; if (sqv == 2.0) sq_w = 0.f, ir_w = 1.0f; Vector2 basis = (Gradient2Tensor(Vector2(i->elev->gradient_x_bilinear(xe,ye),i->elev->gradient_y_bilinear(xe,ye))) * gRoadPrefs.elevation_weight); if(ir_w > 0.0f) basis += (Gradient2Tensor(Vector2(i->urad->gradient_x_bilinear(xr,yr),i->urad->gradient_y_bilinear(xr,yr))) * gRoadPrefs.radial_weight * ir_w); if (sq_w > 0.0f) basis += Vector2(i->grdx->get(xg,yg),i->grdy->get(xg,yg)); return basis; } bool CheckSeed( const TensorSeed& s, DEMGeo& d) { int old = dem_get(d,s.x,s.y); if(old==DEM_NO_DATA) return false; int mask = s.major ? 1 : 2; if ((old & mask) == 0) { return true; } return false; } void QueueSeed( const Point2& p, bool major, DEMGeo& dem, SeedQueue& q) { TensorSeed s; s.p = p; s.major = major; s.x = dem.lon_to_x(p.x()); s.y = dem.lat_to_y(p.y()); int old = dem_get(dem,s.x,s.y); if(old==DEM_NO_DATA)return; int mask = s.major ? 5 : 6; if ((old & mask) == 0) { old |= 4; dem(s.x,s.y) = old; q.push_back(s); } } bool CheckStats(const Point2& p, const Point2& p_old, const DEMGeo& elev, const DEMGeo& slope, const DEMGeo& density, float amp) { // return true; float d = density.get(density.lon_to_x(p.x()),density.lat_to_y(p.y())); float s = slope.get(slope.lon_to_x(p.x()),slope.lat_to_y(p.y())); if(d == DEM_NO_DATA) return false; d += amp; if (!RollDice(d)) return false; // if (!RollDice((d*gRoadPrefs.density_amp))) return false; float ss = fabs(elev.value_linear(p.x(),p.y())-elev.value_linear(p_old.x(),p_old.y())); float rr = pythag(elev.x_dist_to_m(elev.lon_to_x(p.x())-elev.lon_to_x(p_old.x())), elev.y_dist_to_m(elev.lat_to_y(p.y())-elev.lat_to_y(p_old.y()))); if(rr==0.0) return true; if(RollDice(ss / rr)*gRoadPrefs.slope_amp)return false; // if(RollDice(s * gRoadPrefs.slope_amp)) return false; return true; } bool CheckAndRegister( const Point2& p, DEMGeo& dem, int& ox, int& oy, int& ctr, bool major) { int x = intlim(dem.lon_to_x(p.x()),0,dem.mWidth -1); int y = intlim(dem.lat_to_y(p.y()),0,dem.mHeight-1); if(x == ox && y == oy) return (ctr-- > 0); ox =x; oy =y; ctr = 10; int old = dem.get(x,y); if(old==DEM_NO_DATA)return false; int mask = major ? 1 : 2; if ((old & mask) == 0) { old |= mask; dem(x,y) = old; return true; } return false; } void TensorForFace( const DEMGeo& inElevation, const DEMGeo& inUrbanDensity, const DEMGeo& inUrbanRadial, const DEMGeo& inUrbanSquare, const DEMGeo& inGridX, const DEMGeo& inGridY, Tensor_info& t) { t.elev = &inElevation; t.urad = &inUrbanRadial; t.usqr = &inUrbanSquare; t.uden = &inUrbanDensity; t.grdx = &inGridX; t.grdy = &inGridY; t.bounds.p1.x_ = inElevation.mWest ; t.bounds.p1.y_ = inElevation.mSouth; t.bounds.p2.x_ = inElevation.mEast ; t.bounds.p2.y_ = inElevation.mNorth; } void RasterEdge( Halfedge_handle e, DEMGeo& dem, Vector2 (* tensorFunc)(const Point2& p, void * ref), void * tensorRef) { int x1 = intlim(dem.lon_to_x(CGAL::to_double(e->source()->point().x())),0,dem.mWidth-1); int x2 = intlim(dem.lon_to_x(CGAL::to_double(e->target()->point().x())),0,dem.mWidth-1); int y1 = intlim(dem.lat_to_y(CGAL::to_double(e->source()->point().y())),0,dem.mHeight-1); int y2 = intlim(dem.lat_to_y(CGAL::to_double(e->target()->point().y())),0,dem.mHeight-1); Vector2 road_dir(cgal2ben(e->source()->point()),cgal2ben(e->target()->point())); road_dir.normalize(); if(std::abs(x2-x1) > std::abs(y2-y1)) { // "Horizontal line" if(x2 < x1) { swap(x1,x2); swap(y1,y2); } for(int x = x1; x <= x2; ++x) { int y = intlim(interp(x1,y1,x2,y2,x),0,dem.mHeight-1); Vector2 e(Tensor2Eigen(tensorFunc( Point2(interp(0,0,dem.mWidth -1,1,x), interp(0,0,dem.mHeight-1,1,y)),tensorRef))); double align_major = fabs(road_dir.dot(e)); e = e.perpendicular_ccw(); double align_minor = fabs(road_dir.dot(e)); int old = dem.get(x,y); if(align_major > 0.7) old |= 1; if(align_minor > 0.7) old |= 2; dem(x,y)=old; } } else { // "Vertical line" if(y2 < y1) { swap(x1,x2); swap(y1,y2); } for(int y = y1; y < y2; ++y) { int x = intlim(interp(y1,x1,y2,x2,y),0,dem.mWidth-1); Vector2 e(Tensor2Eigen(tensorFunc( Point2(interp(0,0,dem.mWidth -1,1,x), interp(0,0,dem.mHeight-1,1,y)),tensorRef))); double align_major = fabs(road_dir.dot(e)); e = e.perpendicular_ccw(); double align_minor = fabs(road_dir.dot(e)); int old = dem.get(x,y); if(align_major > 0.8) old |= 1; if(align_minor > 0.8) old |= 2; dem(x,y)=old; } } } void BuildRoadsForFace( Pmwx& ioMap, const DEMGeo& inElevation, const DEMGeo& inSlope, const DEMGeo& inUrbanDensity, const DEMGeo& inUrbanRadial, const DEMGeo& inUrbanSquare, Face_handle inFace, ProgressFunc inProg, ImageInfo * ioTensorImage, double outTensorBounds[4]) { Pmwx::Face_iterator f; int rx1, rx2, x, y; Tensor_info t; // gMeshLines.clear(); // gMeshPoints.clear(); DEMGeo road_restrict(inElevation.mWidth,inElevation.mHeight); DEMGeo grid_x(inElevation.mWidth,inElevation.mHeight); DEMGeo grid_y(inElevation.mWidth,inElevation.mHeight); road_restrict.copy_geo_from(inElevation); grid_x.copy_geo_from(inElevation); grid_y.copy_geo_from(inElevation); /********************************************************************************************************************************** * INITIALIZE THE ROAD RESTRICTION GRID USING WATER AND OTHER NON-PASSABLES! **********************************************************************************************************************************/ // Best to zap out a lot here since more possiblep points means more time in the alg. { TIMER(burn_water) set<Face_handle> no_road_faces; set<Halfedge_handle> bounds; PolyRasterizer<double> raster; for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f) if (!f->is_unbounded()) if(!RoadsForThisFace(f)) no_road_faces.insert(f); FindEdgesForFaceSet<Pmwx>(no_road_faces, bounds); y = SetupRasterizerForDEM(bounds, road_restrict, raster); raster.StartScanline(y); while (!raster.DoneScan()) { while (raster.GetRange(rx1, rx2)) { rx1 = intlim(rx1,0,road_restrict.mWidth-1); rx2 = intlim(rx2,0,road_restrict.mWidth-1); for (x = rx1; x < rx2; ++x) { road_restrict(x,y)=3.0; } } ++y; if (y >= road_restrict.mHeight) break; raster.AdvanceScanline(y); } { DEMGeo temp(road_restrict); for(y = 0; y < temp.mHeight; ++y) for(x = 0; x < temp.mWidth ; ++x) { if(temp.get_radial(x,y,1,0.0) != 0.0) road_restrict(x,y) = 3.0; } } } /********************************************************************************************************************************** * BURN EACH VECTOR INTO THE RESTRICTION GRID TOO **********************************************************************************************************************************/ { TIMER(burn_roads) TensorForFace( inElevation, inUrbanDensity, inUrbanRadial, inUrbanSquare, grid_x, grid_y, t); for(Pmwx::Edge_iterator e = ioMap.edges_begin(); e != ioMap.edges_end(); ++e) RasterEdge(e, road_restrict, Tensor_Func, &t); } #if DEV // gDem[dem_Wizard] = road_restrict; #endif /********************************************************************************************************************************** * BUILD GRID TENSOR FIELD **********************************************************************************************************************************/ // Running a tensor func that accesses every polygon vertex in its evaluator would be unacceptably slow. So we simply rasterize // each polygon's interior using its own internal tensor func, which simplifies the cost of building this. This lowers the accuracy // of the grid tensor field, but we don't care that much anyway. { TIMER(calc_linear_tensors) // int tcalcs = 0; for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f) if (!f->is_unbounded()) if(RoadsForThisFace(f)) { // First build a polygon with tensor weights for the face we're working on. vector<Point2> poly; vector<Vector2> tensors; PolyRasterizer<double> raster; Pmwx::Ccb_halfedge_circulator circ = f->outer_ccb(); Pmwx::Ccb_halfedge_circulator start = circ; Bbox2 bounds(cgal2ben(circ->source()->point())); do { poly.push_back(cgal2ben(circ->target()->point())); bounds += cgal2ben(circ->target()->point()); Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point())); Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point())); prev.normalize(); next.normalize(); Vector2 v(prev+next); v.normalize(); tensors.push_back(/*Eigen2Tensor*/(v)); ++circ; } while (circ != start); for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h) { Pmwx::Ccb_halfedge_circulator circ(*h); Pmwx::Ccb_halfedge_circulator start = circ; do { poly.push_back(cgal2ben(circ->target()->point())); Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point())); Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point())); prev.normalize(); next.normalize(); Vector2 v(prev+next); v.normalize(); tensors.push_back(/*Eigen2Tensor*/(v)); ++circ; } while(circ != start); } // Now rasterize into the polygon... double sz = (bounds.p2.y() - bounds.p1.y()) * (bounds.p2.x() - bounds.p1.x()); y = SetupRasterizerForDEM(f, road_restrict, raster); raster.StartScanline(y); while (!raster.DoneScan()) { while (raster.GetRange(rx1, rx2)) { rx1 = intlim(rx1,0,road_restrict.mWidth-1); rx2 = intlim(rx2,0,road_restrict.mWidth-1); for (x = rx1; x < rx2; ++x) if(road_restrict.get(x,y) != 3.0) { float sq = inUrbanSquare.get( inUrbanSquare.lon_to_x(grid_x.x_to_lon(x)), inUrbanSquare.lat_to_y(grid_x.y_to_lat(y))); if(sq == 1.0) { Vector2 t(grid_x.get(x,y),grid_y.get(x,y)); for (int n = 0; n < poly.size(); ++n) { // ++tcalcs; t += (Linear_Tensor(poly[n],tensors[n], 4.0 / sz, Point2(road_restrict.x_to_lon(x),road_restrict.y_to_lat(y)))); } grid_x(x,y) = t.dx; grid_y(x,y) = t.dy; } } } ++y; if (y >= road_restrict.mHeight) break; raster.AdvanceScanline(y); } } // printf("Total tensor calcs for road grid: %d\n",tcalcs); } /********************************************************************************************************************************** * SEED THE QUEUE! **********************************************************************************************************************************/ SeedQueue seedQ; { TIMER(build_seedQ) for(Pmwx::Vertex_iterator v = ioMap.vertices_begin(); v != ioMap.vertices_end(); ++v) { bool has_road = false; Pmwx::Halfedge_around_vertex_circulator circ(v->incident_halfedges()); Pmwx::Halfedge_around_vertex_circulator stop(circ); do { if (!circ->data().mSegments.empty() || !circ->twin()->data().mSegments.empty()) { has_road = true; break; } ++circ; } while (circ != stop); if(has_road) { QueueSeed(cgal2ben(v->point()),false,road_restrict,seedQ); } } printf("Queued %llu seeds origially.\n", (unsigned long long)seedQ.size()); } /********************************************************************************************************************************** * RUN THROUGH THE QUEUE, BUILDING ROADS **********************************************************************************************************************************/ vector<Segment2> roads; int ctr=0; { TIMER(eval_seed_Q) while(!seedQ.empty()) { ++ctr; if(CheckSeed(seedQ.front(),road_restrict)) { list<Point2> pts; Point2 fp(seedQ.front().p); Point2 bp(fp); pts.push_back(fp); bool front_alive = true; bool back_alive = true; bool major = seedQ.front().major; int fx(seedQ.front().x); int fy(seedQ.front().y); int fc=10,bc=10; int bx = fx, by = fy; Vector2 fe(0.0,0.0); Vector2 be(0.0,0.0); do { if (front_alive) { Vector2 e = Tensor2Eigen(Tensor_Func( Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,fp.x()), interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,fp.y())),&t)); if (!seedQ.front().major) e = e.perpendicular_ccw(); if(e.dot(fe) < 0) e = -e; fe = e; e *= ADVANCE_RATIO; fp += e; front_alive = CheckAndRegister(fp,road_restrict,fx, fy, fc, major); if(front_alive) front_alive = CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp); if(front_alive) { pts.push_front(fp); if (CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, 0.0f)) QueueSeed(fp,!major,road_restrict,seedQ); } } if (back_alive) { Vector2 e = -Tensor2Eigen(Tensor_Func( Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,bp.x()), interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,bp.y())),&t)); if (!seedQ.front().major) e = e.perpendicular_ccw(); if (e.dot(be) < 0) e = -e; be = e; e *= ADVANCE_RATIO; bp+= e; back_alive = CheckAndRegister(bp,road_restrict,bx, by, bc, major); if(back_alive) back_alive = CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp); if(back_alive) { pts.push_back(bp); if(CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, 0.0f)) QueueSeed(bp,!major,road_restrict,seedQ); } } } while (front_alive || back_alive); Point3 c(1,1,0); if(!major)c.y = 0; int k = ThinLine(pts, 10.0 * MTR_TO_NM * NM_TO_DEG_LAT, 500 * MTR_TO_NM * NM_TO_DEG_LAT); // printf("Killed %d points, kept %d points.\n", k, pts.size()); for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i) { // gMeshPoints.push_back(pair<Point2,Point3>(*i,c)); if(i != pts.begin()) { list<Point2>::iterator j(i); --j; // gMeshLines.push_back(pair<Point2,Point3>(*j,c)); // gMeshLines.push_back(pair<Point2,Point3>(*i,c)); // can't do this - makes a point cloud of roads - TOTALLY gross. // if(RollDice(max(inUrbanDensity.value_linear(j->x,j->y),inUrbanDensity.value_linear(i->x,i->y)))) roads.push_back(Segment2(*j,*i)); } } } seedQ.pop_front(); // if((ctr%1000)==0) // printf("Q contains: %d, pts: %d\n", seedQ.size(), gMeshPoints.size()); } } { TIMER(build_real_roads) Pmwx sub; sub.unbounded_face()->data().mTerrainType = terrain_Natural; BulkInsertRoads(roads, sub); BulkZapRoads(inUrbanDensity, sub); DebugAssert(sub.is_valid()); // TopoIntegrateMaps(&ioMap, &sub); // for(Pmwx::Face_iterator sf = sub.faces-begin(); sf != sub.faces_end(); ++sf) // sf->mTerrainType = terrain_Natural; DebugAssert(ioMap.is_valid()); DebugAssert(sub.is_valid()); #if SHOW_GENERATED_ROADS for(Pmwx::Edge_iterator eit = sub.edges_begin(); eit != sub.edges_end(); ++eit) debug_mesh_line(cgal2ben(eit->source()->point()),cgal2ben(eit->target()->point()),1,0,0, 0,1,0); #endif if(!sub.is_empty()) MergeMaps_legacy(ioMap, sub, false, NULL, true, inProg); } /********************************************************************************************************************************** * DEBUG OUTPUT **********************************************************************************************************************************/ #if OPENGL_MAP if(inFace != Face_handle() && ioTensorImage) { Pmwx::Ccb_halfedge_circulator circ = inFace->outer_ccb(); Pmwx::Ccb_halfedge_circulator start = circ; t.bounds = Bbox2(cgal2ben(circ->source()->point())); do { t.bounds += cgal2ben(circ->source()->point()); ++circ; } while (circ != start); TensorDDA(*ioTensorImage,Tensor_Func,&t); outTensorBounds[0] = t.bounds.p1.x(); outTensorBounds[1] = t.bounds.p1.y(); outTensorBounds[2] = t.bounds.p2.x(); outTensorBounds[3] = t.bounds.p2.y(); } #endif #if SHOW_ROAD_RESTRICT gDem[dem_Wizard] = road_restrict; #endif }
28,682
13,261
// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifdef TWO_MODULES module; #include <infra/Cpp20.h> module TWO(infra); #else #include <cstdlib> #include <infra/ToValue.h> #endif namespace two { #ifndef USE_STL template <> void to_value(const string& str, bool& val) { val = atoi(str.c_str()) != 0; } //str == "true" ? true : false; } template <> void to_value(const string& str, char& val) { val = char(atoi(str.c_str())); } template <> void to_value(const string& str, schar& val) { val = schar(atoi(str.c_str())); } template <> void to_value(const string& str, short& val) { val = short(atoi(str.c_str())); } template <> void to_value(const string& str, int& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, long& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, llong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, uchar& val) { val = uchar(atoi(str.c_str())); } template <> void to_value(const string& str, ushort& val) { val = ushort(atoi(str.c_str())); } template <> void to_value(const string& str, uint& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, ulong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, ullong& val) { val = atoi(str.c_str()); } template <> void to_value(const string& str, float& val) { val = float(atof(str.c_str())); } template <> void to_value(const string& str, double& val) { val = atof(str.c_str()); } //sscanf(str.c_str(), "%lf", &val); } template <> void to_value(const string& str, ldouble& val) { val = atof(str.c_str()); } #else template <> void to_value(const string& str, bool& val) { val = std::stoi(str) != 0; } //str == "true" ? true : false; } template <> void to_value(const string& str, char& val) { val = char(std::stoi(str)); } template <> void to_value(const string& str, schar& val) { val = schar(std::stoi(str)); } template <> void to_value(const string& str, short& val) { val = short(std::stoi(str)); } template <> void to_value(const string& str, int& val) { val = std::stoi(str); } template <> void to_value(const string& str, long& val) { val = std::stoi(str); } template <> void to_value(const string& str, llong& val) { val = std::stoi(str); } template <> void to_value(const string& str, uchar& val) { val = uchar(std::stoi(str)); } template <> void to_value(const string& str, ushort& val) { val = ushort(std::stoi(str)); } template <> void to_value(const string& str, uint& val) { val = std::stoi(str); } template <> void to_value(const string& str, ulong& val) { val = std::stoi(str); } template <> void to_value(const string& str, ullong& val) { val = std::stoi(str); } template <> void to_value(const string& str, float& val) { val = std::stof(str); } template <> void to_value(const string& str, double& val) { val = std::stod(str); } template <> void to_value(const string& str, ldouble& val) { val = std::stod(str); } #endif }
3,174
1,164
#ifndef FRAMEWORK_MATH_DETAILS #error You should include math/math.hpp instead of matrix_functions.hpp #endif #ifndef FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP #define FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP #include <math/inc/matrix_functions_details.hpp> #include <math/inc/matrix_type.hpp> namespace framework::math { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @addtogroup math_matrix_functions /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name transpose /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the transpose of a Matrix. /// /// @param value Specifies the Matrix of which to take the transpose. /// /// @return The transpose of the Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<R, C, T> transpose(const Matrix<C, R, T>& value) { return matrix_functions_details::transpose(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name component_wise_multiplication /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Perform a component-wise multiplication of two matrices. /// /// @param lhs Specifies the first Matrix multiplicand. /// @param rhs Specifies the second Matrix multiplicand. /// /// @return The component-wise multiplication of two matrices. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> component_wise_multiplication(const Matrix<C, R, T>& lhs, const Matrix<C, R, T>& rhs) { Matrix<C, R, T> temp{lhs}; for (std::size_t i = 0; i < C; ++i) { temp[i] *= rhs[i]; } return temp; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name outer_product /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the outer product of a pair of vectors. /// /// @param lhs Specifies the parameter to be treated as a column vector. /// @param rhs Specifies the parameter to be treated as a row vector. /// /// @return The outer product of a pair of vectors. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> outer_product(const Vector<R, T>& lhs, const Vector<C, T>& rhs) { return matrix_functions_details::outer_product(lhs, rhs); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name determinant /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the determinant of a Matrix. /// /// @param value Specifies the Matrix of which to take the determinant. /// /// @return The determinant of the Matrix. template <std::size_t C, std::size_t R, typename T> inline T determinant(const Matrix<C, R, T>& value) { return matrix_functions_details::determinant(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name inverse /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse of a Matrix. /// /// The values in the returned Matrix are undefined if Matrix is singular or /// poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The inverse of a Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> inverse(const Matrix<C, R, T>& value) { return matrix_functions_details::inverse(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name affine_inverse /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse of a affine Matrix. /// /// The values in the returned Matrix are undefined if Matrix contains not /// affine transformations, or Matrix is singular or /// poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The inverse of a Matrix. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> affine_inverse(const Matrix<C, R, T>& value) { return matrix_functions_details::affine_inverse(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @name inverse_transpose /// @{ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief Calculate the inverse-transpose of a Matrix. /// /// The values in the returned Matrix are undefined if Matrix is singular /// or poorly-conditioned (nearly singular). /// /// @param value Specifies the Matrix of which to take the inverse. /// /// @return The Matrix which is equivalent to `transpose(inverse(Matrix))`. template <std::size_t C, std::size_t R, typename T> inline Matrix<C, R, T> inverse_transpose(const Matrix<C, R, T>& value) { return matrix_functions_details::inverse_transpose(value); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace framework::math #endif
7,778
1,563
#include <iostream> #include "trompeloeil_doctest.h" #include <fstream> #include <future> #include <iterator> #include "fs-helpers/utils.h" #include "ietf-hardware/FspYhPsu.h" #include "ietf-hardware/IETFHardware.h" #include "ietf-hardware/sysrepo/Sysrepo.h" #include "mock/ietf_hardware.h" #include "pretty_printers.h" #include "test_log_setup.h" #include "test_sysrepo_helpers.h" #include "tests/configure.cmake.h" using namespace std::literals; TEST_CASE("HardwareState") { TEST_INIT_LOGS; static const auto modulePrefix = "/ietf-hardware:hardware"s; trompeloeil::sequence seq1; auto ietfHardware = std::make_shared<velia::ietf_hardware::IETFHardware>(); auto fans = std::make_shared<FakeHWMon>(); auto sysfsTempCpu = std::make_shared<FakeHWMon>(); auto sysfsTempFront = std::make_shared<FakeHWMon>(); auto sysfsTempMII0 = std::make_shared<FakeHWMon>(); auto sysfsTempMII1 = std::make_shared<FakeHWMon>(); auto sysfsVoltageAc = std::make_shared<FakeHWMon>(); auto sysfsVoltageDc = std::make_shared<FakeHWMon>(); auto sysfsPower = std::make_shared<FakeHWMon>(); auto sysfsCurrent = std::make_shared<FakeHWMon>(); auto emmc = std::make_shared<FakeEMMC>(); std::map<std::string, std::string> attributesEMMC; std::map<std::string, int64_t> attributesHWMon; // initialize all mocks attributesEMMC = { // FIXME passing initializer_list to macro is hell {"date"s, "02/2017"s}, {"serial"s, "0x00a8808d"s}, {"name"s, "8GME4R"s}, }; FAKE_EMMC(emmc, attributesEMMC); REQUIRE_CALL(*fans, attribute("fan1_input"s)).RETURN( 253); REQUIRE_CALL(*fans, attribute("fan2_input"s)).RETURN( 0); REQUIRE_CALL(*fans, attribute("fan3_input"s)).RETURN( 1280); REQUIRE_CALL(*fans, attribute("fan4_input"s)).RETURN( 666); REQUIRE_CALL(*sysfsTempFront, attribute("temp1_input")).RETURN(30800); REQUIRE_CALL(*sysfsTempCpu, attribute("temp1_input")).RETURN(41800); REQUIRE_CALL(*sysfsTempMII0, attribute("temp1_input")).RETURN(39000); REQUIRE_CALL(*sysfsTempMII1, attribute("temp1_input")).RETURN(36000); REQUIRE_CALL(*sysfsVoltageAc, attribute("in1_input")).RETURN(220000); REQUIRE_CALL(*sysfsVoltageDc, attribute("in1_input")).RETURN(12000); REQUIRE_CALL(*sysfsPower, attribute("power1_input")).RETURN(14000000); REQUIRE_CALL(*sysfsCurrent, attribute("curr1_input")).RETURN(200); attributesEMMC = {{"life_time"s, "40"s}}; FAKE_EMMC(emmc, attributesEMMC); using velia::ietf_hardware::data_reader::SensorType; using velia::ietf_hardware::data_reader::StaticData; using velia::ietf_hardware::data_reader::Fans; using velia::ietf_hardware::data_reader::SysfsValue; using velia::ietf_hardware::data_reader::EMMC; // register components into hw state ietfHardware->registerDataReader(StaticData("ne", std::nullopt, {{"class", "iana-hardware:chassis"}, {"mfg-name", "CESNET"s}})); ietfHardware->registerDataReader(StaticData("ne:ctrl", "ne", {{"class", "iana-hardware:module"}})); ietfHardware->registerDataReader(Fans("ne:fans", "ne", fans, 4)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-front", "ne:ctrl", sysfsTempFront, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-cpu", "ne:ctrl", sysfsTempCpu, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-internal-0", "ne:ctrl", sysfsTempMII0, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Temperature>("ne:ctrl:temperature-internal-1", "ne:ctrl", sysfsTempMII1, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::VoltageAC>("ne:ctrl:voltage-in", "ne:ctrl", sysfsVoltageAc, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::VoltageDC>("ne:ctrl:voltage-out", "ne:ctrl", sysfsVoltageDc, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Power>("ne:ctrl:power", "ne:ctrl", sysfsPower, 1)); ietfHardware->registerDataReader(SysfsValue<SensorType::Current>("ne:ctrl:current", "ne:ctrl", sysfsCurrent, 1)); ietfHardware->registerDataReader(EMMC("ne:ctrl:emmc", "ne:ctrl", emmc)); SECTION("Test HardwareState without sysrepo") { std::map<std::string, std::string> expected = { {"/ietf-hardware:hardware/component[name='ne']/class", "iana-hardware:chassis"}, {"/ietf-hardware:hardware/component[name='ne']/mfg-name", "CESNET"}, {"/ietf-hardware:hardware/component[name='ne:fans']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:fans']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/parent", "ne:fans:fan1"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value", "253"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan1:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/parent", "ne:fans:fan2"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan2:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/parent", "ne:fans:fan3"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value", "1280"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan3:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4']/parent", "ne:fans"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/parent", "ne:fans:fan4"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value", "666"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:fans:fan4:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:ctrl']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:ctrl']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value", "41800"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-cpu']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value", "30800"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-front']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value", "39000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-0']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value", "36000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:temperature-internal-1']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value", "14000000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:power']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value", "220000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-in']/sensor-data/value-type", "volts-AC"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value", "12000"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:voltage-out']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value", "200"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:current']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/parent", "ne:ctrl"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/serial-num", "0x00a8808d"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/mfg-date", "2017-02-01T00:00:00Z"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc']/model-name", "8GME4R"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/parent", "ne:ctrl:emmc"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value", "40"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/value-type", "other"}, {"/ietf-hardware:hardware/component[name='ne:ctrl:emmc:lifetime']/sensor-data/units-display", "percent"}, }; // exclude last-change node auto result = ietfHardware->process(); result.erase(modulePrefix + "/last-change"); REQUIRE(result == expected); } SECTION("Test IETF Hardware from sysrepo's view") { TEST_SYSREPO_INIT_LOGS; TEST_SYSREPO_INIT; TEST_SYSREPO_INIT_CLIENT; auto ietfHardwareSysrepo = std::make_shared<velia::ietf_hardware::sysrepo::Sysrepo>(srSubs, ietfHardware); SECTION("test last-change") { // at least check that there is some timestamp REQUIRE(dataFromSysrepo(client, modulePrefix, SR_DS_OPERATIONAL).count("/last-change") > 0); } SECTION("test components") { std::map<std::string, std::string> expected = { {"[name='ne']/name", "ne"}, {"[name='ne']/class", "iana-hardware:chassis"}, {"[name='ne']/mfg-name", "CESNET"}, {"[name='ne']/sensor-data", ""}, {"[name='ne:fans']/class", "iana-hardware:module"}, {"[name='ne:fans']/name", "ne:fans"}, {"[name='ne:fans']/parent", "ne"}, {"[name='ne:fans']/sensor-data", ""}, {"[name='ne:fans:fan1']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan1']/name", "ne:fans:fan1"}, {"[name='ne:fans:fan1']/parent", "ne:fans"}, {"[name='ne:fans:fan1']/sensor-data", ""}, {"[name='ne:fans:fan1:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan1:rpm']/name", "ne:fans:fan1:rpm"}, {"[name='ne:fans:fan1:rpm']/parent", "ne:fans:fan1"}, {"[name='ne:fans:fan1:rpm']/sensor-data", ""}, {"[name='ne:fans:fan1:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value", "253"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan1:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan2']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan2']/name", "ne:fans:fan2"}, {"[name='ne:fans:fan2']/parent", "ne:fans"}, {"[name='ne:fans:fan2']/sensor-data", ""}, {"[name='ne:fans:fan2:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan2:rpm']/name", "ne:fans:fan2:rpm"}, {"[name='ne:fans:fan2:rpm']/parent", "ne:fans:fan2"}, {"[name='ne:fans:fan2:rpm']/sensor-data", ""}, {"[name='ne:fans:fan2:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value", "0"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan2:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan3']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan3']/name", "ne:fans:fan3"}, {"[name='ne:fans:fan3']/parent", "ne:fans"}, {"[name='ne:fans:fan3']/sensor-data", ""}, {"[name='ne:fans:fan3:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan3:rpm']/name", "ne:fans:fan3:rpm"}, {"[name='ne:fans:fan3:rpm']/parent", "ne:fans:fan3"}, {"[name='ne:fans:fan3:rpm']/sensor-data", ""}, {"[name='ne:fans:fan3:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value", "1280"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan3:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:fans:fan4']/class", "iana-hardware:fan"}, {"[name='ne:fans:fan4']/name", "ne:fans:fan4"}, {"[name='ne:fans:fan4']/parent", "ne:fans"}, {"[name='ne:fans:fan4']/sensor-data", ""}, {"[name='ne:fans:fan4:rpm']/class", "iana-hardware:sensor"}, {"[name='ne:fans:fan4:rpm']/name", "ne:fans:fan4:rpm"}, {"[name='ne:fans:fan4:rpm']/parent", "ne:fans:fan4"}, {"[name='ne:fans:fan4:rpm']/sensor-data", ""}, {"[name='ne:fans:fan4:rpm']/sensor-data/oper-status", "ok"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value", "666"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-precision", "0"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-scale", "units"}, {"[name='ne:fans:fan4:rpm']/sensor-data/value-type", "rpm"}, {"[name='ne:ctrl']/name", "ne:ctrl"}, {"[name='ne:ctrl']/parent", "ne"}, {"[name='ne:ctrl']/class", "iana-hardware:module"}, {"[name='ne:ctrl']/sensor-data", ""}, {"[name='ne:ctrl:temperature-cpu']/name", "ne:ctrl:temperature-cpu"}, {"[name='ne:ctrl:temperature-cpu']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-cpu']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data", ""}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value", "41800"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-cpu']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-front']/name", "ne:ctrl:temperature-front"}, {"[name='ne:ctrl:temperature-front']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-front']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-front']/sensor-data", ""}, {"[name='ne:ctrl:temperature-front']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value", "30800"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-front']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-internal-0']/name", "ne:ctrl:temperature-internal-0"}, {"[name='ne:ctrl:temperature-internal-0']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-internal-0']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data", ""}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value", "39000"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-internal-0']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:temperature-internal-1']/name", "ne:ctrl:temperature-internal-1"}, {"[name='ne:ctrl:temperature-internal-1']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:temperature-internal-1']/parent", "ne:ctrl"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data", ""}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value", "36000"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:temperature-internal-1']/sensor-data/value-type", "celsius"}, {"[name='ne:ctrl:power']/name", "ne:ctrl:power"}, {"[name='ne:ctrl:power']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:power']/parent", "ne:ctrl"}, {"[name='ne:ctrl:power']/sensor-data", ""}, {"[name='ne:ctrl:power']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:power']/sensor-data/value", "14000000"}, {"[name='ne:ctrl:power']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:power']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:power']/sensor-data/value-type", "watts"}, {"[name='ne:ctrl:voltage-in']/name", "ne:ctrl:voltage-in"}, {"[name='ne:ctrl:voltage-in']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:voltage-in']/parent", "ne:ctrl"}, {"[name='ne:ctrl:voltage-in']/sensor-data", ""}, {"[name='ne:ctrl:voltage-in']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value", "220000"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:voltage-in']/sensor-data/value-type", "volts-AC"}, {"[name='ne:ctrl:voltage-out']/name", "ne:ctrl:voltage-out"}, {"[name='ne:ctrl:voltage-out']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:voltage-out']/parent", "ne:ctrl"}, {"[name='ne:ctrl:voltage-out']/sensor-data", ""}, {"[name='ne:ctrl:voltage-out']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value", "12000"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-scale", "micro"}, {"[name='ne:ctrl:voltage-out']/sensor-data/value-type", "volts-DC"}, {"[name='ne:ctrl:current']/name", "ne:ctrl:current"}, {"[name='ne:ctrl:current']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:current']/parent", "ne:ctrl"}, {"[name='ne:ctrl:current']/sensor-data", ""}, {"[name='ne:ctrl:current']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:current']/sensor-data/value", "200"}, {"[name='ne:ctrl:current']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:current']/sensor-data/value-scale", "milli"}, {"[name='ne:ctrl:current']/sensor-data/value-type", "amperes"}, {"[name='ne:ctrl:emmc']/name", "ne:ctrl:emmc"}, {"[name='ne:ctrl:emmc']/parent", "ne:ctrl"}, {"[name='ne:ctrl:emmc']/class", "iana-hardware:module"}, {"[name='ne:ctrl:emmc']/serial-num", "0x00a8808d"}, {"[name='ne:ctrl:emmc']/mfg-date", "2017-02-01T00:00:00Z"}, {"[name='ne:ctrl:emmc']/model-name", "8GME4R"}, {"[name='ne:ctrl:emmc']/sensor-data", ""}, {"[name='ne:ctrl:emmc:lifetime']/name", "ne:ctrl:emmc:lifetime"}, {"[name='ne:ctrl:emmc:lifetime']/class", "iana-hardware:sensor"}, {"[name='ne:ctrl:emmc:lifetime']/parent", "ne:ctrl:emmc"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data", ""}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/oper-status", "ok"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value", "40"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-precision", "0"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-scale", "units"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/value-type", "other"}, {"[name='ne:ctrl:emmc:lifetime']/sensor-data/units-display", "percent"}, }; REQUIRE(dataFromSysrepo(client, modulePrefix + "/component", SR_DS_OPERATIONAL) == expected); } SECTION("test leafnode query") { const auto xpath = modulePrefix + "/component[name='ne:ctrl:emmc:lifetime']/class"; client->session_switch_ds(SR_DS_OPERATIONAL); auto val = client->get_item(xpath.c_str()); client->session_switch_ds(SR_DS_RUNNING); REQUIRE(!!val); REQUIRE(val->data()->get_identityref() == "iana-hardware:sensor"s); } } } class FakeI2C : public velia::ietf_hardware::TransientI2C { public: FakeI2C(const std::string& fakeHwmonRoot) : TransientI2C({}, {}, {}) , m_fakeHwmonRoot(fakeHwmonRoot) { } MAKE_CONST_MOCK0(isPresent, bool(), override); MAKE_CONST_MOCK0(bind_mock, void()); MAKE_CONST_MOCK0(unbind_mock, void()); void removeHwmonFile(const std::string& name) const { std::filesystem::remove(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo)) / name); } void bind() const override { bind_mock(); removeDirectoryTreeIfExists(m_fakeHwmonRoot); std::filesystem::create_directory(m_fakeHwmonRoot); std::filesystem::create_directory(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo))); for (const auto& filename : {"name", "temp1_input", "temp2_input", "curr1_input", "curr2_input", "curr3_input", "in1_input", "in2_input", "in3_input", "power1_input", "power2_input", "fan1_input"} ) { std::ofstream ofs(m_fakeHwmonRoot / ("hwmon" + std::to_string(m_hwmonNo)) / filename); // I don't really care about the values here, I just need the HWMon class to think that the files exist. ofs << 0 << "\n"; } } void unbind() const override { unbind_mock(); removeDirectoryTreeIfExists(m_fakeHwmonRoot); m_hwmonNo++; } private: std::filesystem::path m_fakeHwmonRoot; mutable std::atomic<int> m_hwmonNo = 1; }; TEST_CASE("FspYhPsu") { TEST_INIT_LOGS; std::atomic<int> counter = 0; const auto fakeHwmonRoot = CMAKE_CURRENT_BINARY_DIR + "/tests/psu"s; removeDirectoryTreeIfExists(fakeHwmonRoot); auto fakeI2c = std::make_shared<FakeI2C>(fakeHwmonRoot); trompeloeil::sequence seq1; std::shared_ptr<velia::ietf_hardware::FspYhPsu> psu; std::vector<std::unique_ptr<trompeloeil::expectation>> expectations; auto i2cPresence = [&counter] { switch (counter) { case 0: case 2: case 4: return false; case 1: case 3: return true; } REQUIRE(false); __builtin_unreachable(); }; ALLOW_CALL(*fakeI2c, isPresent()).LR_RETURN(i2cPresence()); REQUIRE_CALL(*fakeI2c, bind_mock()).LR_WITH(counter == 1).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, unbind_mock()).LR_WITH(counter == 2).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, bind_mock()).LR_WITH(counter == 3).IN_SEQUENCE(seq1); REQUIRE_CALL(*fakeI2c, unbind_mock()).LR_WITH(counter == 4).IN_SEQUENCE(seq1); psu = std::make_shared<velia::ietf_hardware::FspYhPsu>(fakeHwmonRoot, "psu", fakeI2c); for (auto i : {0, 1, 2, 3, 4}) { std::this_thread::sleep_for(std::chrono::seconds(4)); velia::ietf_hardware::DataTree expected; switch (i) { case 0: break; case 1: expected = { {"/ietf-hardware:hardware/component[name='ne:psu']/class", "iana-hardware:power-supply"}, {"/ietf-hardware:hardware/component[name='ne:psu']/parent", "ne"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-12V']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-5Vsb']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:current-in']/sensor-data/value-type", "amperes"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan']/class", "iana-hardware:module"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1']/class", "iana-hardware:fan"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1']/parent", "ne:psu:fan"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/parent", "ne:psu:fan:fan1"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-scale", "units"}, {"/ietf-hardware:hardware/component[name='ne:psu:fan:fan1:rpm']/sensor-data/value-type", "rpm"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-in']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:power-out']/sensor-data/value-type", "watts"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-1']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-scale", "milli"}, {"/ietf-hardware:hardware/component[name='ne:psu:temperature-2']/sensor-data/value-type", "celsius"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-12V']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-5Vsb']/sensor-data/value-type", "volts-DC"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/class", "iana-hardware:sensor"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/parent", "ne:psu"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/oper-status", "ok"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-precision", "0"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-scale", "micro"}, {"/ietf-hardware:hardware/component[name='ne:psu:voltage-in']/sensor-data/value-type", "volts-AC"}, }; break; case 2: break; case 3: // Here I simulate read failure by a file from the hwmon directory. This happens when the user wants data from // a PSU that's no longer there and the watcher thread didn't unbind it yet. fakeI2c->removeHwmonFile("temp1_input"); break; case 4: break; } REQUIRE(psu->readValues() == expected); counter++; } waitForCompletionAndBitMore(seq1); }
41,541
15,290
#pragma once #include <SDL.h> #include <string> class Engine { public: Engine(); SDL_Window* createWindow(const int width, const int height, std::string name = "WINDOW NAME"); SDL_Surface* createSurface(SDL_Window* window); SDL_Surface* createImageSurface(SDL_Surface* surface, std::string path); SDL_Renderer* createRenderer(SDL_Window* window); void freeSurface(SDL_Surface* surface); void destroyWindow(SDL_Window* window); void destroyRenderer(SDL_Renderer* renderer); void close(); private: };
591
181
#include "Generators/ClearMeshGenerator.h" #include "Utils/Utils.h" #include "Data/ApplicationState.h" #include "Profiler.h" ClearMeshGenerator::ClearMeshGenerator(ApplicationState *as, ComputeKernel *kernels) { bool tmp = false; appState = as; } void ClearMeshGenerator::Generate(ComputeKernel *kernels) { START_PROFILER(); if(useGPU) { if (appState->mode == ApplicationMode::TERRAIN) { kernels->SetKernelArg("clear_mesh_terrain", 0, "mesh"); kernels->ExecuteKernel("clear_mesh_terrain", cl::NDRange(1), cl::NDRange(appState->models.coreTerrain->mesh->vertexCount)); } else if (appState->mode == ApplicationMode::CUSTOM_BASE) { kernels->SetKernelArg("clear_mesh_custom_base", 0, "mesh"); kernels->SetKernelArg("clear_mesh_custom_base", 1, "mesh_copy"); kernels->ExecuteKernel("clear_mesh_custom_base", cl::NDRange(1), cl::NDRange(appState->models.customBase->mesh->vertexCount)); } } else { if (appState->mode == ApplicationMode::TERRAIN) { Mesh *mes = appState->models.coreTerrain->mesh; int vc = mes->vertexCount; for(int i=0; i<vc; i++) { mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = mes->vert[i].position.y = 0.0f; mes->vert[i].extras1.x = 0.0f; mes->vert[i].extras1.y = 0.0f; mes->vert[i].extras1.z = 0.0f; } } else if (appState->mode == ApplicationMode::CUSTOM_BASE) { Mesh *mes = appState->models.customBase->mesh; Mesh *mesC = appState->models.customBaseCopy->mesh; int vc = mesC->vertexCount; for(int i=0; i<vc; i++) { mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = 0.0f; mes->vert[i].position = mesC->vert[i].position; mes->vert[i].extras1.x = 0.0f; mes->vert[i].extras1.y = 0.0f; mes->vert[i].extras1.z = 0.0f; } } } END_PROFILER(time); } nlohmann::json ClearMeshGenerator::Save() { nlohmann::json data; data["uiActive"] = uiActive; data["useGPU"] = useGPU; return data; } void ClearMeshGenerator::Load(nlohmann::json data) { uiActive = data["uiActive"]; useGPU = data["useGPU"]; } void ClearMeshGenerator::ShowSettings() { if(ImGui::Checkbox("Use GPU##CMG", &useGPU)) { } ImGui::Checkbox("Use GPU For Normals(Flat Shading)##CMG", &appState->states.useGPUForNormals); ImGui::Text("Time : %lf ms", time); }
2,312
1,045
#include <vector> #include <string> #include <stack> #include "gtest/gtest.h" using namespace std; // 150. Evaluate Reverse Polish Notation // https://leetcode.com/problems/evaluate-reverse-polish-notation/?fbclid=IwAR1ELnj87j9bLdIIOatPq595iDYISE1rOH99AIiWEIdA72jBTwVuPfw6XPE class Solution { public: bool isOperand(string& operand) { if (operand == "+" || operand == "-" || operand == "*" || operand == "/") { return true; } else { return false; } } int operate(int val1, string& operand, int val2) { if (operand == "+") { return val1 + val2; } else if (operand == "-") { return val1 - val2; } else if (operand == "*") { return val1 * val2; } else if (operand == "/") { return val1 / val2; } } int evalRPN(vector<string>& tokens) { vector<string>::iterator itr; stack<string> tokenstack; for (itr = tokens.begin(); itr != tokens.end(); itr++) { string token = *itr; if (isOperand(token)) { string val2 = tokenstack.top(); tokenstack.pop(); string val1 = tokenstack.top(); tokenstack.pop(); int value = operate(stoi(val1), token, stoi(val2)); tokenstack.push(to_string(value)); } else { // value tokenstack.push(token); } } return stoi(tokenstack.top()); } }; TEST(EvaluateRPN, HandlesPositiveInput) { Solution solution; vector<string> input; input = {"2", "1", "+", "3", "*"}; EXPECT_EQ(solution.evalRPN(input) , 9); input = {"4", "13", "5", "/", "+"}; EXPECT_EQ(solution.evalRPN(input) , 6); input = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"}; EXPECT_EQ(solution.evalRPN(input) , 22); }
2,131
690
#pragma once #ifndef LENGTHCOMPONENT_H #define LENGTHCOMPONENT_H #include <cstdint> namespace GGB::Hardware::Audio { class LengthComponent { public: void setLength(uint16_t value, bool stopAfterLength) { length = length == 0 ? value : length; lengthStop = stopAfterLength; } bool tick() { length -= length != 0 ? 1 : 0; return !lengthStop || (length != 0 && lengthStop); } private: bool lengthStop = false; uint16_t length = 0; }; } #endif // LENGTHCOMPONENT_H
656
201
#include "kmain.h" _declspec(naked) void multiboot_entry(void) { __asm { align 4 multiboot_header: //멀티부트 헤더 사이즈 : 0X20 dd(MULTIBOOT_HEADER_MAGIC); magic number dd(MULTIBOOT_HEADER_FLAGS); flags dd(CHECKSUM); checksum dd(HEADER_ADRESS); //헤더 주소 KERNEL_LOAD_ADDRESS+ALIGN(0x100064) dd(KERNEL_LOAD_ADDRESS); //커널이 로드된 가상주소 공간 dd(00); //사용되지 않음 dd(00); //사용되지 않음 dd(HEADER_ADRESS + 0x20); //커널 시작 주소 : 멀티부트 헤더 주소 + 0x20, kernel_entry kernel_entry : mov esp, KERNEL_STACK; //스택 설정 push 0; //플래그 레지스터 초기화 popf //GRUB에 의해 담겨 있는 정보값을 스택에 푸쉬한다. push ebx; //멀티부트 구조체 포인터 push eax; //매직 넘버 //위의 두 파라메터와 함께 kmain 함수를 호출한다. call kmain; //C++ 메인 함수 호출 //루프를 돈다. kmain이 리턴되지 않으면 아래 코드는 수행되지 않는다. halt: jmp halt; } } void kmain(unsigned long magic, unsigned long addr) { SkyConsole::Initialize(); SkyConsole::Print("Hello World!!\n"); for (;;); }
913
687
#ifndef PAGE_H_INCLUDED #define PAGE_H_INCLUDED #include "common/Types.hpp" #include "core/SQLEntity.hpp" #include <iostream> class JSONSerializable; class Page: public SQLEntity, public JSONSerializable { public: Page(); virtual ~Page(); void setId(INTEGER<12> id) { p_id = id; } void setName(STRING<255> name) { p_name = name; } void setUserId(INTEGER<12> userId) { p_userId = userId; } void setPageViews(INTEGER<12> pageViews) { p_pageViews = pageViews; } INTEGER<12> getId() { return p_id; } STRING<255> getName() { return p_name; } INTEGER<12> getUserId() { return p_userId; } INTEGER<12> getPageViews() { return p_pageViews; } private: INTEGER<12> p_id; STRING<255> p_name; INTEGER<12> p_userId; INTEGER<12> p_pageViews; protected: virtual std::map<std::string, const JSONSerializable*> getSerializedData() const { std::map<std::string, const JSONSerializable*> result; result["id"] = &p_id; result["name"] = &p_name; result["pageViews"] = &p_pageViews; return result; } }; #endif // PAGE_H_INCLUDED
1,130
450
class Solution { public: void dfs(vector<vector<int>>& grid, int i, int j) { int n = grid.size(), m = grid[0].size(); if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0) return ; grid[i][j] = 0; int d1[] = {0, 1, 0, -1}, d2[] = {1, 0, -1, 0}; for(int k = 0; k < 4; k++) dfs(grid, i + d1[k], j + d2[k]); return ; } bool isConn(vector<vector<int>> grid) { if(grid.size() == 0) return false; int n = grid.size(), m = grid[0].size(); int flag = false; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { if(flag == false) { dfs(grid, i, j); flag = true; } else return false; } } } if(flag == false) return false; return true; } int minDays(vector<vector<int>>& grid) { if(grid.size() == 0) return true; int n = grid.size(), m = grid[0].size(); if(isConn(grid) == false) return 0; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(grid[i][j] == 1) { grid[i][j] = 0; if(isConn(grid) == false) return 1; grid[i][j] = 1; } } } return 2; } };
1,652
555
#include <iostream> using namespace std; int N,P,E; int X[22]; int Y[22]; int check[22]; int answer[22]; bool isAnswer = false; void result() { if(isAnswer) return; int cnt = 0,Sx = 0,Sy = 0; for(int x = 0; x<N; x++) { if(check[x] == 1) { cnt++; Sx +=X[x]; Sy +=Y[x]; } } if(cnt != P) return; if(Sx <= E && E <=Sy) { isAnswer = true; // for(int x = 0; x<N; x++) { // cout << check[x] << " "; // } int left = E; for(int x = 0; x<N; x++) { if(check[x] == 1) { answer[x] +=X[x]; left-=X[x]; } } for(int x = 0; x<N; x++) { if(check[x] == 1 && left>0) { int K = min(left,Y[x]-answer[x]); answer[x] += K; left -= K; } } for(int x = 0; x<N; x++) { cout << answer[x] << " "; } } } void DFS(int current) { if(current == N) { for(int t = 0; t<2; t++) { check[current] = t; result(); } return ; } for(int t = 0; t<2; t++) { check[current] = t; DFS(current+1); } } int main() { cin >> N >> P >> E; for(int i = 0; i < N; i++) { cin >> X[i] >> Y[i]; } DFS(0); if(!isAnswer) { cout<<-1; } }
1,418
570
// // Booking.cpp // Hw 11 // Object Oriented Vieshow Cinemas Taipei QSquare system // // Created by Tomy Hsieh on 2018/6/3. // Copyright © 2018年 Tomy Hsieh. All rights reserved. // #include "Booking.h" #include "MovieDatabase.h" #include <iostream> using std::cout; using std::endl; Booking::Booking() {} string Booking::getEmail() { return string(email); } int Booking::getMovieCode() { return movieCode; } int Booking::getDateCode() { return dateCode; } int Booking::getSessionTimeCode() { return sessionTimeCode; } int Booking::getNumTickets(int ticketType) { return numTickets[ticketType]; } string Booking::getSeletedSeat(int number) { return seletedSeats[number]; } void Booking::setEmail(string theEmail) { unsigned long length = theEmail.size(); length = (length < 40 ? length : 39); for (int i = 0; i < length; i++) { email[i] = theEmail[i]; } email[length] = '\0'; } void Booking::setMovieCode(int theMovieCode) { movieCode = (theMovieCode > 0 ? theMovieCode : 0); } void Booking::setDateCode(int theDateCode) { dateCode = (theDateCode > 0 ? theDateCode : 0); } void Booking::setSessionTimeCode(int theSessionTimeCode) { sessionTimeCode = (theSessionTimeCode > 0 ? theSessionTimeCode : 0); } void Booking::setNumTickets(int theNumTickets[]) { for (int i = 0; i < 4; i++) { numTickets[i] = (theNumTickets[i] > 0 ? theNumTickets[i] : 0); } } void Booking::setSeletedSeats(string theSeletedSeats[], int numSeats) { for (int i = 0; i < numSeats; i++) { seletedSeats[i][0] = theSeletedSeats[i][0]; seletedSeats[i][1] = theSeletedSeats[i][1]; seletedSeats[i][2] = '\0'; } cout << endl; } void Booking::displayBooking(MovieDatabase &movieDatabase) { cout << "\t\t\t\tNo. of Tickets\t\tPrice\t\tSubtotal" << endl; int Num = 0, Price = 0, Sub = 0, Total = 0; char ticketType[4][15] = {"Adult\t\t\t", "Concession\t\t", "Disability\t\t", "Elderly\t\t\t"}; for (int i = 0; i < 4; i++) { if (numTickets[i] != 0) { Num = numTickets[i]; Price = movieDatabase.getMovie(movieCode).getPrice(i); Sub = Num * Price; Total += Sub; cout << ticketType[i] << Num << "\t\t\t\t\t" << Price << "\t\t\t" << Sub << endl; } } cout << endl << "Total Amount For Tickets: " << Total << endl; }
2,321
917
#include "CommonTypeDefines.h" #include "streams/DS_FileStream.h" #include "fileUtils/_fileExists.h" #include <algorithm> using std::min; namespace DataStructures { //------------------------------------------------------------------- Stream ------------------------------------------------------------------------ #if __WORDSIZE == 64 template <> size_t Stream::Write(const unsigned int &buffer) { if (mForce32bitCompatable) { __u32 val = buffer; return this->Write(&val, sizeof(__u32)); } else return this->Write(&buffer, sizeof(unsigned int)); } template <> size_t Stream::Write(const int &buffer) { if (mForce32bitCompatable) { __s32 val = buffer; return this->Write(&val, sizeof(__s32)); } else return this->Write(&buffer, sizeof(int)); } template <> size_t Stream::Write(const unsigned long &buffer) { if (mForce32bitCompatable) { __u32 val = buffer; return this->Write(&val, sizeof(__u32)); } else return this->Write(&buffer, sizeof(unsigned long)); } template <> size_t Stream::Write(const long &buffer) { if (mForce32bitCompatable) { __s32 val = buffer; return this->Write(&val, sizeof(__s32)); } else return this->Write(&buffer, sizeof(long)); } template <> bool Stream::Read(unsigned int &dst) { if (mForce32bitCompatable) { __u32 t; bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(unsigned int)) == sizeof(unsigned int); } template <> bool Stream::Read(int &dst) { if (mForce32bitCompatable) { __s32 t; bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(int)) == sizeof(int); } template <> bool Stream::Read(unsigned long &dst) { if (mForce32bitCompatable) { __u32 t; bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(unsigned long)) == sizeof(unsigned long); } template <> bool Stream::Read(long &dst) { if (mForce32bitCompatable) { __s32 t; bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32); dst = t; return res; } else return this->Read((void *)&dst, sizeof(long)) == sizeof(long); } #endif size_t Stream::WriteString(const char *buffer, size_t maxsize) { if (!CanWrite()) return 0; __u16 size = min(strlen(buffer), maxsize + sizeof(__u16)); size_t actSize = this->Write(&size, sizeof(size)); actSize += this->Write(buffer, size); return actSize; } size_t Stream::ReadString(char *dst, size_t maxsize) { if (Eof() || !dst || !CanRead()) return 0; __u16 size; size_t readIn = this->Read(&size, sizeof(size)); readIn += this->Read(dst, min((size_t)size, maxsize)); dst[size] = 0; return readIn; } size_t Stream::CopyFrom(Stream *stream, size_t count) { const size_t _max_buffer_size = 0xf0000; size_t size = count; if (count == 0) { stream->Seek(0, SEEK_SET); size = stream->Length(); } size_t result = size; size_t bufferSize; if (size > _max_buffer_size) bufferSize = _max_buffer_size; else bufferSize = size; char *buffer = (char *)malloc(bufferSize); size_t n; while (size != 0) { if (size > bufferSize) n = bufferSize; else n = size; stream->Read(buffer, n); Write(buffer, n); size -= n; } free(buffer); return result; } bool Stream::SaveToStream(Stream *stream) { if (!stream) return false; __s64 oldPos = Position(); __s64 oldPos1 = stream->Position(); bool res = stream->CopyFrom(this, 0) == Length(); Seek(oldPos, SEEK_SET); stream->Seek(oldPos1, SEEK_SET); return res; } bool Stream::LoadFromStream(Stream *stream) { if (!stream) return false; __s64 oldPos = Position(); __s64 oldPos1 = stream->Position(); size_t size = stream->Length(); SetLength(size); Seek(0, SEEK_SET); bool res = CopyFrom(stream, 0) == size; Seek(oldPos, SEEK_SET); stream->Seek(oldPos1, SEEK_SET); return res; } bool Stream::SaveToFile(const char *fileName) { FileStream *stream = new FileStream(fileName, "wb+"); bool result = SaveToStream(stream); stream->Close(); delete stream; return result; } bool Stream::LoadFromFile(const char *fileName) { if (!_fileExists(fileName)) return false; FileStream *stream = new FileStream(fileName, "rb"); bool result = LoadFromStream(stream); stream->Close(); delete stream; return result; } __s64 Stream::Length() { __s64 oldPos = Seek(0, SEEK_CUR); __s64 length = Seek(0, SEEK_END); Seek(oldPos, SEEK_SET); return length; } __s64 Stream::Position() { return Seek(0, SEEK_CUR); } char *Stream::ReadLine(char *str, int num) { if (num <= 0) return NULL; char c = 0; size_t maxCharsToRead = num - 1; for (size_t i = 0; i < maxCharsToRead; ++i) { size_t result = Read(&c, 1); if (result != 1) { str[i] = '\0'; break; } if (c == '\n') { str[i] = c; str[i + 1] = '\0'; break; } else if(c == '\r') { str[i] = c; // next may be '\n' size_t pos = Position(); char nextChar = 0; if (Read(&nextChar, 1) != 1) { // no more characters str[i + 1] = '\0'; break; } if (nextChar == '\n') { if (i == maxCharsToRead - 1) { str[i + 1] = '\0'; break; } else { str[i + 1] = nextChar; str[i + 2] = '\0'; break; } } else { Seek(pos, SEEK_SET); str[i + 1] = '\0'; break; } } str[i] = c; } return str; // what if first read failed? } bool Stream::Eof() { return Position() >= Length(); } bool Stream::Rewind() { if (!CanSeek()) return 0; else return Seek(0, SEEK_SET) == 0; } std::string Stream::GetAsString() { char *buffer; __s64 fileLen = Length(); __s64 oldPosition = Position(); buffer = (char *)malloc(fileLen + 1); Seek(0, SEEK_SET); Read(buffer, fileLen); Seek(oldPosition, SEEK_SET); buffer[fileLen] = 0; std::string result(buffer); free(buffer); return result; } __u32 Stream::GetMemoryCost() { //this value is not very accurate because of class HexString's cache using return static_cast<__u32>(sizeof(*this) + strlen(mFileName)); } }
6,385
2,896
/********************************************************************************* * Copyright (C) 1999,2004 by srl, Inc. All Rights Reserved. * ********************************************************************************* * Authors: Ian C. Starnes, Dr. J. Shane Frasier, Shaun Grant ********************************************************************************* * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * ********************************************************************************* * Last $Author: ians $ $Revision: 248 $ * Last Modified $Date: 2006-03-08 22:50:35 -0500 (Wed, 08 Mar 2006) $ *********************************************************************************/ #include "srl/Time.h" using namespace SRL; // Basic Time Logic Time::Time(bool local_time, bool empty) { if (!empty) update(local_time); } Time::Time(TimeValue &tval) { _update(tval.tv_sec, tval.tv_usec, tval.tv_zone); } Time::Time(float64 sec) : _time(sec) { } Time::Time(uint8 hour, uint8 minute, float32 second, uint8 tz) { _update(hour, minute, second, tz); } Time::Time(time_t ts) { _update(static_cast<int32>(ts), 0, 0); } Time::Time(tm *dt) { _time = dt->tm_hour*3600.0f + dt->tm_min*60.0f + dt->tm_sec; //_tz = dt->tm_tz; } // Time::Time(String &str_time) // { // // TODO: Add String Construtor support // } Time::Time(const Time &time) { *this = time; } uint8 Time::hour() const { return (uint8)((uint32)(_time / 3600))%24; } uint8 Time::minute() const { return (uint8)((int32)(_time / 60)%60); } float32 Time::second() const { register uint32 itime = (uint32)_time; float32 ms = _time - itime; return ((float32)(itime % 60))+ms; } void Time::addToHour(const int32 &hours) { _time += hours * 3600; } void Time::addToMinute(const int32 &minutes) { _time += minutes * 60; } void Time::update(bool local_time) { TimeValue tv; System::GetCurrentTime(tv); if (local_time) { #ifdef linux const time_t t = tv.tv_sec; tm *lt = localtime(&t); tv.tv_dst = lt->tm_isdst; #endif tv.tv_sec -= (tv.tv_zone*3600) - (tv.tv_dst ? 3600 : 0); } _update(tv.tv_sec, tv.tv_usec, tv.tv_zone); } void Time::update(TimeValue &tv) { _update(tv.tv_sec, tv.tv_usec, tv.tv_zone); } void Time::_update(int32 ts, uint32 micro_seconds, uint8 tz) { if (ts > 86400) { _time = ts % 86400; //_time = ts-((int32)(ts / 86400.0f)*(86400.0f)); } else { _time = (float64)ts; } _time += ((float64)micro_seconds/1000000.0); _tz = tz; } void Time::_update(uint8 hour, uint8 minute, float32 second, uint8 tz) { _time = hour*3600.0f + minute*60.0f + second; _tz = tz; } bool Time::isValid() const { if ((_time > 0) && (_time < 86400)) return true; return false; } // String Time::formatString(const char *str_format) const // { // char tmp[256]; // //tm dt; // //toTM(&dt); // //strftime(tmp, 255, str_format, dt); // return tmp; // } String Time::asString() const { return String::Format("%02d:%02d:%2.4f", hour(), minute(), second()); } time_t Time::toUnix() const { return (time_t)_time; } void Time::toTM(tm *dt) const { //memset (dt, 0x0, sizeof (struct tm)); dt->tm_hour = hour(); dt->tm_min = minute(); dt->tm_sec = (int32)second(); } int32 Time::rescale() { if ((_time > SECONDS_IN_DAY)||(_time < 0)) { // calculate how many days to change int32 new_days = (int32)(_time / SECONDS_IN_DAY); _time = _time - ((float32)(new_days * SECONDS_IN_DAY)); return new_days; } return 0; } Time& Time::operator=(const Time &d) { _time = d._time; return *this; } Time& Time::operator++() { ++_time; return *this; } Time& Time::operator--() { --_time; return *this; } Time& Time::operator+=(const Time& t) { _time += t.getTime(); return *this; } Time& Time::operator-=(const Time& t) { _time -= t.getTime(); return *this; } Time& Time::operator+=(const int32 seconds) { _time += seconds; return *this; } Time& Time::operator-=(const int32 seconds) { _time -= seconds; return *this; } Time SRL::operator+(const Time& t1, const Time& t2) { return Time(t1.getTime()+t2.getTime()); } Time SRL::operator+(const Time& t1, const int32& seconds) { return Time(t1.getTime()+seconds); } Time SRL::operator+(const int32& seconds, const Time& t1) { return Time(seconds+t1.getTime()); } Time SRL::operator-(const Time& t1, const Time& t2) { return Time(t1.getTime()-t2.getTime()); } Time SRL::operator-(const Time& t1, const int32& seconds) { return Time(t1.getTime()-seconds); } Time SRL::operator-(const int32& seconds, const Time& t1) { return Time(seconds-t1.getTime()); } // COMPARISON OPERATIONS bool SRL::operator==(const Time& time1, const Time& time2) { // lets estimate if it is within milliseconds return time1.getTime() == time2.getTime(); } bool SRL::operator!=(const Time& time1, const Time& time2) { return time1.getTime() != time2.getTime(); } bool SRL::operator<(const Time& time1, const Time& time2) { return time1.getTime() < time2.getTime(); } bool SRL::operator<=(const Time& time1, const Time& time2) { return time1.getTime() <= time2.getTime(); } bool SRL::operator>(const Time& time1, const Time& time2) { return time1.getTime() > time2.getTime(); } bool SRL::operator>=(const Time& time1, const Time& time2) { return time1.getTime() >= time2.getTime(); }
6,733
2,448
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /mnt/c/Users/BrianTaylor/Documents/Software/dronecan/dsdl/uavcan/equipment/ice/reciprocating/1120.Status.uavcan */ #ifndef UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED #define UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> #include <uavcan/equipment/ice/reciprocating/CylinderStatus.hpp> /******************************* Source text ********************************** # # Generic status message of a piston engine control system. # # All integer fields are required unless stated otherwise. # All floating point fields are optional unless stated otherwise; unknown/unapplicable fields should be set to NaN. # # # Abstract engine state. The flags defined below can provide further elaboration. # This is a required field. # uint2 state # # The engine is not running. This is the default state. # Next states: STARTING, FAULT # uint2 STATE_STOPPED = 0 # # The engine is starting. This is a transient state. # Next states: STOPPED, RUNNING, FAULT # uint2 STATE_STARTING = 1 # # The engine is running normally. # Some error flags may be set to indicate non-fatal issues, e.g. overheating. # Next states: STOPPED, FAULT # uint2 STATE_RUNNING = 2 # # The engine can no longer function. # The error flags may contain additional information about the nature of the fault. # Next states: STOPPED. # uint2 STATE_FAULT = 3 # # General status flags. # Note that not all flags are required. Those that aren't are prepended with a validity flag, which is, obviously, # always required; when the validity flag is set, it is assumed that the relevant flags are set correctly. # If the validity flag is cleared, then the state of the relevant flags should be ignored. # All unused bits must be cleared. # uint30 flags # # General error. This flag is required, and it can be used to indicate an error condition # that does not fit any of the other flags. # Note that the vendor may also report additional status information via the vendor specific status code # field of the NodeStatus message. # uint30 FLAG_GENERAL_ERROR = 1 # # Error of the crankshaft sensor. This flag is optional. # uint30 FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2 uint30 FLAG_CRANKSHAFT_SENSOR_ERROR = 4 # # Temperature levels. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_TEMPERATURE_SUPPORTED = 8 uint30 FLAG_TEMPERATURE_BELOW_NOMINAL = 16 # Under-temperature warning uint30 FLAG_TEMPERATURE_ABOVE_NOMINAL = 32 # Over-temperature warning uint30 FLAG_TEMPERATURE_OVERHEATING = 64 # Critical overheating uint30 FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128 # Exhaust gas over-temperature warning # # Fuel pressure. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_FUEL_PRESSURE_SUPPORTED = 256 uint30 FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512 # Under-pressure warning uint30 FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024 # Over-pressure warning # # Detonation warning. This flag is optional. # This warning is cleared immediately after broadcasting is done if detonation is no longer happening. # uint30 FLAG_DETONATION_SUPPORTED = 2048 uint30 FLAG_DETONATION_OBSERVED = 4096 # Detonation condition observed warning # # Misfire warning. This flag is optional. # This warning is cleared immediately after broadcasting is done if misfire is no longer happening. # uint30 FLAG_MISFIRE_SUPPORTED = 8192 uint30 FLAG_MISFIRE_OBSERVED = 16384 # Misfire condition observed warning # # Oil pressure. These flags are optional; either none of them or all of them are supported. # uint30 FLAG_OIL_PRESSURE_SUPPORTED = 32768 uint30 FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536 # Under-pressure warning uint30 FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072 # Over-pressure warning # # Debris warning. This flag is optional. # uint30 FLAG_DEBRIS_SUPPORTED = 262144 uint30 FLAG_DEBRIS_DETECTED = 524288 # Detection of debris warning # # Reserved space # void16 # # Engine load estimate. # Unit: percent. # Range: [0, 127]. # uint7 engine_load_percent # # Engine speed. # Unit: revolutions per minute. # uint17 engine_speed_rpm # # Spark dwell time. # Unit: millisecond. # float16 spark_dwell_time_ms # # Atmospheric (barometric) pressure. # Unit: kilopascal. # float16 atmospheric_pressure_kpa # # Engine intake manifold pressure. # Unit: kilopascal. # float16 intake_manifold_pressure_kpa # # Engine intake manifold temperature. # Unit: kelvin. # float16 intake_manifold_temperature # # Engine coolant temperature. # Unit: kelvin. # float16 coolant_temperature # # Oil pressure. # Unit: kilopascal. # float16 oil_pressure # # Oil temperature. # Unit: kelvin. # float16 oil_temperature # # Fuel pressure. # Unit: kilopascal. # float16 fuel_pressure # # Instant fuel consumption estimate. # The estimated value should be low-pass filtered in order to prevent aliasing effects. # Unit: (centimeter^3)/minute. # float32 fuel_consumption_rate_cm3pm # # Estimate of the consumed fuel since the start of the engine. # This variable MUST be reset when the engine is stopped. # Unit: centimeter^3. # float32 estimated_consumed_fuel_volume_cm3 # # Throttle position. # Unit: percent. # uint7 throttle_position_percent # # The index of the publishing ECU. # uint6 ecu_index # # Spark plug activity report. # Can be used during pre-flight tests of the spark subsystem. # uint3 spark_plug_usage # uint3 SPARK_PLUG_SINGLE = 0 uint3 SPARK_PLUG_FIRST_ACTIVE = 1 uint3 SPARK_PLUG_SECOND_ACTIVE = 2 uint3 SPARK_PLUG_BOTH_ACTIVE = 3 # # Per-cylinder status information. # CylinderStatus[<=16] cylinder_status ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.equipment.ice.reciprocating.Status saturated uint2 state saturated uint30 flags void16 saturated uint7 engine_load_percent saturated uint17 engine_speed_rpm saturated float16 spark_dwell_time_ms saturated float16 atmospheric_pressure_kpa saturated float16 intake_manifold_pressure_kpa saturated float16 intake_manifold_temperature saturated float16 coolant_temperature saturated float16 oil_pressure saturated float16 oil_temperature saturated float16 fuel_pressure saturated float32 fuel_consumption_rate_cm3pm saturated float32 estimated_consumed_fuel_volume_cm3 saturated uint7 throttle_position_percent saturated uint6 ecu_index saturated uint3 spark_plug_usage uavcan.equipment.ice.reciprocating.CylinderStatus[<=16] cylinder_status ******************************************************************************/ #undef state #undef flags #undef _void_0 #undef engine_load_percent #undef engine_speed_rpm #undef spark_dwell_time_ms #undef atmospheric_pressure_kpa #undef intake_manifold_pressure_kpa #undef intake_manifold_temperature #undef coolant_temperature #undef oil_pressure #undef oil_temperature #undef fuel_pressure #undef fuel_consumption_rate_cm3pm #undef estimated_consumed_fuel_volume_cm3 #undef throttle_position_percent #undef ecu_index #undef spark_plug_usage #undef cylinder_status #undef STATE_STOPPED #undef STATE_STARTING #undef STATE_RUNNING #undef STATE_FAULT #undef FLAG_GENERAL_ERROR #undef FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED #undef FLAG_CRANKSHAFT_SENSOR_ERROR #undef FLAG_TEMPERATURE_SUPPORTED #undef FLAG_TEMPERATURE_BELOW_NOMINAL #undef FLAG_TEMPERATURE_ABOVE_NOMINAL #undef FLAG_TEMPERATURE_OVERHEATING #undef FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL #undef FLAG_FUEL_PRESSURE_SUPPORTED #undef FLAG_FUEL_PRESSURE_BELOW_NOMINAL #undef FLAG_FUEL_PRESSURE_ABOVE_NOMINAL #undef FLAG_DETONATION_SUPPORTED #undef FLAG_DETONATION_OBSERVED #undef FLAG_MISFIRE_SUPPORTED #undef FLAG_MISFIRE_OBSERVED #undef FLAG_OIL_PRESSURE_SUPPORTED #undef FLAG_OIL_PRESSURE_BELOW_NOMINAL #undef FLAG_OIL_PRESSURE_ABOVE_NOMINAL #undef FLAG_DEBRIS_SUPPORTED #undef FLAG_DEBRIS_DETECTED #undef SPARK_PLUG_SINGLE #undef SPARK_PLUG_FIRST_ACTIVE #undef SPARK_PLUG_SECOND_ACTIVE #undef SPARK_PLUG_BOTH_ACTIVE namespace uavcan { namespace equipment { namespace ice { namespace reciprocating { template <int _tmpl> struct UAVCAN_EXPORT Status_ { typedef const Status_<_tmpl>& ParameterType; typedef Status_<_tmpl>& ReferenceType; struct ConstantTypes { typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STOPPED; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STARTING; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_RUNNING; typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_FAULT; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_GENERAL_ERROR; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_OVERHEATING; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_OBSERVED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_OBSERVED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_BELOW_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_ABOVE_NOMINAL; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_SUPPORTED; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_DETECTED; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SINGLE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_FIRST_ACTIVE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SECOND_ACTIVE; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_BOTH_ACTIVE; }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > state; typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > flags; typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > _void_0; typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_load_percent; typedef ::uavcan::IntegerSpec< 17, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_speed_rpm; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > spark_dwell_time_ms; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > atmospheric_pressure_kpa; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_pressure_kpa; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > coolant_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_pressure; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_temperature; typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > fuel_pressure; typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > fuel_consumption_rate_cm3pm; typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > estimated_consumed_fuel_volume_cm3; typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > throttle_position_percent; typedef ::uavcan::IntegerSpec< 6, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ecu_index; typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > spark_plug_usage; typedef ::uavcan::Array< ::uavcan::equipment::ice::reciprocating::CylinderStatus, ::uavcan::ArrayModeDynamic, 16 > cylinder_status; }; enum { MinBitLen = FieldTypes::state::MinBitLen + FieldTypes::flags::MinBitLen + FieldTypes::_void_0::MinBitLen + FieldTypes::engine_load_percent::MinBitLen + FieldTypes::engine_speed_rpm::MinBitLen + FieldTypes::spark_dwell_time_ms::MinBitLen + FieldTypes::atmospheric_pressure_kpa::MinBitLen + FieldTypes::intake_manifold_pressure_kpa::MinBitLen + FieldTypes::intake_manifold_temperature::MinBitLen + FieldTypes::coolant_temperature::MinBitLen + FieldTypes::oil_pressure::MinBitLen + FieldTypes::oil_temperature::MinBitLen + FieldTypes::fuel_pressure::MinBitLen + FieldTypes::fuel_consumption_rate_cm3pm::MinBitLen + FieldTypes::estimated_consumed_fuel_volume_cm3::MinBitLen + FieldTypes::throttle_position_percent::MinBitLen + FieldTypes::ecu_index::MinBitLen + FieldTypes::spark_plug_usage::MinBitLen + FieldTypes::cylinder_status::MinBitLen }; enum { MaxBitLen = FieldTypes::state::MaxBitLen + FieldTypes::flags::MaxBitLen + FieldTypes::_void_0::MaxBitLen + FieldTypes::engine_load_percent::MaxBitLen + FieldTypes::engine_speed_rpm::MaxBitLen + FieldTypes::spark_dwell_time_ms::MaxBitLen + FieldTypes::atmospheric_pressure_kpa::MaxBitLen + FieldTypes::intake_manifold_pressure_kpa::MaxBitLen + FieldTypes::intake_manifold_temperature::MaxBitLen + FieldTypes::coolant_temperature::MaxBitLen + FieldTypes::oil_pressure::MaxBitLen + FieldTypes::oil_temperature::MaxBitLen + FieldTypes::fuel_pressure::MaxBitLen + FieldTypes::fuel_consumption_rate_cm3pm::MaxBitLen + FieldTypes::estimated_consumed_fuel_volume_cm3::MaxBitLen + FieldTypes::throttle_position_percent::MaxBitLen + FieldTypes::ecu_index::MaxBitLen + FieldTypes::spark_plug_usage::MaxBitLen + FieldTypes::cylinder_status::MaxBitLen }; // Constants static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STOPPED >::Type STATE_STOPPED; // 0 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STARTING >::Type STATE_STARTING; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_RUNNING >::Type STATE_RUNNING; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_FAULT >::Type STATE_FAULT; // 3 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_GENERAL_ERROR >::Type FLAG_GENERAL_ERROR; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type FLAG_CRANKSHAFT_SENSOR_ERROR; // 4 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type FLAG_TEMPERATURE_SUPPORTED; // 8 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type FLAG_TEMPERATURE_BELOW_NOMINAL; // 16 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_ABOVE_NOMINAL; // 32 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type FLAG_TEMPERATURE_OVERHEATING; // 64 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL; // 128 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type FLAG_FUEL_PRESSURE_SUPPORTED; // 256 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type FLAG_FUEL_PRESSURE_BELOW_NOMINAL; // 512 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_FUEL_PRESSURE_ABOVE_NOMINAL; // 1024 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type FLAG_DETONATION_SUPPORTED; // 2048 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_OBSERVED >::Type FLAG_DETONATION_OBSERVED; // 4096 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type FLAG_MISFIRE_SUPPORTED; // 8192 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type FLAG_MISFIRE_OBSERVED; // 16384 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type FLAG_OIL_PRESSURE_SUPPORTED; // 32768 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type FLAG_OIL_PRESSURE_BELOW_NOMINAL; // 65536 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_OIL_PRESSURE_ABOVE_NOMINAL; // 131072 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type FLAG_DEBRIS_SUPPORTED; // 262144 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_DETECTED >::Type FLAG_DEBRIS_DETECTED; // 524288 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SINGLE >::Type SPARK_PLUG_SINGLE; // 0 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type SPARK_PLUG_FIRST_ACTIVE; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type SPARK_PLUG_SECOND_ACTIVE; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type SPARK_PLUG_BOTH_ACTIVE; // 3 // Fields typename ::uavcan::StorageType< typename FieldTypes::state >::Type state; typename ::uavcan::StorageType< typename FieldTypes::flags >::Type flags; typename ::uavcan::StorageType< typename FieldTypes::engine_load_percent >::Type engine_load_percent; typename ::uavcan::StorageType< typename FieldTypes::engine_speed_rpm >::Type engine_speed_rpm; typename ::uavcan::StorageType< typename FieldTypes::spark_dwell_time_ms >::Type spark_dwell_time_ms; typename ::uavcan::StorageType< typename FieldTypes::atmospheric_pressure_kpa >::Type atmospheric_pressure_kpa; typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_pressure_kpa >::Type intake_manifold_pressure_kpa; typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_temperature >::Type intake_manifold_temperature; typename ::uavcan::StorageType< typename FieldTypes::coolant_temperature >::Type coolant_temperature; typename ::uavcan::StorageType< typename FieldTypes::oil_pressure >::Type oil_pressure; typename ::uavcan::StorageType< typename FieldTypes::oil_temperature >::Type oil_temperature; typename ::uavcan::StorageType< typename FieldTypes::fuel_pressure >::Type fuel_pressure; typename ::uavcan::StorageType< typename FieldTypes::fuel_consumption_rate_cm3pm >::Type fuel_consumption_rate_cm3pm; typename ::uavcan::StorageType< typename FieldTypes::estimated_consumed_fuel_volume_cm3 >::Type estimated_consumed_fuel_volume_cm3; typename ::uavcan::StorageType< typename FieldTypes::throttle_position_percent >::Type throttle_position_percent; typename ::uavcan::StorageType< typename FieldTypes::ecu_index >::Type ecu_index; typename ::uavcan::StorageType< typename FieldTypes::spark_plug_usage >::Type spark_plug_usage; typename ::uavcan::StorageType< typename FieldTypes::cylinder_status >::Type cylinder_status; Status_() : state() , flags() , engine_load_percent() , engine_speed_rpm() , spark_dwell_time_ms() , atmospheric_pressure_kpa() , intake_manifold_pressure_kpa() , intake_manifold_temperature() , coolant_temperature() , oil_pressure() , oil_temperature() , fuel_pressure() , fuel_consumption_rate_cm3pm() , estimated_consumed_fuel_volume_cm3() , throttle_position_percent() , ecu_index() , spark_plug_usage() , cylinder_status() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<1565 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindMessage }; enum { DefaultDataTypeID = 1120 }; static const char* getDataTypeFullName() { return "uavcan.equipment.ice.reciprocating.Status"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); }; /* * Out of line struct method definitions */ template <int _tmpl> bool Status_<_tmpl>::operator==(ParameterType rhs) const { return state == rhs.state && flags == rhs.flags && engine_load_percent == rhs.engine_load_percent && engine_speed_rpm == rhs.engine_speed_rpm && spark_dwell_time_ms == rhs.spark_dwell_time_ms && atmospheric_pressure_kpa == rhs.atmospheric_pressure_kpa && intake_manifold_pressure_kpa == rhs.intake_manifold_pressure_kpa && intake_manifold_temperature == rhs.intake_manifold_temperature && coolant_temperature == rhs.coolant_temperature && oil_pressure == rhs.oil_pressure && oil_temperature == rhs.oil_temperature && fuel_pressure == rhs.fuel_pressure && fuel_consumption_rate_cm3pm == rhs.fuel_consumption_rate_cm3pm && estimated_consumed_fuel_volume_cm3 == rhs.estimated_consumed_fuel_volume_cm3 && throttle_position_percent == rhs.throttle_position_percent && ecu_index == rhs.ecu_index && spark_plug_usage == rhs.spark_plug_usage && cylinder_status == rhs.cylinder_status; } template <int _tmpl> bool Status_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(state, rhs.state) && ::uavcan::areClose(flags, rhs.flags) && ::uavcan::areClose(engine_load_percent, rhs.engine_load_percent) && ::uavcan::areClose(engine_speed_rpm, rhs.engine_speed_rpm) && ::uavcan::areClose(spark_dwell_time_ms, rhs.spark_dwell_time_ms) && ::uavcan::areClose(atmospheric_pressure_kpa, rhs.atmospheric_pressure_kpa) && ::uavcan::areClose(intake_manifold_pressure_kpa, rhs.intake_manifold_pressure_kpa) && ::uavcan::areClose(intake_manifold_temperature, rhs.intake_manifold_temperature) && ::uavcan::areClose(coolant_temperature, rhs.coolant_temperature) && ::uavcan::areClose(oil_pressure, rhs.oil_pressure) && ::uavcan::areClose(oil_temperature, rhs.oil_temperature) && ::uavcan::areClose(fuel_pressure, rhs.fuel_pressure) && ::uavcan::areClose(fuel_consumption_rate_cm3pm, rhs.fuel_consumption_rate_cm3pm) && ::uavcan::areClose(estimated_consumed_fuel_volume_cm3, rhs.estimated_consumed_fuel_volume_cm3) && ::uavcan::areClose(throttle_position_percent, rhs.throttle_position_percent) && ::uavcan::areClose(ecu_index, rhs.ecu_index) && ::uavcan::areClose(spark_plug_usage, rhs.spark_plug_usage) && ::uavcan::areClose(cylinder_status, rhs.cylinder_status); } template <int _tmpl> int Status_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0; int res = 1; res = FieldTypes::state::encode(self.state, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::encode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::_void_0::encode(_void_0, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_load_percent::encode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_speed_rpm::encode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_dwell_time_ms::encode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::atmospheric_pressure_kpa::encode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_pressure_kpa::encode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_temperature::encode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::coolant_temperature::encode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_pressure::encode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_temperature::encode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_pressure::encode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_consumption_rate_cm3pm::encode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::estimated_consumed_fuel_volume_cm3::encode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::throttle_position_percent::encode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::ecu_index::encode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_plug_usage::encode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::cylinder_status::encode(self.cylinder_status, codec, tao_mode); return res; } template <int _tmpl> int Status_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0; int res = 1; res = FieldTypes::state::decode(self.state, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::decode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::_void_0::decode(_void_0, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_load_percent::decode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::engine_speed_rpm::decode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_dwell_time_ms::decode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::atmospheric_pressure_kpa::decode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_pressure_kpa::decode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::intake_manifold_temperature::decode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::coolant_temperature::decode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_pressure::decode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::oil_temperature::decode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_pressure::decode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::fuel_consumption_rate_cm3pm::decode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::estimated_consumed_fuel_volume_cm3::decode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::throttle_position_percent::decode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::ecu_index::decode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::spark_plug_usage::decode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::cylinder_status::decode(self.cylinder_status, codec, tao_mode); return res; } /* * Out of line type method definitions */ template <int _tmpl> ::uavcan::DataTypeSignature Status_<_tmpl>::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0x5465C0CF37619F32ULL); FieldTypes::state::extendDataTypeSignature(signature); FieldTypes::flags::extendDataTypeSignature(signature); FieldTypes::_void_0::extendDataTypeSignature(signature); FieldTypes::engine_load_percent::extendDataTypeSignature(signature); FieldTypes::engine_speed_rpm::extendDataTypeSignature(signature); FieldTypes::spark_dwell_time_ms::extendDataTypeSignature(signature); FieldTypes::atmospheric_pressure_kpa::extendDataTypeSignature(signature); FieldTypes::intake_manifold_pressure_kpa::extendDataTypeSignature(signature); FieldTypes::intake_manifold_temperature::extendDataTypeSignature(signature); FieldTypes::coolant_temperature::extendDataTypeSignature(signature); FieldTypes::oil_pressure::extendDataTypeSignature(signature); FieldTypes::oil_temperature::extendDataTypeSignature(signature); FieldTypes::fuel_pressure::extendDataTypeSignature(signature); FieldTypes::fuel_consumption_rate_cm3pm::extendDataTypeSignature(signature); FieldTypes::estimated_consumed_fuel_volume_cm3::extendDataTypeSignature(signature); FieldTypes::throttle_position_percent::extendDataTypeSignature(signature); FieldTypes::ecu_index::extendDataTypeSignature(signature); FieldTypes::spark_plug_usage::extendDataTypeSignature(signature); FieldTypes::cylinder_status::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STOPPED >::Type Status_<_tmpl>::STATE_STOPPED = 0U; // 0 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STARTING >::Type Status_<_tmpl>::STATE_STARTING = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_RUNNING >::Type Status_<_tmpl>::STATE_RUNNING = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_FAULT >::Type Status_<_tmpl>::STATE_FAULT = 3U; // 3 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_GENERAL_ERROR >::Type Status_<_tmpl>::FLAG_GENERAL_ERROR = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR = 4U; // 4 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_TEMPERATURE_SUPPORTED = 8U; // 8 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_BELOW_NOMINAL = 16U; // 16 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_ABOVE_NOMINAL = 32U; // 32 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type Status_<_tmpl>::FLAG_TEMPERATURE_OVERHEATING = 64U; // 64 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128U; // 128 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_SUPPORTED = 256U; // 256 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512U; // 512 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024U; // 1024 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type Status_<_tmpl>::FLAG_DETONATION_SUPPORTED = 2048U; // 2048 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_OBSERVED >::Type Status_<_tmpl>::FLAG_DETONATION_OBSERVED = 4096U; // 4096 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type Status_<_tmpl>::FLAG_MISFIRE_SUPPORTED = 8192U; // 8192 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type Status_<_tmpl>::FLAG_MISFIRE_OBSERVED = 16384U; // 16384 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_SUPPORTED = 32768U; // 32768 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536U; // 65536 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type Status_<_tmpl>::FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072U; // 131072 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type Status_<_tmpl>::FLAG_DEBRIS_SUPPORTED = 262144U; // 262144 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_DETECTED >::Type Status_<_tmpl>::FLAG_DEBRIS_DETECTED = 524288U; // 524288 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SINGLE >::Type Status_<_tmpl>::SPARK_PLUG_SINGLE = 0U; // 0 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_FIRST_ACTIVE = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_SECOND_ACTIVE = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type Status_<_tmpl>::SPARK_PLUG_BOTH_ACTIVE = 3U; // 3 /* * Final typedef */ typedef Status_<0> Status; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::equipment::ice::reciprocating::Status > _uavcan_gdtr_registrator_Status; } } // Namespace reciprocating } // Namespace ice } // Namespace equipment } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "state: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::state >::stream(s, obj.state, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "flags: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::flags >::stream(s, obj.flags, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "engine_load_percent: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_load_percent >::stream(s, obj.engine_load_percent, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "engine_speed_rpm: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_speed_rpm >::stream(s, obj.engine_speed_rpm, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "spark_dwell_time_ms: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_dwell_time_ms >::stream(s, obj.spark_dwell_time_ms, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "atmospheric_pressure_kpa: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::atmospheric_pressure_kpa >::stream(s, obj.atmospheric_pressure_kpa, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "intake_manifold_pressure_kpa: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_pressure_kpa >::stream(s, obj.intake_manifold_pressure_kpa, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "intake_manifold_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_temperature >::stream(s, obj.intake_manifold_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "coolant_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::coolant_temperature >::stream(s, obj.coolant_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "oil_pressure: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_pressure >::stream(s, obj.oil_pressure, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "oil_temperature: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_temperature >::stream(s, obj.oil_temperature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "fuel_pressure: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_pressure >::stream(s, obj.fuel_pressure, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "fuel_consumption_rate_cm3pm: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_consumption_rate_cm3pm >::stream(s, obj.fuel_consumption_rate_cm3pm, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "estimated_consumed_fuel_volume_cm3: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::estimated_consumed_fuel_volume_cm3 >::stream(s, obj.estimated_consumed_fuel_volume_cm3, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "throttle_position_percent: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::throttle_position_percent >::stream(s, obj.throttle_position_percent, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "ecu_index: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::ecu_index >::stream(s, obj.ecu_index, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "spark_plug_usage: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_plug_usage >::stream(s, obj.spark_plug_usage, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "cylinder_status: "; YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::cylinder_status >::stream(s, obj.cylinder_status, level + 1); } } namespace uavcan { namespace equipment { namespace ice { namespace reciprocating { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(s, obj, 0); return s; } } // Namespace reciprocating } // Namespace ice } // Namespace equipment } // Namespace uavcan #endif // UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED
47,102
17,501
#include "BombDropSkill.h" #include "PlayerMovement.h" #include "Application.h" #include "ModuleNavigation.h" #include "ModuleTime.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ComponentBoxTrigger.h" #include "PlayerState.h" BombDropSkill::BombDropSkill(PlayerMovement* PM, const char* trigger, ComponentBoxTrigger* attackBox) : MeleeSkill(PM, trigger, attackBox) { } BombDropSkill::~BombDropSkill() { path.clear(); } void BombDropSkill::Start() { MeleeSkill::Start(); player->App->navigation->setPlayerBB(player->gameobject->bbox); if (player->App->navigation->NavigateTowardsCursor(player->gameobject->transform->position, path, math::float3(player->OutOfMeshCorrectionXZ, player->OutOfMeshCorrectionY, player->OutOfMeshCorrectionXZ), intersectionPoint, bombDropMaxDistance, PathFindType::NODODGE)) { pathIndex = 0; player->gameobject->transform->LookAt(intersectionPoint); if (bombDropFX) { bombDropFX->SetActive(true); } player->ResetCooldown(HUD_BUTTON_E); } //Create the hitbox boxSize = math::float3(250.f, 100.f, 250.f); //attackBoxTrigger.set // Set delay for hit hitDelay = 0.5f; } void BombDropSkill::UseSkill() { if (path.size() > 0 && timer > bombDropPreparationTime && timer < hitDelay) { math::float3 currentPosition = player->gameobject->transform->GetPosition(); while (pathIndex < path.size() && currentPosition.DistanceSq(path[pathIndex]) < MINIMUM_PATH_DISTANCE) { pathIndex++; } if (pathIndex < path.size()) { player->gameobject->transform->LookAt(path[pathIndex]); math::float3 direction = (path[pathIndex] - currentPosition).Normalized(); player->gameobject->transform->SetPosition(currentPosition + bombDropSpeed * direction * player->App->time->fullGameDeltaTime); } } if (player->attackBoxTrigger != nullptr && !player->attackBoxTrigger->enabled) { // Update hitbox boxPosition = player->transform->up * 100.f; //this front stuff isnt working well when rotating the chicken player->attackBoxTrigger->SetBoxPosition(boxPosition.x, boxPosition.y, boxPosition.z + 200.f); } } void BombDropSkill::CheckInput() { if (timer > player->currentState->duration) //CAN SWITCH? { if (player->IsUsingSkill()) { player->currentState = (PlayerState*)player->attack; } else if (player->IsMovingToAttack()) { if (player->ThirdStageBoss) { player->currentState = (PlayerState*)player->walkToHit3rdBoss; } else { player->currentState = (PlayerState*)player->walkToHit; } } else if (player->IsMovingToItem()) { player->currentState = (PlayerState*)player->walkToPickItem; } else if (player->IsMoving()) { player->currentState = (PlayerState*)player->walk; } } }
2,738
1,050
#include "isogram.h" #include <iostream> #include <vector> #include <algorithm> #include <list> #include <locale> namespace isogram { bool is_isogram(const std::string& str) { std::list<char>parsed = {}; for (const char letter : str) { if (' ' == letter || '-' == letter) continue; const char normalized = std::tolower(letter, std::locale()); if(std::find(parsed.begin(),parsed.end(),normalized) != parsed.end()) { std::cout << str << " is Not Isogram " << std::endl; return false; } parsed.push_back(normalized); } std::cout << str << " is Isogram" << std::endl; return true; } } // namespace isogram
714
229
//============================================================================= /// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief Implementation of the Setup Target Application panel interface. //============================================================================= #include <QStandardItemModel> #include <QFileDialog> #include <QFontMetrics> #include <QGridLayout> #include <QSpacerItem> #include "SetupTargetApplicationView.h" #include "ui_SetupTargetApplicationView.h" #include "../RDPDefinitions.h" #include "../Settings/RDPSettings.h" #include "../Util/RDPUtil.h" #include "../Models/SetupTargetApplicationModel.h" #include "../Models/DeveloperPanelModel.h" #include <QtUtil.h> //----------------------------------------------------------------------------- /// Explicit constructor /// \param pPanelModel The panel model. /// \param pParent The parent widget. //----------------------------------------------------------------------------- SetupTargetApplicationView::SetupTargetApplicationView(DeveloperPanelModel* pPanelModel, QWidget* pParent) : QWidget(pParent), ui(new Ui::SetupTargetApplicationView), m_pSetupTargetApplicationModel(nullptr), m_traceInProgress(false) { ui->setupUi(this); // Create a model for the table view. m_pSetupTargetApplicationModel = new SetupTargetApplicationModel(); Q_ASSERT(m_pSetupTargetApplicationModel != nullptr); QtCommon::QtUtil::ApplyStandardTableStyle(ui->TargetApplicationList); ui->TargetApplicationList->setModel(m_pSetupTargetApplicationModel->GetTableModel()); ui->TargetApplicationList->SetTargetApplicationModel(m_pSetupTargetApplicationModel); Q_ASSERT(pPanelModel); pPanelModel->SetTargetApplicationsModel(m_pSetupTargetApplicationModel); // Set up signals/slots. connect(ui->addToListButton, &QPushButton::clicked, this, &SetupTargetApplicationView::AddToList); connect(ui->targetExeLineEdit, &QLineEdit::returnPressed, this, &SetupTargetApplicationView::OnReturnPressedOnExecutableLine); connect(ui->removeFromListButton, &QPushButton::clicked, this, &SetupTargetApplicationView::RemoveFromList); connect(ui->targetExeBrowseButton, &QPushButton::clicked, this, &SetupTargetApplicationView::OnTargetExeBrowseButtonPressed); connect(ui->TargetApplicationList, &AppListTreeView::clicked, this, &SetupTargetApplicationView::OnApplicationSelected); connect(ui->targetExeLineEdit, &QLineEdit::textChanged, this, &SetupTargetApplicationView::OnTargetExeLineEditTextChanged); // Disable the remove from list button for now ui->removeFromListButton->setEnabled(false); // Disable the add to list button for now ui->addToListButton->setEnabled(false); // Enable sorting for target application list ui->TargetApplicationList->setSortingEnabled(true); ui->TargetApplicationList->sortByColumn(TARGET_APPLICATION_TABLE_COLUMN_EXECUTABLE_NAME, Qt::AscendingOrder); // Update the model. m_pSetupTargetApplicationModel->Update(); AdjustTableColumns(); } //----------------------------------------------------------------------------- /// Destructor //----------------------------------------------------------------------------- SetupTargetApplicationView::~SetupTargetApplicationView() { SAFE_DELETE(ui); SAFE_DELETE(m_pSetupTargetApplicationModel); } //----------------------------------------------------------------------------- /// Slot to handle what happens when the user clicks the 'Add to list' /// button /// \param clicked Whether the button is clicked //----------------------------------------------------------------------------- void SetupTargetApplicationView::AddToList(bool clicked) { Q_UNUSED(clicked); QString applicationFilepath = ui->targetExeLineEdit->text(); if (applicationFilepath.isEmpty()) { RDPUtil::ShowNotification(gs_PRODUCT_NAME_STRING, gs_NO_FILE_SPECIFIED_TEXT, NotificationWidget::Button::Ok); } else { // Remove any leading and trailing whitespace from the specified executable. applicationFilepath = applicationFilepath.trimmed(); AddExecutableToList(applicationFilepath); } } //----------------------------------------------------------------------------- /// Add the given executable filename to the Target Applications table. /// \param executableFilename The executable filename to add to the target list. /// \returns True if the new item was added to the list successfully, and false if it failed. //----------------------------------------------------------------------------- bool SetupTargetApplicationView::AddExecutableToList(const QString& executableFilename) { bool addedSuccessfully = m_pSetupTargetApplicationModel->AddApplication(executableFilename); if (addedSuccessfully == false) { RDPUtil::ShowNotification(gs_PRODUCT_NAME_STRING, gs_DUPLICATE_FILE_TEXT, NotificationWidget::Button::Ok); } else { // The executable was added successfully, so clear out the textbox. ui->targetExeLineEdit->setText(""); AdjustTableColumns(); // Select the last application added by the user. QModelIndex firstRow = ui->TargetApplicationList->model()->index(0, 0); ui->TargetApplicationList->setCurrentIndex(firstRow); // Enable the "Remove from list" button ui->removeFromListButton->setEnabled(true); } return addedSuccessfully; } //----------------------------------------------------------------------------- /// Handler invoked when the 'Remove from list' button is clicked. /// \param clicked Flag that indicates if the button is checked. //----------------------------------------------------------------------------- void SetupTargetApplicationView::RemoveFromList(bool clicked) { Q_UNUSED(clicked); QModelIndex selectedRowIndex = ui->TargetApplicationList->currentIndex(); if (selectedRowIndex.isValid()) { int selectedRow = selectedRowIndex.row(); int sourceModelRow = m_pSetupTargetApplicationModel->MapToSourceModelRow(ui->TargetApplicationList->currentIndex()); RDPSettings& rdpSettings = RDPSettings::Get(); // If a trace is currently being collected or this application is currently being profiled, disallow this operation. if (m_traceInProgress || (rdpSettings.isAllowTargetApplicationProfiling(sourceModelRow) && !GetSetupTargetApplicationModel()->ActivelyProfiledApplication().isEmpty()) ) { RDPUtil::ShowNotification(gs_DELETE_WHILE_PROFILING_TITLE, gs_DELETE_WHILE_PROFILING_MSG, NotificationWidget::Button::Ok); return; } // Pop up a confirmation dialog box NotificationWidget::Button resultButton = RDPUtil::ShowNotification(gs_DELETE_APPLICATION_TITLE, gs_DELETE_APPLICATION, NotificationWidget::Button::Yes | NotificationWidget::Button::No, NotificationWidget::Button::No); if (resultButton == NotificationWidget::Button::Yes) { // Get the name of the application being removed QString executableName; bool result = m_pSetupTargetApplicationModel->GetExecutableNameAtRow(sourceModelRow, executableName); m_pSetupTargetApplicationModel->RemoveApplication(selectedRow); AdjustTableColumns(); // Get the model QAbstractItemModel* pModel = m_pSetupTargetApplicationModel->GetTableModel(); // Get the data from the first row/column QString text = pModel->data(pModel->index(0, 0)).toString(); // If the table is empty, disable the "Remove from list" button if (text.isEmpty()) { ui->removeFromListButton->setEnabled(false); } // emit a signal to indicate that an app was removed if (result == true) { emit ApplicationRemovedFromList(executableName); } } } } //----------------------------------------------------------------------------- /// Handler invoked when the user presses the "Enter" key while the target executable textbox has focus. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnReturnPressedOnExecutableLine() { // Add whatever is in the textbox as the next target executable. AddToList(false); } //----------------------------------------------------------------------------- /// Target exe browse button pressed SLOT - Determines what to do when the /// browse button next to the target executable edit field is pressed. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTargetExeBrowseButtonPressed() { // Fill the dialog with the existing target executable directory. const QString& lastAppPath = RDPSettings::Get().GetLastTargetExecutableDirectory(); #ifdef WIN32 // Create file filters for the windows file dialog box QString fileNameFilter = "All files (*.*);;Exe files (*.exe)"; QString defaultFilter = "Exe files (*.exe)"; // Open a new file selection dialog so the user can choose a target executable. const QString& applicationFilepath = QFileDialog::getOpenFileName(this, gs_BROWSE_APPLICATION_FILEPATH_CAPTION_TEXT, lastAppPath, fileNameFilter, &defaultFilter); #else // Open a new file selection dialog so the user can choose a target executable. const QString& applicationFilepath = QFileDialog::getOpenFileName(this, gs_BROWSE_APPLICATION_FILEPATH_CAPTION_TEXT, lastAppPath); #endif // WIN32 // getOpenFileName returns a "null" QString if the user cancels the dialog. Only continue if they select something. if (!applicationFilepath.isNull()) { // Trim the full path to just the application filename to filter with. QFileInfo fileInfo(applicationFilepath); QString executableOnly(fileInfo.fileName()); // Keep the user's last directory to start at next time. RDPSettings::Get().SetLastTargetExecutableDirectory(applicationFilepath); ui->targetExeLineEdit->setText(executableOnly); AddToList(true); } } //----------------------------------------------------------------------------- /// Adjust the column widths of the target applications table //----------------------------------------------------------------------------- void SetupTargetApplicationView::AdjustTableColumns() { int numRows = m_pSetupTargetApplicationModel->GetTableModel()->rowCount(); QtCommon::QtUtil::AutoAdjustTableColumns(ui->TargetApplicationList, numRows, 10); } //----------------------------------------------------------------------------- /// Enable the "Remove from list" button when an exe is selected from the list /// \param index the model index of the clicked item //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnApplicationSelected(const QModelIndex& index) { Q_UNUSED(index); // A row was clicked on, so enable the "Remove from list" button ui->removeFromListButton->setEnabled(true); } //----------------------------------------------------------------------------- /// Enable/disable the "Add to list" button as necessary /// \param text The text enetered into the line edit //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTargetExeLineEditTextChanged(const QString& text) { // Enable/Disable the add to list button ui->addToListButton->setEnabled(!text.isEmpty()); } //----------------------------------------------------------------------------- /// Slot invoked when the RGPTraceModel either starts or finishes collecting an RGP trace. /// \param traceIsBeingCollected A flag that indicates the current state of RGP Trace collection. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnTraceCollectionStatusUpdated(bool traceIsBeingCollected) { m_traceInProgress = traceIsBeingCollected; } //----------------------------------------------------------------------------- /// Return the model object pointer. /// \return SetupTargetApplicationModel pointer //----------------------------------------------------------------------------- SetupTargetApplicationModel* SetupTargetApplicationView::GetSetupTargetApplicationModel() { return m_pSetupTargetApplicationModel; } //----------------------------------------------------------------------------- /// Slot invoked when the user profiling checkbox click is not valid //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilingCheckboxClickError() { // Put up an error message RDPUtil::ShowNotification(gs_UNCHECK_PROFILE_WHILE_COLLECTING_TRACE_TITLE, gs_UNCHECK_PROFILE_WHILE_COLLECTING_TRACE_MSG, NotificationWidget::Button::Ok); } //----------------------------------------------------------------------------- /// Slot invoked when the user attempts to profile multiple instances of the same application /// \param profiledProcessInfo Process information for the latest application instance started. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilingMultipleTargetsWarning(const ProcessInfoModel& profiledProcessInfo) { // Put up an warning message QString message = QString(gs_MULTIPLE_TARGET_APPLICATION_INSTANCES_MSG).arg(profiledProcessInfo.GetProcessName().toStdString().c_str()).arg(profiledProcessInfo.GetProcessId()); RDPUtil::ShowNotification(gs_MULTIPLE_TARGET_APPLICATION_INSTANCES_TITLE, message, NotificationWidget::Button::Ok); } //----------------------------------------------------------------------------- /// Slot invoked when the user attempts to select another targe application for profiles while /// another application is already being profiled. /// \param processInfo Process information for the latest application instance started. //----------------------------------------------------------------------------- void SetupTargetApplicationView::OnProfilerInUseWarning(const ProcessInfoModel& processInfo) { // Put up an warning message QString message = QString(gs_PROFILER_ALREADY_IN_USE_MSG).arg(processInfo.GetProcessName().toStdString().c_str()).arg(processInfo.GetProcessId()); RDPUtil::ShowNotification(gs_PROFILER_ALREADY_IN_USE_TITLE, message, NotificationWidget::Button::Ok); }
14,657
3,580
// Copyright 2014 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/types.h" #include "src/ostreams.h" #include "src/types-inl.h" namespace v8 { namespace internal { // ----------------------------------------------------------------------------- // Range-related custom order on doubles. // We want -0 to be less than +0. static bool dle(double x, double y) { return x <= y && (x != 0 || IsMinusZero(x) || !IsMinusZero(y)); } static bool deq(double x, double y) { return dle(x, y) && dle(y, x); } // ----------------------------------------------------------------------------- // Glb and lub computation. // The largest bitset subsumed by this type. template<class Config> int TypeImpl<Config>::BitsetType::Glb(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); DCHECK(unioned->Wellformed()); return unioned->Get(0)->BitsetGlb(); // Other BitsetGlb's are kNone anyway. } else { return kNone; } } // The smallest bitset subsuming this type. template<class Config> int TypeImpl<Config>::BitsetType::Lub(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); int bitset = kNone; for (int i = 0; i < unioned->Length(); ++i) { bitset |= unioned->Get(i)->BitsetLub(); } return bitset; } else if (type->IsClass()) { // Little hack to avoid the need for a region for handlification here... return Config::is_class(type) ? Lub(*Config::as_class(type)) : type->AsClass()->Bound(NULL)->AsBitset(); } else if (type->IsConstant()) { return type->AsConstant()->Bound()->AsBitset(); } else if (type->IsRange()) { return type->AsRange()->Bound()->AsBitset(); } else if (type->IsContext()) { return type->AsContext()->Bound()->AsBitset(); } else if (type->IsArray()) { return type->AsArray()->Bound()->AsBitset(); } else if (type->IsFunction()) { return type->AsFunction()->Bound()->AsBitset(); } else { UNREACHABLE(); return kNone; } } // The smallest bitset subsuming this type, ignoring explicit bounds. template<class Config> int TypeImpl<Config>::BitsetType::InherentLub(TypeImpl* type) { DisallowHeapAllocation no_allocation; if (type->IsBitset()) { return type->AsBitset(); } else if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); int bitset = kNone; for (int i = 0; i < unioned->Length(); ++i) { bitset |= unioned->Get(i)->InherentBitsetLub(); } return bitset; } else if (type->IsClass()) { return Lub(*type->AsClass()->Map()); } else if (type->IsConstant()) { return Lub(*type->AsConstant()->Value()); } else if (type->IsRange()) { return Lub(type->AsRange()->Min(), type->AsRange()->Max()); } else if (type->IsContext()) { return kInternal & kTaggedPtr; } else if (type->IsArray()) { return kArray; } else if (type->IsFunction()) { return kFunction; } else { UNREACHABLE(); return kNone; } } template<class Config> int TypeImpl<Config>::BitsetType::Lub(i::Object* value) { DisallowHeapAllocation no_allocation; if (value->IsNumber()) { return Lub(value->Number()) & (value->IsSmi() ? kTaggedInt : kTaggedPtr); } return Lub(i::HeapObject::cast(value)->map()); } template<class Config> int TypeImpl<Config>::BitsetType::Lub(double value) { DisallowHeapAllocation no_allocation; if (i::IsMinusZero(value)) return kMinusZero; if (std::isnan(value)) return kNaN; if (IsUint32Double(value)) return Lub(FastD2UI(value)); if (IsInt32Double(value)) return Lub(FastD2I(value)); return kOtherNumber; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(double min, double max) { DisallowHeapAllocation no_allocation; DCHECK(dle(min, max)); if (deq(min, max)) return BitsetType::Lub(min); // Singleton range. int bitset = BitsetType::kNumber ^ SEMANTIC(BitsetType::kNaN); if (dle(0, min) || max < 0) bitset ^= SEMANTIC(BitsetType::kMinusZero); return bitset; // TODO(neis): Could refine this further by doing more checks on min/max. } template<class Config> int TypeImpl<Config>::BitsetType::Lub(int32_t value) { if (value >= 0x40000000) { return i::SmiValuesAre31Bits() ? kOtherUnsigned31 : kUnsignedSmall; } if (value >= 0) return kUnsignedSmall; if (value >= -0x40000000) return kOtherSignedSmall; return i::SmiValuesAre31Bits() ? kOtherSigned32 : kOtherSignedSmall; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(uint32_t value) { DisallowHeapAllocation no_allocation; if (value >= 0x80000000u) return kOtherUnsigned32; if (value >= 0x40000000u) { return i::SmiValuesAre31Bits() ? kOtherUnsigned31 : kUnsignedSmall; } return kUnsignedSmall; } template<class Config> int TypeImpl<Config>::BitsetType::Lub(i::Map* map) { DisallowHeapAllocation no_allocation; switch (map->instance_type()) { case STRING_TYPE: case ASCII_STRING_TYPE: case CONS_STRING_TYPE: case CONS_ASCII_STRING_TYPE: case SLICED_STRING_TYPE: case SLICED_ASCII_STRING_TYPE: case EXTERNAL_STRING_TYPE: case EXTERNAL_ASCII_STRING_TYPE: case EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE: case SHORT_EXTERNAL_STRING_TYPE: case SHORT_EXTERNAL_ASCII_STRING_TYPE: case SHORT_EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE: case INTERNALIZED_STRING_TYPE: case ASCII_INTERNALIZED_STRING_TYPE: case EXTERNAL_INTERNALIZED_STRING_TYPE: case EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE: case EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE: case SHORT_EXTERNAL_INTERNALIZED_STRING_TYPE: case SHORT_EXTERNAL_ASCII_INTERNALIZED_STRING_TYPE: case SHORT_EXTERNAL_INTERNALIZED_STRING_WITH_ONE_BYTE_DATA_TYPE: return kString; case SYMBOL_TYPE: return kSymbol; case ODDBALL_TYPE: { Heap* heap = map->GetHeap(); if (map == heap->undefined_map()) return kUndefined; if (map == heap->null_map()) return kNull; if (map == heap->boolean_map()) return kBoolean; DCHECK(map == heap->the_hole_map() || map == heap->uninitialized_map() || map == heap->no_interceptor_result_sentinel_map() || map == heap->termination_exception_map() || map == heap->arguments_marker_map()); return kInternal & kTaggedPtr; } case HEAP_NUMBER_TYPE: return kNumber & kTaggedPtr; case JS_VALUE_TYPE: case JS_DATE_TYPE: case JS_OBJECT_TYPE: case JS_CONTEXT_EXTENSION_OBJECT_TYPE: case JS_GENERATOR_OBJECT_TYPE: case JS_MODULE_TYPE: case JS_GLOBAL_OBJECT_TYPE: case JS_BUILTINS_OBJECT_TYPE: case JS_GLOBAL_PROXY_TYPE: case JS_ARRAY_BUFFER_TYPE: case JS_TYPED_ARRAY_TYPE: case JS_DATA_VIEW_TYPE: case JS_SET_TYPE: case JS_MAP_TYPE: case JS_SET_ITERATOR_TYPE: case JS_MAP_ITERATOR_TYPE: case JS_WEAK_MAP_TYPE: case JS_WEAK_SET_TYPE: if (map->is_undetectable()) return kUndetectable; return kOtherObject; case JS_ARRAY_TYPE: return kArray; case JS_FUNCTION_TYPE: return kFunction; case JS_REGEXP_TYPE: return kRegExp; case JS_PROXY_TYPE: case JS_FUNCTION_PROXY_TYPE: return kProxy; case MAP_TYPE: // When compiling stub templates, the meta map is used as a place holder // for the actual map with which the template is later instantiated. // We treat it as a kind of type variable whose upper bound is Any. // TODO(rossberg): for caching of CompareNilIC stubs to work correctly, // we must exclude Undetectable here. This makes no sense, really, // because it means that the template isn't actually parametric. // Also, it doesn't apply elsewhere. 8-( // We ought to find a cleaner solution for compiling stubs parameterised // over type or class variables, esp ones with bounds... return kDetectable; case DECLARED_ACCESSOR_INFO_TYPE: case EXECUTABLE_ACCESSOR_INFO_TYPE: case SHARED_FUNCTION_INFO_TYPE: case ACCESSOR_PAIR_TYPE: case FIXED_ARRAY_TYPE: case FOREIGN_TYPE: case CODE_TYPE: return kInternal & kTaggedPtr; default: UNREACHABLE(); return kNone; } } // ----------------------------------------------------------------------------- // Predicates. // Check this <= that. template<class Config> bool TypeImpl<Config>::SlowIs(TypeImpl* that) { DisallowHeapAllocation no_allocation; // Fast path for bitsets. if (this->IsNone()) return true; if (that->IsBitset()) { return BitsetType::Is(BitsetType::Lub(this), that->AsBitset()); } if (that->IsClass()) { return this->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map() && ((Config::is_class(that) && Config::is_class(this)) || BitsetType::New(this->BitsetLub())->Is( BitsetType::New(that->BitsetLub()))); } if (that->IsConstant()) { return this->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value() && this->AsConstant()->Bound()->Is(that->AsConstant()->Bound()); } if (that->IsRange()) { return this->IsRange() && this->AsRange()->Bound()->Is(that->AsRange()->Bound()) && dle(that->AsRange()->Min(), this->AsRange()->Min()) && dle(this->AsRange()->Max(), that->AsRange()->Max()); } if (that->IsContext()) { return this->IsContext() && this->AsContext()->Outer()->Equals(that->AsContext()->Outer()); } if (that->IsArray()) { return this->IsArray() && this->AsArray()->Element()->Equals(that->AsArray()->Element()); } if (that->IsFunction()) { // We currently do not allow for any variance here, in order to keep // Union and Intersect operations simple. if (!this->IsFunction()) return false; FunctionType* this_fun = this->AsFunction(); FunctionType* that_fun = that->AsFunction(); if (this_fun->Arity() != that_fun->Arity() || !this_fun->Result()->Equals(that_fun->Result()) || !that_fun->Receiver()->Equals(this_fun->Receiver())) { return false; } for (int i = 0; i < this_fun->Arity(); ++i) { if (!that_fun->Parameter(i)->Equals(this_fun->Parameter(i))) return false; } return true; } // (T1 \/ ... \/ Tn) <= T <=> (T1 <= T) /\ ... /\ (Tn <= T) if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (!unioned->Get(i)->Is(that)) return false; } return true; } // T <= (T1 \/ ... \/ Tn) <=> (T <= T1) \/ ... \/ (T <= Tn) // (iff T is not a union) DCHECK(!this->IsUnion() && that->IsUnion()); UnionHandle unioned = handle(that->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (this->Is(unioned->Get(i))) return true; if (this->IsBitset()) break; // Fast fail, only first field is a bitset. } return false; } template<class Config> bool TypeImpl<Config>::NowIs(TypeImpl* that) { DisallowHeapAllocation no_allocation; // TODO(rossberg): this is incorrect for // Union(Constant(V), T)->NowIs(Class(M)) // but fuzzing does not cover that! if (this->IsConstant()) { i::Object* object = *this->AsConstant()->Value(); if (object->IsHeapObject()) { i::Map* map = i::HeapObject::cast(object)->map(); for (Iterator<i::Map> it = that->Classes(); !it.Done(); it.Advance()) { if (*it.Current() == map) return true; } } } return this->Is(that); } // Check if this contains only (currently) stable classes. template<class Config> bool TypeImpl<Config>::NowStable() { DisallowHeapAllocation no_allocation; for (Iterator<i::Map> it = this->Classes(); !it.Done(); it.Advance()) { if (!it.Current()->is_stable()) return false; } return true; } // Check this overlaps that. template<class Config> bool TypeImpl<Config>::Maybe(TypeImpl* that) { DisallowHeapAllocation no_allocation; // (T1 \/ ... \/ Tn) overlaps T <=> (T1 overlaps T) \/ ... \/ (Tn overlaps T) if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->Maybe(that)) return true; } return false; } // T overlaps (T1 \/ ... \/ Tn) <=> (T overlaps T1) \/ ... \/ (T overlaps Tn) if (that->IsUnion()) { UnionHandle unioned = handle(that->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { if (this->Maybe(unioned->Get(i))) return true; } return false; } DCHECK(!this->IsUnion() && !that->IsUnion()); if (this->IsBitset() || that->IsBitset()) { return BitsetType::IsInhabited(this->BitsetLub() & that->BitsetLub()); } if (this->IsClass()) { return that->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map(); } if (this->IsConstant()) { return that->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value(); } if (this->IsContext()) { return this->Equals(that); } if (this->IsArray()) { // There is no variance! return this->Equals(that); } if (this->IsFunction()) { // There is no variance! return this->Equals(that); } return false; } // Check if value is contained in (inhabits) type. template<class Config> bool TypeImpl<Config>::Contains(i::Object* value) { DisallowHeapAllocation no_allocation; if (this->IsRange()) { return value->IsNumber() && dle(this->AsRange()->Min(), value->Number()) && dle(value->Number(), this->AsRange()->Max()) && BitsetType::Is(BitsetType::Lub(value), this->BitsetLub()); } for (Iterator<i::Object> it = this->Constants(); !it.Done(); it.Advance()) { if (*it.Current() == value) return true; } return BitsetType::New(BitsetType::Lub(value))->Is(this); } template<class Config> bool TypeImpl<Config>::UnionType::Wellformed() { DCHECK(this->Length() >= 2); for (int i = 0; i < this->Length(); ++i) { DCHECK(!this->Get(i)->IsUnion()); if (i > 0) DCHECK(!this->Get(i)->IsBitset()); for (int j = 0; j < this->Length(); ++j) { if (i != j) DCHECK(!this->Get(i)->Is(this->Get(j))); } } return true; } // ----------------------------------------------------------------------------- // Union and intersection template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Rebound( int bitset, Region* region) { TypeHandle bound = BitsetType::New(bitset, region); if (this->IsClass()) { return ClassType::New(this->AsClass()->Map(), bound, region); } else if (this->IsConstant()) { return ConstantType::New(this->AsConstant()->Value(), bound, region); } else if (this->IsRange()) { return RangeType::New( this->AsRange()->Min(), this->AsRange()->Max(), bound, region); } else if (this->IsContext()) { return ContextType::New(this->AsContext()->Outer(), bound, region); } else if (this->IsArray()) { return ArrayType::New(this->AsArray()->Element(), bound, region); } else if (this->IsFunction()) { FunctionHandle function = Config::handle(this->AsFunction()); int arity = function->Arity(); FunctionHandle type = FunctionType::New( function->Result(), function->Receiver(), bound, arity, region); for (int i = 0; i < arity; ++i) { type->InitParameter(i, function->Parameter(i)); } return type; } UNREACHABLE(); return TypeHandle(); } template<class Config> int TypeImpl<Config>::BoundBy(TypeImpl* that) { DCHECK(!this->IsUnion()); if (that->IsUnion()) { UnionType* unioned = that->AsUnion(); int length = unioned->Length(); int bitset = BitsetType::kNone; for (int i = 0; i < length; ++i) { bitset |= BoundBy(unioned->Get(i)->unhandle()); } return bitset; } else if (that->IsClass() && this->IsClass() && *this->AsClass()->Map() == *that->AsClass()->Map()) { return that->BitsetLub(); } else if (that->IsConstant() && this->IsConstant() && *this->AsConstant()->Value() == *that->AsConstant()->Value()) { return that->AsConstant()->Bound()->AsBitset(); } else if (that->IsContext() && this->IsContext() && this->Is(that)) { return that->AsContext()->Bound()->AsBitset(); } else if (that->IsArray() && this->IsArray() && this->Is(that)) { return that->AsArray()->Bound()->AsBitset(); } else if (that->IsFunction() && this->IsFunction() && this->Is(that)) { return that->AsFunction()->Bound()->AsBitset(); } return that->BitsetGlb(); } template<class Config> int TypeImpl<Config>::IndexInUnion( int bound, UnionHandle unioned, int current_size) { DCHECK(!this->IsUnion()); for (int i = 0; i < current_size; ++i) { TypeHandle that = unioned->Get(i); if (that->IsBitset()) { if (BitsetType::Is(bound, that->AsBitset())) return i; } else if (that->IsClass() && this->IsClass()) { if (*this->AsClass()->Map() == *that->AsClass()->Map()) return i; } else if (that->IsConstant() && this->IsConstant()) { if (*this->AsConstant()->Value() == *that->AsConstant()->Value()) return i; } else if (that->IsContext() && this->IsContext()) { if (this->Is(that)) return i; } else if (that->IsArray() && this->IsArray()) { if (this->Is(that)) return i; } else if (that->IsFunction() && this->IsFunction()) { if (this->Is(that)) return i; } } return -1; } // Get non-bitsets from type, bounded by upper. // Store at result starting at index. Returns updated index. template<class Config> int TypeImpl<Config>::ExtendUnion( UnionHandle result, int size, TypeHandle type, TypeHandle other, bool is_intersect, Region* region) { if (type->IsUnion()) { UnionHandle unioned = handle(type->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { TypeHandle type_i = unioned->Get(i); DCHECK(i == 0 || !(type_i->IsBitset() || type_i->Is(unioned->Get(0)))); if (!type_i->IsBitset()) { size = ExtendUnion(result, size, type_i, other, is_intersect, region); } } } else if (!type->IsBitset()) { DCHECK(type->IsClass() || type->IsConstant() || type->IsRange() || type->IsContext() || type->IsArray() || type->IsFunction()); int inherent_bound = type->InherentBitsetLub(); int old_bound = type->BitsetLub(); int other_bound = type->BoundBy(other->unhandle()) & inherent_bound; int new_bound = is_intersect ? (old_bound & other_bound) : (old_bound | other_bound); if (new_bound != BitsetType::kNone) { int i = type->IndexInUnion(new_bound, result, size); if (i == -1) { i = size++; } else if (result->Get(i)->IsBitset()) { return size; // Already fully subsumed. } else { int type_i_bound = result->Get(i)->BitsetLub(); new_bound |= type_i_bound; if (new_bound == type_i_bound) return size; } if (new_bound != old_bound) type = type->Rebound(new_bound, region); result->Set(i, type); } } return size; } // Union is O(1) on simple bitsets, but O(n*m) on structured unions. template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Union( TypeHandle type1, TypeHandle type2, Region* region) { // Fast case: bit sets. if (type1->IsBitset() && type2->IsBitset()) { return BitsetType::New(type1->AsBitset() | type2->AsBitset(), region); } // Fast case: top or bottom types. if (type1->IsAny() || type2->IsNone()) return type1; if (type2->IsAny() || type1->IsNone()) return type2; // Semi-fast case: Unioned objects are neither involved nor produced. if (!(type1->IsUnion() || type2->IsUnion())) { if (type1->Is(type2)) return type2; if (type2->Is(type1)) return type1; } // Slow case: may need to produce a Unioned object. int size = 0; if (!type1->IsBitset()) { size += (type1->IsUnion() ? type1->AsUnion()->Length() : 1); } if (!type2->IsBitset()) { size += (type2->IsUnion() ? type2->AsUnion()->Length() : 1); } int bitset = type1->BitsetGlb() | type2->BitsetGlb(); if (bitset != BitsetType::kNone) ++size; DCHECK(size >= 1); UnionHandle unioned = UnionType::New(size, region); size = 0; if (bitset != BitsetType::kNone) { unioned->Set(size++, BitsetType::New(bitset, region)); } size = ExtendUnion(unioned, size, type1, type2, false, region); size = ExtendUnion(unioned, size, type2, type1, false, region); if (size == 1) { return unioned->Get(0); } else { unioned->Shrink(size); DCHECK(unioned->Wellformed()); return unioned; } } // Intersection is O(1) on simple bitsets, but O(n*m) on structured unions. template<class Config> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Intersect( TypeHandle type1, TypeHandle type2, Region* region) { // Fast case: bit sets. if (type1->IsBitset() && type2->IsBitset()) { return BitsetType::New(type1->AsBitset() & type2->AsBitset(), region); } // Fast case: top or bottom types. if (type1->IsNone() || type2->IsAny()) return type1; if (type2->IsNone() || type1->IsAny()) return type2; // Semi-fast case: Unioned objects are neither involved nor produced. if (!(type1->IsUnion() || type2->IsUnion())) { if (type1->Is(type2)) return type1; if (type2->Is(type1)) return type2; } // Slow case: may need to produce a Unioned object. int size = 0; if (!type1->IsBitset()) { size += (type1->IsUnion() ? type1->AsUnion()->Length() : 1); } if (!type2->IsBitset()) { size += (type2->IsUnion() ? type2->AsUnion()->Length() : 1); } int bitset = type1->BitsetGlb() & type2->BitsetGlb(); if (bitset != BitsetType::kNone) ++size; DCHECK(size >= 1); UnionHandle unioned = UnionType::New(size, region); size = 0; if (bitset != BitsetType::kNone) { unioned->Set(size++, BitsetType::New(bitset, region)); } size = ExtendUnion(unioned, size, type1, type2, true, region); size = ExtendUnion(unioned, size, type2, type1, true, region); if (size == 0) { return None(region); } else if (size == 1) { return unioned->Get(0); } else { unioned->Shrink(size); DCHECK(unioned->Wellformed()); return unioned; } } // ----------------------------------------------------------------------------- // Iteration. template<class Config> int TypeImpl<Config>::NumClasses() { DisallowHeapAllocation no_allocation; if (this->IsClass()) { return 1; } else if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); int result = 0; for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->IsClass()) ++result; } return result; } else { return 0; } } template<class Config> int TypeImpl<Config>::NumConstants() { DisallowHeapAllocation no_allocation; if (this->IsConstant()) { return 1; } else if (this->IsUnion()) { UnionHandle unioned = handle(this->AsUnion()); int result = 0; for (int i = 0; i < unioned->Length(); ++i) { if (unioned->Get(i)->IsConstant()) ++result; } return result; } else { return 0; } } template<class Config> template<class T> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Iterator<T>::get_type() { DCHECK(!Done()); return type_->IsUnion() ? type_->AsUnion()->Get(index_) : type_; } // C++ cannot specialise nested templates, so we have to go through this // contortion with an auxiliary template to simulate it. template<class Config, class T> struct TypeImplIteratorAux { static bool matches(typename TypeImpl<Config>::TypeHandle type); static i::Handle<T> current(typename TypeImpl<Config>::TypeHandle type); }; template<class Config> struct TypeImplIteratorAux<Config, i::Map> { static bool matches(typename TypeImpl<Config>::TypeHandle type) { return type->IsClass(); } static i::Handle<i::Map> current(typename TypeImpl<Config>::TypeHandle type) { return type->AsClass()->Map(); } }; template<class Config> struct TypeImplIteratorAux<Config, i::Object> { static bool matches(typename TypeImpl<Config>::TypeHandle type) { return type->IsConstant(); } static i::Handle<i::Object> current( typename TypeImpl<Config>::TypeHandle type) { return type->AsConstant()->Value(); } }; template<class Config> template<class T> bool TypeImpl<Config>::Iterator<T>::matches(TypeHandle type) { return TypeImplIteratorAux<Config, T>::matches(type); } template<class Config> template<class T> i::Handle<T> TypeImpl<Config>::Iterator<T>::Current() { return TypeImplIteratorAux<Config, T>::current(get_type()); } template<class Config> template<class T> void TypeImpl<Config>::Iterator<T>::Advance() { DisallowHeapAllocation no_allocation; ++index_; if (type_->IsUnion()) { UnionHandle unioned = handle(type_->AsUnion()); for (; index_ < unioned->Length(); ++index_) { if (matches(unioned->Get(index_))) return; } } else if (index_ == 0 && matches(type_)) { return; } index_ = -1; } // ----------------------------------------------------------------------------- // Conversion between low-level representations. template<class Config> template<class OtherType> typename TypeImpl<Config>::TypeHandle TypeImpl<Config>::Convert( typename OtherType::TypeHandle type, Region* region) { if (type->IsBitset()) { return BitsetType::New(type->AsBitset(), region); } else if (type->IsClass()) { TypeHandle bound = BitsetType::New(type->BitsetLub(), region); return ClassType::New(type->AsClass()->Map(), bound, region); } else if (type->IsConstant()) { TypeHandle bound = Convert<OtherType>(type->AsConstant()->Bound(), region); return ConstantType::New(type->AsConstant()->Value(), bound, region); } else if (type->IsRange()) { TypeHandle bound = Convert<OtherType>(type->AsRange()->Bound(), region); return RangeType::New( type->AsRange()->Min(), type->AsRange()->Max(), bound, region); } else if (type->IsContext()) { TypeHandle bound = Convert<OtherType>(type->AsContext()->Bound(), region); TypeHandle outer = Convert<OtherType>(type->AsContext()->Outer(), region); return ContextType::New(outer, bound, region); } else if (type->IsUnion()) { int length = type->AsUnion()->Length(); UnionHandle unioned = UnionType::New(length, region); for (int i = 0; i < length; ++i) { TypeHandle t = Convert<OtherType>(type->AsUnion()->Get(i), region); unioned->Set(i, t); } return unioned; } else if (type->IsArray()) { TypeHandle element = Convert<OtherType>(type->AsArray()->Element(), region); TypeHandle bound = Convert<OtherType>(type->AsArray()->Bound(), region); return ArrayType::New(element, bound, region); } else if (type->IsFunction()) { TypeHandle res = Convert<OtherType>(type->AsFunction()->Result(), region); TypeHandle rcv = Convert<OtherType>(type->AsFunction()->Receiver(), region); TypeHandle bound = Convert<OtherType>(type->AsFunction()->Bound(), region); FunctionHandle function = FunctionType::New( res, rcv, bound, type->AsFunction()->Arity(), region); for (int i = 0; i < function->Arity(); ++i) { TypeHandle param = Convert<OtherType>( type->AsFunction()->Parameter(i), region); function->InitParameter(i, param); } return function; } else { UNREACHABLE(); return None(region); } } // ----------------------------------------------------------------------------- // Printing. template<class Config> const char* TypeImpl<Config>::BitsetType::Name(int bitset) { switch (bitset) { case REPRESENTATION(kAny): return "Any"; #define RETURN_NAMED_REPRESENTATION_TYPE(type, value) \ case REPRESENTATION(k##type): return #type; REPRESENTATION_BITSET_TYPE_LIST(RETURN_NAMED_REPRESENTATION_TYPE) #undef RETURN_NAMED_REPRESENTATION_TYPE #define RETURN_NAMED_SEMANTIC_TYPE(type, value) \ case SEMANTIC(k##type): return #type; SEMANTIC_BITSET_TYPE_LIST(RETURN_NAMED_SEMANTIC_TYPE) #undef RETURN_NAMED_SEMANTIC_TYPE default: return NULL; } } template <class Config> void TypeImpl<Config>::BitsetType::Print(OStream& os, // NOLINT int bitset) { DisallowHeapAllocation no_allocation; const char* name = Name(bitset); if (name != NULL) { os << name; return; } static const int named_bitsets[] = { #define BITSET_CONSTANT(type, value) REPRESENTATION(k##type), REPRESENTATION_BITSET_TYPE_LIST(BITSET_CONSTANT) #undef BITSET_CONSTANT #define BITSET_CONSTANT(type, value) SEMANTIC(k##type), SEMANTIC_BITSET_TYPE_LIST(BITSET_CONSTANT) #undef BITSET_CONSTANT }; bool is_first = true; os << "("; for (int i(ARRAY_SIZE(named_bitsets) - 1); bitset != 0 && i >= 0; --i) { int subset = named_bitsets[i]; if ((bitset & subset) == subset) { if (!is_first) os << " | "; is_first = false; os << Name(subset); bitset -= subset; } } DCHECK(bitset == 0); os << ")"; } template <class Config> void TypeImpl<Config>::PrintTo(OStream& os, PrintDimension dim) { // NOLINT DisallowHeapAllocation no_allocation; if (dim != REPRESENTATION_DIM) { if (this->IsBitset()) { BitsetType::Print(os, SEMANTIC(this->AsBitset())); } else if (this->IsClass()) { os << "Class(" << static_cast<void*>(*this->AsClass()->Map()) << " < "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsConstant()) { os << "Constant(" << static_cast<void*>(*this->AsConstant()->Value()) << " : "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsRange()) { os << "Range(" << this->AsRange()->Min() << ".." << this->AsRange()->Max() << " : "; BitsetType::New(BitsetType::Lub(this))->PrintTo(os, dim); os << ")"; } else if (this->IsContext()) { os << "Context("; this->AsContext()->Outer()->PrintTo(os, dim); os << ")"; } else if (this->IsUnion()) { os << "("; UnionHandle unioned = handle(this->AsUnion()); for (int i = 0; i < unioned->Length(); ++i) { TypeHandle type_i = unioned->Get(i); if (i > 0) os << " | "; type_i->PrintTo(os, dim); } os << ")"; } else if (this->IsArray()) { os << "Array("; AsArray()->Element()->PrintTo(os, dim); os << ")"; } else if (this->IsFunction()) { if (!this->AsFunction()->Receiver()->IsAny()) { this->AsFunction()->Receiver()->PrintTo(os, dim); os << "."; } os << "("; for (int i = 0; i < this->AsFunction()->Arity(); ++i) { if (i > 0) os << ", "; this->AsFunction()->Parameter(i)->PrintTo(os, dim); } os << ")->"; this->AsFunction()->Result()->PrintTo(os, dim); } else { UNREACHABLE(); } } if (dim == BOTH_DIMS) os << "/"; if (dim != SEMANTIC_DIM) { BitsetType::Print(os, REPRESENTATION(this->BitsetLub())); } } #ifdef DEBUG template <class Config> void TypeImpl<Config>::Print() { OFStream os(stdout); PrintTo(os); os << endl; } #endif // ----------------------------------------------------------------------------- // Instantiations. template class TypeImpl<ZoneTypeConfig>; template class TypeImpl<ZoneTypeConfig>::Iterator<i::Map>; template class TypeImpl<ZoneTypeConfig>::Iterator<i::Object>; template class TypeImpl<HeapTypeConfig>; template class TypeImpl<HeapTypeConfig>::Iterator<i::Map>; template class TypeImpl<HeapTypeConfig>::Iterator<i::Object>; template TypeImpl<ZoneTypeConfig>::TypeHandle TypeImpl<ZoneTypeConfig>::Convert<HeapType>( TypeImpl<HeapTypeConfig>::TypeHandle, TypeImpl<ZoneTypeConfig>::Region*); template TypeImpl<HeapTypeConfig>::TypeHandle TypeImpl<HeapTypeConfig>::Convert<Type>( TypeImpl<ZoneTypeConfig>::TypeHandle, TypeImpl<HeapTypeConfig>::Region*); } } // namespace v8::internal
32,279
11,012
#include <squirrel.h> #include "engge/System/Locator.hpp" #include "engge/Engine/EntityManager.hpp" #include "engge/Engine/Thread.hpp" #include <utility> namespace ng { Thread::Thread(std::string name, bool isGlobal, HSQUIRRELVM v, HSQOBJECT thread_obj, HSQOBJECT env_obj, HSQOBJECT closureObj, std::vector<HSQOBJECT> args) : m_name(std::move(name)), m_v(v), m_threadObj(thread_obj), m_envObj(env_obj), m_closureObj(closureObj), m_args(std::move(args)), m_isGlobal(isGlobal) { sq_addref(m_v, &m_threadObj); sq_addref(m_v, &m_envObj); sq_addref(m_v, &m_closureObj); m_id = Locator<EntityManager>::get().getThreadId(); } Thread::~Thread() { sq_release(m_v, &m_threadObj); sq_release(m_v, &m_envObj); sq_release(m_v, &m_closureObj); } std::string Thread::getName() const { return m_name; } HSQUIRRELVM Thread::getThread() const { return m_threadObj._unVal.pThread; } bool Thread::call() { auto thread = getThread(); // call the closure in the thread SQInteger top = sq_gettop(thread); sq_pushobject(thread, m_closureObj); sq_pushobject(thread, m_envObj); for (auto arg : m_args) { sq_pushobject(thread, arg); } if (SQ_FAILED(sq_call(thread, 1 + m_args.size(), SQFalse, SQTrue))) { sq_settop(thread, top); return false; } return true; } } // namespace ng
1,391
540
/** * Copyright (c) 2017 Melown Technologies SE * * 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 "../camera.hpp" #include "../navigation.hpp" #include "../traverseNode.hpp" #include "../coordsManip.hpp" #include "../mapLayer.hpp" #include "../mapConfig.hpp" #include "../map.hpp" #include "../gpuResource.hpp" #include "../renderTasks.hpp" #include <optick.h> namespace vts { using vtslibs::vts::NodeInfo; namespace { double cross(const vec2 &a, const vec2 &b) { return a[0] * b[1] - a[1] * b[0]; } double sign(double a) { return a < 0 ? -1 : 1; } double lineSolver(const vec2 &p, const vec2 &a, const vec2 &b, double av, double bv) { vec2 v1 = b - a; if (dot(v1, v1) < 1e-4) return av; // degenerated into a point vec2 v2 = p - a; double l1 = length(v1); double l2 = length(v2); double u = l2 / l1 * sign(dot(v2, v1)); return interpolate(av, bv, u); } double triangleSolver(const vec2 &p, const vec2 &a, const vec2 &b, const vec2 &c, double av, double bv, double cv) { vec2 v0 = b - a; vec2 v1 = c - a; vec2 v2 = p - a; double d00 = dot(v0, v0); double d01 = dot(v0, v1); double d11 = dot(v1, v1); double d20 = dot(v2, v0); double d21 = dot(v2, v1); { // detect degenerated cases (lines) if (d00 < 1e-4) return lineSolver(p, a, c, av, cv); if (d11 < 1e-4) return lineSolver(p, a, b, av, bv); vec2 v3 = c - b; double d33 = dot(v3, v3); if (d33 < 1e-4) return lineSolver(p, a, b, av, bv); } double invDenom = 1.0 / (d00 * d11 - d01 * d01); double v = (d11 * d20 - d01 * d21) * invDenom; double w = (d00 * d21 - d01 * d20) * invDenom; double u = 1 - v - w; return u * av + v * bv + w * cv; } double bilinearInterpolation(double u, double v, double av, double bv, double cv, double dv) { assert(u >= 0 && u <= 1 && v >= 0 && v <= 1); double p = interpolate(av, bv, u); double q = interpolate(cv, dv, u); return interpolate(p, q, v); } double quadrilateralSolver(const vec2 &p, const vec2 &a, const vec2 &b, const vec2 &c, const vec2 &d, double av, double bv, double cv, double dv) { const vec2 e = b - a; const vec2 f = c - a; { // detect degenerated cases (triangles) vec2 q3 = b - d; vec2 q4 = c - d; if (dot(e, e) < 1e-4) return triangleSolver(p, a, c, d, av, cv, dv); if (dot(f, f) < 1e-4) return triangleSolver(p, a, b, d, av, bv, dv); if (dot(q3, q3) < 1e-4) return triangleSolver(p, a, b, c, av, bv, cv); if (dot(q4, q4) < 1e-4) return triangleSolver(p, a, b, c, av, bv, cv); } vec2 g = a - b + d - c; vec2 h = p - a; double k2 = cross(g, f); if (std::abs(k2) < 1e-7) { // rectangle double u = h[0] / e[0]; double v = h[1] / f[1]; if (v >= 0 && v <= 1 && u >= 0 && u <= 1) return bilinearInterpolation(u, v, av, bv, cv, dv); return nan1(); // the query is outside the quadrilateral } double k0 = cross(h, e); double k1 = cross(e, f) + cross(h, g); double w = k1 * k1 - 4 * k0 * k2; if (w < 0) return nan1(); // the quadrilateral has negative area w = sqrt(w); double v1 = (-k1 - w) / (2 * k2); double u1 = (h[0] - f[0] * v1) / (e[0] + g[0] * v1); double v2 = (-k1 + w) / (2 * k2); double u2 = (h[0] - f[0] * v2) / (e[0] + g[0] * v2); if (v1 >= 0 && v1 <= 1 && u1 >= 0 && u1 <= 1) return bilinearInterpolation(u1, v1, av, bv, cv, dv); if (v2 >= 0 && v2 <= 1 && u2 >= 0 && u2 <= 1) return bilinearInterpolation(u2, v2, av, bv, cv, dv); return nan1(); // the query is outside the quadrilateral } double altitudeInterpolation( const vec2 &query, const vec2 points[4], double values[4]) { return quadrilateralSolver(query, points[0], points[1], points[2], points[3], values[0], values[1], values[2], values[3] ); } TraverseNode *findTravSds(CameraImpl *camera, TraverseNode *where, const vec2 &pointSds, uint32 maxLod) { assert(where && where->meta); if (where->id.lod >= maxLod) return where; math::Point2 ublasSds = vecToUblas<math::Point2>(pointSds); for (auto &ci : where->childs) { // avoid computing new extents if we already have them if (ci.meta) { if (!math::inside(ci.meta->extents, ublasSds)) continue; } else { const Extents2 ce = subExtents( where->meta->extents, where->id, ci.id); if (!math::inside(ce, ublasSds)) continue; } if (!camera->travInit(&ci)) continue; return findTravSds(camera, &ci, pointSds, maxLod); } return where; } } // namespace bool CameraImpl::getSurfaceOverEllipsoid( double &result, const vec3 &navPos, double sampleSize, bool renderDebug) { OPTICK_EVENT(); assert(map->convertor); assert(!map->layers.empty()); //std::string s = map->layers.empty() ? "true" : "false"; //LOG(info3) << "map" << std::endl; //LOG(info3) << map << std::endl; //LOG(info3) << "map layers 0" << std::endl; //// LOG(info3) << map->layers << std::endl; //LOG(info3) << "map->layers.empty() : " << s; //LOG(info3) << map->layers[0] << std::endl; //LOG(info3) << "map layers 0 traverseRoot" << std::endl; //LOG(info3) << map->layers[0]->traverseRoot << std::endl; //LOG(info3) << "map end" << std::endl; //if (map->layers[0] == nullptr) { // return false; //} //---------------------------------------crash region -------------------------------------- TraverseNode *root = map->layers[0]->traverseRoot.get(); //------------------------------------------------------------------------------------------- if (!root || !root->meta) return false; if (sampleSize <= 0) sampleSize = getSurfaceAltitudeSamples(); // find surface division coordinates (and appropriate node info) vec2 sds; boost::optional<NodeInfo> info; uint32 index = 0; for (const auto &it : map->mapconfig->referenceFrame.division.nodes) { struct I { uint32 &i; I(uint32 &i) : i(i) {} ~I() { ++i; } } inc(index); if (it.second.partitioning.mode != vtslibs::registry::PartitioningMode::bisection) continue; const NodeInfo &ni = map->mapconfig->referenceDivisionNodeInfos[index]; try { sds = vec3to2(map->convertor->convert(navPos, Srs::Navigation, it.second.srs)); if (!ni.inside(vecToUblas<math::Point2>(sds))) continue; info = ni; break; } catch(const std::exception &) { // do nothing } } if (!info) return false; // desired lod uint32 desiredLod = std::max(0.0, -std::log2(sampleSize / info->extents().size())); // find corner positions vec2 points[4]; { NodeInfo i = *info; while (i.nodeId().lod < desiredLod) { for (auto j : vtslibs::vts::children(i.nodeId())) { NodeInfo k = i.child(j); if (!k.inside(vecToUblas<math::Point2>(sds))) continue; i = k; break; } } math::Extents2 ext = i.extents(); vec2 center = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5; vec2 size = vecFromUblas<vec2>(ext.ur - ext.ll); vec2 p = sds; if (sds(0) < center(0)) p(0) -= size(0); if (sds(1) < center(1)) p(1) -= size(1); points[0] = p; points[1] = p + vec2(size(0), 0); points[2] = p + vec2(0, size(1)); points[3] = p + size; // todo periodicity } // find the actual corners TraverseNode *travRoot = findTravById(root, info->nodeId()); if (!travRoot || !travRoot->meta) return false; double altitudes[4]; const TraverseNode *nodes[4]; for (int i = 0; i < 4; i++) { auto t = findTravSds(this, travRoot, points[i], desiredLod); if (!t) return false; if (!t->meta->surrogateNav) return false; const math::Extents2 &ext = t->meta->extents; points[i] = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5; altitudes[i] = *t->meta->surrogateNav; nodes[i] = t; } // interpolate double res = altitudeInterpolation(sds, points, altitudes); // debug visualization if (renderDebug) { RenderInfographicsTask task; task.mesh = map->getMesh("internal://data/meshes/sphere.obj"); task.mesh->priority = inf1(); if (*task.mesh) { float c = std::isnan(res) ? 0.0 : 1.0; task.color = vec4f(c, c, c, 0.7f); double scaleSum = 0; for (int i = 0; i < 4; i++) { const TraverseNode *t = nodes[i]; double scale = t->meta->extents.size() * 0.035; task.model = translationMatrix(*t->meta->surrogatePhys) * scaleMatrix(scale); draws.infographics.push_back(convert(task)); scaleSum += scale; } if (!std::isnan(res)) { vec3 p = navPos; p[2] = res; p = map->convertor->convert(p, Srs::Navigation, Srs::Physical); task.model = translationMatrix(p) * scaleMatrix(scaleSum / 4); task.color = vec4f(c, c, c, 1.f); draws.infographics.push_back(convert(task)); } } } // output if (std::isnan(res)) return false; result = res; return true; } double CameraImpl::getSurfaceAltitudeSamples() { double targetDistance = length(vec3(target - eye)); double viewExtent = targetDistance / (apiProj(1, 1) * 0.5); double result = viewExtent / options.samplesForAltitudeLodSelection; if (std::isnan(result)) return 10; return result; } } // namespace vts
11,669
4,232
// Copyright 2004-present Facebook. All Rights Reserved. #include "ResumeCache.h" #include <algorithm> #include "src/framing/Frame.h" #include "src/framing/FrameTransport.h" #include "src/statemachine/RSocketStateMachine.h" namespace { using rsocket::FrameType; bool shouldTrackFrame(const FrameType frameType) { switch (frameType) { case FrameType::REQUEST_CHANNEL: case FrameType::REQUEST_STREAM: case FrameType::REQUEST_RESPONSE: case FrameType::REQUEST_FNF: case FrameType::REQUEST_N: case FrameType::CANCEL: case FrameType::ERROR: case FrameType::PAYLOAD: return true; case FrameType::RESERVED: case FrameType::SETUP: case FrameType::LEASE: case FrameType::KEEPALIVE: case FrameType::METADATA_PUSH: case FrameType::RESUME: case FrameType::RESUME_OK: case FrameType::EXT: default: return false; } } } // anonymous namespace rsocket { ResumeCache::~ResumeCache() { clearFrames(position_); } void ResumeCache::trackReceivedFrame( const folly::IOBuf& serializedFrame, const FrameType frameType, const StreamId streamId) { onStreamOpen(streamId, frameType); if (shouldTrackFrame(frameType)) { VLOG(6) << "received frame " << frameType; // TODO(tmont): this could be expensive, find a better way to get length impliedPosition_ += serializedFrame.computeChainDataLength(); } } void ResumeCache::trackSentFrame( const folly::IOBuf& serializedFrame, const FrameType frameType, const folly::Optional<StreamId> streamIdPtr) { if (streamIdPtr) { const StreamId streamId = *streamIdPtr; onStreamOpen(streamId, frameType); } if (shouldTrackFrame(frameType)) { // TODO(tmont): this could be expensive, find a better way to get length auto frameDataLength = serializedFrame.computeChainDataLength(); // if the frame is too huge, we don't cache it if (frameDataLength > capacity_) { resetUpToPosition(position_); position_ += frameDataLength; DCHECK(size_ == 0); return; } addFrame(serializedFrame, frameDataLength); position_ += frameDataLength; } } void ResumeCache::resetUpToPosition(ResumePosition position) { if (position <= resetPosition_) { return; } if (position > position_) { position = position_; } clearFrames(position); resetPosition_ = position; DCHECK(frames_.empty() || frames_.front().first == resetPosition_); } bool ResumeCache::isPositionAvailable(ResumePosition position) const { return (position_ == position) || std::binary_search( frames_.begin(), frames_.end(), std::make_pair(position, std::unique_ptr<folly::IOBuf>()), [](decltype(frames_.back()) pairA, decltype(frames_.back()) pairB) { return pairA.first < pairB.first; }); } void ResumeCache::addFrame(const folly::IOBuf& frame, size_t frameDataLength) { size_ += frameDataLength; while (size_ > capacity_) { evictFrame(); } frames_.emplace_back(position_, frame.clone()); stats_->resumeBufferChanged(1, static_cast<int>(frameDataLength)); } void ResumeCache::evictFrame() { DCHECK(!frames_.empty()); auto position = frames_.size() > 1 ? std::next(frames_.begin())->first : position_; resetUpToPosition(position); } void ResumeCache::clearFrames(ResumePosition position) { if (frames_.empty()) { return; } DCHECK(position <= position_); DCHECK(position >= resetPosition_); auto end = std::lower_bound( frames_.begin(), frames_.end(), position, [](decltype(frames_.back()) pair, ResumePosition pos) { return pair.first < pos; }); DCHECK(end == frames_.end() || end->first >= resetPosition_); auto pos = end == frames_.end() ? position : end->first; stats_->resumeBufferChanged( -static_cast<int>(std::distance(frames_.begin(), end)), -static_cast<int>(pos - resetPosition_)); frames_.erase(frames_.begin(), end); size_ -= static_cast<decltype(size_)>(pos - resetPosition_); } void ResumeCache::sendFramesFromPosition( ResumePosition position, FrameTransport& frameTransport) const { DCHECK(isPositionAvailable(position)); if (position == position_) { // idle resumption return; } auto found = std::lower_bound( frames_.begin(), frames_.end(), position, [](decltype(frames_.back()) pair, ResumePosition pos) { return pair.first < pos; }); DCHECK(found != frames_.end()); DCHECK(found->first == position); while (found != frames_.end()) { frameTransport.outputFrameOrEnqueue(found->second->clone()); found++; } } void ResumeCache::onStreamClosed(StreamId streamId) { // This is crude. We could try to preserve the stream type in // RSocketStateMachine and pass it down explicitly here. activeRequestStreams_.erase(streamId); activeRequestChannels_.erase(streamId); activeRequestResponses_.erase(streamId); } void ResumeCache::onStreamOpen(StreamId streamId, FrameType frameType) { if (frameType == FrameType::REQUEST_STREAM) { activeRequestStreams_.insert(streamId); } else if (frameType == FrameType::REQUEST_CHANNEL) { activeRequestChannels_.insert(streamId); } else if (frameType == FrameType::REQUEST_RESPONSE) { activeRequestResponses_.insert(streamId); } } } // reactivesocket
5,411
1,707
// evolveDoc.cpp : implementation of the CevolveDoc class // #include "stdafx.h" #include "evolve.h" #include "evolveDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CevolveDoc IMPLEMENT_DYNCREATE(CevolveDoc, CDocument) BEGIN_MESSAGE_MAP(CevolveDoc, CDocument) END_MESSAGE_MAP() // CevolveDoc construction/destruction CevolveDoc::CevolveDoc() { universe = NULL; } CevolveDoc::~CevolveDoc() { if( universe != NULL ) { Universe_Delete(universe); universe = NULL; } } BOOL CevolveDoc::OnNewDocument() { UNIVERSE *u; CevolveApp *app; char errbuf[1000]; NewUniverseOptions *nuo; if( ! CDocument::OnNewDocument() ) return FALSE; app = (CevolveApp *) AfxGetApp(); nuo = app->GetNewUniverseOptions(); u = CreateUniverse(nuo, errbuf); if( u == NULL ) { AfxMessageBox(errbuf, MB_OK, 0); return false; } SetModifiedFlag(true); universe = u; return true; } void CevolveDoc::Serialize(CArchive& ar) { // // do nothing as we have arn't using seriaize mechanism // return; } void CevolveDoc::DeleteContents() { if( universe != NULL ) { Universe_Delete(universe); universe = NULL; } } BOOL CevolveDoc::OnOpenDocument(LPCTSTR lpszPathName) { char errbuf[1000]; UNIVERSE *u; u = LoadUniverse(lpszPathName, errbuf); if( u == NULL ) { AfxMessageBox(errbuf, MB_OK, 0); universe = NULL; return false; } universe = u; return true; } BOOL CevolveDoc::OnSaveDocument(LPCTSTR lpszPathName) { int n; char errbuf[1000]; n = StoreUniverse(lpszPathName, universe, errbuf); if( n == 0 ) { AfxMessageBox(errbuf, MB_OK, 0); return false; } SetModifiedFlag(false); return true; } // CevolveDoc diagnostics #ifdef _DEBUG void CevolveDoc::AssertValid() const { CDocument::AssertValid(); } void CevolveDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CevolveDoc commands
1,865
813
//%Header { /***************************************************************************** * * File: src/Mustl/MustlWebLink.cpp * * Copyright: Andy Southgate 2002-2007, 2020 * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ****************************************************************************/ //%Header } ol7C6mm/6AFh/4txRC+jvA /* * $Id: MustlWebLink.cpp,v 1.30 2006/06/29 10:12:36 southa Exp $ * $Log: MustlWebLink.cpp,v $ * Revision 1.30 2006/06/29 10:12:36 southa * 64 bit compatibility fixes * * Revision 1.29 2006/06/01 15:39:55 southa * DrawArray verification and fixes * * Revision 1.28 2005/05/19 13:02:20 southa * Mac release work * * Revision 1.27 2004/09/26 21:07:16 southa * Mustl compilation fixes * * Revision 1.26 2004/01/02 21:13:16 southa * Source conditioning * * Revision 1.25 2004/01/01 21:15:46 southa * Created XCode project * * Revision 1.24 2003/10/06 22:23:45 southa * Game to GameMustl move * * Revision 1.23 2003/09/17 19:40:38 southa * Source conditioning upgrades * * Revision 1.22 2003/08/21 23:09:32 southa * Fixed file headers * * Revision 1.21 2003/01/20 10:45:31 southa * Singleton tidying * * Revision 1.20 2003/01/18 13:34:00 southa * Created MushcoreSingleton * * Revision 1.19 2003/01/17 13:30:41 southa * Source conditioning and build fixes * * Revision 1.18 2003/01/17 12:20:41 southa * Fixed auto_ptr duplication * * Revision 1.17 2003/01/16 15:58:02 southa * Mustl exception handling * * Revision 1.16 2003/01/16 12:03:55 southa * Platform and invalid socket fixes * * Revision 1.15 2003/01/14 20:46:12 southa * Post data handling * * Revision 1.14 2003/01/14 17:38:22 southa * Mustl web configuration * * Revision 1.13 2003/01/13 23:05:22 southa * Mustl test application * * Revision 1.12 2003/01/13 16:50:50 southa * win32 support * * Revision 1.11 2003/01/13 15:01:20 southa * Fix Mustl command line build * * Revision 1.10 2003/01/12 17:33:01 southa * Mushcore work * * Revision 1.9 2003/01/11 17:58:15 southa * Mustl fixes * * Revision 1.8 2003/01/09 14:57:08 southa * Created Mushcore * * Revision 1.7 2003/01/07 17:13:45 southa * Fixes for gcc 3.1 * * Revision 1.6 2002/12/29 21:00:00 southa * More build fixes * * Revision 1.5 2002/12/29 20:30:57 southa * Work for gcc 3.1 build * * Revision 1.4 2002/12/20 13:17:46 southa * Namespace changes, licence changes and source conditioning * * Revision 1.3 2002/12/17 12:53:34 southa * Mustl library * * Revision 1.2 2002/12/12 18:38:25 southa * Mustl separation * * Revision 1.14 2002/11/23 14:39:06 southa * Store ports in network order * * Revision 1.13 2002/11/22 11:42:07 southa * Added developer controls * * Revision 1.12 2002/11/18 14:11:04 southa * win32 support * * Revision 1.11 2002/11/15 11:47:56 southa * Web processing and error handling * * Revision 1.10 2002/11/14 11:40:28 southa * Configuration handling * * Revision 1.9 2002/11/12 18:02:13 southa * POST handling and handlepostvalues command * * Revision 1.8 2002/11/12 17:05:01 southa * Tidied localweb server * * Revision 1.7 2002/11/12 11:49:22 southa * Initial MHTML processing * * Revision 1.6 2002/11/08 11:54:40 southa * Web fixes * * Revision 1.5 2002/11/08 11:29:24 southa * Web fixes and debug * * Revision 1.4 2002/11/08 00:15:31 southa * Fixed errors * * Revision 1.3 2002/11/07 00:53:37 southa * localweb work * * Revision 1.2 2002/11/06 14:16:57 southa * Basic web server * * Revision 1.1 2002/11/05 18:15:17 southa * Web server * */ #include "MustlWebLink.h" #include "Mustl.h" #include "MustlHTTP.h" #include "MustlPlatform.h" #include "MustlSTL.h" #include "MustlMushcore.h" using namespace Mustl; using namespace std; MUSHCORE_DATA_INSTANCE(MustlWebLink); string MustlWebLink::m_webPath=""; MustlWebLink::MustlWebLink(tSocket inSocket) : m_receiveState(kReceiveInitial), m_tcpSocket(MustlPlatform::InvalidSocketValueGet()), m_linkErrors(0), m_isDead(false) { // I am the server end of the link try { m_tcpSocket = inSocket; MustlPlatform::SocketNonBlockingSet(m_tcpSocket); } catch (...) { MustlPlatform::SocketClose(inSocket); throw; } m_linkState=kLinkStateNew; m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); m_creationMsec=m_currentMsec; m_lastAccessMsec=m_currentMsec; // Not used } MustlWebLink::~MustlWebLink() { MustlLog::Sgl().WebLog() << "Closing web link" << endl; try { Disconnect(); } catch (exception& e) { MustlLog::Sgl().WebLog() << "~MustlWebLink exception: " << e.what() << endl; } } void MustlWebLink::Disconnect(void) { if (m_tcpSocket != MustlPlatform::InvalidSocketValueGet()) { MustlPlatform::SocketClose(m_tcpSocket); m_tcpSocket=MustlPlatform::InvalidSocketValueGet(); } m_isDead = true; } void MustlWebLink::Tick(void) { m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); } bool MustlWebLink::IsDead(void) { m_currentMsec = MustlTimer::Sgl().CurrentMsecGet(); if (m_isDead || m_currentMsec > m_creationMsec + kLinkLifetime || m_linkErrors > kErrorLimit) { return true; } return false; } bool MustlWebLink::Receive(string& outStr) { if (m_isDead) return false; U8 byte='-'; int result; outStr=""; do { try { result=MustlPlatform::TCPReceive(m_tcpSocket, &byte, 1); } catch (MustlPermanentFail &e) { (void) e; Disconnect(); throw; } catch (MustlTemporaryFail &e) { (void) e; ++m_linkErrors; throw; } if (result == 1) { outStr += byte; if (byte == 0xa) break; } } while (result > 0); // MustlLog::Sgl().WebLog() << "Received " << MustlUtils::MakePrintable(outStr) << endl; return (outStr.size() != 0); } void MustlWebLink::Send(MustlData& ioData) { if (m_isDead) { throw(MustlFail("Attempt to send on dead WebLink")); } try { U32 sendSize = ioData.ReadSizeGet(); MustlPlatform::TCPSend(m_tcpSocket, ioData.ReadPtrGet(), sendSize); ioData.ReadPosAdd(sendSize); } catch (MustlPermanentFail &e) { (void) e; Disconnect(); throw; } catch (MustlTemporaryFail &e) { (void) e; ++m_linkErrors; throw; } // MustlLog::Sgl().WebLog() << "Sending " << ioData << endl; } void MustlWebLink::Send(const string& inStr) { MustlData netData;; netData.Write(inStr); Send(netData); } void MustlWebLink::Send(istream& ioStream) { MustlData netData; while (ioStream.good() && !ioStream.eof()) { netData.PrepareForWrite(); ioStream.read(reinterpret_cast<char *>(netData.WritePtrGet()), netData.WriteSizeGet()); U32 length=ioStream.gcount(); netData.WritePosAdd(length); if (length == 0) break; } Send(netData); } void MustlWebLink::ReceivedProcess(const string& inStr) { switch (m_receiveState) { case kReceiveInitial: { if (inStr.substr(0,3) == "GET") { m_requestLine = inStr; m_requestType = kRequestGet; } else if (inStr.substr(0,4) == "POST") { m_requestLine = inStr; m_requestType = kRequestPost; } } m_receiveState = kReceiveHeaders; break; case kReceiveHeaders: { bool lineEnd=false; if (inStr.size() > 0 && (inStr[0] == 0xd || inStr[0] == 0xa)) { lineEnd=true; } switch (m_requestType) { case kRequestGet: if (lineEnd) { GetProcess(m_requestLine.substr(4)); m_receiveState = kReceiveInitial; } break; case kRequestPost: if (lineEnd) { m_receiveState = kReceiveBody; } break; default: SendErrorPage("Unrecognised request"); break; } } break; case kReceiveBody: { switch (m_requestType) { case kRequestGet: throw(MustlFail("Bad receive state for GET")); break; case kRequestPost: PostProcess(inStr); GetProcess(m_requestLine.substr(5)); break; default: SendErrorPage("Unrecognised request"); break; } } break; default: throw(MustlFail("Bad value for m_receiveState")); break; } } void MustlWebLink::GetProcess(const string& inFilename) { string localFilename; U32 dotCount=0; U32 slashCount=0; MustlLog::Sgl().WebLog() << "Serving fetch request for " << MustlUtils::MakePrintable(inFilename) << endl; try { for (U32 i=0; i<inFilename.size(); ++i) { U8 byte=inFilename[i]; if (byte == '.') { if (dotCount > 0) { throw(MustlFail("Bad filename (dots)")); } ++dotCount; localFilename+=byte; } if (byte == '/') { if (slashCount > 0) { throw(MustlFail("Bad filename (slashes)")); } ++slashCount; } if (byte >= 'a' && byte <= 'z') { localFilename+=byte; } if (byte <= ' ') { break; } } if (localFilename == "") localFilename = "index.html"; if (localFilename == "test.html") { SendTestPage(); } else { if (m_webPath == "") { const MushcoreScalar *pScalar; if (MushcoreGlobalConfig::Sgl().GetIfExists(pScalar, "MUSTL_WEB_PATH")) { m_webPath = pScalar->StringGet(); } } if (m_webPath == "") { throw(MustlFail("Path to web files (MUSTL_WEB_PATH) not set")); } localFilename = m_webPath+"/"+localFilename; SendFile(localFilename); } } catch (MushcoreNonFatalFail &e) { MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl; if (!m_isDead) { try { SendErrorPage(e.what()); } catch (MushcoreNonFatalFail &e2) { MustlLog::Sgl().WebLog() << "Exception sending error page: " << e2.what() << endl; } } } } void MustlWebLink::PostProcess(const string& inValues) { try { if (inValues.find("'") != inValues.npos) { throw(MustlFail("Invalid POST values")); } MushcoreCommand command(string("mustlpostvalues('")+inValues+"')"); command.Execute(); } catch (MushcoreNonFatalFail &e) { MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl; } } void MustlWebLink::SendFile(const string& inFilename) { bool processFile=false; ifstream fileStream(inFilename.c_str()); if (!fileStream) { throw(MustlFail("File not found: "+inFilename)); } MustlHTTP http; http.Reply200(); string::size_type dotPos = inFilename.rfind('.'); if (dotPos == string::npos) { throw(MustlFail("Unknown file type: "+inFilename)); } string fileTypeStr = inFilename.substr(dotPos+1); if (fileTypeStr == "html") { http.ContentTypeHTML(); } else if (fileTypeStr == "mhtml") { http.ContentTypeHTML(); processFile=true; } else if (fileTypeStr == "jpg" || fileTypeStr == "jpeg") { http.AllowCachingSet(); http.ContentType("image/jpeg"); } else if (fileTypeStr == "tif" || fileTypeStr == "tiff") { http.AllowCachingSet(); http.ContentType("image/tiff"); } else if (fileTypeStr == "png") { http.AllowCachingSet(); http.ContentType("image/png"); } else if (fileTypeStr == "css") { http.AllowCachingSet(); http.ContentType("text/css"); } else { throw(MustlFail("Unknown file type: "+fileTypeStr)); } if (processFile) { SendMHTML(fileStream, http); } else { http.Endl(); MustlData netData; http.ContentGet(netData); Send(netData); Send(fileStream); } Disconnect(); } void MustlWebLink::SendMHTML(istream& ioStream, MustlHTTP& ioHTTP) { MustlData netData; ioHTTP.Endl(); ioHTTP.ContentGet(netData); Send(netData); while (ioStream.good() && !ioStream.eof()) { string dataStr; getline(ioStream, dataStr, '\0'); U32 startPos; while (startPos = dataStr.find("<?mush"), startPos != dataStr.npos) { U32 endPos = dataStr.find("?>", startPos); if (endPos == dataStr.npos) { throw(MustlFail("Unterminated <?mush (expecting ?>)")); } string content=dataStr.substr(startPos+6, endPos - startPos - 6); // MustlLog::Sgl().WebLog() << "Found mush command '" << content << "'" << endl; try { MushcoreCommand command(content); ostringstream commandOutput; MushcoreEnvOutput envOutput(MushcoreEnv::Sgl(), commandOutput); command.Execute(); dataStr.replace(startPos, endPos - startPos + 2, commandOutput.str()); } catch (MushcoreNonFatalFail& e) { ostringstream errorOutput; errorOutput << "<pre>Command '" << content << "' failed: " << e.what() << "</pre>" << endl; dataStr.replace(startPos, endPos - startPos + 2, errorOutput.str()); } } Send(dataStr); } } void MustlWebLink::SendTestPage(void) { MustlHTTP http; http.Reply200(); http.ContentTypeHTML(); http.Endl(); http.Header(); http.Out() << "Mustl test page"; http.Endl(); http.Footer(); MustlData netData; http.ContentGet(netData); Send(netData); Disconnect(); } void MustlWebLink::SendErrorPage(const string& inText) { MustlHTTP http; http.Reply200(); http.ContentTypeHTML(); http.Endl(); http.Header(); http.Out() << "<h1>Error from Mustl web server</h1>"; http.Out() << "<p>" << inText << "</p>"; http.Out() << "<p><a target=\"_top\" href=\"/index.html\">Back to main page</a></p>"; http.Endl(); http.Footer(); MustlData netData; http.ContentGet(netData); Send(netData); Disconnect(); } void MustlWebLink::Print(ostream& ioOut) const { ioOut << "["; ioOut << "requestLine=" << m_requestLine; ioOut << ", requestType=" << m_requestType; ioOut << ", linkState=" << m_linkState; ioOut << ", receiveState=" << m_receiveState; ioOut << ", tcpSocket=" << m_tcpSocket; ioOut << ", currentMsec=" << m_currentMsec; ioOut << ", creationMsec=" << m_creationMsec; ioOut << ", lastAccessMsec=" << m_lastAccessMsec; ioOut << ", linkErrors=" << m_linkErrors; ioOut << ", isDead=" << m_isDead; ioOut << ", webPath=" << m_webPath; ioOut << "]"; }
17,155
6,297
#include "client.h" #include "ui_client.h" #include <QTime> client::client(QWidget *parent) : QDialog(parent), ui(new Ui::client) { ui->setupUi(this); this->setWindowTitle("client"); cSocket = new QTcpSocket(); ui->lineEdit->setText("127.0.0.1"); ui->lineEdit_2->setText("1234"); connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(linkSlot())); } client::~client() { delete ui; } void client::linkSlot(){ QString IP = ui->lineEdit->text(); QString PORT = ui->lineEdit_2->text(); cSocket->connectToHost("127.0.0.1",PORT.toInt()); ui->pushButton->setEnabled(0); connect(cSocket,SIGNAL(readyRead()),this,SLOT(receiveData())); connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(sendData())); } void client::receiveData(){ current_date_time = QDateTime::currentDateTime(); QString str_date_time = current_date_time.toString("yyyy-MM-dd hh:mm:ss"); QString data = cSocket->readAll(); ui->textBrowser->append("server "+str_date_time+"\n"+data); } void client::sendData(){ current_date_time = QDateTime::currentDateTime(); QString str_date_time = current_date_time.toString("yyyy-MM-dd hh:mm:ss"); QByteArray dd = ui->lineEdit_3->text().toLatin1(); cSocket->write(dd); cSocket->flush(); ui->textBrowser->append("You "+str_date_time+"\n"+dd); }
1,355
502
/** * Autogenerated by Thrift Compiler (0.14.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "impl/pch.h" #include <iosfwd> #include <thrift/Thrift.h> #include <thrift/TApplicationException.h> #include <thrift/protocol/TProtocol.h> #include <thrift/transport/TTransport.h> #include <functional> #include <memory> #include "snappydata_struct_PrepareResult.h" #include <algorithm> #include <ostream> #include <thrift/TToString.h> namespace io { namespace snappydata { namespace thrift { PrepareResult::~PrepareResult() noexcept { } void PrepareResult::__set_statementId(const int64_t val) { this->statementId = val; } void PrepareResult::__set_statementType(const int8_t val) { this->statementType = val; } void PrepareResult::__set_parameterMetaData(const std::vector<ColumnDescriptor> & val) { this->parameterMetaData = val; } void PrepareResult::__set_resultSetMetaData(const std::vector<ColumnDescriptor> & val) { this->resultSetMetaData = val; __isset.resultSetMetaData = true; } void PrepareResult::__set_warnings(const SnappyExceptionData& val) { this->warnings = val; __isset.warnings = true; } std::ostream& operator<<(std::ostream& out, const PrepareResult& obj) { obj.printTo(out); return out; } uint32_t PrepareResult::read(::apache::thrift::protocol::TProtocol* iprot) { uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_statementId = false; bool isset_statementType = false; bool isset_parameterMetaData = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->statementId); isset_statementId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_BYTE) { xfer += iprot->readByte(this->statementType); isset_statementType = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->parameterMetaData.clear(); uint32_t _size258; ::apache::thrift::protocol::TType _etype261; xfer += iprot->readListBegin(_etype261, _size258); this->parameterMetaData.resize(_size258); uint32_t _i262; for (_i262 = 0; _i262 < _size258; ++_i262) { xfer += this->parameterMetaData[_i262].read(iprot); } xfer += iprot->readListEnd(); } isset_parameterMetaData = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->resultSetMetaData.clear(); uint32_t _size263; ::apache::thrift::protocol::TType _etype266; xfer += iprot->readListBegin(_etype266, _size263); this->resultSetMetaData.resize(_size263); uint32_t _i267; for (_i267 = 0; _i267 < _size263; ++_i267) { xfer += this->resultSetMetaData[_i267].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.resultSetMetaData = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_STRUCT) { xfer += this->warnings.read(iprot); this->__isset.warnings = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_statementId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_statementType) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_parameterMetaData) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t PrepareResult::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; xfer += oprot->writeStructBegin("PrepareResult"); xfer += oprot->writeFieldBegin("statementId", ::apache::thrift::protocol::T_I64, 1); xfer += oprot->writeI64(this->statementId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("statementType", ::apache::thrift::protocol::T_BYTE, 2); xfer += oprot->writeByte(this->statementType); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("parameterMetaData", ::apache::thrift::protocol::T_LIST, 3); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->parameterMetaData.size())); std::vector<ColumnDescriptor> ::const_iterator _iter268; for (_iter268 = this->parameterMetaData.begin(); _iter268 != this->parameterMetaData.end(); ++_iter268) { xfer += (*_iter268).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); if (this->__isset.resultSetMetaData) { xfer += oprot->writeFieldBegin("resultSetMetaData", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->resultSetMetaData.size())); std::vector<ColumnDescriptor> ::const_iterator _iter269; for (_iter269 = this->resultSetMetaData.begin(); _iter269 != this->resultSetMetaData.end(); ++_iter269) { xfer += (*_iter269).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.warnings) { xfer += oprot->writeFieldBegin("warnings", ::apache::thrift::protocol::T_STRUCT, 5); xfer += this->warnings.write(oprot); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(PrepareResult &a, PrepareResult &b) { using ::std::swap; swap(a.statementId, b.statementId); swap(a.statementType, b.statementType); swap(a.parameterMetaData, b.parameterMetaData); swap(a.resultSetMetaData, b.resultSetMetaData); swap(a.warnings, b.warnings); swap(a.__isset, b.__isset); } PrepareResult::PrepareResult(const PrepareResult& other270) { statementId = other270.statementId; statementType = other270.statementType; parameterMetaData = other270.parameterMetaData; resultSetMetaData = other270.resultSetMetaData; warnings = other270.warnings; __isset = other270.__isset; } PrepareResult::PrepareResult( PrepareResult&& other271) { statementId = std::move(other271.statementId); statementType = std::move(other271.statementType); parameterMetaData = std::move(other271.parameterMetaData); resultSetMetaData = std::move(other271.resultSetMetaData); warnings = std::move(other271.warnings); __isset = std::move(other271.__isset); } PrepareResult& PrepareResult::operator=(const PrepareResult& other272) { statementId = other272.statementId; statementType = other272.statementType; parameterMetaData = other272.parameterMetaData; resultSetMetaData = other272.resultSetMetaData; warnings = other272.warnings; __isset = other272.__isset; return *this; } PrepareResult& PrepareResult::operator=(PrepareResult&& other273) { statementId = std::move(other273.statementId); statementType = std::move(other273.statementType); parameterMetaData = std::move(other273.parameterMetaData); resultSetMetaData = std::move(other273.resultSetMetaData); warnings = std::move(other273.warnings); __isset = std::move(other273.__isset); return *this; } void PrepareResult::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "PrepareResult("; out << "statementId=" << to_string(statementId); out << ", " << "statementType=" << to_string(statementType); out << ", " << "parameterMetaData=" << to_string(parameterMetaData); out << ", " << "resultSetMetaData="; (__isset.resultSetMetaData ? (out << to_string(resultSetMetaData)) : (out << "<null>")); out << ", " << "warnings="; (__isset.warnings ? (out << to_string(warnings)) : (out << "<null>")); out << ")"; } }}} // namespace
8,588
3,047
// Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the // University of Virginia, University of Heidelberg, and University // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <raptor.h> #include <string.h> #include <stdlib.h> #include "copasi/copasi.h" #include "CRaptorInit.h" // static bool CRaptorInit::Initialized = false; CRaptorInit::CRaptorInit() { if (!Initialized) { raptor_init(); Initialized = true; atexit(&raptor_finish); } } CRaptorInit::~CRaptorInit() {} // static bool CRaptorInit::isLocalURI(raptor_uri * pURI) { raptor_uri * pTmp = raptor_new_uri_for_retrieval(pURI); bool isLocal = (strcmp("/", (char *) raptor_uri_as_string(pTmp)) == 0); pRaptorFreeUri(pTmp); return isLocal; }
1,368
484