text
stringlengths
8
6.88M
/** * Copyright (C) 2019 Sergey Morozov <sergey@morozov.ch> * * 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 "Renderer.hpp" namespace lidar_obstacle_detection { void Renderer::RenderHighway() { // units in meters float roadLength = 50.0; float roadWidth = 12.0; float roadHeight = 0.2; viewer_->addCube(-roadLength/2., roadLength/2., -roadWidth/2., roadWidth/2., -roadHeight, 0.0, 0.2, 0.2, 0.2, "highwayPavement"); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_SURFACE, "highwayPavement"); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.2, 0.2, 0.2, "highwayPavement"); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 1.0, "highwayPavement"); viewer_->addLine(pcl::PointXYZ(-roadLength/2,-roadWidth/6, 0.01), pcl::PointXYZ(roadLength/2, -roadWidth/6, 0.01), 1.0, 1.0, 0.0, "line1"); viewer_->addLine(pcl::PointXYZ(-roadLength/2, roadWidth/6, 0.01), pcl::PointXYZ(roadLength/2, roadWidth/6, 0.01), 1.0, 1.0, 0.0, "line2"); } void Renderer::RenderRays(const Eigen::Vector3f& origin, const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud) { for(pcl::PointXYZ point : cloud->points) { viewer_->addLine(pcl::PointXYZ(origin.x(), origin.y(), origin.z()), point, 1.0, 0.0, 0.0, "ray"+std::to_string(rays_counter_)); ++rays_counter_; } } void Renderer::ClearRays() { while(rays_counter_ --> 0) { viewer_->removeShape("ray"+std::to_string(rays_counter_)); } } void Renderer::RenderPointCloud( const pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud, const std::string& name, const Color& color) { viewer_->addPointCloud<pcl::PointXYZ>(cloud, name); viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 4, name); viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, name); } void Renderer::RenderPointCloud( const pcl::PointCloud<pcl::PointXYZI>::Ptr& cloud, const std::string& name, const Color& color) { if(color.r==-1) { // Select color based off of cloud intensity pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> intensity_distribution(cloud,"intensity"); viewer_->addPointCloud<pcl::PointXYZI>(cloud, intensity_distribution, name); } else { // Select color based off input value viewer_->addPointCloud<pcl::PointXYZI>(cloud, name); viewer_->setPointCloudRenderingProperties( pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, name); } viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, name); } // Draw wire frame box with filled transparent color void Renderer::RenderBox(const Box& box, const int id, const Color& color, float opacity) { if(opacity > 1.0) opacity = 1.0; if(opacity < 0.0) opacity = 0.0; std::string cube = "box"+std::to_string(id); viewer_->addCube(box.x_min, box.x_max, box.y_min, box.y_max, box.z_min, box.z_max, color.r, color.g, color.b, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cube); std::string cubeFill = "boxFill"+std::to_string(id); viewer_->addCube(box.x_min, box.x_max, box.y_min, box.y_max, box.z_min, box.z_max, color.r, color.g, color.b, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_SURFACE, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, opacity*0.3, cubeFill); } void Renderer::RenderBox(const BoxQ& box, const int id, const Color& color, float opacity) { if(opacity > 1.0) opacity = 1.0; if(opacity < 0.0) opacity = 0.0; std::string cube = "box"+std::to_string(id); viewer_->addCube(box.bbox_transform, box.bbox_quaternion, box.cube_length, box.cube_width, box.cube_height, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, cube); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, opacity, cube); std::string cubeFill = "boxFill"+std::to_string(id); viewer_->addCube(box.bbox_transform, box.bbox_quaternion, box.cube_length, box.cube_width, box.cube_height, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_SURFACE, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color.r, color.g, color.b, cubeFill); viewer_->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, opacity*0.3, cubeFill); } void Renderer::InitCamera(CameraAngle view_angle) { viewer_->setBackgroundColor (0, 0, 0); // set camera position and angle viewer_->initCameraParameters(); // distance away in meters int distance = 16; switch(view_angle) { case CameraAngle::XY: { viewer_->setCameraPosition(-distance, -distance, distance, 1, 1, 0); break; } case CameraAngle::TopDown: { viewer_->setCameraPosition(0, 0, distance, 1, 0, 1); break; } case CameraAngle::Side: { viewer_->setCameraPosition(0, -distance, 0, 0, 0, 1); break; } case CameraAngle::FPS: { viewer_->setCameraPosition(-10, 0, 0, 0, 0, 1); break; } default: { throw std::logic_error("unknown CameraAngle"); } } if(view_angle != CameraAngle::FPS) { viewer_->addCoordinateSystem(1.0); } } void Renderer::ClearViewer() { viewer_->removeAllPointClouds(); viewer_->removeAllShapes(); } bool Renderer::WasViewerStopped() const { return viewer_->wasStopped(); } Renderer::Renderer() : viewer_{new pcl::visualization::PCLVisualizer("3D Viewer")}, rays_counter_{0} { } void Renderer::SpinViewerOnce() const { viewer_->spinOnce(); } }
#include "quicksorter.h" template<typename T> void Quicksorter<T>::Quicksort( std::vector<T> &items, int start, int end) { if( start >= end ) { return; } int p = Partition( items, start, end ); Quicksort(items, start, p); Quicksort(items, p+1, end); } template<typename T> int Quicksorter<T>::Partition(std::vector<T> &items, int start, int end) { int pivot = items[start]; int storeIndex = start+1; for(int i=start+1; i<=end; i++) { if( items[i] < pivot ) { std::swap(items[i], items[storeIndex]); storeIndex++; } } storeIndex--; std::swap(items[start], items[storeIndex]); return storeIndex; } template class Quicksorter<int>;
// // SSH1106 driver 132x64 // #ifndef SJSU_DEV_OLEDDRIVER_H #define SJSU_DEV_OLEDDRIVER_H #include "i2c2.hpp" #include "utilities.h" #include "string.h" /** * Contains specs. of OLED, addresses, and registers */ enum { OLED_WIDTH = 132, OLED_HEIGHT = 64, PAGE_COUNT = 8, OLED_ADDRESS = 0x78, DATA = 0x40, CONTROL = 0x00, SET_LOW_COLUMN = 0x00, /* 0x00 - 0x0F */ SET_HIGH_COLUMN = 0x10, /* 0x10 - 0x1F */ SET_PUMP_VOL = 0x30, /* 0x30 - 0x33 */ SET_START_LINE = 0x40, /* 0x40 - 0x7F */ SET_CONTRAST = 0x81, /** multi-byte write; send 0x81 address then 0x00 - 0xFF into contrast data register */ SEG_REMAP = 0xA0, /* 0xA0 - 0xA1 */ DISPLAY_ALLON_RESUME = 0xA4, DISPLAY_ALLON = 0xA5, NORMAL_DISPLAY = 0xA6, REVERSE_DISPLAY = 0xA7, SET_MULTIPLEX = 0xA8, /** multi-byte write; send 0xA8 then 0x00 - 0x3F */ SET_DCDC = 0xAD, /** multi-byte write; send 0xAD then 0x8A - 0x8B */ DISPLAY_OFF = 0xAE, DISPLAY_ON = 0xAF, SET_PAGE_ADDR = 0xB0, /* 0xB0 - 0xB7, 8 pages in total */ COM_OUT_SCAN = 0xC0, /* 0xC0 - 0xC8 */ SET_DISPLAY_OFFSET = 0xD3, /** multi-byte write; send 0xD3 then 0x00 - 0x3F; for setting COM0-COM63 (height?) */ SET_DISPLAY_CLOCKDIV = 0xD5, /** multi-byte write; send 0xD5 then 0x00 - 0xFF */ SET_PRECHARGE = 0xD9, /** multi-byte write; send 0xD9 then 0x00 - 0xFF */ SET_COM_PINS = 0xDA, /** multi-byte write; send 0xDA then 0x02 - 0x12 */ SET_VCOM_DETECT = 0xDB, /** multi-byte write; send 0xDB then 0x00 - 0xFF */ READ_MODIFY_WRITE = 0xE0, END = 0xEE, NOP = 0xE3 }; typedef enum { VOL_ZERO = 0x000000000000, VOL_ONE = 0x000000000100, VOL_TWO = 0x000003000100, VOL_THREE = 0x070003000100, VOL_FOUR = 0x000000000F00, VOL_FIVE = 0x00003F000F00, } volume_t; typedef enum { TOP = 0x00, MID, BOT } position_t; class OLEDDriver { private: I2C2 * i2c2; public: OLEDDriver(); bool Init(); typedef enum { PAUSE = 0x007F7F007F7F, PLAY = 0x00081C3E7F7F, ARROW = 0x00081c3e0808, SPACE = 0x000000000000, COLON = 0x000066660000, PERIOD = 0x000003030000, } symbol_t; void toggleDisplay(); void fillDisplay(uint8_t byte); void testDisplay(); void clearDisplay(); void resetCursor(); void moveCursor(uint8_t row, uint8_t column); uint64_t charToDisplay(char c); //retrieves look up table value of a char void printChar(char c); void printLine(const char *s,uint8_t row, uint8_t column); void printSymbolAtPosition(symbol_t symbol, uint8_t row, uint8_t column); void printSymbol(symbol_t sym); void printCurrentSong(const char *s); void printPause(); void printPlay(); void initVolume(uint8_t vol); void printListSong(const char *s, position_t pos); void printListArrow(uint8_t pos); void eraseSymbolAtPosition(uint8_t row, uint8_t column); void setVolumeBars(uint8_t vol); void printVolumeBars(volume_t first, volume_t second); void setSongList(const char *topSong, const char *midSong, const char *botSong, uint8_t arrowPosition); //ALPHABET LOOKUP TABLE const uint64_t charHexValues[36] = { [0] = 0x003F4848483F, //A [1] = 0x00364949497F, //B [2] = 0x00224141413E, //C [3] = 0x003E4141417F, //D [4] = 0x00634149497F, //E [5] = 0x00604048487F, //F [6] = 0x00264545413E, //G [7] = 0x007F0808087F, //H [8] = 0x0041417F4141, //I [9] = 0x0040407F4147, //J [10] = 0x00412214087F, //K [11] = 0x00030101017F, //L [12] = 0x007F2010207F, //M [13] = 0x007F021C207F, //N [14] = 0x003E4141413E, //O [15] = 0x00304848483F, //P [16] = 0x003F4345413E, //Q [17] = 0x0030494A4C3F, //R [18] = 0x002649494932, //S [19] = 0x0040407F4040, //T [20] = 0x007E0101017E, //U [21] = 0x007804030478, //V [22] = 0x007E010E017E, //W [23] = 0x004136083641, //X [24] = 0x0040201F2040, //Y [25] = 0x006151494543, //Z [26] = 0x003E615D433E, //0 [27] = 0x00007F402000, //1 [28] = 0x007149454321, //2 [29] = 0x003649494122, //3 [30] = 0x00087F281808, //4 [31] = 0x00464949497A, //5 [32] = 0x00264949493E, //6 [33] = 0x007844424160, //7 [34] = 0x003649494936, //8 [35] = 0x003F48484830 //9 }; }; #endif //SJSU_DEV_OLEDDRIVER_H
// Copyright 2020 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. #include <iostream> #include <sstream> #include <vector> #include "screen/Screen.h" #include "translator/Translator.h" namespace { // clang-format off //--------------------- // // 0 1 1 2 // // 0 ABBBCBBBCBBBD // E F F G // 1 HIIIJIIIJIIIK // L M M N // 2 OPPPQPPPQPPPR // L M M N // 2 OPPPQPPPQPPPR // L M M N // 3 STTTUTTTUTTTV // // A B C D E F G H I J K L M N O P Q R S T U V // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // //--------------------- struct Style { std::wstring charset[22]; int width[3]; int height[4]; }; std::map<std::string, Style> styles = { { "ascii", Style{ // charset { L"+" , L"-" , L"+" , L"+" , L"|" , L"|" , L"|" , L"+" , L"-" , L"+" , L"+" , L"|" , L"|" , L"|" , L"+" , L"-" , L"+" , L"+" , L"+" , L"-" , L"+" , L"+" , }, // width/height {1,1,1}, {1,1,1,1}, } }, { "ascii rounded", Style{ // charset { L"." , L"-" , L"+" , L"." , L"|" , L"|" , L"|" , L"|" , L"-" , L"+" , L"|" , L"|" , L"|" , L"|" , L"|" , L"-" , L"+" , L"|" , L"'" , L"-" , L"+" , L"'" , }, // width/height {1,1,1}, {1,1,1,1}, } }, { "ascii with header 1", Style{ // charset { L"|=" , L"=" , L"=" , L"=|" , L"| " , L"|" , L" |" , L"|=" , L"=" , L"=" , L"=|" , L" |" , L"|" , L"| " , L" +" , L"-" , L"+" , L"+ " , L" +" , L"-" , L"+" , L"+ " , }, // width {2,1,2},{1,1,1,1}, } }, { "ascii with header 2", Style{ // charset { L"=" , L"=" , L"=" , L"=" , L"|" , L"|" , L"|" , L"=" , L"=" , L"=" , L"=" , L"|" , L"|" , L"|" , L"+" , L"-" , L"+" , L"+" , L"+" , L"-" , L"+" , L"+" , }, // width {1,1,1},{1,1,1,1}, } }, { "ascii light header", Style{ // charset { L"" , L"" , L"" , L"" , L"" , L" " , L"" , L"" , L"-", L" " , L"" , L"" , L" ", L"" , L"" , L"", L"" , L"" , L"" , L"", L"" , L"" , }, // width {0,1,0},{0,1,0,0}, } }, { "ascii light header/separator", Style{ // charset { L"" , L"" , L"" , L"" , L"" , L"|" , L"" , L"" , L"-", L"|" , L"" , L"" , L"|", L"" , L"" , L"", L"" , L"" , L"" , L"", L"" , L"" , }, // width {0,1,0},{0,1,0,0}, } }, { "ascii light header/separator/border", Style{ // charset { L"+" , L"-", L"+" , L"+" , L"|" , L"|" , L"|" , L"+" , L"-", L"+" , L"|" , L"|" , L"|" , L"|" , L"|" , L"", L"|" , L"|" , L"+" , L"-", L"+" , L"+" , }, // width {1,1,1},{1,1,0,1}, } }, { "ascii light separator/border", Style{ // charset { L"+", L"-" , L"+" , L"+" , L"|", L"|" , L"|" , L"" , L"", L"" , L"" , L"|" , L"|" , L"|" , L"|" , L"", L"|" , L"|" , L"+" , L"-", L"+" , L"+" , }, // width {1,1,1},{1,0,0,1}, } }, { "ascii light border", Style{ // charset { L"+" , L"-" , L"-" , L"+" , L"|", L" " , L"|" , L"" , L"", L"" , L"" , L"|" , L" " , L"|" , L"|" , L"", L" " , L"|" , L"+" , L"-", L"-" , L"+" , }, // width {1,1,1},{1,0,0,1}, } }, { "unicode", Style{ // charset { L"┌" , L"─" , L"┬" , L"┐" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"└" , L"─" , L"┴" , L"┘" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode rounded", Style{ // charset { L"╭" , L"─" , L"┬" , L"╮" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"╰" , L"─" , L"┴" , L"╯" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode bold", Style{ // charset { L"┏" , L"━" , L"┳" , L"┓" , L"┃" , L"┃" , L"┃" , L"┣" , L"━" , L"╋" , L"┫" , L"┃" , L"┃" , L"┃" , L"┣" , L"━" , L"╋" , L"┫" , L"┗" , L"━" , L"┻" , L"┛" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode double", Style{ // charset { L"╔" , L"═" , L"╦" , L"╗" , L"║" , L"║" , L"║" , L"╠" , L"═" , L"╬" , L"╣" , L"║" , L"║" , L"║" , L"╠" , L"═" , L"╬" , L"╣" , L"╚" , L"═" , L"╩" , L"╝" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode with bold header", Style{ // charset { L"┏" , L"━" , L"┳" , L"┓" , L"┃" , L"┃" , L"┃" , L"┡" , L"━" , L"╇" , L"┩" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"└" , L"─" , L"┴" , L"┘" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode with double header", Style{ // charset { L"╒" , L"═" , L"╤" , L"╕" , L"│" , L"│" , L"│" , L"╞" , L"═" , L"╪" , L"╡" , L"│" , L"│" , L"│" , L"├" , L"─" , L"┼" , L"┤" , L"└" , L"─" , L"┴" , L"┘" , }, // width {1,1,1},{1,1,1,1}, } }, { "unicode cells", Style{ // charset { L"╭" , L"─" , L"╮╭" , L"╮" , L"│" , L"││" , L"│" , L"╰╭" , L"──" , L"╯╰╮╭" , L"╯╮" , L"│" , L"││" , L"│" , L"╰╭" , L"──" , L"╯╰╮╭" , L"╯╮" , L"╰" , L"─" , L"╯╰" , L"╯" , }, // width {1,2,1},{1,2,2,1}, } }, { "unicode cells 2", Style{ // charset { L"╭─│╭" , L"──" , L"──╮╭" , L"─╮╮│" , L"││" , L"││" , L"││" , L"│╰│╭" , L"──" , L"╯╰╮╭" , L"╯│╮│" , L"││" , L"││" , L"││" , L"│╰│╭" , L"──" , L"╯╰╮╭" , L"╯│╮│" , L"│╰╰─" , L"──" , L"╯╰──" , L"╯│─╯" , }, // width {2,2,2},{2,2,2,2}, } }, { "conceptual", Style{ // charset { L" " , L"_" , L" " , L" " , L"/" , L"\\/" , L"\\" , L"\\" , L"_" , L"/\\" , L"/" , L"/" , L"\\/" , L"\\" , L"\\" , L"_" , L"/\\" , L"/" , L"\\" , L"_" , L"/\\" , L"/" , }, // width {1,2,1},{1,1,1,1}, } }, }; }; // clang-format on class Table : public Translator { public: virtual ~Table() = default; private: const char* Name() final { return "Table"; } const char* Identifier() final { return "Table"; } const char* Description() final { return "Draw table"; } std::vector<Translator::OptionDescription> Options() final { return { { "style", { "unicode", "unicode rounded", "unicode bold", "unicode double", "unicode with bold header", "unicode with double header", "unicode cells", "unicode cells 2", "ascii", "ascii rounded", "ascii with header 1", "ascii with header 2", "ascii light header", "ascii light header/separator", "ascii light header/separator/border", "ascii light separator/border", "ascii light border", "conceptual", }, "unicode", "The style of the table.", Widget::Combobox, }, }; } std::vector<Translator::Example> Examples() final { return { {"1-simple", "Column 1,Column 2,Column 3\n" "C++,Web,Assembly\n" "Javascript,CSS,HTML"}, }; } std::string Translate(const std::string& input, const std::string& options_string) override { auto options = SerializeOption(options_string); // Style. std::string style_option = options["style"]; Style style = styles["unicode"]; if (styles.count(style_option)) { style = styles[style_option]; } // Separator. std::wstring separator = to_wstring(options["separator"]); if (separator.size() != 1) { separator = L','; } // Parse data. std::vector<std::vector<std::wstring>> data; std::wstring line; std::wstringstream ss(to_wstring(input)); while (std::getline(ss, line)) { data.emplace_back(); std::wstring cell; std::wstringstream ss_line(line); while (std::getline(ss_line, cell, separator[0])) { data.back().push_back(cell); } } // Compute row/line count. int row_count = data.size(); int column_count = 0; for (const auto& line : data) { column_count = std::max(column_count, (int)line.size()); } // Uniformize the number of cells per lines. for (auto& line : data) { line.resize(column_count); } // Compute column_width; std::vector<int> column_width(column_count, 0); for (const auto& line : data) { for (int i = 0; i < line.size(); ++i) { column_width[i] = std::max(column_width[i], (int)line[i].size()); } } // Compute sum_column_width; int column_width_global = 0; for (const auto it : column_width) { column_width_global += it; } // Compute screen dimension. int width = style.width[0] + style.width[1] * (column_count - 1) + style.width[2] + column_width_global; int height = style.height[0] + style.height[1] + style.height[2] * (row_count - 2) + style.height[3] + row_count; Screen screen(width, height); // Draw table. int Y = 0; for (int y = 0; y < row_count; ++y) { bool last_line = (y == row_count - 1); int X = 0; const int cell_top = Y + style.height[std::min(2, y)]; const int cell_bottom = cell_top + 1; for (int x = 0; x < data[y].size(); ++x) { bool last_row = (x == column_count - 1); // clang-format off const int top_char = y == 0 ? 1 : y == 1 ? 8 : 15; const int left_char = y == 0 ? (x == 0 ? 4 : 5) : (x == 0 ? 11:12) ; const int right_char = y == 0 ? 6: 13; const int bottom_char = 19; const int top_left_char = y == 0 ? (x == 0 ? 0 : 2): y == 1 ? (x == 0 ? 7 : 9): (x == 0 ? 14:16); const int top_right_char = y == 0 ? 3 : y == 1 ? 10: 17; const int bottom_left_char = x == 0 ? 18: 20; const int bottom_right_char = 21; const int cell_left = X + style.width[std::min(1,x)]; const int cell_right = cell_left + column_width[x]; // clang-format on // Draw Top. { int i = 0; for (int yy = Y; yy < cell_top; ++yy) { for (int xx = cell_left; xx < cell_right; ++xx) { screen.DrawPixel(xx, yy, style.charset[top_char][i]); } ++i; } } // Draw Down. if (last_line) { int i = 0; for (int yy = cell_bottom; yy < height; ++yy) { for (int xx = cell_left; xx < cell_right; ++xx) { screen.DrawPixel(xx, yy, style.charset[bottom_char][i]); } ++i; } } // Draw Left. for (int yy = cell_top; yy < cell_bottom; ++yy) { screen.DrawText(X, yy, style.charset[left_char]); } // Draw Right. if (last_row) { for (int yy = cell_top; yy < cell_bottom; ++yy) { screen.DrawText(cell_right, yy, style.charset[right_char]); } } // Draw Left/Top { int i = 0; for (int yy = Y; yy < cell_top; ++yy) { for (int xx = X; xx < cell_left; ++xx) { screen.DrawPixel(xx, yy, style.charset[top_left_char][i]); ++i; } } } // Draw Right/Top if (last_row) { int i = 0; for (int yy = Y; yy < cell_top; ++yy) { for (int xx = cell_right; xx < width; ++xx) { screen.DrawPixel(xx, yy, style.charset[top_right_char][i]); ++i; } } } // Draw Left/Bottom if (last_line) { int i = 0; for (int yy = cell_bottom; yy < height; ++yy) { for (int xx = X; xx < cell_left; ++xx) { screen.DrawPixel(xx, yy, style.charset[bottom_left_char][i]); ++i; } } } // Draw Right/Bottom if (last_row && last_line) { int i = 0; for (int yy = cell_bottom; yy < height; ++yy) { for (int xx = cell_right; xx < width; ++xx) { screen.DrawPixel(xx, yy, style.charset[bottom_right_char][i]); ++i; } } } // Draw Text. screen.DrawText(cell_left, cell_top, data[y][x]); X = cell_right; } Y = cell_bottom; } return screen.ToString(); } }; std::unique_ptr<Translator> TableTranslator() { return std::make_unique<Table>(); }
#pragma once #include "Shape.h" class Rect : public Shape { int m_left, m_right, m_top, m_bottom; public: Rect(); Rect(int left, int right, int top, int bottom, Color c = RED); Rect(const Rect & other); ~Rect(); void WhereAmI(); void Inflate(int left, int right, int top, int bottom); void Inflate(int dX = 1, int dY = 1); void Inflate(int dX); void SetAll(int left, int right, int top, int bottom); void GetAll(int & left, int & right, int & top, int & bottom) const; // константный метод void BoundingRect(const Rect & rect1, const Rect & rect2); private: void Normalize(); void Swap(int &a, int &b); }; Rect BoundingRect(Rect rect1, Rect rect2); Rect BoundingRect2(const Rect & rect1, const Rect & rect2);
#include<stdio.h> int max(int a[],int n) { int i,m,ind; m=a[0]; ind=0; for(i=0; i<n; i++) { if(a[i]>m) { m=a[i]; ind=i; } } return ind; } int min(int a[],int n) { int i,m,ind; m=a[0]; ind=0; for(i=0; i<n; i++) { if(a[i]<m) { m=a[i]; ind=i; } } return ind; } int check(int a[],int n,int height) { int i,j; for(i=0;i<n;i++) { if(a[i]!=height) return 0; } return 1; } int main() { int i,j,k,n,a[100],b[100],ind=0,count,sum=0,height,high,low; while(1) { sum=0; scanf("%d",&n); if(n==0) break; for(i=0; i<n; i++) { scanf("%d",&a[i]); sum=sum+a[i]; } height=sum/n; count =0; while(check(a,n,height)!=1) { high = max(a, n); low = min(a, n); k = a[high]-height; a[high]=a[high] - k; if((a[low] + k)<=height) { a[low]=a[low] + k; } else { j=(a[low]+k)-height; a[high]=a[high]+j; k=k-j; a[low]=a[low]+k; } count = count + k; } printf("Set #%d\nThe minimum number of moves is %d.\n\n",ind+1,count); ind++; } return 0; }
// // Example for a DHT11 sensor // #include <Wire.h> #include <dht.h> #define DHT11PIN 8 dht1wire DHT(DHT11PIN, dht::DHT11); void setup() { Serial.begin(9600); Serial.println(F("DHTxx TEST PROGRAM")); } void loop() { unsigned long b = micros(); dht::ReadStatus chk = DHT.read(); unsigned long e = micros(); Serial.print(F("\nRead sensor: ")); switch (chk) { case dht::OK: Serial.print(F("OK, took ")); Serial.print (e - b); Serial.println(F(" usec")); break; case dht::ERROR_CHECKSUM: Serial.println(F("Checksum error")); break; case dht::ERROR_TIMEOUT: Serial.println(F("Timeout error")); break; case dht::ERROR_CONNECT: Serial.println(F("Connect error")); break; case dht::ERROR_ACK_L: Serial.println(F("AckL error")); break; case dht::ERROR_ACK_H: Serial.println(F("AckH error")); break; default: Serial.println(F("Unknown error")); break; } Serial.print(F("Humidity (%): ")); Serial.println(DHT.getHumidity()); Serial.print(F("Temperature (°C): ")); Serial.println(DHT.getTemperature()); Serial.print(F("Dew Point (°C): ")); Serial.println(DHT.dewPoint()); delay(5000); } // // END OF FILE //
#ifndef SINGLETON_HPP #define SINGLETON_HPP #include <atomic> #include <mutex> class Singleton{ public: static Singleton* getInstance(); private: static std::atomic<Singleton*> instance; static std::mutex m_mutex; }; #endif
#include<bits/stdc++.h> using namespace std; // O(n2) and O(1) space int main() { int n; cin >> n; int* arr = new int[n]; for(int i=0;i<n;i++) { cin >> arr[i]; } int i=1; while(i<=n-1) { for(int j=0;j<n-1;j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } i+=1; } for(int i=0;i<n;i++) { cout << arr[i] << " "; } cout << endl; return 0; }
#ifndef TEXT_FIELD #define TEXT_FIELD 1 #include<qlineedit.h> class textField:public QLineEdit{ Q_OBJECT public: textField(QWidget*parent=0); signals: void valueChanged(float); public slots: void setFloat(float); private slots: void text(const QString&); }; #endif
#pragma once /** * \brief Represents one cell in a field */ class Cell { public: Cell(int x, int y); ~Cell(); void PlantMine(); void AddNeighbouringMine(); void Clear(); bool IsMine(); bool IsCleared(); bool IsFlagged(); void DiscoverMine(); int MinesNeighbouring(); void ToggleFlag(); void Blank(); private: int x_; int y_; bool ismine_; bool flagged_; bool cleared_; int minesneighbouring_; };
#include<iostream> #include"Grid.h" Grid::Grid(int X, int Y) { setXY(X, Y); initialize(); } Grid::~Grid() { destroy(); } Grid::Grid(const Grid& other) { copy(other); } Grid& Grid::operator=(const Grid& other) { if (this != &other) { destroy(); copy(other); } return *this; } int Grid::getX() const { return this->x; } int Grid::getY() const { return this->y; } void Grid::setLineY(int Y, std::string line) { if (line.length() != x) { std::cout << "Error: Length of the string is different from x!\n"; return; } for (int i = 0; i < x; i++) { if (line[i] == '0') { cells[Y][i] = Red; } else if (line[i] == '1') { cells[Y][i] = Green; } else { std::cout << "Error: The symbol #" << i << " is different from 0 or 1!\n"; return; } } } void Grid::changeColor(int X, int Y) { cells[X][Y] = !cells[X][Y]; } int Grid::countNeighboursHelper(int X, int Y, Cell color, bool isItInDifferentColumn) const { if (X < 0 || X >= this->x) { return 0; } int count = 0; if (Y - 1 >= 0) { if (cells[X][Y - 1] == color) count++; } if (Y + 1 < this->y) { if (cells[X][Y + 1] == color) count++; } if (isItInDifferentColumn) { if (cells[X][Y] == color) count++; } return count; } int Grid::countNeighbours(int X, int Y, Cell color) const { return countNeighboursHelper(X - 1, Y, color, true) + countNeighboursHelper(X + 1, Y, color, true) + countNeighboursHelper(X, Y, color, false); } bool Grid::rule1(int X, int Y, int greenNeighboursNum) const { if (cells[X][Y] == Green) { return false; } return (greenNeighboursNum == 3 || greenNeighboursNum == 6); } bool Grid::rule3(int X, int Y, int greenNeighboursNum) const { if (cells[X][Y] == Red) { return false; } return (greenNeighboursNum != 2 && greenNeighboursNum != 3 && greenNeighboursNum != 6); } int Grid::calculate(int X, int Y, int N) { int result = 0; int countGreen = countNeighbours(X, Y, Green); for (int i = 0; i <= N; i++) { if (cells[X][Y] == Green) { result++; } if (rule1(X, Y, countGreen) || rule3(X, Y, countGreen)) { changeColor(X, Y); } } return result; } void Grid::initialize() { cells = new Cell*[y]; for (int i = 0; i < y; i++) { cells[i] = new Cell[x]; } } void Grid::setXY(int X, int Y) { this->x = X; this->y = Y; } void Grid::copy(const Grid& other) { setXY(other.x, other.y); initialize(); for (int i = 0; i < y; i++) { for (int j = 0; j < x; j++) { this->cells[i][j] = other.cells[i][j]; } } } void Grid::destroy() { for (int i = 0; i < y; i++) { delete[] cells[i]; } delete[] cells; }
#include "header.h" #include <iostream> #include <string> #include <algorithm> using namespace std; void string_sort(){ string str; cout << "please type a string" << endl; getline(cin,str,'\r'); sort(str.begin(),str.end()); cout << str; }
#include <iostream> #include <string> #include <stdlib.h> #include "battle.h" battle::battle(){ //be careful, think about what might happen if you construct and empty battle array with nothing in it. Remember to take precautions with this (later on though because too lazy). } battle::battle(player user, enemy enemy1){ battlearray=new gameobject[2]; battlearray[0]=user; battlearray[1]=enemy1; currentturn=0; currentlyattacking=0; participants=2; p(); //std::cout << battlearray[0].getname() << " you are now in a battle with a " << battlearray[1].getname() << std::endl; } void battle::battleturn(){ currentturn++; currentlyattacking=currentturn%(participants-1); std::cout << currentturn << std::endl; //if(battlearray[1].dead()==false){ // enemyatk(); //} } /* void battle::checkalive(gameobject obj){ for(int i=0;i<participants;i++){ if(obj.dead()==true){ participants--; } } }*/ void battle::chooseatk(){ std::cout << "which attack would you like to use?" << std::endl; while(ischoosing==true){ std::cin >> atknumber; if(atknumber=="0"){ //could use an attack array here to speed things up ischoosing=false; battlearray[1].takedmg(0); //need to determine an algorithm for damage taken battlearray[0].basicattack(); //this needs to be better defined std::cout<<"Enemy 1 has "<<battlearray[1].check_hp()<<" hp"<<std::endl; //ischoosing=true; } else if(atknumber=="1"){ ischoosing=false; battlearray[1].takedmg(1); battlearray[0].attack1(); std::cout<<"Enemy 1 has "<<battlearray[1].check_hp()<<" hp"<<std::endl; //ischoosing=true; } else if(atknumber=="2"){ ischoosing=false; battlearray[1].takedmg(2); battlearray[0].attack2(); std::cout<<"Enemy 1 has "<<battlearray[1].check_hp()<<" hp"<<std::endl; //ischoosing=true; } else if(atknumber=="3"){ ischoosing=false; battlearray[1].takedmg(3); battlearray[0].attack3(); std::cout<<"Enemy 1 has "<<battlearray[1].check_hp()<<" hp"<<std::endl; //ischoosing=true; } else if(atknumber=="4"){ ischoosing=false; battlearray[1].takedmg(4); battlearray[0].attack4(); std::cout << "Enemy 1 has "<<battlearray[1].check_hp()<<" hp"<<std::endl; //ischoosing=true; } else{ std::cout << "you only have a basic attack (0) and 4 special attacks (1-4) at the moment, please choose a number between 1-4 for your basic attack" << std::endl; } } if(battlearray[1].check_hp()>0){ battleturn(); enemyatk(); } else{ //destroy enemy } } void battle::enemyatk(){ int random=rand()%5; if(random>4||random<0){ std::cout << "Enemy attack error" << std::endl; } else if(random==0){ battlearray[1].basicattack(); battlearray[0].takedmg(0); std::cout<<"Reimu has "<<battlearray[0].check_hp()<<" hp"<<std::endl; } else if(random==1){ battlearray[1].attack1(); battlearray[0].takedmg(1); std::cout<<"Reimu has "<<battlearray[0].check_hp()<<" hp"<<std::endl; } else if(random==2){ battlearray[1].attack2(); battlearray[0].takedmg(2); std::cout<<"Reimu has "<<battlearray[0].check_hp()<<" hp"<<std::endl; } else if(random==3){ battlearray[1].attack3(); battlearray[0].takedmg(3); std::cout<<"Reimu has "<<battlearray[0].check_hp()<<" hp"<<std::endl; } else if(random==4){ battlearray[1].attack4(); battlearray[0].takedmg(4); std::cout<<"Reimu has "<<battlearray[0].check_hp()<<" hp"<<std::endl; } if(battlearray[0].check_hp()>0){ ischoosing=true; chooseatk(); } } void battle::p(){ if(battlearray[1].dead()==false){ // this is no longer needed if the above stuff works chooseatk(); } } battle::~battle(){ delete[] battlearray; } /* Test cases for attacking and taking damage Run game and go through attacks 0-4. Enemy is taking damage accordingly. Type in any other number and it gives the error string. Now to test if it dies? */
#include "04_abstractlistmodel/animallistmodel.h" AnimalListModel::AnimalListModel(QObject *parent) : QAbstractListModel(parent) { } int AnimalListModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return mListAnimals.count(); } QVariant AnimalListModel::data(const QModelIndex &index, int role) const { QVariant var; if(index.isValid()){ if(role == AnimalRoles::ROLE_ANIMAL_NAME){ var = mListAnimals.at(index.row())->getName(); } else if(role == AnimalRoles::ROLE_ANIMAL_COLOR){ var = mListAnimals.at(index.row())->getColor(); } }else{ var = ""; } return var; } void AnimalListModel::addAminal(Animal *pAnimal) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); mListAnimals.append(pAnimal); endInsertRows(); } void AnimalListModel::addAminal(QString name, QString color) { addAminal(new Animal(name, color)); } void AnimalListModel::removeAnimal(int index) { if(mListAnimals.count() > index && index >= 0){ beginRemoveRows(QModelIndex(), index, index); Animal *pAnimal = mListAnimals.at(index); mListAnimals.removeAt(index); delete pAnimal; endRemoveRows(); } } void AnimalListModel::removeAnimal() { if(!mListAnimals.isEmpty()){ removeAnimal(mListAnimals.count() - 1); } } QHash<int, QByteArray> AnimalListModel::roleNames() const { QHash<int, QByteArray> hashRoles; hashRoles.insert(AnimalRoles::ROLE_ANIMAL_NAME, "mName"); hashRoles.insert(AnimalRoles::ROLE_ANIMAL_COLOR, "mColor"); return hashRoles; }
// github.com/andy489 #include <stdio.h> int main() { int n, k; scanf("%d %d", &n, &k); int a[n], i, j; for (i = 0; i < n; ++i) { scanf("%d", a + i); } int c = 0, pg = 1; for (i = 0; i < n; ++i) { for (j = 1; j <= a[i]; ++j) { if (j == pg) ++c; if (j % k == 0 && j < a[i]) ++pg; } ++pg; } printf("%d", c); return 0; }
/************************************************************************* * adamkov Bedside Clock * (c) 2018-2019 * code based on William Moeur's Arduino_ESP8266 examples * https://github.com/moeur/Arduino_ESP8266 *************************************************************************/ /* You must dedicate two GPIO pins to be used to communicate with the tm1637 module * Make sure to connect: * tm1637_clk_pin to the CLK pin on the tm1637 clock module * tm1637_data_pin to the pin on the clock module labeled DIO */ #define tm1637_clk_pin D3 #define tm1637_data_pin D4 #include <ESP8266WiFi.h> #include <ArduinoOTA.h> #include <WiFiUdp.h> #include <Ticker.h> #include <Time.h> #include "ntp.h" #include "TM1637.h" #include "wifi.h" void digitalClockDisplay(); void toggleColon(void); NTP NTPclient; tm1637 display(tm1637_clk_pin, tm1637_data_pin); Ticker clockticker; bool colon = true; bool updateTime = true; #define PST -8 // pacific standard time #define CET 1 // central european time time_t getNTPtime(void) { return NTPclient.getNtpTime(); } void setup() { Serial.begin(9600); Serial.println(); Serial.println(); // Until WiFi is connected display 8008 display.setBrightness(2); display.writeTime(80,8,1); setupWiFi(); // Once WiFi is connected display 0001 display.writeTime(0,1,0); ArduinoOTA.begin(); NTPclient.begin("hu.pool.ntp.org", CET); setSyncInterval(SECS_PER_HOUR); setSyncProvider(getNTPtime); // Once NTP sync is setup display 0002 display.writeTime(0,2,0); clockticker.attach(0.5, toggleColon); } void loop() { if (updateTime) { updateTime = false; if (timeStatus() != timeNotSet) { digitalClockDisplay(); } } ArduinoOTA.handle(); } void digitalClockDisplay() { // digital clock display of the time display.writeTime(hour(), minute(), colon); colon = !colon; } void toggleColon(void) { updateTime = true; }
/********************************************************************************* Pubnub Subscribe *********************************************************************************/ #include <ESP8266WiFi.h> #include "VirtualDelay.h" #include <math.h> VirtualDelay virtualDelay(millis); #include "ShiftRegister74HC595.h" const char* g_ssid = "Dialog 4G"; const char* g_password = "*******"; const char* g_host = "pubsub.pubnub.com"; const char* g_pubKey = "pub-c-89d87bfb-89a1-4ae9-941c-631dd1ea5dbd"; const char* g_subKey = "sub-c-e7c47d7a-13be-11e7-a9ec-0619f8945a4f"; const char* g_channel = "0"; String timeToken = "0"; double temp=0; int soil=0; int rain=0; bool decodePending = true; bool decodePending2 = true; WiFiClient client; //int SER_Pin = 5; //pin 14 on the 75HC595 //int RCLK_Pin = 4; //pin 12 on the 75HC595 //nt SRCLK_Pin = 0; //pin 11 on the 75HC595 /* ShiftRegister74HC595.h - Library for easy control of the 74HC595 shift register. Created by Timo Denk (www.simsso.de), Nov 2014. Additional information are available on http://shiftregister.simsso.de/ Released into the public domain. kaludamalu */ // create shift register object (number of shift registers, data pin, clock pin, latch pin) ShiftRegister74HC595 sr (4, 5, 4, 0); void GET(); void POST(); void getNextTimeToken(String l); void readTemp(); void readRain(); void readSoil(); void decodeLine(String l); void applyChanges(String msg); void setDisplay(int T); void setup() { Serial.begin(9600); Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(g_ssid); WiFi.begin(g_ssid, g_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); sr.setAllLow(); } void loop() { // delay(10); //DATA FORMAT : http://pubsub.pubnub.com /publish/pub-key/sub-key/signature/channel/callback/message //SUB FORMAT : http://pubsub.pubnub.com /subscribe/sub-key/channel/callback/timetoken //if(virtualDelay.done(1000)) readTemp(); readSoil(); readRain(); POST(); delay(1000); GET(); if(temp>33) sr.set(7,HIGH); else sr.set(7,LOW); } void getNextTimeToken(String l){ //l=l.substring(l.lastIndexOf(',')).substring(2,l.length()-2) l=l.substring(l.lastIndexOf(',')); l=l.substring(2,l.length()-2); //Serial.println(l); if(l == timeToken){ timeToken= "0"; } else{ timeToken = l; decodePending=true; } } void decodeLine(String l){ decodePending=false; l = l.substring(4,l.indexOf(',')-2); Serial.println(l); delay(100); applyChanges(l); } void applyChanges(String msg){ for(int i =0 ; i < 8 ; i ++) //Serial.println(msg.charAt(i)); if(msg.charAt(i)=='0') sr.set(i,LOW); else sr.set(i,HIGH); } void POST(){ const int l_httpPort = 80; String puburl = "/publish/"; puburl += g_pubKey; puburl += "/"; puburl += g_subKey; puburl += "/0/"; //puburl += '"'; puburl += g_channel; // puburl += '"'; puburl += "/0/"; puburl += '"'; puburl += (int)temp; puburl += '!'; puburl += soil; puburl += '!'; puburl += rain; puburl += '!'; puburl += '"'; if (!client.connect("pubsub.pubnub.com", 80)) { Serial.println("connection failed"); return; } else{ Serial.println("Connected to PUBNUB PUBLISH"); } client.print(String("GET ") + puburl + " HTTP/1.1\r\n" + "Host: " + g_host + "\r\n"+ "Connection: close\r\n\r\n"); delay(1); while (client.available()) { String line = client.readStringUntil('\r'); if (line.endsWith("]")) { Serial.println(line); } } client.stop(); client.flush(); } void GET(){ String url = "/subscribe/"; url += g_subKey; url += "/"; url += g_channel; url += "/0/"; url += timeToken; //WiFiClient client; const int l_httpPort = 80; if (!client.connect("pubsub.pubnub.com", 80)) { Serial.println("connection failed"); return; } else{ Serial.println("Connected to PUBNUB"); } client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + g_host + "\r\n"+ "Connection: close\r\n\r\n"); delay(1); while (client.available()) { String line = client.readStringUntil('\r'); if (line.endsWith("]")) { Serial.println(line); getNextTimeToken(line); if(decodePending) decodeLine(line); } } client.stop(); client.flush(); } void readTemp(){ int pretemp = temp; sr.set(13,LOW); sr.set(14,LOW); sr.set(15,LOW); delay(100); temp=analogRead(A0); //temp=temp-1024; temp= ((1024-temp)/1024.0 -0.5)*100; if(pretemp != (int)temp) setDisplay(temp); } void readSoil(){ sr.set(13,LOW); sr.set(14,LOW); sr.set(15,HIGH); delay(100); soil=analogRead(A0); } void readRain(){ sr.set(13,LOW); sr.set(14,HIGH); sr.set(15,LOW); delay(100); rain=analogRead(A0); } void setDisplay(int T){ int a = T/10; int b = T%10; switch(b){ case 0: sr.set(28,LOW); sr.set(29,LOW); sr.set(30,LOW); sr.set(31,LOW); break; case 1: sr.set(28,HIGH); sr.set(29,LOW); sr.set(30,LOW); sr.set(31,LOW); break; case 2: sr.set(28,LOW); sr.set(29,HIGH); sr.set(30,LOW); sr.set(31,LOW); break; case 3: sr.set(28,HIGH); sr.set(29,HIGH); sr.set(30,LOW); sr.set(31,LOW); break; case 4: sr.set(28,LOW); sr.set(29,LOW); sr.set(30,HIGH); sr.set(31,LOW); break; case 5: sr.set(28,HIGH); sr.set(29,LOW); sr.set(30,HIGH); sr.set(31,LOW); break; case 6: sr.set(28,LOW); sr.set(29,HIGH); sr.set(30,HIGH); sr.set(31,LOW); break; case 7: sr.set(28,HIGH); sr.set(29,HIGH); sr.set(30,HIGH); sr.set(31,LOW); break; case 8: sr.set(28,LOW); sr.set(29,LOW); sr.set(30,LOW); sr.set(31,HIGH); break; case 9: sr.set(28,HIGH); sr.set(29,LOW); sr.set(30,LOW); sr.set(31,HIGH); break; } switch(a){ case 0: sr.set(24,LOW); sr.set(25,LOW); sr.set(26,LOW); sr.set(27,LOW); break; case 1: sr.set(24,HIGH); sr.set(25,LOW); sr.set(26,LOW); sr.set(27,LOW); break; case 2: sr.set(24,LOW); sr.set(25,HIGH); sr.set(26,LOW); sr.set(27,LOW); break; case 3: sr.set(24,HIGH); sr.set(25,HIGH); sr.set(26,LOW); sr.set(27,LOW); break; case 4: sr.set(24,LOW); sr.set(25,LOW); sr.set(26,HIGH); sr.set(27,LOW); break; case 5: sr.set(24,HIGH); sr.set(25,LOW); sr.set(26,HIGH); sr.set(27,LOW); break; case 6: sr.set(24,LOW); sr.set(25,HIGH); sr.set(26,HIGH); sr.set(27,LOW); break; case 7: sr.set(24,HIGH); sr.set(25,HIGH); sr.set(26,HIGH); sr.set(27,LOW); break; case 8: sr.set(24,LOW); sr.set(25,LOW); sr.set(26,LOW); sr.set(27,HIGH); break; case 9: sr.set(24,HIGH); sr.set(25,LOW); sr.set(26,LOW); sr.set(27,HIGH); break; } }
#include <bits/stdc++.h> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define max(a,b)(a>b?a:b) #define min(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define PI acos(0)*2.0 #define eps 1.0e-9 #define are_equal(a,b)fabs(a-b)<eps #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int,int> ii; typedef pair<int,char> ic; typedef pair<long,char> lc; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);} int lcm(int a,int b){return a*(b/gcd(a,b));} int main(){ string s = "dir1\n dir11\n dir12\n picture.jpeg\n dir121\n file1.txt\ndir2\n file2.gif\n"; string images[3] = {"jpeg", "gif", "png"}; vector<string> stk; int i = 0, j; int spc = 0; int stklen = 0, maxlen = 0; for (; i < s.size();) { stringstream ss(""); int dir = 1, img = 0, space = 0; for (j = i; j < s.size(); j++) { if (s[j] == ' ') { space++; continue; } if (s[j] == '.') { ss << s[j]; dir = 0; int k = j+1; stringstream ss1(""); for (; k < s.size(); k++) { if ('a' <= s[k] && s[k] <= 'z') ss1 << s[k]; else break; } string tmp1 = ss1.str(); for (int l = 0; l < 3; l++) if (images[l] == tmp1) { img = 1; ss << tmp1; } j = k-1; continue; } if (s[j] == '\n') { string tmp = ss.str(); if (dir) { if (space > spc) { stk.push_back(tmp); stklen += tmp.size() + 1; spc++; } else { while (spc > space) { stklen -= (stk.back().size() + 1); stk.pop_back(); spc--; } if (stk.size() > 0) { stklen -= (stk.back().size() + 1); stk.pop_back(); spc--; } stk.push_back(tmp); stklen += tmp.size() + 1; } break; } if (img) { int len = stklen + tmp.size() + 1; maxlen = max(maxlen, len); break; } break; } else ss << s[j]; } i = j+1; } cout << maxlen << endl; return 0; }
/************************************************************* * > File Name : P2176.cpp * > Author : Tony * > Created Time : 2019年01月22日 星期二 15时51分24秒 **************************************************************/ #include<bits/stdc++.h> using namespace std; const int maxn = 110; const int maxm = 5010; struct Edge { int to, nxt, l; }edge[maxm << 1]; int head[maxn], cnt; void add(int a, int b, int l) { edge[cnt].to = b; edge[cnt].nxt = head[a]; edge[cnt].l = l; head[a] = cnt; cnt++; } int n, m, ai, bi, li, dx[maxm], dy[maxm], ans = -1, dist[maxn], p[maxm], sum; struct heap { int u, d; bool operator < (const heap& a) const { return d < a.d; } }; void Dijkstra() { priority_queue<heap> q; for (int i = 0; i <= n; ++i) dist[i] = INT_MAX; dist[1] = 0; q.push((heap){1, 0}); while (!q.empty()) { heap top = q.top(); q.pop(); int tx = top.u; int td = top.d; if (td != dist[tx]) continue; for (int i = head[tx]; i; i = edge[i].nxt) { int v = edge[i].to; if (dist[v] > dist[tx] + edge[i].l) { dist[v] = dist[tx] + edge[i].l; dy[v] = i; dx[v] = tx; q.push((heap){v, dist[v]}); } } } } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= m; ++i) { scanf("%d %d %d", &ai, &bi, &li); add(ai, bi, li); add(bi, ai, li); } Dijkstra(); int old = dist[n]; int q = n; while (q != 1) { p[++sum] = dy[q]; q = dx[q]; } for (int i = 1; i <= sum; ++i) { edge[p[i]].l *= 2; edge[p[i] ^ 1].l *= 2; Dijkstra(); ans = max(ans, dist[n]); edge[p[i]].l /= 2; edge[p[i] ^ 1].l /= 2; } // printf("%d %d\n", ans, old); printf("%d\n", ans - old); return 0; }
#include <windows.h> #include <vector> #include <cstdint> #include <algorithm> #include <functional> #include <string> #include "ReClassNET_Plugin.hpp" bool IsValidMemoryRange(LPCVOID address, int length) { const auto endAddress = static_cast<const uint8_t*>(address) + length; do { MEMORY_BASIC_INFORMATION info; if (!VirtualQuery(address, &info, sizeof(MEMORY_BASIC_INFORMATION))) { return false; } if (info.State != MEM_COMMIT) { return false; } switch (info.Protect) { case PAGE_EXECUTE_READ: case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: case PAGE_READONLY: case PAGE_READWRITE: case PAGE_WRITECOPY: break; default: return false; } address = static_cast<uint8_t*>(info.BaseAddress) + info.RegionSize; } while (endAddress > address); return true; } //--------------------------------------------------------------------------- bool ReadMemory(LPCVOID address, std::vector<uint8_t>& buffer) { if (!IsValidMemoryRange(address, static_cast<int>(buffer.size()))) { return false; } std::memcpy(buffer.data(), address, buffer.size()); return true; } //--------------------------------------------------------------------------- bool WriteMemory(LPVOID address, const std::vector<uint8_t>& buffer) { if (!IsValidMemoryRange(address, static_cast<int>(buffer.size()))) { return false; } DWORD oldProtect; if (VirtualProtect(address, buffer.size(), PAGE_EXECUTE_READWRITE, &oldProtect)) { std::memcpy(address, buffer.data(), buffer.size()); VirtualProtect(address, buffer.size(), oldProtect, nullptr); return true; } return false; } //--------------------------------------------------------------------------- void EnumerateRemoteSectionsAndModules(const std::function<void(RC_Pointer, RC_Pointer, std::wstring&&)>& moduleCallback, const std::function<void(RC_Pointer, RC_Pointer, SectionType, SectionCategory, SectionProtection, std::wstring&&, std::wstring&&)>& sectionCallback) { std::vector<EnumerateRemoteSectionData> sections; // First enumerate all memory sections. MEMORY_BASIC_INFORMATION memInfo = { }; memInfo.RegionSize = 0x1000; size_t address = 0; while (VirtualQuery(reinterpret_cast<LPCVOID>(address), &memInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0 && address + memInfo.RegionSize > address) { if (memInfo.State == MEM_COMMIT) { EnumerateRemoteSectionData section = {}; section.BaseAddress = memInfo.BaseAddress; section.Size = memInfo.RegionSize; switch (memInfo.Protect & 0xFF) { case PAGE_EXECUTE: section.Protection = SectionProtection::Execute; break; case PAGE_EXECUTE_READ: section.Protection = SectionProtection::Execute | SectionProtection::Read; break; case PAGE_EXECUTE_READWRITE: case PAGE_EXECUTE_WRITECOPY: section.Protection = SectionProtection::Execute | SectionProtection::Read | SectionProtection::Write; break; case PAGE_NOACCESS: section.Protection = SectionProtection::NoAccess; break; case PAGE_READONLY: section.Protection = SectionProtection::Read; break; case PAGE_READWRITE: case PAGE_WRITECOPY: section.Protection = SectionProtection::Read | SectionProtection::Write; break; } if ((memInfo.Protect & PAGE_GUARD) == PAGE_GUARD) { section.Protection |= SectionProtection::Guard; } switch (memInfo.Type) { case MEM_IMAGE: section.Type = SectionType::Image; break; case MEM_MAPPED: section.Type = SectionType::Mapped; break; case MEM_PRIVATE: section.Type = SectionType::Private; break; } section.Category = section.Type == SectionType::Private ? SectionCategory::HEAP : SectionCategory::Unknown; sections.push_back(std::move(section)); } address = reinterpret_cast<size_t>(memInfo.BaseAddress) + memInfo.RegionSize; } struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; }; struct LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID BaseAddress; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; LIST_ENTRY HashTableEntry; ULONG TimeDateStamp; }; struct PEB_LDR_DATA { ULONG Length; BOOLEAN Initialized; PVOID SsHandle; LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; }; struct PEB { BOOLEAN InheritedAddressSpace; BOOLEAN ReadImageFileExecOptions; BOOLEAN BeingDebugged; BOOLEAN Spare; HANDLE Mutant; PVOID ImageBaseAddress; PEB_LDR_DATA *LoaderData; }; // Second enumerate all modules. #ifdef _WIN64 const auto peb = reinterpret_cast<PEB*>(__readgsqword(0x60)); #else const auto peb = reinterpret_cast<PEB*>(__readfsdword(0x30)); #endif auto ldr = reinterpret_cast<LDR_MODULE*>(peb->LoaderData->InLoadOrderModuleList.Flink); while (ldr->BaseAddress != nullptr) { moduleCallback(static_cast<RC_Pointer>(ldr->BaseAddress), reinterpret_cast<RC_Pointer>(static_cast<intptr_t>(ldr->SizeOfImage)), ldr->FullDllName.Buffer); const auto it = std::lower_bound(std::begin(sections), std::end(sections), ldr->BaseAddress, [&sections](const auto& lhs, const LPVOID& rhs) { return lhs.BaseAddress < rhs; }); const auto dosHeader = reinterpret_cast<IMAGE_DOS_HEADER*>(ldr->BaseAddress); const auto ntHeader = reinterpret_cast<IMAGE_NT_HEADERS*>(reinterpret_cast<intptr_t>(ldr->BaseAddress) + dosHeader->e_lfanew); int i = 0; for (auto sectionHeader = IMAGE_FIRST_SECTION(ntHeader); i < ntHeader->FileHeader.NumberOfSections; i++, sectionHeader++) { const auto sectionAddress = reinterpret_cast<intptr_t>(ldr->BaseAddress) + static_cast<intptr_t>(sectionHeader->VirtualAddress); for (auto j = it; j != std::end(sections); ++j) { if (sectionAddress >= reinterpret_cast<intptr_t>(j->BaseAddress) && sectionAddress < reinterpret_cast<intptr_t>(j->BaseAddress) + static_cast<intptr_t>(j->Size)) { // Copy the name because it is not null padded. char buffer[IMAGE_SIZEOF_SHORT_NAME + 1] = { 0 }; std::memcpy(buffer, sectionHeader->Name, IMAGE_SIZEOF_SHORT_NAME); if (std::strcmp(buffer, ".text") == 0 || std::strcmp(buffer, "code") == 0) { j->Category = SectionCategory::CODE; } else if (std::strcmp(buffer, ".data") == 0 || std::strcmp(buffer, "data") == 0 || std::strcmp(buffer, ".rdata") == 0 || std::strcmp(buffer, ".idata") == 0) { j->Category = SectionCategory::DATA; } size_t convertedChars = 0; mbstowcs_s(&convertedChars, j->Name, IMAGE_SIZEOF_SHORT_NAME, buffer, _TRUNCATE); std::memcpy(j->ModulePath, ldr->FullDllName.Buffer, sizeof(EnumerateRemoteSectionData::ModulePath)); break; } } } ldr = reinterpret_cast<LDR_MODULE*>(ldr->InLoadOrderModuleList.Flink); } for (auto&& section : sections) { sectionCallback(section.BaseAddress, reinterpret_cast<RC_Pointer>(section.Size), section.Type, section.Category, section.Protection, section.Name, section.ModulePath); } } //---------------------------------------------------------------------------
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct book { char bookTitle[20]; char nameOfAuthor[20]; int volumes; book* next; }book; book* library = NULL; //global variable void addBook() { char bookName[20]; char author[20]; printf("Input Book title: "); scanf("%s", bookName); printf("Input Author: "); scanf("%s", author); if (library == NULL) //library에 book이 없는경우. { library = (book*)malloc(sizeof(book)); book* newBook = (book*)malloc(sizeof(book)); strcpy(newBook->bookTitle, bookName); strcpy(newBook->nameOfAuthor, author); newBook->volumes = 1; newBook->next =NULL; library->next = newBook; } else { //library에 1권이상 있는경우. book* curPos = library->next; //리스트 탐색할 변수 int check = 0; while (curPos != NULL) { if (strcmp(bookName, curPos->bookTitle) ==0) //library에 책이 있는경우. { if (strcmp(curPos->nameOfAuthor, author) ==0) //저자 이름도 같은경우 한권을 더해준다. { curPos->volumes += 1; check = 1; break; } } curPos = curPos->next; } if (!check) //같은 이름의 책이 없는경우 + 같은이름의 책은 있지만 저자이름이 다른경우. 마지막에 새로운 book추가 { curPos = library; book* newBook = (book*)malloc(sizeof(book)); strcpy(newBook->bookTitle, bookName); strcpy(newBook->nameOfAuthor, author); newBook->volumes = 1; newBook->next =NULL; while (curPos->next != NULL) curPos = curPos->next; curPos->next = newBook; } } printf("================================================\n"); printf("The book entitled %s is added to the library\n", bookName); printf("================================================\n"); } void bookbyAuthor() { if(library ==NULL) { printf("Doesn't exist author\n"); return; } book* curPos =library->next; char author[20]; int check =0; printf("Input Author: "); scanf("%s", author); while (curPos !=NULL) { /* printf("library의 저자: %s\n", curPos->nameOfAuthor); printf("원하는 저자: %s\n", author); */ if (strcmp(author, curPos->nameOfAuthor) ==0) //library에 같은이름의 저자가 있으면 출력. { printf("================================================\n"); printf("Book title: %s\n", curPos->bookTitle); printf("Author information: %s\n", curPos->nameOfAuthor); printf("Number of books in the library: %d\n", curPos->volumes); printf("================================================\n\n\n"); check =1; } curPos = curPos->next; } if(check ==0) printf("Doesn't exist author: %s\n", author); } void countBooks() { if (library == NULL) //library가 NULL이면 1권도 없는경우. { printf("================================================\n"); printf("total number of books in the library: 0\n"); printf("================================================\n"); return; } int sum = 0; book* curPos = library->next; while (curPos != NULL) { sum += curPos->volumes; curPos = curPos->next; } printf("================================================\n"); printf("total number of books in the library: %d\n", sum); printf("================================================\n"); } void borrowBook() { if(library ==NULL) { printf("there isn't any books!\n"); return; } char bookName[20]; int check = 0; //책이 library에 있는지 확인하는 변수 없으면0, 있으면1 book* curPos = library->next; printf("Input Book title: "); scanf("%s", bookName); while (curPos !=NULL) { if (strcmp(bookName, curPos->bookTitle) ==0) //책이 library에 등록되어 있는경우 { check =1; if (curPos->volumes ==0) //책이 1권이상 있는경우(0이 아닌경우) { printf("================================================\n"); printf("Oops! Sorry. All books in the library are currently on loan.\n"); printf("================================================\n"); }else { printf("================================================\n"); printf("You should return the book within next 30 days. Here is is.\n"); printf("================================================\n"); curPos->volumes -= 1; } break; } curPos = curPos->next; } if(check ==0) //원하는 책이 아예없는경우. { printf("================================================\n"); printf("The book that you have requested is not currently available.\n"); printf("================================================\n"); } } /* void print() { book* cur =library->next; while(cur !=NULL) { printf("%s\n", cur->bookTitle); cur = cur->next; } } */ int main() { int menu; while (1) { printf("1. Add a new Book\n"); printf("2. Display all the books in the library of a particular author\n"); printf("3. Display the total number of books in the library\n"); printf("4. Borrow a book\n"); printf("0. Quit program\n\n"); printf("--> Choose a menu in the list:"); scanf("%d", &menu); switch (menu) { case 0: return 0; case 1: addBook(); break; case 2: bookbyAuthor(); break; case 3: countBooks(); break; case 4: borrowBook(); break; default: printf("You have input a wrong number\n"); continue; } } }
/*************************************************************************** Copyright (c) 2020 Philip Fortier 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. ***************************************************************************/ // SCIFontDialog.cpp : implementation file // #include "stdafx.h" #include "AppState.h" #include "SCIFontDialog.h" // CSCIFontDialog IMPLEMENT_DYNAMIC(CSCIFontDialog, CFontDialog) CSCIFontDialog::CSCIFontDialog(LPLOGFONT lplfInitial, DWORD dwFlags, CDC* pdcPrinter, CWnd* pParentWnd) : CFontDialog(lplfInitial, dwFlags, pdcPrinter, pParentWnd) { } CSCIFontDialog::~CSCIFontDialog() { } BEGIN_MESSAGE_MAP(CSCIFontDialog, CFontDialog) END_MESSAGE_MAP() // CSCIFontDialog message handlers
#include "ProtoManager.h" #include "Log.h" #include "Testing.h" #include "Crypt.h" #include "FileUtils.h" #include "StringUtils.h" #include "IniFile.h" ProtoManager ProtoMngr; template< class T > static void WriteProtosToBinary( UCharVec& data, const map< hash, T* >& protos ) { WriteData( data, (uint) protos.size() ); for( auto& kv : protos ) { hash proto_id = kv.first; ProtoEntity* proto_item = kv.second; WriteData( data, proto_id ); WriteData( data, (ushort) proto_item->Components.size() ); for( hash component : proto_item->Components ) WriteData( data, component ); PUCharVec* props_data; UIntVec* props_data_sizes; proto_item->Props.StoreData( true, &props_data, &props_data_sizes ); WriteData( data, (ushort) props_data->size() ); for( size_t i = 0; i < props_data->size(); i++ ) { uint cur_size = props_data_sizes->at( i ); WriteData( data, cur_size ); WriteDataArr( data, props_data->at( i ), cur_size ); } } } template< class T > static void ReadProtosFromBinary( UCharVec& data, uint& pos, map< hash, T* >& protos ) { PUCharVec props_data; UIntVec props_data_sizes; uint protos_count = ReadData< uint >( data, pos ); for( uint i = 0; i < protos_count; i++ ) { hash proto_id = ReadData< hash >( data, pos ); T* proto = new T( proto_id ); ushort components_count = ReadData< ushort >( data, pos ); for( ushort j = 0; j < components_count; j++ ) proto->Components.insert( ReadData< hash >( data, pos ) ); uint data_count = ReadData< ushort >( data, pos ); props_data.resize( data_count ); props_data_sizes.resize( data_count ); for( uint j = 0; j < data_count; j++ ) { props_data_sizes[ j ] = ReadData< uint >( data, pos ); props_data[ j ] = ReadDataArr< uchar >( data, props_data_sizes[ j ], pos ); } proto->Props.RestoreData( props_data, props_data_sizes ); RUNTIME_ASSERT( !protos.count( proto_id ) ); protos.insert( std::make_pair( proto_id, proto ) ); } } static void InsertMapValues( const StrMap& from_kv, StrMap& to_kv, bool overwrite ) { for( auto& kv : from_kv ) { RUNTIME_ASSERT( !kv.first.empty() ); if( kv.first[ 0 ] != '$' ) { if( overwrite ) to_kv[ kv.first ] = kv.second; else to_kv.insert( std::make_pair( kv.first, kv.second ) ); } else if( kv.first == "$Components" && !kv.second.empty() ) { if( !to_kv.count( "$Components" ) ) to_kv[ "$Components" ] = kv.second; else to_kv[ "$Components" ] += " " + kv.second; } } } #pragma warning( disable : 4503 ) template< class T > static int ParseProtos( const string& ext, const string& app_name, map< hash, T* >& protos ) { int errors = 0; // Collect data FileCollection files( ext ); map< hash, StrMap > files_protos; map< hash, map< string, StrMap > > files_texts; while( files.IsNextFile() ) { string proto_name; File& file = files.GetNextFile( &proto_name ); if( !file.IsLoaded() ) { WriteLog( "Unable to open file '{}'.\n", proto_name ); errors++; continue; } IniFile fopro; fopro.AppendStr( file.GetCStr() ); PStrMapVec protos_data; fopro.GetApps( app_name, protos_data ); if( std::is_same< T, ProtoMap >::value && protos_data.empty() ) fopro.GetApps( "Header", protos_data ); for( auto& pkv : protos_data ) { auto& kv = *pkv; const string& name = ( kv.count( "$Name" ) ? kv[ "$Name" ] : proto_name ); hash pid = _str( name ).toHash(); if( files_protos.count( pid ) ) { WriteLog( "Proto '{}' already loaded.\n", name ); errors++; continue; } files_protos.insert( std::make_pair( pid, kv ) ); StrSet apps; fopro.GetAppNames( apps ); for( auto& app_name : apps ) { if( app_name.size() == 9 && app_name.find( "Text_" ) == 0 ) { if( !files_texts.count( pid ) ) { map< string, StrMap > texts; files_texts.insert( std::make_pair( pid, texts ) ); } files_texts[ pid ].insert( std::make_pair( app_name, fopro.GetApp( app_name ) ) ); } } } if( protos_data.empty() ) { WriteLog( "File '{}' does not contain any proto.\n", proto_name ); errors++; } } if( errors ) return errors; // Injection auto injection = [ &files_protos, &errors ] ( const char* key_name, bool overwrite ) { for( auto& inject_kv : files_protos ) { if( inject_kv.second.count( key_name ) ) { for( auto& inject_name : _str( inject_kv.second[ key_name ] ).split( ' ' ) ) { if( inject_name == "All" ) { for( auto& kv : files_protos ) if( kv.first != inject_kv.first ) InsertMapValues( inject_kv.second, kv.second, overwrite ); } else { hash inject_name_hash = _str( inject_name ).toHash(); if( !files_protos.count( inject_name_hash ) ) { WriteLog( "Proto '{}' not found for injection from proto '{}'.\n", inject_name.c_str(), _str().parseHash( inject_kv.first ) ); errors++; continue; } InsertMapValues( inject_kv.second, files_protos[ inject_name_hash ], overwrite ); } } } } }; injection( "$Inject", false ); if( errors ) return errors; // Protos for( auto& kv : files_protos ) { hash pid = kv.first; string base_name = _str().parseHash( pid ); RUNTIME_ASSERT( protos.count( pid ) == 0 ); // Fill content from parents StrMap final_kv; std::function< bool(const string&, StrMap&) > fill_parent = [ &fill_parent, &base_name, &files_protos, &final_kv ] ( const string &name, StrMap & cur_kv ) { const char* parent_name_line = ( cur_kv.count( "$Parent" ) ? cur_kv[ "$Parent" ].c_str() : "" ); for( auto& parent_name : _str( parent_name_line ).split( ' ' ) ) { hash parent_pid = _str( parent_name ).toHash(); auto parent = files_protos.find( parent_pid ); if( parent == files_protos.end() ) { if( base_name == name ) WriteLog( "Proto '{}' fail to load parent '{}'.\n", base_name, parent_name ); else WriteLog( "Proto '{}' fail to load parent '{}' for proto '{}'.\n", base_name, parent_name, name ); return false; } if( !fill_parent( parent_name, parent->second ) ) return false; InsertMapValues( parent->second, final_kv, true ); } return true; }; if( !fill_parent( base_name, kv.second ) ) { errors++; continue; } // Actual content InsertMapValues( kv.second, final_kv, true ); // Final injection injection( "$InjectOverride", true ); if( errors ) return errors; // Create proto T* proto = new T( pid ); if( !proto->Props.LoadFromText( final_kv ) ) { WriteLog( "Proto item '{}' fail to load properties.\n", base_name ); errors++; continue; } // Components if( final_kv.count( "$Components" ) ) { for( const string& component_name : _str( final_kv[ "$Components" ] ).split( ' ' ) ) { hash component_name_hash = _str( component_name ).toHash(); if( !proto->Props.GetRegistrator()->IsComponentRegistered( component_name_hash ) ) { WriteLog( "Proto item '{}' invalid component '{}'.\n", base_name, component_name ); errors++; continue; } proto->Components.insert( component_name_hash ); } } // Add to collection protos.insert( std::make_pair( pid, proto ) ); } if( errors ) return errors; // Texts for( auto& kv : files_texts ) { T* proto = protos[ kv.first ]; RUNTIME_ASSERT( proto ); for( auto& text : kv.second ) { FOMsg temp_msg; temp_msg.LoadFromMap( text.second ); FOMsg* msg = new FOMsg(); uint str_num = 0; while( ( str_num = temp_msg.GetStrNumUpper( str_num ) ) ) { uint count = temp_msg.Count( str_num ); uint new_str_num = str_num; if( std::is_same< T, ProtoItem >::value ) new_str_num = ITEM_STR_ID( proto->ProtoId, str_num ); else if( std::is_same< T, ProtoCritter >::value ) new_str_num = CR_STR_ID( proto->ProtoId, str_num ); else if( std::is_same< T, ProtoLocation >::value ) new_str_num = LOC_STR_ID( proto->ProtoId, str_num ); for( uint n = 0; n < count; n++ ) msg->AddStr( new_str_num, temp_msg.GetStr( str_num, n ) ); } proto->TextsLang.push_back( *(uint*) text.first.substr( 5 ).c_str() ); proto->Texts.push_back( msg ); } } return errors; } void ProtoManager::ClearProtos() { for( auto& proto : itemProtos ) proto.second->Release(); itemProtos.clear(); for( auto& proto : crProtos ) proto.second->Release(); crProtos.clear(); for( auto& proto : mapProtos ) proto.second->Release(); mapProtos.clear(); for( auto& proto : locProtos ) proto.second->Release(); locProtos.clear(); } bool ProtoManager::LoadProtosFromFiles() { WriteLog( "Load prototypes...\n" ); ClearProtos(); // Load protos int errors = 0; errors += ParseProtos( "foitem", "ProtoItem", itemProtos ); errors += ParseProtos( "focr", "ProtoCritter", crProtos ); errors += ParseProtos( "fomap", "ProtoMap", mapProtos ); errors += ParseProtos( "foloc", "ProtoLocation", locProtos ); if( errors ) return false; // Mapper collections #ifdef FONLINE_EDITOR for( auto& kv : itemProtos ) { ProtoItem* proto_item = (ProtoItem*) kv.second; if( !proto_item->Components.empty() ) proto_item->CollectionName = _str().parseHash( *proto_item->Components.begin() ).lower(); else proto_item->CollectionName = "other"; } for( auto& kv : crProtos ) { ProtoCritter* proto_cr = (ProtoCritter*) kv.second; proto_cr->CollectionName = "all"; } #endif // Check player proto if( !crProtos.count( _str( "Player" ).toHash() ) ) { WriteLog( "Player proto 'Player.focr' not loaded.\n" ); errors++; } if( errors ) return false; // Check maps for locations for( auto& kv : locProtos ) { CScriptArray* map_pids = kv.second->GetMapProtos(); for( uint i = 0, j = map_pids->GetSize(); i < j; i++ ) { hash map_pid = *(hash*) map_pids->At( i ); if( !mapProtos.count( map_pid ) ) { WriteLog( "Proto map '{}' not found for proto location '{}'.\n", _str().parseHash( map_pid ), kv.second->GetName() ); errors++; } } map_pids->Release(); } if( errors ) return false; // Load maps data #if defined ( FONLINE_SERVER ) || defined ( FONLINE_EDITOR ) for( auto& kv : mapProtos ) { if( !kv.second->Load_Server() ) { WriteLog( "Load proto map '{}' fail.\n", kv.second->GetName() ); errors++; } } if( errors ) return false; #endif WriteLog( "Load prototypes complete, count {}.\n", (uint) ( itemProtos.size() + crProtos.size() + mapProtos.size() + locProtos.size() ) ); return true; } void ProtoManager::GetBinaryData( UCharVec& data ) { data.clear(); WriteProtosToBinary( data, itemProtos ); WriteProtosToBinary( data, crProtos ); WriteProtosToBinary( data, mapProtos ); WriteProtosToBinary( data, locProtos ); Crypt.Compress( data ); } void ProtoManager::LoadProtosFromBinaryData( UCharVec& data ) { ClearProtos(); if( data.empty() ) return; if( !Crypt.Uncompress( data, 15 ) ) return; uint pos = 0; ReadProtosFromBinary( data, pos, itemProtos ); ReadProtosFromBinary( data, pos, crProtos ); ReadProtosFromBinary( data, pos, mapProtos ); ReadProtosFromBinary( data, pos, locProtos ); } template< typename T > static int ValidateProtoResourcesExt( map< hash, T* >& protos, HashSet& hashes ) { int errors = 0; for( auto& kv : protos ) { T* proto = kv.second; PropertyRegistrator* registrator = proto->Props.GetRegistrator(); for( uint i = 0; i < registrator->GetCount(); i++ ) { Property* prop = registrator->Get( i ); if( prop->IsResource() ) { hash h = proto->Props.template GetPropValue< hash >( prop ); if( h && !hashes.count( h ) ) { WriteLog( "Resource '{}' not found for property '{}' in prototype '{}'.\n", _str().parseHash( h ), prop->GetName(), proto->GetName() ); errors++; } } } } return errors; } bool ProtoManager::ValidateProtoResources( StrVec& resource_names ) { HashSet hashes; for( auto& name : resource_names ) hashes.insert( _str( name ).toHash() ); int errors = 0; errors += ValidateProtoResourcesExt( itemProtos, hashes ); errors += ValidateProtoResourcesExt( crProtos, hashes ); errors += ValidateProtoResourcesExt( mapProtos, hashes ); errors += ValidateProtoResourcesExt( locProtos, hashes ); return errors == 0; } ProtoItem* ProtoManager::GetProtoItem( hash pid ) { auto it = itemProtos.find( pid ); return it != itemProtos.end() ? it->second : nullptr; } ProtoCritter* ProtoManager::GetProtoCritter( hash pid ) { auto it = crProtos.find( pid ); return it != crProtos.end() ? it->second : nullptr; } ProtoMap* ProtoManager::GetProtoMap( hash pid ) { auto it = mapProtos.find( pid ); return it != mapProtos.end() ? it->second : nullptr; } ProtoLocation* ProtoManager::GetProtoLocation( hash pid ) { auto it = locProtos.find( pid ); return it != locProtos.end() ? it->second : nullptr; }
#include <iostream> using namespace std; int main(int argc, char *argv[]) { unsigned long long t, a, b; cin >> t; for (unsigned long long i = 0; i < t; i++){ cin >> a >> b; if (a > b) cout << ">\n"; else if (a < b) cout << "<\n"; else cout << "=\n"; } return 0; }
// This file has been generated by Py++. #ifndef _PropertyInitialiser__value_traits_pypp_hpp_hpp__pyplusplus_wrapper #define _PropertyInitialiser__value_traits_pypp_hpp_hpp__pyplusplus_wrapper namespace boost { namespace python { namespace indexing { template<> struct value_traits< CEGUI::PropertyInitialiser >{ static bool const equality_comparable = false; static bool const less_than_comparable = false; template<typename PythonClass, typename Policy> static void visit_container_class(PythonClass &, Policy const &){ } }; }/*indexing*/ } /*python*/ } /*boost*/ #endif//_PropertyInitialiser__value_traits_pypp_hpp_hpp__pyplusplus_wrapper
#ifndef _FITMODEL_H_ #define _FITMODEL_H_ #include<iostream> #include<vector> #include<string> #include <algorithm> #include <Rinternals.h> enum MODEL{ DISEASE=0, HETERO=1, QT=2 }; enum HYPOTHESIS{ H0, H1 }; using namespace std; extern "C"{ class CNV_signal { public: int nind, ncomp, length, ncohorts; double likelihood, rms; double * temp; double * posterior; double * u; double * logp; //loglikelihood double * weights; double * newWeights; double * Xb; double * proba_disease; int * cn; int * individual; // Prior values double mean_p; double shrinkage; double dof; double scale; double * fitted; double * residuals; int * stratum; const int * cohort; const double * signal; const double * disease_status; double * mean; double * variance; double * nu; double * alpha; const double * offset; const double * X_mean; const double * X_variance; const double * X_disease; int designColMeans, designColVariances, designColDisease; MODEL model; HYPOTHESIS hypothesis; double logP_threshold; double min_n; const int * variance_strata; int nstrat_var; const int * mean_strata; int nstrat_mean; const int * assoc_strata; int nstrat_assoc; vector<double> max_logP, proba_not_outlier; //for each individual stores the maximum logp //vector<double> postLogit; //vector< vector<double> > postLogit2, proba_d; vector< vector<double> > variances, means, alphas, nus, postTable; //depends on batch and copy number CNV_signal (const int nind, const int ncomp, const int * cohort, const double * signal, const double * disease, const double * mean, const double * variance, const double * nu, const double * alpha, const double * offset, const double * design_mean, const double * design_var, const double * design_disease, const int designColMeans_a, const int designColVariances_a, const int designColDisease_a, MODEL m, HYPOTHESIS h, const double logP_threshold_a, const double min_n_a, const int * variance_strata_a, const int nstrat_var_a, const int * mean_strata_a, const int nstrat_mean_a, const int * assoc_strata_a, const int nstrat_assoc_a ); ~CNV_signal (); double GetLogLikelihood() const; vector<double> GetPosterior() const; void ComputePosterior(); // alpha/disease model void MaximizeAlpha(const int& t); void MaximizeAlpha(); void MaximizeDisease(); void MaximizeQuantitativeTrait(); // Gaussian specific functions void ExpectationG(); void MaximizeMeansG(); void MaximizeVariancesG(); void MaximizeMeansPosteriorG(); void MaximizeVariancesPosteriorG(const int& t); // t distribution specific functions double logpT(double x, double mu, double var, double nu); void ExpectationT(); void MaximizeMeansT(const int& t); void MaximizeVariancesT(const int& t); void MaximizeNuT(const int& t); void FillGaps(); void Check_order(); void Print() const; void PrintOneLine(const int i) const; void PrintParams() const; }; } class myRank { public: vector<double> index; int operator()(int i1, int i2) const { return(index[i1] < index[i2]); } void get_orders(vector<int> & w) const { w.assign(index.size(), 0); for (int i = 0; i != (int) index.size(); i++) w[i] = i; std::sort(w.begin(), w.end(), *this); } myRank (vector<double> & index_a): index (index_a) {}; }; #endif
#include "gltools_Renderable.hpp" #include <mutex> #include <sstream> #include "gltools_Loader.hpp" #include "cpptools_Logger.hpp" #include "cpptools_Strings.hpp" #include "Settings.hpp" #include "helpers/Consts.hpp" #include "helpers/GLAssert.hpp" namespace imog { // * static // ====================================================================== // // ====================================================================== // // Global Renderable objects counter // ====================================================================== // unsigned int Renderable::g_RenderablesLastID{0u}; // ====================================================================== // // ====================================================================== // // Global pool for renderables // ====================================================================== // std::vector<std::shared_ptr<Renderable>> Renderable::pool{}; std::unordered_map<std::string, unsigned int> Renderable::poolIndices{}; // ====================================================================== // // ====================================================================== // // Get a shared ptr to Renderable obj from global pool // by name // ====================================================================== // std::shared_ptr<Renderable> Renderable::getByName(const std::string& name) { auto _name = Strings::toLower(name); if (poolIndices.count(_name) > 0) { return pool[poolIndices[_name]]; } LOGE("Zero entries @ renderables pool with name {}.", name); return nullptr; } // ====================================================================== // // ====================================================================== // // Create a new Renderable if it isn't on the gloabl pool // ====================================================================== // std::shared_ptr<Renderable> Renderable::create(bool allowGlobalDraw, const std::string& name, const std::string& objFilePath, const std::string& texturePath, const glm::vec3& color, const std::shared_ptr<Shader>& shader, bool culling) { auto _name = Strings::toLower(name); pool.push_back(std::make_shared<Renderable>(allowGlobalDraw, _name, objFilePath, texturePath, color, shader, culling)); poolIndices[_name] = pool.size() - 1; return pool.at(poolIndices[_name]); } // ====================================================================== // // ====================================================================== // // Draw all renderables of the pool // ====================================================================== // void Renderable::poolDraw(const std::shared_ptr<Camera>& camera) { for (const auto& r : Renderable::pool) { if (r->globalDraw) r->draw(camera); } } // * public // ====================================================================== // // ====================================================================== // // Param constructor w/o OBJ file // ====================================================================== // Renderable::Renderable(bool allowGlobalDraw, const std::string& name, const std::string& objFilePath, const std::string& texturePath, const glm::vec3& color, const std::shared_ptr<Shader>& shader, bool culling) : m_ID(g_RenderablesLastID++), m_name(name), m_meshPath(objFilePath), m_shader(shader), m_texture(Texture::create(texturePath)), m_culling(culling), m_color(color), m_vao(0), m_loc(0), m_eboSize(0), globalDraw(allowGlobalDraw) { GL_ASSERT(glGenVertexArrays(1, &m_vao)); if (!m_shader) { m_shader = Shader::getByName("base"); } if (m_name.empty()) { m_name = std::string("R_" + std::to_string(m_ID)); } if (!objFilePath.empty()) { Renderable::data renderData = loader::OBJ(objFilePath); this->fillEBO(renderData.indices); // No location, just internal data. this->addVBO(renderData.vertices); // Location = 0 this->addVBO(renderData.normals); // Location = 1 this->addVBO(renderData.uvs); // Location = 2 } } // ====================================================================== // // ====================================================================== // // Destructor // ====================================================================== // Renderable::~Renderable() { if (!Settings::quiet) LOGD("Destroyed @ {}.{}", m_ID, m_name); } // ====================================================================== // // ====================================================================== // // Bind this Renderable VAO(m_vao) as active to auto attach VBO, EBO, ... // ====================================================================== // void Renderable::bind() { GL_ASSERT(glBindVertexArray(m_vao)); } // ====================================================================== // // ====================================================================== // // Unbind this Renderable VAO(m_vao) as active to avoid modify VBO, EBO, ... // ====================================================================== // void Renderable::unbind() { GL_ASSERT(glBindVertexArray(0)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL_ASSERT(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); } // ====================================================================== // // ====================================================================== // // Getter for ID // ====================================================================== // unsigned int Renderable::ID() const { return m_ID; } // ====================================================================== // // ====================================================================== // // Getter for name // ====================================================================== // std::string Renderable::name() const { return m_name; } // ====================================================================== // // ====================================================================== // // G/Setter for shader // ====================================================================== // std::shared_ptr<Shader> Renderable::shader() const { return m_shader; } void Renderable::shader(const std::shared_ptr<Shader>& newShader) { m_shader = newShader; } // ====================================================================== // // ====================================================================== // // G/Setter for color // ====================================================================== // glm::vec3 Renderable::color() const { return m_color; } void Renderable::color(const glm::vec3& newColor) { m_color = newColor; } // ====================================================================== // // ====================================================================== // // Add a vertex attribute to this Renderable // ====================================================================== // template <typename T> void Renderable::addVBO(const std::vector<T>& data) { this->bind(); { // Upload data to OpenGL unsigned int vbo; GL_ASSERT(glGenBuffers(1, &vbo)); GL_ASSERT(glBindBuffer(GL_ARRAY_BUFFER, vbo)); GL_ASSERT(glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(T), &data[0], GL_DYNAMIC_DRAW)); // Link data to a vertex attribute (in order of entry) GL_ASSERT(glEnableVertexAttribArray(m_loc)); GL_ASSERT(glVertexAttribPointer( m_loc, data[0].length(), GL_FLOAT, GL_FALSE, 0, 0)); // Increment location index for vertex attribs // [!] Check that order in your shader is the order in which you add VBOs ++m_loc; } this->unbind(); } // ====================================================================== // // ====================================================================== // // Store indices in the internal variable m_ebo // ====================================================================== // void Renderable::fillEBO(const std::vector<unsigned int>& indices) { this->bind(); // Store indices count m_eboSize = indices.size(); // Upload indices to OpenGL unsigned int ebo; GL_ASSERT(glGenBuffers(1, &ebo)); GL_ASSERT(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)); GL_ASSERT(glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_eboSize * sizeof(unsigned int), &indices[0], GL_DYNAMIC_DRAW)); this->unbind(); } // ====================================================================== // // ====================================================================== // // Draw execute the Renderable in the viewport using its shader and vbos // ====================================================================== // void Renderable::draw(const std::shared_ptr<Camera>& camera) { this->bind(); m_shader->bind(); (m_texture) ? m_shader->uInt1("u_texture", m_texture->bind()) : m_shader->uInt1("u_texture", Texture::pool.size()); // "Disable" texture m_shader->uFloat3("u_color", m_color); auto currModel = this->transform.asMatrix(); glm::mat4 matMV = camera->view() * currModel; m_shader->uMat4("u_matMV", matMV); m_shader->uMat4("u_matN", glm::transpose(glm::inverse(matMV))); m_shader->uMat4("u_matM", currModel); m_shader->uMat4("u_matMVP", camera->viewproj() * currModel); if (!m_culling) { glDisable(GL_CULL_FACE); } GL_ASSERT(glDrawElements(GL_TRIANGLES, m_eboSize, GL_UNSIGNED_INT, 0)); if (!m_culling) { glEnable(GL_CULL_FACE); } if (m_texture) m_texture->unbind(); m_shader->unbind(); this->unbind(); } // ====================================================================== // // ====================================================================== // // Draw a line between 2points // ====================================================================== // // std::shared_ptr<Renderable> Renderable::line(const glm::vec3& P1, const glm::vec3& P2, float scale) { auto stick = Renderable::getByName("stick"); { stick->transform.pos = (P1 + P2) * 0.5f; // --- auto C1 = stick->transform.pos + glm::vec3(0, 0.5f, 0); auto C2 = stick->transform.pos - glm::vec3(0, 0.5f, 0); auto vP = glm::normalize(P1 - P2); auto vC = glm::normalize(C1 - C2); stick->transform.rotAngle = glm::angle(vC, vP); stick->transform.rotAxis = glm::cross(vC, vP); // --- stick->transform.scl = glm::vec3{1.f, scale, 1.0f}; } return stick; } } // namespace imog
#pragma once #ifndef _SERIAL_HADLER_H_ #define _SERIAL_HADLER_H_ #include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/asio/serial_port.hpp> class Serial { private: boost::asio::serial_port* port; union Scomp_float { float n_float; uint32_t n_int; uint8_t n_bytes[4]; }; union Scomp_msg_tag { uint16_t n_16b; uint8_t n_bytes[2]; }; public: Serial(std::string com); /// <summary> /// sincronizza arduino ed il pc /// </summary> void sinc(); /// <summary> /// invia un floar ad arduino /// </summary> /// <param name="n"></param> void send_float(float n); /// <summary> /// riceve un float da arduino /// </summary> /// <returns></returns> float receive_float(); void send_char(char ch); char receive_char(); /// <summary> /// receive the data of acc, gy, magn from arduino /// </summary> /// <param name="acc_xyz"></param> /// <param name="g_xyz"></param> /// <param name="magn"></param> /// <param name="temp"></param> /// <returns> /// -> 0 if the trasmission is good /// -> 1 if it falied /// </returns> int receive_data(float* acc_xyz, float* g_xyz, float* magn, float* temp); ~Serial() { port->close(); } }; #endif // #ifndef _SERIAL_HADLER_H_
#include<iostream> #include<stdlib.h> using namespace std; int main() { int n,i,j,d; cin>>n; int a[n]; for(i=0;i<n;i++) cin>>a[i]; d=n; int min=n; int f=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i!=j && a[i]==a[j]) d=abs(i-j); } if(d<min) { min=d; f--; } } if(f==0) min = -1; cout<<min; }
#include <bits/stdc++.h> using namespace std; string frequencySort(string s) { map<char, int> m; for (auto c : s) m[c]++; priority_queue<pair<int, char>> max_heap; for (auto el : m) max_heap.push(make_pair(el.second, el.first)); string ans = ""; while (!max_heap.empty()) { for (int i = 0; i < max_heap.top().first; i++) ans+= max_heap.top().second; max_heap.pop(); } return ans; } int main() { string s = "tree"; cout << frequencySort(s) << endl; return 0; }
#include <TESTS/test_assertions.h> #include <TESTS/testcase.h> #include <CORE/HASH/crc32.h> #include <CORE/types.h> #include <cstring> using namespace core::hash; REGISTER_TEST_CASE(crc32TestHash) { const char *hellostr = "Hello World"; const size_t hellolen = strlen(hellostr); TEST(testing::assertEquals(0x4A17B156, CRC32(hellostr, hellolen))); TEST(testing::assertEquals(0x87E5865B, CiCRC32(hellostr, hellolen))); TEST(testing::assertEquals(0x4A17B156, CRC32(hellostr, hellostr + hellolen))); TEST(testing::assertEquals( 0x87E5865B, CiCRC32(hellostr, hellostr + hellolen))); }
//====================================================================================== // Game Institute - C++ Module 1 Textbook Exercises // Main.cpp The main Program Entry point. // Exercise 7.9.1 - Fraction Class // TODO: - // // Your program output should be formatted as follows: // /* */ //====================================================================================== // include directives #include "Fraction.h" // using directives using std::cout; using std::cin; using std::endl; /// NOTE: - We could just put using namespace std; to achieve the same results. // main program entry point int main() { // variables // Output to the console window // output a message telling the user to press a key to exit the program cout << "Press any key to continue.." << endl; // ignore user input (for keeping the console window open) cin.get(); cin.ignore(); // ensure we exit without error return 0; }
#ifndef MYGLWIDGET_H #define MYGLWIDGET_H #pragma once #include "paint_color.h" #include "modelloader.h" #include "planet.h" #include "shadercontext.h" #include <QWidget> #include <QOpenGLWidget> #include <QOpenGLBuffer> #include <QOpenGLVertexArrayObject> #include <QOpenGLShaderProgram> #include <QOpenGLTexture> #include <QTimer> struct Planets { Planet sun; Planet mercury; Planet venus; Planet earth; Planet mars; Planet jupiter; Planet saturn; Planet uranus; Planet neptune; Planet moonEarth; Planet moonMars1; Planet moonMars2; }; class MyGLWidget : public QOpenGLWidget { Q_OBJECT public: MyGLWidget(QWidget *parent) : QOpenGLWidget(parent) { setFocusPolicy(Qt::StrongFocus); connect(&timer, SIGNAL(timeout()), this, SLOT(update())); timer.start(30); } void initializeGL(); void resizeGL(int width, int height); void paintGL(); signals: valueChanged(double value); protected: void keyPressEvent(QKeyEvent *event); void wheelEvent(QWheelEvent *event); public slots: void receiveRotationZ(int); private: double camera_X = 0.0, camera_Y = 0.0, camera_Z = -20.0; GLfloat vertices[(6 * 6) * 8]; GLubyte indices[6 * 6]; // OpenGL State Information QOpenGLBuffer vbo = QOpenGLBuffer(QOpenGLBuffer::VertexBuffer); QOpenGLBuffer ibo = QOpenGLBuffer(QOpenGLBuffer::IndexBuffer); // speichert den Kontext vom Vertex Buffer und vom Index Buffer QOpenGLVertexArrayObject vao; QOpenGLShaderProgram shaderProgram; QOpenGLShaderProgram shaderProgramNormalColors; QOpenGLShaderProgram* shaderSelected; QMatrix4x4 modelMatrix, viewMatrix, perspectiveMatrix; GLfloat* vboData; GLuint* indexData; unsigned int vboLength; unsigned int iboLength; QOpenGLTexture* qTex; Planets planets; QTimer timer; void setupPlanets(); void renderPlanet(Planet, QOpenGLShaderProgram* shader); void addVertex(int index, GLfloat x, GLfloat y, GLfloat z, GLfloat r, GLfloat g, GLfloat b, GLfloat a); void addRectangle(int index, GLubyte A, GLubyte B, GLubyte C, GLubyte D); void setupBuffers(); void writeBuffers(); }; #endif // MYGLWIDGET_H
#include <bits/stdc++.h> using namespace std; int main() { int n,temp; cin >> n; int ans = 0; //no need to store entire array somewhere //keep adding elements to the ans while reading input for(int i=0;i<n;i++){ cin >> temp; ans += temp; } cout << ans; return 0; }
#include<iostream> using namespace std; // 拷贝构造函数的调用时机: //1. 使用一个已经创建完成的对象来初始化一个新对象 //2. 值传递的方式给函数参数传值 //3. 以值方式返回局部对象 class Person { public: Person() { cout<<"Person默认函数构造"<<endl; } Person(int age) { m_age = age; cout<<"Person有参函数构造"<<endl; } Person(const Person & p) { m_age = p.m_age; cout<<"Person拷贝函数构造"<<endl; } ~Person() { cout<<"Person析构函数调用"<<endl; } int m_age; }; //1. 使用一个已经创建完成的对象来初始化一个新对象,简单理解为复制一个类 void test01() { Person p1(10); Person p2(p1); cout<<p2.m_age<<endl; } //2. 值传递的方式给函数参数传值(相当于将实参复制给形参,所以也会调用拷贝构造) void dowork(Person p) { } void test02() { Person p3; dowork(p3); } //3. 以值方式返回局部对象 Person dowork02() { Person p; p.m_age = 4; return p; } void test03() { Person p4 = dowork02(); cout<<p4.m_age<<endl; } int main() { // test01(); // test02(); test03(); return 0; }
#include <stdio.h> int H, W, N; int maxAns = 0, minAns = 2e9, bCnt; struct node { int sx, sy, ex, ey, color; node* left, *right; node* mAlloc(int _sx, int _sy, int _ex, int _ey, int _color) { sx = _sx, sy = _sy, ex = _ex, ey = _ey, color = _color; return this; } void push(int x, int y, node buf[]) { // leaf, (항상 2개씩 만드는 이진완성(?) 트리 if (left == 0) { if (color == 1) { left = buf[bCnt++].mAlloc(sx, sy, x, ey, 0); right = buf[bCnt++].mAlloc(x, sy, ex, ey, 0); return; } if (color == 0) { left = buf[bCnt++].mAlloc(sx, sy, ex, y, 1); right = buf[bCnt++].mAlloc(sx, y, ex, ey, 1); return; } } if (x < left->ex && y < left->ey) left->push(x, y, buf); else right->push(x, y, buf); } void area() { // leaf이면 if (left == 0) { int area = (ex - sx)*(ey - sy); if (maxAns < area) maxAns = area; if (minAns > area) minAns = area; return; } left->area(); right->area(); } }buf[600100], *root; int main() { scanf("%d %d %d", &H, &W, &N); root = buf[bCnt++].mAlloc(0, 0, H, W, 0); for (int i = 0; i < N; i++) { int x, y; scanf("%d%d", &x, &y); root->push(x, y, buf); } root->area(); printf("%d %d\n", maxAns, minAns); return 0; }
#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <signal.h> #include <stdio.h> #include <string.h> #include "BasicTasks.h" #include "InternalCommands.h" #include "ExternalCommands.h" #include "Pipe.h" #include <ctype.h> #include <unistd.h> #include <algorithm> using namespace std; void xshLoop(); int HandleInput(char* line, BasicTasks* bt, InternalCommands* ic, ExternalCommands* ec,Pipe* pipe); bool ValidateCommandLine(int argc, char *argv[]); void printHelp(string arg); int pgid; //process group id string manualLocation; int main(int argc, char * argv[]) { //set session ID, this allows for killing all child processes at the end, more easily setsid(); //get process group id pgid = getpgid(0); //manualLocation = string(get_current_dir_name()); manualLocation += string("/") + string("readme"); ValidateCommandLine(argc, argv); //command loop: xshLoop(); return 0; } /** * sigHandler(int signum) * handles all appropriate signals and ignores the rest */ void sigHandler(int signum){ int pid = getpid(); //if foreground process if(pid == 0) { switch(signum){ case SIGINT: kill(pid, SIGINT); break; case SIGQUIT: kill(pid, SIGQUIT); break; case SIGCONT: kill(pid, SIGCONT); break; case SIGTSTP: kill(pid, SIGSTOP); break; default: //ignore break; } } } /* * Control Loop for the shell xsh */ void xshLoop(void) { BasicTasks bt; InternalCommands ic; ExternalCommands ec; Pipe pipe; char * tempLine = NULL; char *line = NULL; int status; //catch signals signal(SIGINT, sigHandler); signal(SIGQUIT, sigHandler); signal(SIGCONT, sigHandler); signal(SIGTSTP, sigHandler); signal(SIGABRT, sigHandler); signal(SIGALRM, sigHandler); signal(SIGHUP, sigHandler); signal(SIGTERM, sigHandler); signal(SIGUSR1, sigHandler); signal(SIGUSR2, sigHandler); //ic.setEnvVars(); do { cout <<"xsh >> "; //Reading line user inputs: line =(char *) bt.readLine(); //deep copy to ensure no tampering tempLine = new char[strlen(line) +1]; strcpy(tempLine, line); //check for batch file vector<string> args; bt.parseLine(tempLine,args); if(args.at(0) == "-f" && args.size() == 2){ ifstream batchFile(args.at(1)); if (batchFile.is_open()){ string bLine; int i = 1; while(getline(batchFile, bLine)){ if(!bLine.empty() && bLine.at(0) != '#'){ char * cmd = &bLine[0u]; status = HandleInput(cmd, &bt, &ic, &ec, &pipe); if(status == -1){ return; } } // cout << i <<endl; ++i; } } else { cout << "Error opening batch file" <<endl; } } else{ //Not likely but if this is true; BAIL! if(line == NULL){ cout<<"line is equal to NULL"<<endl; return; } status = HandleInput(line, &bt, &ic, &ec, &pipe); //if -1, exit command was sent if(status == -1) { return; } delete [] line ; line = NULL; } } while (status); } /* * HandleInput(): * designed to handle the parsing of input line * this is created so that it can be recalled when the repeat command is issued */ int HandleInput(char* line, BasicTasks* bt, InternalCommands* ic, ExternalCommands* ec,Pipe* pipe) { //Variables for handling input vector<string> args; char * preservedLine; int status; //Need a deep copy. preservedLine = new char[strlen(line) + 1]; strcpy(preservedLine, line); bt->parseLine(line,args); //sub variables ic->varSubs(args); if(args.empty()) { #ifdef _VDEBUG cout <<"the command line is empty" << endl; #endif }else if(find(args.begin(), args.end(), "|") != args.end()){ #ifdef _VDEBUG cout << "We have a pipe!"<<endl; for(int i = 0; i < args.size(); i++) { cout<<args.at(i)<< endl; cout << "- - - -"<<endl; } #endif pipe->pipeCommand(args,preservedLine); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="exit") { if(args.size() > 1 && bt->is_number(args.at(1))) { //kill all child processes kill(pgid, 15); //report back whatever is given cout << stoi(args.at(1)) << endl; exit(stoi(args.at(1))); } else if(args.size() > 1) { cout << "Usage: exit [n]" << endl; //else report back an error exit(-1); } else { //else exit //kill all child processes kill(pgid, 15); cout << 0 << endl; //exit normally exit(0); } } else if(args.at(0)=="clr") { ic->clearScreen(); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="echo") { ic->echoCommand(preservedLine); ic->addCmdToHistory(preservedLine); } else if(args.at(0) == "set"){ ic ->setCmd(preservedLine, args); ic->addCmdToHistory(preservedLine); } else if(args.at(0)== "unset"){ ic->unsetCmd(preservedLine); ic->addCmdToHistory(preservedLine); } else if(args.at(0)=="show") { ic->showCommand(args); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="history") { ic->addCmdToHistory(preservedLine); ic->historyCommand(args); } else if(args.at(0) =="export") { ic->exportCmd(preservedLine, args); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="unexport") { ic->unexportCmd(args); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="environ") { ic->environCmd(); ic->addCmdToHistory(preservedLine); } else if(args.at(0) == "dir"){ ic->dirCmd(); ic->addCmdToHistory(preservedLine); } else if(args.at(0) == "chdir"){ ic-> chdirCommand(args); ic ->addCmdToHistory(preservedLine); } else if (args.at(0) == "pause"){ //pause child processes kill(pgid, 20); ic->pauseCmd(); //resume child processes kill(pgid, 18); ic ->addCmdToHistory(preservedLine); } else if(args.at(0) == "wait"){ ic->waitCmd(args); ic->addCmdToHistory(preservedLine); } else if(args.at(0) == "kill"){ ic->killCmd(args); ic->addCmdToHistory(preservedLine); } else if(args.at(0) =="repeat") { int historyItem = -1; //get argument number if there are more than one argument if(args.size() >= 2) { // try // { sscanf(args.at(1).c_str(), "%d", &historyItem); historyItem--; // } // catch(Exception *e) // { // //if it failed, just roll with last command for repeating // cout << "Unable to interpret argument. Repeating last command." << endl; // historyItem = -1; // } } //get history command, recall this function status = HandleInput((char *)ic->getHistoryCommand(historyItem).c_str(), bt, ic, ec,pipe); args.clear(); //do not save repeat command to history list, this mimicks the bang command in linux //handle memory delete [] preservedLine; preservedLine = NULL; return status; } else if(args.at(0) == "help") { if(args.size() >= 2) { printHelp(args.at(1)); } else { printHelp(""); } } else { #ifdef _VDEBUG cout <<"args are:"<<endl; for(unsigned int i= 0; i < args.size(); i++) cout <<"["<<i<<"]: "<<args.at(i)<<endl; #endif //Call External int fg = (args.at(args.size()-1).at(0)!='&'); ec->callExternal(fg, args); ic->addCmdToHistory(preservedLine); } status = 1;//bt->executeLine(args,*ic); args.clear(); //handle memory delete [] preservedLine; preservedLine = NULL; return status; } /** *ValidateCommandLine(): * validates the commandline for valid combinations of option * flags and their arguments. */ bool ValidateCommandLine(int argc, char *argv[]) { char opt; bool status = true; string filename; if(argc == 1) { //return false; } while((opt=getopt(argc,argv,"f:w:h"))!=-1) { switch(opt) { case 'h': //show help and exit: status = false; break; case 'f': filename = optarg; break; case 'w': filename = optarg; break; default: break; } } return status; } /* * printHelp() * used for displaying help on the screen */ void printHelp(const string arg) { string command = "more"; if(arg != "") { command += " +/\"" + arg + "\""; } command += " " + manualLocation; const char* input = command.c_str(); system(input); }
#ifndef BSCHEDULER_CONFIG_HH_IN #define BSCHEDULER_CONFIG_HH_IN #include "@kernel_header@" #define BSCHEDULER_KERNEL_TYPE @kernel_type@ #endif // BSCHEDULER_CONFIG_HH_IN vim:filetype=cpp
#ifndef SCREENSCHECK_H #define SCREENSCHECK_H #include <QObject> #include <QGuiApplication> #include <QDebug> #include <QThread> class ScreensCheck : public QObject { Q_OBJECT public: ScreensCheck(QObject *parent = 0); public slots: void check(); signals: // true, если несклько мониторов void send(bool); }; #endif // SCREENSCHECK_H
#include <iostream> using namespace std; bool kiemTraSoDoiGuong(int i){ int soBanDau=i; int soDao = 0; int chuSo=0; while(i>0){ chuSo = i%10; soDao = soDao * 10 + chuSo; i = i/10; } if(soDao==soBanDau){ return true; } else { return false; } } int main(){ int n; cin >> n; int dem[n]; for (int i=0; i<n; ++i){ dem[i]=0; } int a, b; for (int i=0; i<n; ++i){ cin >> a >> b; for (int j=a; j<=b; ++j){ if(kiemTraSoDoiGuong(j)==true){ dem[i]++; } } cout << dem[i] << endl; } }
// // DarkIllusion.cpp // Boids // // Created by chenyanjie on 5/27/15. // // #include "DarkIllusion.h" #include "../../Utils.h" #include "../../scene/BattleLayer.h" #include "../../AI/Terrain.h" using namespace cocos2d; DarkIllusion::DarkIllusion() { } DarkIllusion::~DarkIllusion() { } DarkIllusion* DarkIllusion::create( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) { DarkIllusion* ret = new DarkIllusion(); if( ret && ret->init( owner, data, params ) ) { ret->autorelease(); return ret; } else { CC_SAFE_DELETE( ret ); return nullptr; } } bool DarkIllusion::init( UnitNode* owner, const cocos2d::ValueMap& data, const cocos2d::ValueMap& params ) { if( !SkillNode::init( owner ) ) { return false; } int level = data.at( "level" ).asInt(); _damage = data.at( "damage" ).asValueVector().at( level - 1 ).asFloat(); _duration = data.at( "duration" ).asFloat(); _elase = 0; _range = data.at( "range" ).asFloat(); _radius = data.at( "radius" ).asFloat(); _stun_duration = data.at( "stun_duration" ).asFloat(); _speed = _range / _duration; _dir = _owner->getUnitDirection(); _dir.normalize(); return true; } void DarkIllusion::updateFrame( float delta ) { if( !_should_recycle ) { if( _elase == 0 ) { std::string resource = "effects/durarara_skill_1"; spine::SkeletonAnimation* skeleton = ArmatureManager::getInstance()->createArmature( resource ); std::string name = Utils::stringFormat( "%s_effect", SKILL_NAME_DARK_ILLUSION ); _component = TimeLimitSpineComponent::create( _duration, skeleton, name, true ); skeleton->getSkeleton()->flipX = ( _dir.x > 0 ); _component->setScale( _owner->getUnitScale() ); _component->setPosition( _owner->getLocalEmitPos() ); _component->setAnimation( 0, "animation", true ); _owner->addUnitComponent( _component, _component->getName(), eComponentLayer::OverObject ); } _elase += delta; if( _elase > _duration ) { this->end(); } else { Point d_pos = _dir * ( _speed * delta ); Point new_pos = _owner->getPosition() + d_pos; std::vector<Collidable*> collidables; Terrain::getInstance()->getMeshByUnitRadius( _owner->getTargetData()->collide )->getNearbyBorders( _owner->getPosition(), _speed * delta, collidables ); bool collide = false; for( auto c : collidables ) { if( c->willCollide( _owner, new_pos ) ) { collide = true; break; } } if( !collide ) { _owner->setPosition( _owner->getPosition() + d_pos ); } Vector<UnitNode*> candidates = _owner->getBattleLayer()->getAliveOpponentsInRange( _owner->getTargetCamp(), _owner->getPosition(), _radius ); if( candidates.size() > 0 ) { ValueMap buff_data; buff_data["duration"] = Value( _stun_duration ); buff_data["buff_type"] = Value( BUFF_TYPE_STUN ); buff_data["buff_name"] = Value( SKILL_NAME_DARK_ILLUSION ); DamageCalculate* calculator = DamageCalculate::create( SKILL_NAME_DARK_ILLUSION, _damage ); for( auto unit : candidates ) { int deployed_id = unit->getDeployId(); bool excluded = false; for( auto v : _exclude_targets ) { if( v.asInt() == deployed_id ) { excluded = true; break; } } if( !excluded ) { //push _exclude_targets.push_back( Value( deployed_id ) ); Point push_dir = unit->getPosition() - _owner->getPosition(); float cross = _dir.cross( push_dir ); if( cross > 0 ) { push_dir = Geometry::clockwisePerpendicularVecToLine( _dir ); } else { push_dir = Geometry::anticlockwisePerpendicularVecToLine( _dir ); } float push_d = _owner->getTargetData()->collide + unit->getTargetData()->collide - Geometry::distanceToLine( unit->getPosition(), _owner->getPosition(), _owner->getPosition() + _dir * 1000.0f ); unit->pushToward( push_dir, push_d ); //stun StunBuff* buff = StunBuff::create( unit, buff_data ); unit->addBuff( buff->getBuffId(), buff ); buff->begin(); //damage ValueMap result = calculator->calculateDamageWithoutMiss( _owner->getTargetData(), unit->getTargetData() ); unit->takeDamage( result, _owner ); } } } } } } void DarkIllusion::begin() { SkillNode::begin(); } void DarkIllusion::end() { _component->setDuration( 0 ); _owner->endCast(); SkillNode::end(); }
#include <Windows.h> #include <stdio.h> #include <stdlib.h> #include "dllfunc.h" #include "showmodule.h" void waitInput() { getchar(); } int main(int argc, const char* argv[]) { showmodule(L"main"); dllfunc(); return 0; }
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "SACPP/Public/CPP_ClickInterface.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeCPP_ClickInterface() {} // Cross Module References SACPP_API UClass* Z_Construct_UClass_UCPP_ClickInterface_NoRegister(); SACPP_API UClass* Z_Construct_UClass_UCPP_ClickInterface(); COREUOBJECT_API UClass* Z_Construct_UClass_UInterface(); UPackage* Z_Construct_UPackage__Script_SACPP(); COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector(); // End Cross Module References DEFINE_FUNCTION(ICPP_ClickInterface::execRightMouseClick) { P_GET_STRUCT(FVector,Z_Param__position); P_FINISH; P_NATIVE_BEGIN; P_THIS->RightMouseClick_Implementation(Z_Param__position); P_NATIVE_END; } DEFINE_FUNCTION(ICPP_ClickInterface::execLeftMouseClick) { P_GET_STRUCT(FVector,Z_Param__position); P_FINISH; P_NATIVE_BEGIN; P_THIS->LeftMouseClick_Implementation(Z_Param__position); P_NATIVE_END; } void ICPP_ClickInterface::LeftMouseClick(FVector _position) { check(0 && "Do not directly call Event functions in Interfaces. Call Execute_LeftMouseClick instead."); } void ICPP_ClickInterface::RightMouseClick(FVector _position) { check(0 && "Do not directly call Event functions in Interfaces. Call Execute_RightMouseClick instead."); } void UCPP_ClickInterface::StaticRegisterNativesUCPP_ClickInterface() { UClass* Class = UCPP_ClickInterface::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "LeftMouseClick", &ICPP_ClickInterface::execLeftMouseClick }, { "RightMouseClick", &ICPP_ClickInterface::execRightMouseClick }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics { static const UE4CodeGen_Private::FStructPropertyParams NewProp__position; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::NewProp__position = { "_position", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(CPP_ClickInterface_eventLeftMouseClick_Parms, _position), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::NewProp__position, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::Function_MetaDataParams[] = { { "Category", "Interaction" }, { "ModuleRelativePath", "Public/CPP_ClickInterface.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPP_ClickInterface, nullptr, "LeftMouseClick", nullptr, nullptr, sizeof(CPP_ClickInterface_eventLeftMouseClick_Parms), Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C820C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics { static const UE4CodeGen_Private::FStructPropertyParams NewProp__position; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::NewProp__position = { "_position", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(CPP_ClickInterface_eventRightMouseClick_Parms, _position), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::NewProp__position, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::Function_MetaDataParams[] = { { "Category", "Interaction" }, { "ModuleRelativePath", "Public/CPP_ClickInterface.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCPP_ClickInterface, nullptr, "RightMouseClick", nullptr, nullptr, sizeof(CPP_ClickInterface_eventRightMouseClick_Parms), Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C820C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UCPP_ClickInterface_NoRegister() { return UCPP_ClickInterface::StaticClass(); } struct Z_Construct_UClass_UCPP_ClickInterface_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UCPP_ClickInterface_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UInterface, (UObject* (*)())Z_Construct_UPackage__Script_SACPP, }; const FClassFunctionLinkInfo Z_Construct_UClass_UCPP_ClickInterface_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UCPP_ClickInterface_LeftMouseClick, "LeftMouseClick" }, // 1764818904 { &Z_Construct_UFunction_UCPP_ClickInterface_RightMouseClick, "RightMouseClick" }, // 3340933464 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCPP_ClickInterface_Statics::Class_MetaDataParams[] = { { "ModuleRelativePath", "Public/CPP_ClickInterface.h" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_UCPP_ClickInterface_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<ICPP_ClickInterface>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UCPP_ClickInterface_Statics::ClassParams = { &UCPP_ClickInterface::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, nullptr, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), 0, 0, 0x000840A1u, METADATA_PARAMS(Z_Construct_UClass_UCPP_ClickInterface_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UCPP_ClickInterface_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UCPP_ClickInterface() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UCPP_ClickInterface_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UCPP_ClickInterface, 815114980); template<> SACPP_API UClass* StaticClass<UCPP_ClickInterface>() { return UCPP_ClickInterface::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UCPP_ClickInterface(Z_Construct_UClass_UCPP_ClickInterface, &UCPP_ClickInterface::StaticClass, TEXT("/Script/SACPP"), TEXT("UCPP_ClickInterface"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UCPP_ClickInterface); static FName NAME_UCPP_ClickInterface_LeftMouseClick = FName(TEXT("LeftMouseClick")); void ICPP_ClickInterface::Execute_LeftMouseClick(UObject* O, FVector _position) { check(O != NULL); check(O->GetClass()->ImplementsInterface(UCPP_ClickInterface::StaticClass())); CPP_ClickInterface_eventLeftMouseClick_Parms Parms; UFunction* const Func = O->FindFunction(NAME_UCPP_ClickInterface_LeftMouseClick); if (Func) { Parms._position=_position; O->ProcessEvent(Func, &Parms); } else if (auto I = (ICPP_ClickInterface*)(O->GetNativeInterfaceAddress(UCPP_ClickInterface::StaticClass()))) { I->LeftMouseClick_Implementation(_position); } } static FName NAME_UCPP_ClickInterface_RightMouseClick = FName(TEXT("RightMouseClick")); void ICPP_ClickInterface::Execute_RightMouseClick(UObject* O, FVector _position) { check(O != NULL); check(O->GetClass()->ImplementsInterface(UCPP_ClickInterface::StaticClass())); CPP_ClickInterface_eventRightMouseClick_Parms Parms; UFunction* const Func = O->FindFunction(NAME_UCPP_ClickInterface_RightMouseClick); if (Func) { Parms._position=_position; O->ProcessEvent(Func, &Parms); } else if (auto I = (ICPP_ClickInterface*)(O->GetNativeInterfaceAddress(UCPP_ClickInterface::StaticClass()))) { I->RightMouseClick_Implementation(_position); } } PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
#include "native_edge_detection.hpp" #include "edge_detector.hpp" #include "image_processor.hpp" #include <stdlib.h> #include <opencv2/opencv.hpp> extern "C" __attribute__((visibility("default"))) __attribute__((used)) struct Coordinate *create_coordinate(double x, double y) { struct Coordinate *coordinate = (struct Coordinate *)malloc(sizeof(struct Coordinate)); coordinate->x = x; coordinate->y = y; return coordinate; } extern "C" __attribute__((visibility("default"))) __attribute__((used)) struct DetectionResult *create_detection_result(Coordinate *topLeft, Coordinate *topRight, Coordinate *bottomLeft, Coordinate *bottomRight) { struct DetectionResult *detectionResult = (struct DetectionResult *)malloc(sizeof(struct DetectionResult)); detectionResult->topLeft = topLeft; detectionResult->topRight = topRight; detectionResult->bottomLeft = bottomLeft; detectionResult->bottomRight = bottomRight; return detectionResult; } extern "C" __attribute__((visibility("default"))) __attribute__((used)) struct DetectionResult *detect_edges(char *str) { struct DetectionResult *coordinate = (struct DetectionResult *)malloc(sizeof(struct DetectionResult)); cv::Mat mat = cv::imread(str); if (mat.size().width == 0 || mat.size().height == 0) { return create_detection_result( create_coordinate(0, 0), create_coordinate(1, 0), create_coordinate(0, 1), create_coordinate(1, 1) ); } vector<cv::Point> points = EdgeDetector::detect_edges(mat); return create_detection_result( create_coordinate((double)points[0].x / mat.size().width, (double)points[0].y / mat.size().height), create_coordinate((double)points[1].x / mat.size().width, (double)points[1].y / mat.size().height), create_coordinate((double)points[2].x / mat.size().width, (double)points[2].y / mat.size().height), create_coordinate((double)points[3].x / mat.size().width, (double)points[3].y / mat.size().height) ); } extern "C" __attribute__((visibility("default"))) __attribute__((used)) bool process_image( char *path, double topLeftX, double topLeftY, double topRightX, double topRightY, double bottomLeftX, double bottomLeftY, double bottomRightX, double bottomRightY ) { cv::Mat mat = cv::imread(path); cv::Mat resizedMat = ImageProcessor::process_image( mat, topLeftX * mat.size().width, topLeftY * mat.size().height, topRightX * mat.size().width, topRightY * mat.size().height, bottomLeftX * mat.size().width, bottomLeftY * mat.size().height, bottomRightX * mat.size().width, bottomRightY * mat.size().height ); return cv::imwrite(path, resizedMat, {cv::ImwriteFlags::IMWRITE_JPEG_QUALITY, 50, cv::ImwriteFlags::IMWRITE_JPEG_OPTIMIZE, 1}); //only support jpeg at the moment }
#include "pill.h" #include <stdlib.h> /* srand, rand */ using namespace std; namespace haunted_house { //TODO Make this global for haunted_house const int RED = 0; const int BLUE = 1; const int GREEN = 2; const int YELLOW = 3; const int MAX_MAGIC = 100; Pill::Pill(){ m_color = GREEN; m_name = "Green pill"; //TODO m_volume = 1; m_price = 0; m_weight = 1; m_magic_power = rand() % MAX_MAGIC + 1; }; Pill::Pill(int col){ m_color = col; m_name = "TODO pill"; //TODO m_volume = 1; m_price = 0; m_weight = 1; m_magic_power = rand() % MAX_MAGIC + 1; } string Pill::name(){ return m_name; }; string Pill::description(){ return string("This is a ")+ color() + string(" pill, eat it if you dare!"); }; int Pill::use(){ //Set everything to 0?? return magic_power(); } string Pill::color(){ if(m_color == RED){ return "red"; }else if(m_color == BLUE){ return "blue"; }else if(m_color == GREEN){ return "green"; }else if(m_color == YELLOW){ return "yellow"; } return "error"; } int Pill::magic_power() const{ return m_magic_power; }; int Pill::weight() const{ return m_weight; }; int Pill::volume() const{ return m_volume; }; int Pill::price() const{ return m_price; }; }
#include "life.h" Life::Life(int rows, int cols) { init(rows, cols); } Life::Life(std::string filename) { std::ifstream file; file.open(filename); if(file.fail()) exit(1); int rows, cols; char ca, cr; // char: active and char: read file >> rows >> cols >> ca; init(rows, cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { file >> cr; if(cr == ca) this->board->set_active(i, j); } } } void Life::init(int rows, int cols) { this->rows = rows; this->cols = cols; this->grid.resize(rows+2, {CELL_DIED}); for(int i = 0; i < rows+2; ++i) this->grid[i].resize(cols+2, CELL_DIED); this->board = new QuadBoard(20, cols, rows, 2); } Life::~Life() { this->grid.resize(0); for(int i = 0; i < this->rows; ++i) this->grid[i].resize(0); } Life & Life::operator=(const Life& lf) { this->rows = lf.rows; // ! this->cols = lf.cols; // | iguala propriedades this->grid.resize(lf.rows); // altera quantidade de linhas for(int i = 0; i < lf.rows+2; ++i) // percorre cada linha { this->grid[i].resize(lf.cols+2); // redimensiona linha for(int j = 0; j < lf.cols+2; ++j) // percorred as colunas { this->grid[i][j] = lf.grid[i][j]; // realiza a atribuição } } return *this; // permite atribuição em cascata // TODO: traduzir comentarios } bool Life::operator==(std::vector<int> id) const { int n = this->id[0]; // number of elements: number of elements distance_1 + ... + distance_n for(int i = 0; i < n+1; ++i){ // if the sizes are different the loop will break at first time if(this->id[i] != id[i]) // different data return false; } return true; } void Life::set_id() { int n = 0; int distance = 0; this->id.resize(0); this->id.push_back(0); for(int i = 0; i < this->rows; ++i) // percorre cada linha { for(int j = 0; j < this->cols; ++j) // percorre as colunas { if(grid[i][j] == CELL_ALIVE) { this->id.push_back(distance); // store distance n++; // increase distance count distance = 0; // reset distance } else { distance++; // increase distance count } } } this->id[0] = n; } void Life::update() { this->bordas(); if(!this->board->is_disable()) return; this->set_id(); this->ids.push_back(this->id); Life lf = *this; int rows = this->get_rows(); int cols = this->get_columns(); for( auto i(1); i < rows+1 ; i++) { for( auto j(1) ; j < cols+1; j++) { // Contabiliza os vizinhos vivos de cada célula. int cont = 0; if(lf.get_value(i-1, j-1) == 1) cont++; if(lf.get_value(i-1, j) == 1) cont++; if(lf.get_value(i-1, j+1) == 1) cont++; if(lf.get_value(i, j-1) == 1) cont++; if(lf.get_value(i, j+1) == 1) cont++; if(lf.get_value(i+1, j-1) == 1) cont++; if(lf.get_value(i+1, j) == 1) cont++; if(lf.get_value(i+1, j+1) == 1) cont++; // Aplica as regras. if(this->get_value(i, j) == 1) { if(cont <= 1 || cont >= 4) this->set_value(i, j, 0); } else { if(cont == 3) this->set_value(i, j, 1); } } } this->load_bordas(); } int Life::get_value(int x, int y ) { return this->grid[x][y]; } void Life::set_value(int x, int y, int value) { if(x > 0 and y > 0 and x <= rows and y <= cols){ if(value == 0) this->board->set_default(x-1, y-1); else this->board->set_active(x-1, y-1); } this->grid[x][y] = value; } int Life::get_rows(){ return this->rows; } int Life::get_columns(){ return this->cols; } bool Life::is_extinct(){ if(this->id[0] == 0) return true; return false; } bool Life::is_stable() { int size = this->ids.size(); for(int i = 0; i < size-1; i++) if(*this == this->ids[i]){ std::cout << "[ "; for(auto &a : this->id) std::cout << a << " "; std::cout << "]" << std::endl; std::cout << "[ "; for(auto &a : this->ids[i]) std::cout << a << " "; std::cout << "]" << std::endl; return true; } return false; } void Life::load_from_board() { this->board->backup(); for( auto i(0) ; i < this->rows; i++ ){ for( auto j(0) ; j < this->cols; j++ ){ if(this->board->get_active(i, j)) this->grid[i+1][j+1] = CELL_ALIVE; else this->grid[i+1][j+1] = CELL_DIED; } } this->load_bordas(); } void Life::clear_ids() { this->id.clear(); this->ids.clear(); } /// Transfere os valores dos limites da grid para a borda. void Life::bordas() { if(!this->board->is_disable()) return; int rows = this->rows; int cols = this->cols; ///Trata as diagonais. set_value(rows, cols, this->grid[0][0]); set_value(1, 1, this->grid[rows+1][cols+1]); set_value(1, cols, this->grid[rows+1][0]); set_value(rows, 1, this->grid[0][cols+1]); /// Borda esquerda for(auto i(1); i <= rows; i++) set_value(i, cols, this->grid[i][0]); // Borda direita for(auto i(1); i <= rows ; i++){ set_value(i, 1, this->grid[i][cols+1]); } /// Borda superior for(auto j(1); j <= cols ; j++) set_value(rows, j, this->grid[0][j]); /// Borda superior for(auto j(1); j <= cols ; j++) set_value(1, j, this->grid[rows+1][j]); } /// Transfere valores dos limites da grid para a borda. void Life::load_bordas() { int rows = this->rows; int cols = this->cols; /// Trata as diagonais. set_value(rows+1, cols+1, this->grid[1][1]); set_value(0, 0, this->grid[rows][cols]); set_value(0, cols+1, this->grid[rows][1]); set_value(rows+1, 0, this->grid[1][cols]); /// Borda esquerda recebe lado direito for(auto i(1); i <= rows; i++) set_value(i, 0, this->grid[i][cols]); // Borda direita recebe lado esquerdo for(auto i(1); i <= rows ; i++){ set_value(i, cols+1, this->grid[i][1]); } /// Borda inferior recebe lado superior for(auto j(1); j <= cols ; j++) set_value(rows+1, j, this->grid[1][j]); /// Borda superior recebe lado inferior for(auto j(1); j <= cols ; j++) set_value(0, j, this->grid[rows][j]); }
#include<iostream> #define _rep(a,b,c) for(int (a)=(b);(a)<(c);(a)++) using namespace std; #define N 33 #define OJ 98 int mp[N][N]; int res[N][N]; int main() { #ifndef OJ freopen("201512-2.txt","r",stdin); #endif int n,m; cin>>n>>m; _rep(i,0,n) { _rep(j,0,m) { cin>>mp[i][j]; res[i][j]=mp[i][j]; //读取的时候判断横向的 if(j>=2) { if(mp[i][j-2]==mp[i][j-1]&&mp[i][j-1]==mp[i][j]) { res[i][j-2]=0; res[i][j-1]=0; res[i][j]=0; } } } } //判断纵向的 _rep(i,0,m) { _rep(j,0,n) { if(j>=2) { if(mp[j-2][i]==mp[j-1][i]&&mp[j-1][i]==mp[j][i]) { res[j-2][i]=0; res[j-1][i]=0; res[j][i]=0; } } } } //输出结构 _rep(i,0,n) { _rep(j,0,m) { if(j!=m-1) cout<<res[i][j]<<" "; else cout<<res[i][j]<<endl; } } #ifndef OJ fclose(stdin); #endif return 0; }
#include <bits/stdc++.h> using namespace std; class Solution { public: int minSteps(int n) { int curr = 1, count = 0, buffer = 0; while (curr < n) { int rest = n - curr; if (rest % curr == 0) { buffer = curr; curr += buffer; count += 2; } else { curr += buffer; count++; } } return count; } }; int main() { int c(100); Solution solve; cout << solve.minSteps(c) << endl; return 0; }
#include<bits/stdc++.h> typedef long long ll; using namespace std; int main() { int n,x,a,b,c; double m; cin>>n; ll count=0; for(int i=1;i<=n;i++) { m=sqrt(i+1); { m=(int)m; a=m*m-1; b=2*m; c=m*m+1; if(a>0&&b>0&&c>0){ cout<<a<<" "<<b<<" "<<c<<" \n"; count++; } } cout<<count<<endl; } }
/* ============================================================================== KrushSync.cpp Created: 22 Nov 2018 4:10:18pm Author: rkubiak ============================================================================== */ #include "KrushSync.h" KrushSync::KrushSync() : internalSync(true), Thread("KrushSync"), currentTransportState(Stopped), outputMidiClock(false) { } KrushSync::~KrushSync() { stop(); } void KrushSync::run() { currentTransportState = Playing; timeTick = 0; while (!threadShouldExit()) { wait(currentSleepMs); timeTick++; if (timeTick % 24 == 0) { listeners.call(&Listener::realtimeEvent, ClockQuarterNote); eventQueue.add(ClockQuarterNote); } if (outputMidiClock) { } if (timeTick == 96) timeTick = 0; listeners.call(&Listener::realtimeEvent, ClockTick); eventQueue.add(ClockTick); triggerAsyncUpdate(); } } void KrushSync::setTempo(double bpm) { ScopedLock sl(syncLock); currentSleepMs = (60.0 * 1000.0) / (bpm * 24.0); DBG("KrushSync::setTempo bpm=" + _S(bpm) + " currentSleepMs=" + _S(currentSleepMs)); } void KrushSync::start() { if (internalSync) { startThread(); } else { ScopedLock sl(syncLock); currentTransportState = Playing; } } void KrushSync::pause() { ScopedLock sl(syncLock); currentTransportState = Paused; } void KrushSync::stop() { if (internalSync) { ScopedLock sl(syncLock); currentTransportState = Stopping; signalThreadShouldExit(); waitForThreadToExit(150); currentTransportState = Stopped; } } void KrushSync::addListener(KrushSync::Listener *l) { ScopedLock sl(syncLock); listeners.add(l); } void KrushSync::removeListener(KrushSync::Listener *l) { ScopedLock sl(syncLock); listeners.remove(l); } void KrushSync::handleAsyncUpdate() { for (int i = 0; i < eventQueue.size(); i++) { listeners.call(&Listener::realtimeEventAsync, eventQueue[i]); } eventQueue.clear(); }
#include <Network/player_client.hpp> namespace Network { PlayerClient::PlayerClient(const PrimeClient& client) : client(client) { std::cout << "Created a new player client for " << client.to_string() << std::endl; // TODO: Wait for information such as nickname (ofc limited time, consider multiple attempts) // If received successfully, create a player instance via the Durak interface // Otherwise, don't do anything and let the destructors do the work // Meanwhile: char buffer[1]; client.socket.client_set_timeout(0); client.socket.client_recv(buffer, 1); // dummy } PlayerClient::~PlayerClient() { std::cout << "Destroyed the player client for " << client.to_string() << std::endl; // TODO: If a player was created successfully, disconnect him } } // namespace Network
#include "GPUOCLLayer.h" #include "crandom.h" #include "cl_scan_gpu.h" #include <algorithm> #undef min #undef max void GPUOCLLayer::trace1D_Rev(int a_minBounce, int a_maxBounce, cl_mem a_rpos, cl_mem a_rdir, size_t a_size, cl_mem a_outColor) { runKernel_ClearAllInternalTempBuffers(a_size); // trace rays // if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); m_timer.start(); } float timeForSample = 0.0f; float timeForBounce = 0.0f; float timeForTrace = 0.0f; float timeBeforeShadow = 0.0f; float timeForShadow = 0.0f; float timeStart = 0.0f; float timeNextBounceStart = 0.0f; float timeForNextBounce = 0.0f; float timeForHitStart = 0.0f; float timeForHit = 0.0f; int measureBounce = m_vars.m_varsI[HRT_MEASURE_RAYS_TYPE]; for (int bounce = 0; bounce < a_maxBounce; bounce++) { const bool measureThisBounce = (bounce == measureBounce); if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS] && measureThisBounce) { clFinish(m_globals.cmdQueue); timeStart = m_timer.getElapsed(); } runKernel_Trace(a_rpos, a_rdir, a_size, m_rays.hits); if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS] && measureThisBounce) { clFinish(m_globals.cmdQueue); timeForHitStart = m_timer.getElapsed(); timeForTrace = timeForHitStart - timeStart; } runKernel_ComputeHit(a_rpos, a_rdir, m_rays.hits, a_size, a_size, m_rays.hitSurfaceAll, m_rays.hitProcTexData); runKernel_HitEnvOrLight(m_rays.rayFlags, a_rpos, a_rdir, a_outColor, bounce, a_minBounce, a_size); if (FORCE_DRAW_SHADOW && bounce == 1) { CopyShadowTo(a_outColor, m_rays.MEGABLOCKSIZE); break; } if((m_vars.m_flags & HRT_PRODUCTION_IMAGE_SAMPLING) != 0 && (bounce%2 == 0)) // opt for empty environment rendering. { if(CountNumActiveThreads(m_rays.rayFlags, a_size) == 0) break; } if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS] && measureThisBounce) { clFinish(m_globals.cmdQueue); timeBeforeShadow = m_timer.getElapsed(); timeForHit = timeBeforeShadow - timeForHitStart; } if (m_vars.shadePassEnable(bounce, a_minBounce, a_maxBounce)) { ShadePass(a_rpos, a_rdir, m_rays.pathShadeColor, a_size, measureThisBounce); } else { memsetf4(m_rays.pathShadeColor, float4(0,0,0,0), a_size); } if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS] && measureThisBounce) { clFinish(m_globals.cmdQueue); timeNextBounceStart = m_timer.getElapsed(); timeForShadow = timeNextBounceStart - timeBeforeShadow; } runKernel_NextBounce(m_rays.rayFlags, a_rpos, a_rdir, a_outColor, a_size); if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS] && measureThisBounce) { clFinish(m_globals.cmdQueue); timeForBounce = (m_timer.getElapsed() - timeStart); timeForNextBounce = (m_timer.getElapsed() - timeNextBounceStart); } } if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); timeForSample = m_timer.getElapsed(); } m_stat.raysPerSec = float(a_size) / timeForTrace; m_stat.traversalTimeMs = timeForTrace*1000.0f; m_stat.sampleTimeMS = timeForSample*1000.0f; m_stat.bounceTimeMS = timeForBounce*1000.0f; //m_stat.shadowTimeMs = timeForShadow*1000.0f; m_stat.evalHitMs = timeForHit*1000.0f; m_stat.nextBounceMs = timeForNextBounce*1000.0f; m_stat.samplesPerSec = float(a_size) / timeForSample; m_stat.traceTimePerCent = int( ((timeForTrace + timeForShadow) / timeForBounce)*100.0f ); //std::cout << "measureBounce = " << measureBounce << std::endl; } void GPUOCLLayer::trace1D_Fwd(int a_minBounce, int a_maxBounce, cl_mem a_rpos, cl_mem a_rdir, size_t a_size, cl_mem a_outColor) { // runKernel_ClearAllInternalTempBuffers(a_size); // called when light is sampled // trace rays // if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); m_timer.start(); } float timeForSample = 0.0f; float timeForBounce = 0.0f; float timeForTrace = 0.0f; float timeBeforeShadow = 0.0f; float timeForShadow = 0.0f; float timeStart = 0.0f; float timeNextBounceStart = 0.0f; float timeForNextBounce = 0.0f; float timeForHitStart = 0.0f; float timeForHit = 0.0f; //int measureBounce = m_vars.m_varsI[HRT_MEASURE_RAYS_TYPE]; for (int bounce = 0; bounce < a_maxBounce - 1; bounce++) { runKernel_Trace(a_rpos, a_rdir, a_size, m_rays.hits); runKernel_ComputeHit(a_rpos, a_rdir, m_rays.hits, a_size, a_size, m_rays.hitSurfaceAll, m_rays.hitProcTexData); // postpone 'ConnectEyePass' call to the end of bounce; // ConnectEyePass(m_rays.rayFlags, m_rays.hitPosNorm, m_rays.hitNormUncompressed, a_rdir, a_outColor, bounce, a_size); // if(bounce >= a_minBounce - 2) { CopyForConnectEye(m_rays.rayFlags, a_rdir, a_outColor, m_rays.oldFlags, m_rays.oldRayDir, m_rays.oldColor, a_size); } runKernel_NextBounce(m_rays.rayFlags, a_rpos, a_rdir, a_outColor, a_size); if(bounce >= a_minBounce - 2) { ConnectEyePass(m_rays.oldFlags, m_rays.oldRayDir, m_rays.oldColor, bounce, a_size); if (m_vars.m_flags & HRT_3WAY_MIS_WEIGHTS) runKernel_UpdateForwardPdfFor3Way(m_rays.oldFlags, m_rays.oldRayDir, m_rays.rayDir, m_rays.accPdf, a_size); } } if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); timeForSample = m_timer.getElapsed(); } m_stat.raysPerSec = float(a_size) / timeForTrace; m_stat.traversalTimeMs = timeForTrace*1000.0f; m_stat.sampleTimeMS = timeForSample*1000.0f; m_stat.bounceTimeMS = timeForBounce*1000.0f; //m_stat.shadowTimeMs = timeForShadow*1000.0f; m_stat.evalHitMs = timeForHit*1000.0f; m_stat.nextBounceMs = timeForNextBounce*1000.0f; m_stat.samplesPerSec = float(a_size) / timeForSample; m_stat.traceTimePerCent = int( ((timeForTrace + timeForShadow) / timeForBounce)*100.0f ); //std::cout << "measureBounce = " << measureBounce << std::endl; } void GPUOCLLayer::EvalPT(cl_mem in_xVector, cl_mem in_zind, int minBounce, int maxBounce, size_t a_size, cl_mem a_outColor) { // This is important fix due to dead threads on last state (black env) could contrib old values (!!!) // Thus, you have to clear 'kmlt.xMultOneMinusAlpha' as trace1D_Rev result because trace1D_Rev _always_ do "+=" operation on result buffer. // memsetf4(a_outColor, float4(0,0,0,0), m_rays.MEGABLOCKSIZE, 0); // create rays from 'in_xVector' samples // runKernel_MakeRaysFromEyeSam(in_zind, in_xVector, m_rays.MEGABLOCKSIZE, m_passNumberForQMC, m_rays.rayPos, m_rays.rayDir); auto temp = kmlt.currVec; // save auto temp2 = kmlt.currZind; // save kmlt.currVec = in_xVector; kmlt.currZind = in_zind; trace1D_Rev(minBounce, maxBounce, m_rays.rayPos, m_rays.rayDir, m_rays.MEGABLOCKSIZE, a_outColor); kmlt.currVec = temp; // restore kmlt.currZind = temp2; // restore } void GPUOCLLayer::EvalLT(cl_mem in_xVector, int minBounce, int maxBounce, size_t a_size, cl_mem a_outColor) { assert(in_xVector == nullptr); // #NOTE: This is not implemeneted yet!!! (and actually will not be implemnented, no reason why we should do that) auto temp = kmlt.currVec; // save auto temp2 = kmlt.currZind; // save kmlt.currVec = nullptr; kmlt.currZind = nullptr; ///////////////////////////////////////////////////////////////////////////////////////////////// runKernel_MakeLightRays(m_rays.rayPos, m_rays.rayDir, a_outColor, m_rays.MEGABLOCKSIZE); if ((m_vars.m_flags & HRT_DRAW_LIGHT_LT) && minBounce <= 1 ) { runKernel_CopyLightSampleToSurfaceHit(m_rays.rayPos, m_rays.MEGABLOCKSIZE, m_rays.hitSurfaceAll); ConnectEyePass(m_rays.rayFlags, nullptr, a_outColor, -1, m_rays.MEGABLOCKSIZE); } trace1D_Fwd(minBounce, maxBounce, m_rays.rayPos, m_rays.rayDir, m_rays.MEGABLOCKSIZE, a_outColor); ///////////////////////////////////////////////////////////////////////////////////////////////// kmlt.currVec = temp; // restore kmlt.currZind = temp2; // restore } int GPUOCLLayer::CountNumActiveThreads(cl_mem a_rayFlags, size_t a_size) { int zero = 0; CHECK_CL(clEnqueueWriteBuffer(m_globals.cmdQueue, m_rays.atomicCounterMem, CL_TRUE, 0, sizeof(int), &zero, 0, NULL, NULL)); { cl_kernel kern = m_progs.screen.kernel("CountNumLiveThreads"); size_t szLocalWorkSize = 256; cl_int iNumElements = cl_int(a_size); a_size = roundBlocks(a_size, int(szLocalWorkSize)); CHECK_CL(clSetKernelArg(kern, 0, sizeof(cl_mem), (void*)&m_rays.atomicCounterMem)); CHECK_CL(clSetKernelArg(kern, 1, sizeof(cl_mem), (void*)&a_rayFlags)); CHECK_CL(clSetKernelArg(kern, 2, sizeof(cl_int), (void*)&iNumElements)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, kern, 1, NULL, &a_size, &szLocalWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } int counter = 0; CHECK_CL(clEnqueueReadBuffer(m_globals.cmdQueue, m_rays.atomicCounterMem, CL_TRUE, 0, sizeof(int), &counter, 0, NULL, NULL)); return counter; } void GPUOCLLayer::trace1DPrimaryOnly(cl_mem a_rpos, cl_mem a_rdir, cl_mem a_outColor, size_t a_size, size_t a_offset) { cl_kernel kernShowN = m_progs.trace.kernel("ShowNormals"); cl_kernel kernShowT = m_progs.trace.kernel("ShowTexCoord"); cl_kernel kernFill = m_progs.trace.kernel("ColorIndexTriangles"); //cl_kernel kern = m_progs.screen.kernel("FillColorTest"); size_t localWorkSize = 256; int isize = int(a_size); int ioffset = int(a_offset); // trace rays // memsetu32(m_rays.rayFlags, 0, a_size); // fill flags with zero data memsetf4(m_rays.hitSurfaceAll, float4(0,0,0,0), SURFACE_HIT_SIZE_IN_F4*m_rays.MEGABLOCKSIZE, 0); // clear surface hit if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); m_timer.start(); } runKernel_Trace(a_rpos, a_rdir, a_size, m_rays.hits); if (m_vars.m_varsI[HRT_ENABLE_MRAYS_COUNTERS]) { clFinish(m_globals.cmdQueue); m_stat.raysPerSec = float(a_size) / m_timer.getElapsed(); } runKernel_ComputeHit(a_rpos, a_rdir, m_rays.hits, a_size, a_size, m_rays.hitSurfaceAll, m_rays.hitProcTexData); // // if (true) { CHECK_CL(clSetKernelArg(kernShowN, 0, sizeof(cl_mem), (void*)&m_rays.hitSurfaceAll)); CHECK_CL(clSetKernelArg(kernShowN, 1, sizeof(cl_mem), (void*)&a_outColor)); CHECK_CL(clSetKernelArg(kernShowN, 2, sizeof(cl_int), (void*)&isize)); CHECK_CL(clSetKernelArg(kernShowN, 3, sizeof(cl_int), (void*)&ioffset)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, kernShowN, 1, NULL, &a_size, &localWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } else if (false) { CHECK_CL(clSetKernelArg(kernShowT, 0, sizeof(cl_mem), (void*)&m_rays.hitSurfaceAll)); CHECK_CL(clSetKernelArg(kernShowT, 1, sizeof(cl_mem), (void*)&a_outColor)); CHECK_CL(clSetKernelArg(kernShowT, 2, sizeof(cl_int), (void*)&isize)); CHECK_CL(clSetKernelArg(kernShowT, 3, sizeof(cl_int), (void*)&ioffset)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, kernShowT, 1, NULL, &a_size, &localWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } else { CHECK_CL(clSetKernelArg(kernFill, 0, sizeof(cl_mem), (void*)&m_rays.hits)); CHECK_CL(clSetKernelArg(kernFill, 1, sizeof(cl_mem), (void*)&a_outColor)); CHECK_CL(clSetKernelArg(kernFill, 2, sizeof(cl_int), (void*)&isize)); CHECK_CL(clSetKernelArg(kernFill, 3, sizeof(cl_int), (void*)&ioffset)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, kernFill, 1, NULL, &a_size, &localWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } } void GPUOCLLayer::CopyShadowTo(cl_mem a_color, size_t a_size) { size_t localWorkSize = CMP_RESULTS_BLOCK_SIZE; int iSize = int(a_size); a_size = roundBlocks(a_size, int(localWorkSize)); cl_kernel kern = m_progs.screen.kernel("CopyShadowTo"); CHECK_CL(clSetKernelArg(kern, 0, sizeof(cl_mem), (void*)&m_rays.pathShadow8B)); CHECK_CL(clSetKernelArg(kern, 1, sizeof(cl_mem), (void*)&a_color)); CHECK_CL(clSetKernelArg(kern, 2, sizeof(cl_int), (void*)&iSize)); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, kern, 1, NULL, &a_size, &localWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); } void GPUOCLLayer::DrawNormals() { //memsetf4(m_screen.color0, float4(0,0,0,0), m_width*m_height, 0); cl_kernel makeRaysKern = m_progs.screen.kernel("MakeEyeRays"); int iter = 0; for (size_t offset = 0; offset < m_width*m_height; offset += m_rays.MEGABLOCKSIZE) { size_t localWorkSize = 256; size_t globalWorkSize = m_rays.MEGABLOCKSIZE; cl_int iOffset = cl_int(offset); if (offset + globalWorkSize > (m_width*m_height)) globalWorkSize = (m_width*m_height) - offset; CHECK_CL(clSetKernelArg(makeRaysKern, 0, sizeof(cl_int), (void*)&iOffset)); CHECK_CL(clSetKernelArg(makeRaysKern, 1, sizeof(cl_mem), (void*)&m_rays.rayPos)); CHECK_CL(clSetKernelArg(makeRaysKern, 2, sizeof(cl_mem), (void*)&m_rays.rayDir)); CHECK_CL(clSetKernelArg(makeRaysKern, 3, sizeof(cl_int), (void*)&m_width)); CHECK_CL(clSetKernelArg(makeRaysKern, 4, sizeof(cl_int), (void*)&m_height)); CHECK_CL(clSetKernelArg(makeRaysKern, 5, sizeof(cl_mem), (void*)&m_scene.allGlobsData)); if (globalWorkSize % localWorkSize != 0) globalWorkSize = (globalWorkSize / localWorkSize)*localWorkSize; CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, makeRaysKern, 1, NULL, &globalWorkSize, &localWorkSize, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); trace1DPrimaryOnly(m_rays.rayPos, m_rays.rayDir, m_screen.color0, globalWorkSize, offset); // m_screen.colorSubBuffers[iter] iter++; } cl_mem tempLDRBuff = m_screen.pbo; //if (!(m_initFlags & GPU_RT_NOWINDOW)) // CHECK_CL(clEnqueueAcquireGLObjects(m_globals.cmdQueue, 1, &tempLDRBuff, 0, 0, 0)); cl_kernel colorKern = m_progs.screen.kernel("RealColorToRGB256"); size_t global_item_size[2] = { size_t(m_width), size_t(m_height) }; size_t local_item_size[2] = { 16, 16 }; RoundBlocks2D(global_item_size, local_item_size); CHECK_CL(clSetKernelArg(colorKern, 0, sizeof(cl_mem), (void*)&m_screen.color0)); CHECK_CL(clSetKernelArg(colorKern, 1, sizeof(cl_mem), (void*)&tempLDRBuff)); CHECK_CL(clSetKernelArg(colorKern, 2, sizeof(cl_int), (void*)&m_width)); CHECK_CL(clSetKernelArg(colorKern, 3, sizeof(cl_int), (void*)&m_height)); CHECK_CL(clSetKernelArg(colorKern, 4, sizeof(cl_mem), (void*)&m_globals.cMortonTable)); CHECK_CL(clSetKernelArg(colorKern, 5, sizeof(cl_float), (void*)&m_globsBuffHeader.varsF[HRT_IMAGE_GAMMA])); CHECK_CL(clEnqueueNDRangeKernel(m_globals.cmdQueue, colorKern, 2, NULL, global_item_size, local_item_size, 0, NULL, NULL)); waitIfDebug(__FILE__, __LINE__); //if (!(m_initFlags & GPU_RT_NOWINDOW)) // CHECK_CL(clEnqueueReleaseGLObjects(m_globals.cmdQueue, 1, &tempLDRBuff, 0, 0, 0)); }
#pragma once #include <deque> #include <memory> #include "Client.h" #include "Game.h" #include <boost/asio.hpp> #include "util\Protos.pb.h" #include "util\Util.h" #include <mutex> using boost::asio::ip::tcp; using namespace util; typedef std::deque<protos::Message> message_queue; class Session : public Client, public std::enable_shared_from_this<Session> { public: Session(tcp::socket socket, Game& game); void start(); void deliver(const protos::Message msg); private: void do_read_header(); void do_read_body(size_t length); void do_write(); tcp::socket socket_; Game& game_; char current_header_[HEADER_SIZE]; message_queue write_msgs_; std::mutex queueLock_; };
#include "pch.h" #include "Object.h" #include "Ray.h" Object::~Object() { }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) cin>>n; #define scc(c) cin>>c; #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define debug cout<<"I am here"<<endl; #define pno cout<<"NO"<<endl #define pys cout<<"YES"<<endl #define l(s) s.size() #define asort(a) sort(a,a+n) #define all(x) (x).begin(), (x).end() #define dsort(a) sort(a,a+n,greater<int>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<int>()); #define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end()) #define pn cout<<endl; #define md 1000000007 #define inf 1e18 #define ps cout<<" "; #define Pi acos(-1.0) #define mem(a,i) memset(a, i, sizeof(a)) #define tcas(i,t) for(ll i=1;i<=t;i++) #define pcas(i) cout<<"Case "<<i<<": "<<"\n"; #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define N 100006 int main() { fast; ll t; ll m,n,b,c,d,i,j,k,x,y,z,l,q,r; while(cin>>r>>c>>x) { ll l=1, h=r*c, mid=0, ans=-1; while(l<=h) { mid=(l+h)/2; ll cnt=0; fr1(i, r) cnt+=min(c, (mid-1)/i ); //cout<<l<<" "<<h<<" "<<mid<<endl; if(cnt<x) { ans=max(ans, mid); l=mid+1; } else h=mid-1; } cout<<ans<<endl; } return 0; } /* i| | elements < x | 1|1 2 3 4 5 6 ...|(x-1)/1 | 2|2 4 6 8 10 12 ...|(x-1)/2 | 3|3 6 9 12 15 18 ...|(x-1)/3 | . . . Let f(x) the number of elements on the multiplication table that are less than x. f can be compute by iterating each row and check how many numbers are less than x, that is (x-1)/i, but you have to remember that you only have m columns, so you take min(m,(x-1)/i). With binary search we want to find largest x so that f(x) < k. */ ///Before submit=> /// *check for integer overflow,array bounds /// *check for n=1
#include "readpara.h" ReaderFileAss::ReaderFileAss (string fn1, string fn2, int maxLine) { this->scoreFileName = fn1; this->targetFileName = fn2; this->maxLine = maxLine; this->nusr = 0; this->nmsg = 0; } void ReaderFileAss::getDataDimension () { ifstream inf; inf.open(this->scoreFileName.c_str(), ifstream::in); cout << " read " << this->scoreFileName.c_str() << endl; size_t index_separator; size_t index_separator_1; int iusr, imsg, usrNum, msgNum; int k = 0; double point; // read all usrId and msgId and save them in a set. set<string> usrIds; set<string> msgIds; string usrId, msgId; string str, line; while (!inf.eof()) { k += 1; if (k > maxLine) break; getline(inf, line); //if (k % 1000 == 0) //cout << line.c_str() << endl; // cout << " k = " << k << endl; index_separator = line.find(',', 0); usrId = line.substr(0, index_separator); index_separator_1 = line.find(',', index_separator + 1); msgId = line.substr(index_separator + 1, index_separator_1 - index_separator - 1); if (!usrId.empty()) usrIds.insert(usrId); if (!msgId.empty()) msgIds.insert(msgId); // cout << usrId.c_str() << " " << msgId.c_str() << endl; } inf.close(); usrNum = usrIds.size(); msgNum = msgIds.size(); cout << " number of users: " << usrNum << endl; cout << " number of messages: " << msgNum << endl; k = 0; for (set<string>::iterator it = usrIds.begin(); it != usrIds.end(); it++) { this->id2usr.insert(pair<int,string>(k, *it)); this->usr2id.insert(pair<string,int>(*it, k)); k += 1; } k = 0; for (set<string>::iterator it = msgIds.begin(); it != msgIds.end(); it++) { this->id2msg.insert(pair<int,string>(k, *it)); this->msg2id.insert(pair<string,int>(*it, k)); k += 1; } this->nusr = usrNum; this->nmsg = msgNum; this->ns = usrNum * msgNum; this->nm = usrNum * (msgNum + 1); this->score = new double[this->ns]; this->upper = new double[this->nmsg]; this->bottom = new double[this->nmsg]; this->target = new double[this->nmsg]; } void ReaderFileAss::readScoreFromFile () { size_t index_separator; size_t index_separator_1; size_t index_separator_2; int iusr, imsg, usrNum, msgNum; int k = 0; double point; string usrId, msgId; string str, line; ifstream inf; inf.open(this->scoreFileName.c_str(), ifstream::in); memset(this->score, 0, this->ns * sizeof(double)); while (!inf.eof()) { k += 1; if (k > maxLine) break; getline(inf, line); index_separator = line.find(',', 0); usrId = line.substr(0, index_separator); index_separator_1 = line.find(',', index_separator + 1); msgId = line.substr(index_separator + 1, index_separator_1 - index_separator - 1); index_separator_2 = line.find(',', index_separator_1 + 1); str = line.substr(index_separator_1 + 1, index_separator_2 - index_separator_1 - 1); if (!usrId.empty() && !msgId.empty()) { iusr = usr2id[usrId]; imsg = msg2id[msgId]; int ks = iusr * nmsg + imsg; if (ks < 0 || ks >= nusr * nmsg) continue; score[ks] = atof(str.c_str()); //cout << " ks = " << ks << ", score = " << score[ks] << endl; } // cout << usrId.c_str() << " " << msgId.c_str() << endl; } inf.close(); } void ReaderFileAss::readTargetFromFile () { size_t index_sep; size_t index_sep1; size_t index_sep2; size_t index_sep3; int iusr, imsg, usrNum, msgNum; int k = 0; string str, line, msgId; ifstream inf; inf.open(this->targetFileName.c_str(), ifstream::in); for (int imsg = 0; imsg < nmsg; imsg ++) { this->target[imsg] = nusr / nmsg; this->bottom[imsg] = 0.0; this->upper[imsg] = nusr; } while (!inf.eof()) { k += 1; if (k > maxLine) break; getline(inf, line); index_sep = line.find(',', 0); msgId = line.substr(0, index_sep); if (msgId.empty()) continue; imsg = msg2id[msgId]; index_sep1 = line.find(',', index_sep + 1); str = line.substr(index_sep + 1, index_sep1 - index_sep - 1); this->bottom[imsg] = atof(str.c_str()); index_sep2 = line.find(',', index_sep1 + 1); str = line.substr(index_sep1 + 1, index_sep2 - index_sep1 - 1); this->upper[imsg] = atof(str.c_str()); index_sep3 = line.find(',', index_sep2 + 1); str = line.substr(index_sep2 + 1, index_sep3 - index_sep2 - 1); this->target[imsg] = atof(str.c_str()); } inf.close(); } void ReaderFileAss::printScore () { for (int iusr = 0; iusr < nusr; iusr ++) for (int imsg = 0; imsg < nmsg; imsg ++) { cout << " score[" << iusr << "][" << imsg << "] = " << score[iusr * nmsg + imsg] << endl; } } void ReaderFileAss::printTarget () { double msg_score; cout << " imsg " << " msgId " << " score " << " bottom " << " upper " << " target " << endl; for (int imsg = 0; imsg < nmsg; imsg ++) { msg_score = 0; for (int iusr = 0; iusr < nusr; iusr ++) msg_score += score[iusr * nmsg + iusr]; cout << imsg << " " << id2msg[imsg].c_str() << " " << msg_score << " " << bottom[imsg] << " " << upper[imsg] << " " << target[imsg] << endl; } } void ReaderFileAss::free() { delete [] this->score; delete [] this->upper; delete [] this->bottom; delete [] this->target; }
#include "Conta.h" #include "ContaEspecial.h" #include "IConta.h" #include "SaldoNaoDisponivelException.h" #include <iostream> using namespace std; //g++ mainConta.cpp ContaEspecial.cpp Conta.cpp IConta.cpp SaldoNaoDisponivelException.cpp int main(){ string n; double slm, sl, lt , vl; int nc; int op; Conta c = Conta(n, slm, nc, sl); ContaEspecial ce; cout << "Digite o seu nome: " << endl; cin >> n; c.setNomeCliente(n); cout << "Digite o numero da conta: " << endl; cin >> nc; c.setNumeroConta(nc); cout << "Digite o seu salario mensal: " << endl; cin >> slm; c.setSalarioMensal(slm); c.setSaldo(slm); cout << endl; cout << " Escolha a sua operacao" << endl; cout << "1 - Sacar" << endl; cout << "2 - Depositar" << endl; cin >> op; switch (op){ case 1: cout << "Digite o valor para sacar: " << endl; cin >> vl; c.setValor(vl); c.sacar(c.getValor()); break; case 2: cout << "Digite o valor para deposito: " << endl; cin >> vl; c.setValor(vl); c.depositar(c.getValor()); break; default: break; } cout << "Para o limite escolha o seu limite de conta" << endl; cout << "1 - Conta normal" << endl; cout << "2 - Conta especial" << endl; cin >> op; switch (op){ case 1: c.definirlimite(c.getSalarioMensal()); break; case 2: ce.definirlimite(ce.getSalarioMensal()); break; default: break; } return 0; }
/** * @file UDPSocket.cpp * Implements the UDPSocket class. * @date Jun 21, 2013 * @author: Alper Sinan Akyurek */ #include "UDPSocket.h" UDPSocket::UDPSocket( void ) { } UDPSocket::~UDPSocket( void ) { } UDPSocket::TNumberOfBytes UDPSocket::SendData( const TBuffer buffer, const TNumberOfBytes length, IPAddress & destinationAddress ) { return ( sendto( this->m_socketId, buffer, length, 0, ( struct sockaddr* )destinationAddress, IPAddress::GetSocketSize() ) ); } UDPSocket::TNumberOfBytes UDPSocket::ReceiveData( TBuffer buffer, const TNumberOfBytes receptionLength, IPAddress & destinationAddress ) { IPAddress::TSocketSize socketSize = IPAddress::GetSocketSize(); return ( recvfrom( this->m_socketId, buffer, receptionLength, 0, ( struct sockaddr* )destinationAddress, &socketSize ) ); } void UDPSocket::SetIPAddress( IPAddress & address ) { bind( this->m_socketId, ( struct sockaddr* )address, IPAddress::GetSocketSize() ); } void UDPSocket::SetPort( const IPAddress::TPort port ) { IPAddress address; address.SetAddress( INADDR_ANY ); address.SetPort( port ); this->SetIPAddress( address ); }
/* *chapter 6 * A is an array i is the index heapSize is the size of A */ void heapsort(A) { build_max_heap(A); while (1 < A.heapSize) { exchange A[1] with A[A.heapSize]; A.heapSize -= 1; max_heapify(A, 1); } }
#ifndef _PLAYER_VIEW_H_ #define _PLAYER_VIEW_H_ //forward declaration class PathingGraph; #include "IGameView.h" /* This is AI Player View */ class AIPlayerView : public IGameView { private: std::shared_ptr<PathingGraph> m_pPathingGraph; protected: unsigned int m_ViewId; unsigned int m_PlayerActorId; public: AIPlayerView(std::shared_ptr<PathingGraph> pPathingGraph); virtual ~AIPlayerView(); virtual HRESULT VOnRestore() { return S_OK; } virtual void VOnRender(double fTime, float fElapsedTime) {} virtual HRESULT VOnLostDevice() { return S_OK; } virtual GameViewType VGetType() { return GameView_AI; } virtual unsigned int VGetId() const { return m_ViewId; } virtual void VOnAttach(unsigned int vid, unsigned int actorId) { m_ViewId = vid; m_PlayerActorId = actorId; } virtual LRESULT CALLBACK VOnMsgProc(AppMsg msg) { return 0; } virtual void VOnUpdate(unsigned long deltaMs) {} std::shared_ptr<PathingGraph> GetPathingGraph(void) const { return m_pPathingGraph; } }; #endif
#include <QApplication> #include "gui_basis/mainwindow.h" #include "kernel/ifc/ICore.h" #include "Context.h" using namespace smeta3d; int main(int argc, char *argv[]) { QApplication a(argc, argv); SP_ICore ptrCore = GetSingltonCore(); CMainWindow w; CContext* context = new CContext(&w); w.setCentralWidget(context); ptrCore->Init((HWND)context->winId()); w.show(); int nRet = a.exec(); ptrCore->DeInit(); return nRet; }
#include "stdafx.h" BackBuffer::BackBuffer() { hMemDC = NULL; hBit = NULL; hOldBit = NULL; width = 0; height = 0; } void BackBuffer::Init(int _width, int _height) { HDC hdc = GetDC(hWnd); hMemDC = CreateCompatibleDC(hdc); hBit = CreateCompatibleBitmap(hdc, _width, _height); hOldBit = (HBITMAP)SelectObject(hMemDC, hBit); width = _width; height = _height; ReleaseDC(hWnd, hdc); } void BackBuffer::Release() { SelectObject(hMemDC, hOldBit); DeleteObject(hBit); DeleteDC(hMemDC); } void BackBuffer::Render(HDC hdc) { BitBlt(hdc, 0, 0, width, height, hMemDC, 0, 0, SRCCOPY); }
#include "PIDcontroller.h" PIDcontroller::PIDcontroller() { Kp = 0.0; Ki = 0.0; Kd = 0.0; dT = 0.0; e_prev = 0.0; e_int = 0.0; } PIDcontroller::PIDcontroller(double Kp_in, double Ki_in, double Kd_in, double dT_in, double e_prev_in, double e_int_in){ Kp = Kp_in; Ki = Ki_in; Kd = Kd_in; dT = dT_in; e_prev = e_prev_in; e_int = e_int_in; } PIDcontroller::~PIDcontroller() { } void PIDcontroller::setGains(double Kp_in, double Ki_in, double Kd_in, double dT_in){ Kp = Kp_in; Ki = Ki_in; Kd = Kd_in; dT = dT_in; } double PIDcontroller::calcControl(double e_now){ e_int = e_now * dT + e_int; double de = (e_now - e_prev) / dT; double u = (Kp*e_now) + (Ki*e_int) + (Kd*de); e_prev = e_now; return u; } double PIDcontroller::calcControl(double e_now, double dT_new){ dT = dT_new; return calcControl(e_now); }
#include "gui\Singularity.Gui.h" using namespace Singularity::Inputs; namespace Singularity { namespace Gui { ListBox::ListBox(String name) : TextControl(name, ""), m_pOptionTexture(NULL), m_pOptionHighlightTexture(NULL), m_cOptionColor(Color(1,1,1,1)), m_cOptionHighlightColor(Color(1,1,1,1)), m_bMouseDown(false) { Set_OptionTexture(this->Get_Texture()); m_pListPanel = new ListPanel(this->Get_Name() + "_ListElementPanel"); this->AddChildControl(m_pListPanel); m_pListPanel->Set_Position(Vector2(0, this->Get_Size().y)); m_pListPanel->Set_Size(Vector2(0, 0)); this->m_pOptionTexture = this->Get_Texture(); this->m_pOptionHighlightTexture = this->Get_Texture(); // just to make sure we're actually never drawing the panel itself m_pListPanel->Set_Texture(new NinePatch(Texture2D::LoadTextureFromFile("..\\..\\..\\Assets\\Textures\\Gui\\Transparent.png"), Vector4(0,0,0,0))); m_pListPanel->Set_Visible(false); } void ListBox::Clear() { this->m_pListPanel->Clear(); } // becomes un-extended so the user doesn't see the removal / void ListBox::RemoveOption(int optionNum) { this->m_pListPanel->RemoveListElement(optionNum); this->RebuildControl(); m_bNeedToRecalc = true; // todo: we still need to update everything's position and all that jazz } void ListBox::RemoveOption(String optionName) { this->m_pListPanel->RemoveListElement(optionName); this->RebuildControl(); m_bNeedToRecalc = true; } void ListBox::AddOption(String optionName) { m_pListPanel->Set_Position(Vector2(0, this->Get_Size().y)); ListBoxElement* element = NULL; m_pListPanel->AddOption(optionName); //m_pListPanel->AddListElement((CreateListElement(optionName))); m_pListPanel->RepositionElements(); this->RebuildControl(); m_bNeedToRecalc = true; if (m_pText == "") { this->Set_Text(optionName); } } void ListBox::AddOption(String optionName, int insertLocation) { m_pListPanel->AddListElement((CreateListElement(optionName)), insertLocation); this->RebuildControl(); m_bNeedToRecalc = true; if (m_pText == "") { this->Set_Text(optionName); } m_pListPanel->RepositionElements(); this->RebuildControl(); } void ListBox::OnMouseDown(Vector2 position) { if (this->Get_Visible()) this->m_bMouseDown = true; } void ListBox::OnMouseUp(Vector2 position) { if(this->m_bMouseDown) this->OnClick(); this->m_bMouseDown = false; } void ListBox::OnClick() { m_pListPanel->Set_Visible(!m_pListPanel->Get_Visible()); m_pListPanel->RebuildControl(true); } void ListBox::OnFocusLost() { // we're never getting here... :/ this->m_bMouseDown = false; m_pListPanel->Set_Visible(false); this->RebuildControl(); } void ListBox::InitializeListBox() { for (int i = 0; i < SINGULARITY_GUI_MAX_LISTBOX_ELEMENT_COUNT; i++) { m_pListPanel->AddListElement((CreateListElement(""))); } } ListBoxElement* ListBox::CreateListElement(String text) { ListBoxElement* retval = new ListBoxElement(text, this); retval->Set_OptionTexture(m_pOptionTexture); retval->Set_HighlightTexture(m_pOptionHighlightTexture); retval->Set_Size(this->Get_Size()); retval->Set_Position(Vector2(0, m_pListPanel->Get_NumberOfChildren() * this->Get_Size().y)); retval->Set_Font(this->Get_Font()); retval->Set_OptionColor(m_cOptionColor); retval->Set_OptionHighlightColor(m_cOptionHighlightColor); return retval; } void ListBox::Set_Extended(bool extended) { m_pListPanel->Set_Visible(extended); m_pListPanel->RebuildControl(true); } void ListBox::ItemSelected(ListBoxElement* item) { this->Set_Text(item->Get_Text()); this->Set_Extended(false); for(unsigned i = 0; i < this->Select.Count(); ++i) ((ListBoxDelegate*)this->Select[i])->Invoke(this, item); } } }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.UI.Xaml.Media.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.UI.Xaml.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.UI.Composition.3.h" #include "internal/Windows.UI.Xaml.Shapes.3.h" #include "Windows.UI.Xaml.h" #include "internal/Windows.UI.Xaml.Shapes.5.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IEllipse> : produce_base<D, Windows::UI::Xaml::Shapes::IEllipse> {}; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::ILine> : produce_base<D, Windows::UI::Xaml::Shapes::ILine> { HRESULT __stdcall get_X1(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().X1()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_X1(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().X1(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Y1(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Y1()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_Y1(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Y1(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_X2(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().X2()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_X2(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().X2(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Y2(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Y2()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_Y2(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Y2(value); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::ILineStatics> : produce_base<D, Windows::UI::Xaml::Shapes::ILineStatics> { HRESULT __stdcall get_X1Property(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().X1Property()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Y1Property(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Y1Property()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_X2Property(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().X2Property()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Y2Property(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Y2Property()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPath> : produce_base<D, Windows::UI::Xaml::Shapes::IPath> { HRESULT __stdcall get_Data(impl::abi_arg_out<Windows::UI::Xaml::Media::IGeometry> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Data()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_Data(impl::abi_arg_in<Windows::UI::Xaml::Media::IGeometry> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Data(*reinterpret_cast<const Windows::UI::Xaml::Media::Geometry *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPathFactory> : produce_base<D, Windows::UI::Xaml::Shapes::IPathFactory> { HRESULT __stdcall abi_CreateInstance(impl::abi_arg_in<Windows::Foundation::IInspectable> outer, impl::abi_arg_out<Windows::Foundation::IInspectable> inner, impl::abi_arg_out<Windows::UI::Xaml::Shapes::IPath> instance) noexcept override { try { typename D::abi_guard guard(this->shim()); *instance = detach_abi(this->shim().CreateInstance(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&outer), *inner)); return S_OK; } catch (...) { *inner = nullptr; *instance = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPathStatics> : produce_base<D, Windows::UI::Xaml::Shapes::IPathStatics> { HRESULT __stdcall get_DataProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DataProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPolygon> : produce_base<D, Windows::UI::Xaml::Shapes::IPolygon> { HRESULT __stdcall get_FillRule(Windows::UI::Xaml::Media::FillRule * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().FillRule()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_FillRule(Windows::UI::Xaml::Media::FillRule value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().FillRule(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Points(impl::abi_arg_out<Windows::Foundation::Collections::IVector<Windows::Foundation::Point>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Points()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_Points(impl::abi_arg_in<Windows::Foundation::Collections::IVector<Windows::Foundation::Point>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Points(*reinterpret_cast<const Windows::UI::Xaml::Media::PointCollection *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPolygonStatics> : produce_base<D, Windows::UI::Xaml::Shapes::IPolygonStatics> { HRESULT __stdcall get_FillRuleProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().FillRuleProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_PointsProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PointsProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPolyline> : produce_base<D, Windows::UI::Xaml::Shapes::IPolyline> { HRESULT __stdcall get_FillRule(Windows::UI::Xaml::Media::FillRule * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().FillRule()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_FillRule(Windows::UI::Xaml::Media::FillRule value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().FillRule(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Points(impl::abi_arg_out<Windows::Foundation::Collections::IVector<Windows::Foundation::Point>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Points()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_Points(impl::abi_arg_in<Windows::Foundation::Collections::IVector<Windows::Foundation::Point>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Points(*reinterpret_cast<const Windows::UI::Xaml::Media::PointCollection *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IPolylineStatics> : produce_base<D, Windows::UI::Xaml::Shapes::IPolylineStatics> { HRESULT __stdcall get_FillRuleProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().FillRuleProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_PointsProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PointsProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IRectangle> : produce_base<D, Windows::UI::Xaml::Shapes::IRectangle> { HRESULT __stdcall get_RadiusX(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RadiusX()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_RadiusX(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().RadiusX(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_RadiusY(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RadiusY()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_RadiusY(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().RadiusY(value); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IRectangleStatics> : produce_base<D, Windows::UI::Xaml::Shapes::IRectangleStatics> { HRESULT __stdcall get_RadiusXProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RadiusXProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_RadiusYProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RadiusYProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IShape> : produce_base<D, Windows::UI::Xaml::Shapes::IShape> { HRESULT __stdcall get_Fill(impl::abi_arg_out<Windows::UI::Xaml::Media::IBrush> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Fill()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_Fill(impl::abi_arg_in<Windows::UI::Xaml::Media::IBrush> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Fill(*reinterpret_cast<const Windows::UI::Xaml::Media::Brush *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Stroke(impl::abi_arg_out<Windows::UI::Xaml::Media::IBrush> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Stroke()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_Stroke(impl::abi_arg_in<Windows::UI::Xaml::Media::IBrush> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Stroke(*reinterpret_cast<const Windows::UI::Xaml::Media::Brush *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeMiterLimit(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeMiterLimit()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeMiterLimit(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeMiterLimit(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeThickness(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeThickness()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeThickness(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeThickness(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeStartLineCap(Windows::UI::Xaml::Media::PenLineCap * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeStartLineCap()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeStartLineCap(Windows::UI::Xaml::Media::PenLineCap value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeStartLineCap(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeEndLineCap(Windows::UI::Xaml::Media::PenLineCap * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeEndLineCap()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeEndLineCap(Windows::UI::Xaml::Media::PenLineCap value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeEndLineCap(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeLineJoin(Windows::UI::Xaml::Media::PenLineJoin * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeLineJoin()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeLineJoin(Windows::UI::Xaml::Media::PenLineJoin value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeLineJoin(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashOffset(double * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashOffset()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeDashOffset(double value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeDashOffset(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashCap(Windows::UI::Xaml::Media::PenLineCap * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashCap()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_StrokeDashCap(Windows::UI::Xaml::Media::PenLineCap value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeDashCap(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashArray(impl::abi_arg_out<Windows::Foundation::Collections::IVector<double>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashArray()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_StrokeDashArray(impl::abi_arg_in<Windows::Foundation::Collections::IVector<double>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StrokeDashArray(*reinterpret_cast<const Windows::UI::Xaml::Media::DoubleCollection *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Stretch(Windows::UI::Xaml::Media::Stretch * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Stretch()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_Stretch(Windows::UI::Xaml::Media::Stretch value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Stretch(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_GeometryTransform(impl::abi_arg_out<Windows::UI::Xaml::Media::ITransform> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GeometryTransform()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IShape2> : produce_base<D, Windows::UI::Xaml::Shapes::IShape2> { HRESULT __stdcall abi_GetAlphaMask(impl::abi_arg_out<Windows::UI::Composition::ICompositionBrush> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().GetAlphaMask()); return S_OK; } catch (...) { *returnValue = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IShapeFactory> : produce_base<D, Windows::UI::Xaml::Shapes::IShapeFactory> { HRESULT __stdcall abi_CreateInstance(impl::abi_arg_in<Windows::Foundation::IInspectable> outer, impl::abi_arg_out<Windows::Foundation::IInspectable> inner, impl::abi_arg_out<Windows::UI::Xaml::Shapes::IShape> instance) noexcept override { try { typename D::abi_guard guard(this->shim()); *instance = detach_abi(this->shim().CreateInstance(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&outer), *inner)); return S_OK; } catch (...) { *inner = nullptr; *instance = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Shapes::IShapeStatics> : produce_base<D, Windows::UI::Xaml::Shapes::IShapeStatics> { HRESULT __stdcall get_FillProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().FillProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeMiterLimitProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeMiterLimitProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeThicknessProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeThicknessProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeStartLineCapProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeStartLineCapProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeEndLineCapProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeEndLineCapProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeLineJoinProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeLineJoinProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashOffsetProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashOffsetProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashCapProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashCapProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StrokeDashArrayProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StrokeDashArrayProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_StretchProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().StretchProperty()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; } namespace Windows::UI::Xaml::Shapes { template <typename D> Windows::UI::Xaml::Media::Brush impl_IShape<D>::Fill() const { Windows::UI::Xaml::Media::Brush value { nullptr }; check_hresult(WINRT_SHIM(IShape)->get_Fill(put_abi(value))); return value; } template <typename D> void impl_IShape<D>::Fill(const Windows::UI::Xaml::Media::Brush & value) const { check_hresult(WINRT_SHIM(IShape)->put_Fill(get_abi(value))); } template <typename D> Windows::UI::Xaml::Media::Brush impl_IShape<D>::Stroke() const { Windows::UI::Xaml::Media::Brush value { nullptr }; check_hresult(WINRT_SHIM(IShape)->get_Stroke(put_abi(value))); return value; } template <typename D> void impl_IShape<D>::Stroke(const Windows::UI::Xaml::Media::Brush & value) const { check_hresult(WINRT_SHIM(IShape)->put_Stroke(get_abi(value))); } template <typename D> double impl_IShape<D>::StrokeMiterLimit() const { double value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeMiterLimit(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeMiterLimit(double value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeMiterLimit(value)); } template <typename D> double impl_IShape<D>::StrokeThickness() const { double value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeThickness(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeThickness(double value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeThickness(value)); } template <typename D> Windows::UI::Xaml::Media::PenLineCap impl_IShape<D>::StrokeStartLineCap() const { Windows::UI::Xaml::Media::PenLineCap value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeStartLineCap(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeStartLineCap(Windows::UI::Xaml::Media::PenLineCap value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeStartLineCap(value)); } template <typename D> Windows::UI::Xaml::Media::PenLineCap impl_IShape<D>::StrokeEndLineCap() const { Windows::UI::Xaml::Media::PenLineCap value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeEndLineCap(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeEndLineCap(Windows::UI::Xaml::Media::PenLineCap value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeEndLineCap(value)); } template <typename D> Windows::UI::Xaml::Media::PenLineJoin impl_IShape<D>::StrokeLineJoin() const { Windows::UI::Xaml::Media::PenLineJoin value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeLineJoin(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeLineJoin(Windows::UI::Xaml::Media::PenLineJoin value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeLineJoin(value)); } template <typename D> double impl_IShape<D>::StrokeDashOffset() const { double value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeDashOffset(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeDashOffset(double value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeDashOffset(value)); } template <typename D> Windows::UI::Xaml::Media::PenLineCap impl_IShape<D>::StrokeDashCap() const { Windows::UI::Xaml::Media::PenLineCap value {}; check_hresult(WINRT_SHIM(IShape)->get_StrokeDashCap(&value)); return value; } template <typename D> void impl_IShape<D>::StrokeDashCap(Windows::UI::Xaml::Media::PenLineCap value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeDashCap(value)); } template <typename D> Windows::UI::Xaml::Media::DoubleCollection impl_IShape<D>::StrokeDashArray() const { Windows::UI::Xaml::Media::DoubleCollection value { nullptr }; check_hresult(WINRT_SHIM(IShape)->get_StrokeDashArray(put_abi(value))); return value; } template <typename D> void impl_IShape<D>::StrokeDashArray(const Windows::UI::Xaml::Media::DoubleCollection & value) const { check_hresult(WINRT_SHIM(IShape)->put_StrokeDashArray(get_abi(value))); } template <typename D> Windows::UI::Xaml::Media::Stretch impl_IShape<D>::Stretch() const { Windows::UI::Xaml::Media::Stretch value {}; check_hresult(WINRT_SHIM(IShape)->get_Stretch(&value)); return value; } template <typename D> void impl_IShape<D>::Stretch(Windows::UI::Xaml::Media::Stretch value) const { check_hresult(WINRT_SHIM(IShape)->put_Stretch(value)); } template <typename D> Windows::UI::Xaml::Media::Transform impl_IShape<D>::GeometryTransform() const { Windows::UI::Xaml::Media::Transform value { nullptr }; check_hresult(WINRT_SHIM(IShape)->get_GeometryTransform(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::FillProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_FillProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeMiterLimitProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeMiterLimitProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeThicknessProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeThicknessProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeStartLineCapProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeStartLineCapProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeEndLineCapProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeEndLineCapProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeLineJoinProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeLineJoinProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeDashOffsetProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeDashOffsetProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeDashCapProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeDashCapProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StrokeDashArrayProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StrokeDashArrayProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IShapeStatics<D>::StretchProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IShapeStatics)->get_StretchProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::Shapes::Shape impl_IShapeFactory<D>::CreateInstance(const Windows::Foundation::IInspectable & outer, Windows::Foundation::IInspectable & inner) const { Windows::UI::Xaml::Shapes::Shape instance { nullptr }; check_hresult(WINRT_SHIM(IShapeFactory)->abi_CreateInstance(get_abi(outer), put_abi(inner), put_abi(instance))); return instance; } template <typename D> Windows::UI::Composition::CompositionBrush impl_IShape2<D>::GetAlphaMask() const { Windows::UI::Composition::CompositionBrush returnValue { nullptr }; check_hresult(WINRT_SHIM(IShape2)->abi_GetAlphaMask(put_abi(returnValue))); return returnValue; } template <typename D> double impl_ILine<D>::X1() const { double value {}; check_hresult(WINRT_SHIM(ILine)->get_X1(&value)); return value; } template <typename D> void impl_ILine<D>::X1(double value) const { check_hresult(WINRT_SHIM(ILine)->put_X1(value)); } template <typename D> double impl_ILine<D>::Y1() const { double value {}; check_hresult(WINRT_SHIM(ILine)->get_Y1(&value)); return value; } template <typename D> void impl_ILine<D>::Y1(double value) const { check_hresult(WINRT_SHIM(ILine)->put_Y1(value)); } template <typename D> double impl_ILine<D>::X2() const { double value {}; check_hresult(WINRT_SHIM(ILine)->get_X2(&value)); return value; } template <typename D> void impl_ILine<D>::X2(double value) const { check_hresult(WINRT_SHIM(ILine)->put_X2(value)); } template <typename D> double impl_ILine<D>::Y2() const { double value {}; check_hresult(WINRT_SHIM(ILine)->get_Y2(&value)); return value; } template <typename D> void impl_ILine<D>::Y2(double value) const { check_hresult(WINRT_SHIM(ILine)->put_Y2(value)); } template <typename D> Windows::UI::Xaml::DependencyProperty impl_ILineStatics<D>::X1Property() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(ILineStatics)->get_X1Property(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_ILineStatics<D>::Y1Property() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(ILineStatics)->get_Y1Property(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_ILineStatics<D>::X2Property() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(ILineStatics)->get_X2Property(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_ILineStatics<D>::Y2Property() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(ILineStatics)->get_Y2Property(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::Media::Geometry impl_IPath<D>::Data() const { Windows::UI::Xaml::Media::Geometry value { nullptr }; check_hresult(WINRT_SHIM(IPath)->get_Data(put_abi(value))); return value; } template <typename D> void impl_IPath<D>::Data(const Windows::UI::Xaml::Media::Geometry & value) const { check_hresult(WINRT_SHIM(IPath)->put_Data(get_abi(value))); } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPathStatics<D>::DataProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IPathStatics)->get_DataProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::Shapes::Path impl_IPathFactory<D>::CreateInstance(const Windows::Foundation::IInspectable & outer, Windows::Foundation::IInspectable & inner) const { Windows::UI::Xaml::Shapes::Path instance { nullptr }; check_hresult(WINRT_SHIM(IPathFactory)->abi_CreateInstance(get_abi(outer), put_abi(inner), put_abi(instance))); return instance; } template <typename D> Windows::UI::Xaml::Media::FillRule impl_IPolygon<D>::FillRule() const { Windows::UI::Xaml::Media::FillRule value {}; check_hresult(WINRT_SHIM(IPolygon)->get_FillRule(&value)); return value; } template <typename D> void impl_IPolygon<D>::FillRule(Windows::UI::Xaml::Media::FillRule value) const { check_hresult(WINRT_SHIM(IPolygon)->put_FillRule(value)); } template <typename D> Windows::UI::Xaml::Media::PointCollection impl_IPolygon<D>::Points() const { Windows::UI::Xaml::Media::PointCollection value { nullptr }; check_hresult(WINRT_SHIM(IPolygon)->get_Points(put_abi(value))); return value; } template <typename D> void impl_IPolygon<D>::Points(const Windows::UI::Xaml::Media::PointCollection & value) const { check_hresult(WINRT_SHIM(IPolygon)->put_Points(get_abi(value))); } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPolygonStatics<D>::FillRuleProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IPolygonStatics)->get_FillRuleProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPolygonStatics<D>::PointsProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IPolygonStatics)->get_PointsProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::Media::FillRule impl_IPolyline<D>::FillRule() const { Windows::UI::Xaml::Media::FillRule value {}; check_hresult(WINRT_SHIM(IPolyline)->get_FillRule(&value)); return value; } template <typename D> void impl_IPolyline<D>::FillRule(Windows::UI::Xaml::Media::FillRule value) const { check_hresult(WINRT_SHIM(IPolyline)->put_FillRule(value)); } template <typename D> Windows::UI::Xaml::Media::PointCollection impl_IPolyline<D>::Points() const { Windows::UI::Xaml::Media::PointCollection value { nullptr }; check_hresult(WINRT_SHIM(IPolyline)->get_Points(put_abi(value))); return value; } template <typename D> void impl_IPolyline<D>::Points(const Windows::UI::Xaml::Media::PointCollection & value) const { check_hresult(WINRT_SHIM(IPolyline)->put_Points(get_abi(value))); } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPolylineStatics<D>::FillRuleProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IPolylineStatics)->get_FillRuleProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IPolylineStatics<D>::PointsProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IPolylineStatics)->get_PointsProperty(put_abi(value))); return value; } template <typename D> double impl_IRectangle<D>::RadiusX() const { double value {}; check_hresult(WINRT_SHIM(IRectangle)->get_RadiusX(&value)); return value; } template <typename D> void impl_IRectangle<D>::RadiusX(double value) const { check_hresult(WINRT_SHIM(IRectangle)->put_RadiusX(value)); } template <typename D> double impl_IRectangle<D>::RadiusY() const { double value {}; check_hresult(WINRT_SHIM(IRectangle)->get_RadiusY(&value)); return value; } template <typename D> void impl_IRectangle<D>::RadiusY(double value) const { check_hresult(WINRT_SHIM(IRectangle)->put_RadiusY(value)); } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IRectangleStatics<D>::RadiusXProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IRectangleStatics)->get_RadiusXProperty(put_abi(value))); return value; } template <typename D> Windows::UI::Xaml::DependencyProperty impl_IRectangleStatics<D>::RadiusYProperty() const { Windows::UI::Xaml::DependencyProperty value { nullptr }; check_hresult(WINRT_SHIM(IRectangleStatics)->get_RadiusYProperty(put_abi(value))); return value; } inline Ellipse::Ellipse() : Ellipse(activate_instance<Ellipse>()) {} inline Line::Line() : Line(activate_instance<Line>()) {} inline Windows::UI::Xaml::DependencyProperty Line::X1Property() { return get_activation_factory<Line, ILineStatics>().X1Property(); } inline Windows::UI::Xaml::DependencyProperty Line::Y1Property() { return get_activation_factory<Line, ILineStatics>().Y1Property(); } inline Windows::UI::Xaml::DependencyProperty Line::X2Property() { return get_activation_factory<Line, ILineStatics>().X2Property(); } inline Windows::UI::Xaml::DependencyProperty Line::Y2Property() { return get_activation_factory<Line, ILineStatics>().Y2Property(); } inline Path::Path() { Windows::Foundation::IInspectable outer, inner; impl_move(get_activation_factory<Path, IPathFactory>().CreateInstance(outer, inner)); } inline Windows::UI::Xaml::DependencyProperty Path::DataProperty() { return get_activation_factory<Path, IPathStatics>().DataProperty(); } inline Polygon::Polygon() : Polygon(activate_instance<Polygon>()) {} inline Windows::UI::Xaml::DependencyProperty Polygon::FillRuleProperty() { return get_activation_factory<Polygon, IPolygonStatics>().FillRuleProperty(); } inline Windows::UI::Xaml::DependencyProperty Polygon::PointsProperty() { return get_activation_factory<Polygon, IPolygonStatics>().PointsProperty(); } inline Polyline::Polyline() : Polyline(activate_instance<Polyline>()) {} inline Windows::UI::Xaml::DependencyProperty Polyline::FillRuleProperty() { return get_activation_factory<Polyline, IPolylineStatics>().FillRuleProperty(); } inline Windows::UI::Xaml::DependencyProperty Polyline::PointsProperty() { return get_activation_factory<Polyline, IPolylineStatics>().PointsProperty(); } inline Rectangle::Rectangle() : Rectangle(activate_instance<Rectangle>()) {} inline Windows::UI::Xaml::DependencyProperty Rectangle::RadiusXProperty() { return get_activation_factory<Rectangle, IRectangleStatics>().RadiusXProperty(); } inline Windows::UI::Xaml::DependencyProperty Rectangle::RadiusYProperty() { return get_activation_factory<Rectangle, IRectangleStatics>().RadiusYProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::FillProperty() { return get_activation_factory<Shape, IShapeStatics>().FillProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeMiterLimitProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeMiterLimitProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeThicknessProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeThicknessProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeStartLineCapProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeStartLineCapProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeEndLineCapProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeEndLineCapProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeLineJoinProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeLineJoinProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeDashOffsetProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeDashOffsetProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeDashCapProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeDashCapProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StrokeDashArrayProperty() { return get_activation_factory<Shape, IShapeStatics>().StrokeDashArrayProperty(); } inline Windows::UI::Xaml::DependencyProperty Shape::StretchProperty() { return get_activation_factory<Shape, IShapeStatics>().StretchProperty(); } } } template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IEllipse> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IEllipse & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::ILine> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::ILine & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::ILineStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::ILineStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPath> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPath & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPathFactory> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPathFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPathStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPathStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPolygon> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPolygon & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPolygonStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPolygonStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPolyline> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPolyline & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IPolylineStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IPolylineStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IRectangle> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IRectangle & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IRectangleStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IRectangleStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IShape> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IShape & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IShape2> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IShape2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IShapeFactory> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IShapeFactory & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::IShapeStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::IShapeStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Ellipse> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Ellipse & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Line> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Line & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Path> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Path & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Polygon> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Polygon & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Polyline> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Polyline & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Rectangle> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Rectangle & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Shapes::Shape> { size_t operator()(const winrt::Windows::UI::Xaml::Shapes::Shape & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
#include "..\Render\VertexBuffer.h" #include <stdlib.h> #include "..\GLRender\opengl.h" VertexBuffer::~VertexBuffer() { } class gl_VertexBuffer : public VertexBuffer { public: gl_VertexBuffer(const unsigned char versionGL[2]); virtual ~gl_VertexBuffer() override { release(); } virtual void release(void) override; virtual void setData(const void* data, unsigned long size, BufferUsage usage) override; virtual void* lock(unsigned long offset, unsigned long length, LockOptions options) override; virtual void* lock(LockOptions options) override; virtual void unlock(void) override; virtual unsigned long getSizeInBytes(void) const override { return m_ulBufferSize; } private: GLuint m_handle; unsigned long m_ulBufferSize; unsigned char m_bZeroLocked; typedef void* (*PFNFOCKPROC)(unsigned long offset, unsigned long length, LockOptions options); PFNFOCKPROC f_glLock; friend static void* glLock_15(unsigned long offset, unsigned long length, LockOptions options); friend static void* glLock_30(unsigned long offset, unsigned long length, LockOptions options); friend static void* glLock_45(unsigned long offset, unsigned long length, LockOptions options); }; gl_VertexBuffer::gl_VertexBuffer(const unsigned char versionGL[2]) : m_handle(0U) , m_ulBufferSize(0UL) , m_bZeroLocked(0) , f_glLock(nullptr) { if (versionGL[0] < 3) { f_glLock = glLock_15; } else { f_glLock = glLock_30; } } void gl_VertexBuffer::release(void) { if (m_handle) { glDeleteBuffers(1, &m_handle); m_handle = 0U; } } void gl_VertexBuffer::setData(const void* data, unsigned long size, BufferUsage usage) { if (!m_handle) { glGenBuffers(1, &m_handle); } glBindBuffer(GL_ARRAY_BUFFER, m_handle); switch (usage) { case Static: glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_STATIC_DRAW); break; case Dynamic: glBufferData(GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW); break; default: break; } m_ulBufferSize = size; } void* gl_VertexBuffer::lock(unsigned long offset, unsigned long length, LockOptions options) { GLenum access; switch (options) { case READ_WRITE: access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break; case WRITE_ONLY_DISCARD: access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; break; case READ_ONLY: access = GL_MAP_READ_BIT; break; case WRITE_ONLY_NO_OVERWRITE: access = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; break; case WRITE_ONLY: access = GL_MAP_WRITE_BIT; break; default: access = 0; break; } glBindBuffer(GL_ARRAY_BUFFER, m_handle); void* buffer = nullptr; if (length) { buffer = f_glLock(offset, length, options); if (!buffer) { // error } m_bZeroLocked = false; } else { m_bZeroLocked = true; } return buffer; } void* gl_VertexBuffer::lock(LockOptions options) { return lock(0, m_ulBufferSize, options); } void gl_VertexBuffer::unlock(void) { glBindBuffer(GL_ARRAY_BUFFER, m_handle); if (!m_bZeroLocked) { glUnmapBuffer(GL_ARRAY_BUFFER); } } static void* glLock_15(unsigned long offset, unsigned long length, LockOptions options) { GLenum access; switch (options) { case READ_WRITE: access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break; case WRITE_ONLY_DISCARD: access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; break; case READ_ONLY: access = GL_MAP_READ_BIT; break; case WRITE_ONLY_NO_OVERWRITE: access = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; break; case WRITE_ONLY: access = GL_MAP_WRITE_BIT; break; default: access = 0; break; } void* buffer = glMapBuffer(GL_ARRAY_BUFFER, access); if (false && offset) { unsigned char* bBuffer = static_cast<unsigned char*>(buffer) + offset; buffer = static_cast<void*>(bBuffer); } return buffer; } static void* glLock_30(unsigned long offset, unsigned long length, LockOptions options) { GLenum access; switch (options) { case READ_WRITE: access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break; case WRITE_ONLY_DISCARD: access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; break; case READ_ONLY: access = GL_MAP_READ_BIT; break; case WRITE_ONLY_NO_OVERWRITE: access = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; break; case WRITE_ONLY: access = GL_MAP_WRITE_BIT; break; default: access = 0; break; } void* buffer = glMapBufferRange(GL_ARRAY_BUFFER, offset, length, access); return buffer; } static void* glLock_45(unsigned long offset, unsigned long length, LockOptions options) { GLenum access; switch (options) { case READ_WRITE: access = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT; break; case WRITE_ONLY_DISCARD: access = GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT; break; case READ_ONLY: access = GL_MAP_READ_BIT; break; case WRITE_ONLY_NO_OVERWRITE: access = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; break; case WRITE_ONLY: access = GL_MAP_WRITE_BIT; break; default: access = 0; break; } void* buffer = glMapNamedBufferRange(GL_ARRAY_BUFFER, offset, length, access); return buffer; } EXTERN_C VertexBuffer* createVertexBuffer(const unsigned char versionGL[2]) { gl_VertexBuffer* result = new gl_VertexBuffer(versionGL); return static_cast<VertexBuffer*>(result); }
/* Firmware to read wireless UART data from datalogger FE4 */ const int ledPin = 13; // the pin that the LED is attached to, internal is 13 uint8_t incomingByte; // a variable to read incoming serial data into uint8_t xbee_msg[16]; uint16_t id; uint32_t timestamp; uint8_t data[8]; uint8_t delimiter[2]; void setup() { // initialize serial communication: Serial.begin(9600); // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); delimiter[0] = 0; delimiter[1] = 0; } void loop() { // see if there's incoming serial data: if (Serial.available() > 17) { //while less than x bytes in buffer digitalWrite(ledPin, HIGH); //readbyte(); //readbuffer(); //readbuffer_noformat(); readbuffer_raw(); digitalWrite(ledPin, LOW); /* // if it's a capital H (ASCII 72), turn on the LED: if (incomingByte == 'H') { digitalWrite(ledPin, HIGH); } // if it's an L (ASCII 76) turn off the LED: if (incomingByte == 'L') { digitalWrite(ledPin, LOW); } */ } } void readbyte() { incomingByte = Serial.read(); // read the oldest byte in the serial buffer: if(incomingByte == 0x20) { //space Serial.print(' '); } else if(incomingByte == 0xFF) { delimiter[0] = 0xFF; delimiter[1] = Serial.read(); //get next byte and check if 0xff10 if(delimiter[0] == 0xFF && delimiter[1] == 0x10) { delimiter[0] = 0; delimiter[1] = 0; Serial.println(); return; } else { //not 0xFF10, just print them out normally Serial.print(delimiter[0]); Serial.print(delimiter[1]); delimiter[0] = 0; delimiter[1] = 0; return; } } else { Serial.print(incomingByte); //prints out in decimal } } //reads buffer and gets formatted to be readeable in serial monitor void readbuffer() { for(int i=0; i<16; i++) { xbee_msg[i] = Serial.read(); } uint16_t mask = xbee_msg[1]; id = xbee_msg[0]; id = id << 8; id = id | mask; uint32_t mask1 = xbee_msg[2]; mask1 = mask1 << 24; uint32_t mask2 = xbee_msg[3]; mask2 = mask2 << 16; uint32_t mask3 = xbee_msg[4]; mask3 = mask3 << 8; uint32_t mask4 = xbee_msg[5]; timestamp = mask1 | mask2 | mask3 | mask4; data[0] = xbee_msg[6]; data[1] = xbee_msg[7]; data[2] = xbee_msg[8]; data[3] = xbee_msg[9]; data[4] = xbee_msg[10]; data[5] = xbee_msg[11]; data[6] = xbee_msg[12]; data[7] = xbee_msg[13]; delimiter[0] = xbee_msg[14]; delimiter[1] = xbee_msg[15]; Serial.print(id, HEX); Serial.print(' '); Serial.print(timestamp); Serial.print(' '); for(int i=0; i<8; i++) { Serial.printf("%02X", data[i]); Serial.print(' '); } Serial.println(); } void readbuffer_noformat() { for(int i=0; i<16; i++) { Serial.print(Serial.read(), HEX); } Serial.println(); } //just reads in hex as they get sent over void readbuffer_raw() { Serial.write(Serial.read()); }
#include <algorithm> #include <array> #include <cstdio> #include <iostream> #include <iterator> #include <map> #include <math.h> #include <queue> #include <set> #include <stack> #include <vector> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } void read_stdin(vector<ll> &buffer) { string line; while (getline(cin, line)) { buffer.push_back(stoll(line)); } } int main() { vector<ll> arr; ll num; while (cin >> num) { arr.push_back(num); } vector<ll> sum; for (ll i = 0; i < arr.size() - 2; i++) { ll temp = 0; for (ll j = 0; j < 3; j++) { temp += arr[i + j]; } sum.push_back(temp); } ll res = 0; for (ll i = 1; i < sum.size(); i++) { if (sum[i] > sum[i - 1]) { res++; } } cout << res << endl; }
#include "pch.h" #include "DbColumn.h" #include "DbColumnDataSource.h" #include "DbColumnStorage.h" DbColumn::DbColumn(DATA_TYPE dt, const int n_max_, DbColumnDataSourceFactory* factory, const int j) : source(factory->create(j)), n(0) { if (dt == DT_BOOL) dt = DT_UNKNOWN; storage.push_back(new DbColumnStorage(dt, 0, n_max_, *source)); } DbColumn::~DbColumn() { } void DbColumn::set_col_value() { DbColumnStorage* last = get_last_storage(); DATA_TYPE dt = last->get_item_data_type(); data_types_seen.insert(dt); DbColumnStorage* next = last->append_col(); if (last != next) storage.push_back(next); } void DbColumn::finalize(const int n_) { n = n_; } void DbColumn::warn_type_conflicts(const cpp11::r_string& name) const { std::set<DATA_TYPE> my_data_types_seen = data_types_seen; DATA_TYPE dt = get_last_storage()->get_data_type(); switch (dt) { case DT_REAL: my_data_types_seen.erase(DT_INT); break; case DT_INT64: my_data_types_seen.erase(DT_INT); break; default: break; } my_data_types_seen.erase(DT_UNKNOWN); my_data_types_seen.erase(DT_BOOL); my_data_types_seen.erase(dt); if (my_data_types_seen.size() == 0) return; std::stringstream ss; ss << "Column `" << static_cast<std::string>(name) << "`: " << "mixed type, first seen values of type " << format_data_type(dt) << ", " << "coercing other values of type "; bool first = true; for (std::set<DATA_TYPE>::const_iterator it = my_data_types_seen.begin(); it != my_data_types_seen.end(); ++it) { if (!first) ss << ", "; else first = false; ss << format_data_type(*it); } cpp11::warning(ss.str()); } DbColumn::operator SEXP() const { DATA_TYPE dt = get_last_storage()->get_data_type(); SEXP ret = PROTECT(DbColumnStorage::allocate(n, dt)); int pos = 0; for (size_t k = 0; k < storage.size(); ++k) { const DbColumnStorage& current = storage[k]; pos += current.copy_to(ret, dt, pos); } UNPROTECT(1); return ret; } DATA_TYPE DbColumn::get_type() const { const DATA_TYPE dt = get_last_storage()->get_data_type(); return dt; } const char* DbColumn::format_data_type(const DATA_TYPE dt) { switch (dt) { case DT_UNKNOWN: return "unknown"; case DT_BOOL: return "boolean"; case DT_INT: return "integer"; case DT_INT64: return "integer64"; case DT_REAL: return "real"; case DT_STRING: return "string"; case DT_BLOB: return "blob"; default: return "<unknown type>"; } } DbColumnStorage* DbColumn::get_last_storage() { return &storage.end()[-1]; } const DbColumnStorage* DbColumn::get_last_storage() const { return &storage.end()[-1]; }
#include "abonnemnt_park.h" #include <QDebug> Abonnemnt_park::Abonnemnt_park() { id_abonnement=0; nom=""; prenom=""; type_abonnement=""; d_f=""; } Abonnemnt_park::Abonnemnt_park(int id_abonnement,QString nom,QString prenom,QString d_f,QString type_abonnement) { this->id_abonnement=id_abonnement; this->nom=nom; this->prenom=prenom; this->d_f=d_f; this->type_abonnement=type_abonnement; } bool Abonnemnt_park::ajouter() { QSqlQuery query; QString res= QString::number(id_abonnement); query.prepare("INSERT INTO abonnement_park (ID_ABONNEMENT, NOM, PRENOM,D_F,TYPE_ABONNEMENT) " "VALUES (:id_abonnement, :nom, :prenom,:d_f,:type_abonnement)"); query.bindValue(":id_abonnement", res); query.bindValue(":nom", nom); query.bindValue(":prenom", prenom); query.bindValue(":d_f",d_f); query.bindValue(":type_abonnement", type_abonnement); return query.exec(); } QSqlQueryModel * Abonnemnt_park::afficher() {QSqlQueryModel * model= new QSqlQueryModel(); model->setQuery("select * from abonnement_park"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID_ABONNEMENT")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Nom ")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Prénom")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("D_F")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("TYPE_ABONNEMENT")); return model; } bool Abonnemnt_park::supprimer(int id) { QSqlQuery query; QString res= QString::number(id); query.prepare("Delete from abonnement_park where ID_ABONNEMENT = :id "); query.bindValue(":id", res); return query.exec(); } bool Abonnemnt_park::modifier(int id_abonnement) { QSqlQuery query; QString res= QString::number(id_abonnement); query.prepare("UPDATE abonnement_park SET NOM=:nom,PRENOM=:prenom,D_F=:d_f,TYPE_ABONNEMENT=:type_abonnement WHERE ID_ABONNEMENT=:id_abonnement"); query.bindValue(":nom",nom); query.bindValue(":prenom",prenom); query.bindValue(":d_f",d_f); query.bindValue(":type_abonnement",type_abonnement); query.bindValue(":id_abonnement",res); return query.exec(); } QSqlQueryModel * Abonnemnt_park::afficher_trie() {QSqlQueryModel* model = new QSqlQueryModel(); model->setQuery("select * from abonnement_park ORDER BY NOM DESC"); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID_ABONNEMENT")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Nom ")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Prénom")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("D_F")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("TYPE_ABONNEMENT")); return model; } QSqlQueryModel * Abonnemnt_park::recherche(const QString &id) { QSqlQueryModel* model = new QSqlQueryModel(); model->setQuery("select * from abonnement_park where (ID_ABONNEMENT LIKE '"+id+"%') "); model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID_ABONNEMENT")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Nom ")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Prénom")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("D_F")); model->setHeaderData(4, Qt::Horizontal, QObject::tr("TYPE_ABONNEMENT")); return model; }
/* json_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 20 Apr 2014 FreeBSD-style copyright and disclaimer apply Json tests. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "types/primitives.h" #include "types/std/string.h" #include "types/std/vector.h" #include "types/std/map.h" #include "dsl/plumbing.h" #include "dsl/type.h" #include "dsl/field.h" #include "utils/json/parser.h" #include "utils/json/printer.h" #include <boost/test/unit_test.hpp> #include <fstream> using namespace reflect; /******************************************************************************/ /* BLEH */ /******************************************************************************/ struct Bleh { long i; bool b; Bleh() : i(0), b(false) {} Bleh(long i, bool b) : i(i), b(b) {} }; reflectType(Bleh) { reflectPlumbing(); reflectField(i); reflectField(b); } /******************************************************************************/ /* BLAH */ /******************************************************************************/ struct Blah { std::string str; std::vector<Bleh> vec; std::map<std::string, Bleh> map; }; reflectType(Blah) { reflectPlumbing(); reflectField(str); reflectField(vec); reflectField(map); } /******************************************************************************/ /* PARSING */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(parsing) { std::ifstream ifs("tests/data/basics.json"); BOOST_CHECK(ifs); auto blah = json::parse<Blah>(ifs); auto checkBleh = [] (const Bleh& bleh, long i, bool b) { BOOST_CHECK_EQUAL(bleh.i, i); BOOST_CHECK_EQUAL(bleh.b, b); }; BOOST_CHECK_EQUAL(blah.str, "I like candy"); BOOST_CHECK_EQUAL(blah.vec.size(), 3u); checkBleh(blah.vec[0], 10, false); checkBleh(blah.vec[1], 0, true); checkBleh(blah.vec[2], 30, false); BOOST_CHECK_EQUAL(blah.map.size(), 2u); checkBleh(blah.map["foo"], 20, true); checkBleh(blah.map["bar"], 0, true); json::print(blah, std::cerr, true); }
#include <fstream> using namespace std; ifstream cin ("minimal.in"); ofstream cout ("minimal.out"); int q, n, m; int a[501], b[501]; int f[501]; #define ma 100000000 void qsort (int left, int right, int *a) { int l=left, r=right,x=a[l]; while (l<r) { while (l<r && a[r]>x) r--; if (l<r) { a[l]=a[r]; l++; } while (l<r && a[l]<x) l++; if (l<r) { a[r] = a[l]; r--; } } a[l] = x; if (left<l) qsort (left, l-1, a); if (r<right) qsort (r+1, right, a); } int solve (int x, int y) { if (x>y) return ma; if (x<=0) return 0; if (f[x]>0) return f[x]; f[x] = min(solve(x-1, y-1)+abs(a[x]-b[y]),solve(x,y-1)); return f[x]; } int main () { cin>>q; for (int i=1; i<=q; i++) { cin>>n>>m; memset (a, 0, sizeof(int)*501); memset (b, 0, sizeof(int)*501); memset (f, 0, sizeof(int)*501); for (int j=1; j<=n; j++) cin>>a[j]; for (int j=1; j<=m; j++) cin>>b[j]; qsort(1,n,a); qsort(1,m,b); solve (n, m); cout<<f[n]<<endl; } // system ("pause"); return 0; }
#include <cstdio> #include <cmath> #include <vector> using namespace std; typedef long long ll; const int MAX_N = 40; //INPUT int N; int X[MAX_N], Y[MAX_N], R[MAX_N]; // the set of circles which are covered by a circle centered (x,y) and radius r ll cover(double x, double y, double r){ ll S=0; for(int i=0; i<N; i++){ if(R[i] <= r){ double dx = x - X[i], dy = y - Y[i], dr = r - R[i]; if (dx * dx + dy * dy <= dr * dr){ S |= 1LL << i; } } } return S; } // decide if two circles of radius r can cover all. bool C(double r){ vector<ll> cand; // list of the set of circles by a circle cand.push_back(0); // pattern a; two circles come in contact with the surrounding circle for (int i=0; i<N; i++){ for (int j=0; j<i; j++){ if (R[i] < r && R[j] < r){ // the intersection of the two circles (R-r1, R-r2) double x1 = X[i], y1 = Y[i], r1 = r - R[i]; double x2 = X[j], y2 = Y[j], r2 = r - R[j]; double dx = x2-x1, dy = y2-y1; double a = dx*dx + dy*dy; double b = ((r1*r1 - r2*r2) / a + 1) / 2; double d = r1*r1 / a - b*b; if (d >= 0){ d = sqrt(d); double x3 = x1 + dx * b; double y3 = y1 + dy * b; double x4 = -dy * d; double y4 = dx * d; // consider error range ll ij = 1LL << i | 1LL << j; cand.push_back(cover(x3 - x4, y3 - y4, r) | ij); cand.push_back(cover(x3 + x4, y3 + y4, r) | ij); } } } } // pattern b; center is same with another circle for (int i=0; i < N; i++){ if(R[i] <= r){ cand.push_back(cover(X[i], Y[i], r) | 1LL<<i); } } // select two circles and verify if they cover all for(int i=0; i < cand.size(); i++){ for(int j=0; j<i; j++){ if ((cand[i] | cand[j]) == (1LL<<N) - 1){ return true; } } } return false; } void solve(){ // binary search on radius r double lb=0, ub=10000; for(int i=0; i < 100; i++){ double mid = (lb+ub)/2; if( C(mid) ) ub = mid; else lb = mid; } printf("%.6f\n", ub); } int main(){ N=3; X[0] = 20, Y[0] = 10, R[0] = 2; X[1] = 20, Y[1] = 20, R[1] = 2; X[2] = 40, Y[2] = 10, R[2] = 2; solve(); N=3; X[0] = 20, Y[0] = 10, R[0] = 3; X[1] = 30, Y[1] = 10, R[1] = 3; X[2] = 40, Y[2] = 10, R[2] = 3; solve(); }
/* * dolier-times.cpp * * Created on: Feb 14, 2014 * Author: vbonnici */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <algorithm> #include "data_ts.h" #include "trim.h" #include "pars_t.h" #include <set> #include <vector> #include <map> using namespace dolierlib; char* scmd; void pusage(){ std::cout<<"Usage: "<<scmd<<" <ifile> <nof_cols> <index_key_col> <index_value_col> <ofile>\n"; } class mpars_t : public pars_t{ public: std::string ifile; int nof_cols; int key_col; int value_col; std::string ofile; mpars_t(int argc, char* argv[]) : pars_t(argc,argv){ nof_cols = 0; key_col = 0; value_col = 0; } ~mpars_t(){} virtual void print(){ std::cout<<"[ARG][ifile]["<<ifile<<"]\n"; std::cout<<"[ARG][nof_cols]["<<nof_cols<<"]\n"; std::cout<<"[ARG][key_col]["<<key_col<<"]\n"; std::cout<<"[ARG][value_col]["<<value_col<<"]\n"; std::cout<<"[ARG][ofile]["<<ofile<<"]\n"; } virtual void usage(){ pusage(); } virtual void check(){ print(); std::cout<<"check..."; ifile = trim(ifile); ofile = trim(ofile); if( (ifile.length() == 0) || (ofile.length() == 0) || (nof_cols < 1) || (key_col < 0) || (key_col >= nof_cols) || (value_col < 0) || (value_col >= nof_cols) ){ usage(); exit(1); } } virtual void parse(){ ifile = next_string(); nof_cols = next_int(); key_col = next_int(); value_col = next_int(); ofile = next_string(); check(); } }; int main(int argc, char* argv[]){ scmd = argv[0]; mpars_t pars(argc, argv); pars.parse(); std::ifstream ifs; ifs.open(pars.ifile.c_str(), std::ios::in); if(!ifs.is_open() || !ifs.good()){ std::cout<<"Warning can not open file "<<pars.ifile<<"\n"; exit(1); } std::ofstream ofs; ofs.open(pars.ofile.c_str(), std::ios::out); if(!ofs.is_open() || ofs.bad()){ std::cout<<"Error on opening output file : "<<pars.ofile<<" \n"; exit(1); } std::map<std::string, double> times; std::map<std::string, double>::iterator IT; bool ok = true; while(ok){ std::string cell; std::string key; double value; for(int i=0; i<pars.nof_cols && ok; i++){ if(ifs >> cell){ if(i==pars.key_col) key = cell; if(i==pars.value_col){ std::istringstream iss(cell); if(!(iss>>value)){ std::cout<<"wrong column value "<<key<<"\n"; exit(1); } } } else{ ok = false; } } if(ok){ IT = times.find(key); if(IT == times.end()){ times.insert(std::pair<std::string, double>(key, value)); } else{ times.erase(IT); times.insert(std::pair<std::string, double>(key, value + IT->second)); } } } for(IT=times.begin(); IT!=times.end(); IT++){ ofs<<IT->first<<"\t"<<IT->second<<"\n"; } ofs.flush(); ofs.close(); ifs.close(); exit(0); }
#ifndef _LOG_H #define _LOG_H #include <string> #include <cstdio> class cLog { public: //Constructor cLog(std::string &); //Loguea un mensaje void loguear(const std::string &mensaje); private: std::string dominio; //Dominio al cual se loguea //Archivos para loguear FILE *fileDominio; //Archivo privado del dominio FILE *fileComun; //Archivo comun para todos los dominios //Metodos para abrir y cerrar los archivos de logueo bool abrirFileDominio(); bool abrirFileComun(); bool cerrarFileDominio(); bool cerrarFileComun(); //No permitir el copy constructor o operador= creacion o operador() creacion cLog(cLog&); cLog& operator=(cLog&); }; //Reporta un error rarisimo con el directorio donde se origino y la funcion que lo origino void reportarErrorRarisimo(std::string mensaje); //Obtiene la fecha y la hora actual del sistema void obtenerDiaHora(std::string &); #endif // _LOG_H
#ifndef FUZZYCORE_UNSUPPORTEDCOMPILEREXCEPTION_H #define FUZZYCORE_UNSUPPORTEDCOMPILEREXCEPTION_H #include "EnvironmentException.h" class UnsupportedCompilerException : EnvironmentException { public: explicit UnsupportedCompilerException(const std::string &); }; #endif
#ifndef CIP_IMPL_TEMPLATE_H #define CIP_IMPL_TEMPLATE_H #include "cip.hpp" #include "func.hpp" #include "exp_func.hpp" #include "cut_exp.hpp" #include "delta.hpp" #include "lin_func.hpp" #include "op.hpp" //#include <boost/static_assert.hpp> #include <boost/type_traits.hpp> #include <boost/utility/enable_if.hpp> namespace l2func { typedef std::complex<double> CD; // ==== Calculation ==== template<class F> F STO_Int(F z, int n); template<class F> F GTO_Int(F z, int n); template<class F> F STO_GTO_Int(F as, F ag, int n); template<class F> F ExpExp_Int(F zA, F zB, int n, sto_tag, sto_tag) { return STO_Int(zA+zB, n); } template<class F> F ExpExp_Int(F zA, F zB, int n, sto_tag, gto_tag) { return STO_GTO_Int(zA, zB, n); } template<class F> F ExpExp_Int(F zA, F zB, int n, gto_tag, sto_tag) { return STO_GTO_Int(zB, zA, n); } template<class F> F ExpExp_Int(F zA, F zB, int n, gto_tag, gto_tag) { return GTO_Int(zB+zA, n); } template<class F> F CutSTO_Int(F z, int n, double r0); // ==== Inner Product ==== // ---- Add ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, func_tag, func_add_tag, typename boost::disable_if< boost::is_same< typename func_traits<A>::func_tag, func_add_tag> >::type* =0 ) { return CIP(a, b.funcA) + CIP(a, b.funcB); } template<class F, class A, class B> F _CIP(const A& a, const B& b, func_add_tag, func_tag) { return CIP(a.funcA, b) + CIP(a.funcB, b); } // ---- Prod ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, func_tag, func_prod_tag, typename boost::disable_if< boost::is_same< typename func_traits<A>::func_tag, func_prod_tag> >::type* =0 ) { return b.c * CIP(a, b.f); } template<class F, class A, class B> F _CIP(const A& a, const B& b, func_prod_tag, func_tag) { return a.c * CIP(a.f, b); } // ---- STO/GTO ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, exp_func_tag, exp_func_tag) { return a.c() * b.c() * ExpExp_Int(a.z(), b.z(), a.n() + b.n(), typename func_traits<A>::func_tag(), typename func_traits<B>::func_tag()); } // ---- CutSTO/CutGTO ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, cut_sto_tag, cut_sto_tag) { double r0 = a.r0() < b.r0() ? a.r0() : b.r0(); return a.c() * b.c() * CutSTO_Int(a.z()+b.z(), a.n()+b.n(), r0); } template<class F, class A, class B> F _CIP(const A& a, const B& b, cut_sto_tag, sto_tag) { double r0 = a.r0(); return a.c() * b.c() * CutSTO_Int(a.z()+b.z(), a.n()+b.n(), r0); } template<class F, class A, class B> F _CIP(const A& a, const B& b, sto_tag, cut_sto_tag) { return _CIP<F, B, A>(b, a, cut_sto_tag(), sto_tag()); } // ----CIP for Delta ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, delta_tag, exp_func_tag) { return b.at(a.r0()); } template<class F, class A, class B> F _CIP(const A& a, const B& b, exp_func_tag, delta_tag) { return _CIP<F, B, A>(b, a, delta_tag(), exp_func_tag()); } template<class F, class A, class B> F _CIP(const A& a, const B& b, delta_tag, cut_exp_tag) { if(a.r0() - a.h() < b.r0()) return b.get_func().at(a.r0()); else return F(0); } template<class F, class A, class B> F _CIP(const A& a, const B& b, cut_exp_tag, delta_tag) { return _CIP<F, B, A>(b, a, delta_tag(), cut_exp_tag()); } // ---- CIP for LinFunc ---- template<class F, class A, class B> F _CIP(const A& a, const B& b, linfunc_tag, func_tag, typename boost::disable_if< boost::is_same< typename func_traits<B>::func_tag, linfunc_tag> >::type* =0 ) { /** Memo: boost::disable_if is for ambiguous error when A and B are both LinFunc */ F acc(0); for(typename A::const_iterator it = a.begin(); it != a.end(); ++it) { acc += it->first * CIP(it->second, b); } return acc; } template<class F, class A, class B> F _CIP(const A& a, const B& b, func_tag, linfunc_tag) { F acc(0); for(typename B::const_iterator it = b.begin(); it != b.end(); ++it) { acc += it->first * CIP(it->second, a); } return acc; } // ---- static interface ---- template<class A, class B> typename A::Field CIP(const A& a, const B& b) { is_l2func<A>(); is_l2func<B>(); typedef typename A::Field FA; typedef typename B::Field FB; // BOOST_STATIC_ASSERT(boost::has_logical_not<boost::is_same<FA, FB> >::value, "Field of A and B must be same"); return _CIP<FA, A, B>(a, b, typename func_traits<A>::func_tag(), typename func_traits<B>::func_tag()); } // ==== normalization ==== template<class A> typename A::Field CNorm(const A& a) { return sqrt(CIP(a, a)); } template<class A> void CNormalize(A *a) { typedef typename A::Field F; F cc = CNorm(*a); a->SetScalarProd(F(1)/cc); } // ==== Matrix Element of Operator ==== // ---- Rm, ExpFunc ---- template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, exp_func_tag, rm_tag, exp_func_tag) { return a.c() * b.c() * ExpExp_Int(a.z(), b.z(), a.n() + b.n() + o.m(), typename func_traits<A>::func_tag(), typename func_traits<B>::func_tag()); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, cut_sto_tag, rm_tag, cut_sto_tag) { double r0 = a.r0() < b.r0() ? a.r0() : b.r0(); return a.c() * b.c() * CutSTO_Int(a.z()+b.z(), a.n()+b.n()+o.m(), r0); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, cut_sto_tag, rm_tag, sto_tag) { double r0 = a.r0(); return a.c() * b.c() * CutSTO_Int(a.z()+b.z(), a.n()+b.n()+o.m(), r0); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, sto_tag, rm_tag, cut_sto_tag) { return _CIP_op(b, o, a, cut_sto_tag(), rm_tag(), sto_tag()); } // ---- D1 ---- template<class ExpFuncA, class ExpFuncB> typename ExpFuncA::Field D1Mat(const ExpFuncA& a, const ExpFuncB& b) { typedef typename ExpFuncA::Field F; int n = b.n(); int m = b.exp_power; return F(n) * CIP(a, OpRm(-1), b) - b.z()*F(m) * CIP(a, OpRm(m-1), b); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O&, const B& b, exp_func_tag, d1_tag, exp_func_tag) { return D1Mat(a, b); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O&, const B& b, cut_exp_tag, d1_tag, cut_exp_tag) { return D1Mat(a, b); } // ---- D2 ---- template<class ExpFuncA, class ExpFuncB> typename ExpFuncA::Field D2Mat(const ExpFuncA& a, const ExpFuncB& b) { // r^n exp(-zr^m) -> n r^(n-1) exp() -zr^(n+m-1) exp() // -> n(n-1) r^(n-2) exp() -nz(m-1)r^(n+m-2) exp() // -z*(n+m-1)r^(n+2m-2) exp() + zz r^(n+2m-2) exp() typedef typename ExpFuncA::Field F; int n = b.n(); int m = b.exp_power; F z = b.z(); F res(0); if(n != 1) res += F(n*n-n) * CIP(a, OpRm(-2), b); res += -z*F(2*n*m+m*m-m) * CIP(a, OpRm(m-2), b); res += F(m*m)*z*z * CIP(a, OpRm(2*m-2), b); return res; } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O&, const B& b, exp_func_tag, d2_tag, exp_func_tag) { return D2Mat(a, b); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O&, const B& b, cut_exp_tag, d2_tag, cut_exp_tag) { return D1Mat(a, b); } // ---- Scalar Prod Op ---- template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_tag, scalar_prod_tag, func_tag) { return o.c * CIP(a, o.op, b); } // ---- Op Add ---- template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_tag, op_add_tag, func_tag) { return CIP(a, o.opA, b) + CIP(a, o.opB, b); } // ---- FuncAdd ---- template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_tag, op_tag, func_add_tag, typename boost::disable_if< is_compound<O> >::type* = 0, typename boost::disable_if< is_compound<A> >::type* = 0) { return CIP(a,o,b.funcA) + CIP(a,o,b.funcB); } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_add_tag, op_tag, func_tag, typename boost::disable_if< is_compound<O> >::type* = 0) { return CIP(a.funcA,o,b) + CIP(a.funcB,o,b); } // ---- linfunc ---- template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, linfunc_tag, op_tag, func_tag, typename boost::disable_if< boost::is_same< typename func_traits<B>::func_tag, linfunc_tag> >::type* =0, typename boost::disable_if< is_compound<O> >::type* = 0) { F acc(0); for(typename A::const_iterator it = a.begin(); it != a.end(); ++it) { acc += it->first * CIP(it->second, o, b); } return acc; } template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_tag, op_tag, linfunc_tag, typename boost::disable_if<is_compound<O> >::type* = 0) { F acc(0); for(typename A::const_iterator it = b.begin(); it != b.end(); ++it) { acc += it->first * CIP(a, o, it->second); } return acc; } template<class F, class A, class B> struct Summer{ // Field const A& a_; const B& b_; // Constructor Summer(const A& _a, const B& _b): a_(_a), b_(_b) {} // function called in boost::fusion::fold template<class OpT> F operator()(F x0, const std::pair<F, OpT>& co) const { return x0 + co.first * CIP(a_, co.second, b_); } }; template<class F, class A, class O, class B> F _CIP_op(const A& a, const O& o, const B& b, func_tag, linop_tag, func_tag) { Summer<F, A, B> summer(a, b); F res = boost::fusion::fold(o.CoefOp(), F(0), summer); return res; } template<class A, class O, class B> typename A::Field CIP(const A& a, const O& o, const B& b) { is_l2func<A>(); is_l2func<B>(); is_op<O>(); typedef typename A::Field FA; typedef typename B::Field FB; return _CIP_op<FA, A, O, B>(a, o, b, typename func_traits<A>::func_tag(), typename op_traits<O>::op_tag(), typename func_traits<B>::func_tag()); } } #endif
#include <iostream> // Input: sorted integer array, integer query // Output: integer representing index of query in array (or -1 // if query is not in array) int BinarySearch(int array[], int size, int query) { int lower_bound = 0; int upper_bound = size - 1; // Iterate repeatedly until we've found the spot where the value should be while (lower_bound <= upper_bound) { // Take a guess int guess = (lower_bound + upper_bound) / 2; // Did we find the value? if (array[guess] == query) { return guess; } // If we're too low, re-search the second half else if (array[guess] < query) { lower_bound = guess + 1; // If we're too high, re-search the first half } else { upper_bound = guess - 1; } } // If we haven't found the value, we return false return -1; } int main() { int a[] = {1,5,6,8,9,10,23,42,59,73,105}; for (int i = 0; i < 11; i++) { std::cout << BinarySearch(a, 11, a[i]) << std::endl; } }
//fill array with random number #include <iostream> #include <stdlib.h> #include <time.h> //zaeem 19L-1196 using namespace std; int main(){ const int size=5; int myarray[size]; srand(time(NULL)); int rand_num; for(int i=0; i<5; i++){ rand_num = rand()%21+5; myarray[i]=rand_num; } for(int i=0; i<5; i++) cout << myarray[i] << " "; cout << endl; system("pause"); return 0; }
#pragma once // IResourceFile.h #include "../Resource/Resource.h" namespace liman { class IResourceFile { public: virtual bool Open() = 0; virtual int GetRawResourceSize(const Resource &r) = 0; virtual int GetRawResource(const Resource &r, char *buffer) = 0; virtual int GetNumResources() const = 0; virtual std::string GetResourceName(int num) const = 0; virtual ~IResourceFile() { } }; }
#include<bits/stdc++.h> using namespace std; int solve(vector<int>& arr,int n) { sort(arr.begin(),arr.end()); int count = 0; int sum = 0; for(int i=0;i<n;i++) { sum+=arr[i]; } int temp = 0; for(int i=n-1;i>=0;i--) { temp+=arr[i]; count+=1; int rem = sum - temp; if(temp > rem) { return count; } } return count; } int main() { int n; cin >> n; vector<int> arr(n); for(int i=0;i<n;i++) { cin >> arr[i]; } cout << solve(arr,n) << endl; return 0; }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Mesh Test 1: mesh constructors and accessors. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes: //----------------------------------------------------------------------------- #include "Pooma/Fields.h" #include "Utilities/Tester.h" //----------------------------------------------------------------------------- // Globals //----------------------------------------------------------------------------- // Meshes are initialized with vertex-based PHYSICAL domains. The total domain // should be the physical domain, expanded by the guard layers in each. // The physical and total cell domains are shrunk by 1 on the right. When // taking a view, the physical and total domains should be zero-based and // the same. Again, the physical and total cell domains are shrunk by 1 on // the right. const int NX = 8, NY = 12; GuardLayers<2> gl(Loc<2>(1, 2), Loc<2>(2, 1)); Interval<1> I(NX), J(NY), IV(NX - 2), JV(NY - 1); Interval<2> physicalVertexDomain(I, J), totalVertexDomain(Interval<1>(-gl.lower(0), NX+gl.upper(0)-1), Interval<1>(-gl.lower(1),NY+gl.upper(1)-1)), physicalCellDomain(shrinkRight(physicalVertexDomain, 1)), totalCellDomain(shrinkRight(totalVertexDomain, 1)); Interval<2> viewDomain(IV + 1, JV - 1), viewPhysVertexDomain(IV, JV), viewPhysCellDomain(shrinkRight(viewPhysVertexDomain, 1)); Vector<2> origin(0.0), spacings(1.0, 2.0), viewOrigin(1.0, -2.0); //----------------------------------------------------------------------------- // Confirm that basic ctors and accessors are correct. //----------------------------------------------------------------------------- // Uniform rectilinear mesh. void urmTest(Pooma::Tester &tester) { // Create a uniform rectilinear mesh using a DomainLayout and test. DomainLayout<2> layout1(physicalVertexDomain, gl); tester.out() << layout1 << std::endl; UniformRectilinearMesh<2> m(layout1, origin, spacings); tester.check("URM.PVD", m.physicalVertexDomain(), physicalVertexDomain); tester.check("URM.TVD", m.totalVertexDomain(), totalVertexDomain); tester.check("URM.PCD", m.physicalCellDomain(), physicalCellDomain); tester.check("URM.TCD", m.totalCellDomain(), totalCellDomain); tester.check("URM.Origin", m.origin(), origin); tester.check("URM.Spacings", m.spacings(), spacings); // Test a view. UniformRectilinearMesh<2> m2(m, viewDomain); tester.check("V.URM.PVD", m2.physicalVertexDomain(), viewPhysVertexDomain); tester.check("V.URM.TVD", m2.totalVertexDomain(), viewPhysVertexDomain); tester.check("V.URM.PCD", m2.physicalCellDomain(), viewPhysCellDomain); tester.check("V.URM.TCD", m2.totalCellDomain(), viewPhysCellDomain); tester.check("V.URM.Origin", m2.origin(), viewOrigin); tester.check("V.URM.Spacings", m2.spacings(), spacings); } // No mesh void nmTest(Pooma::Tester &tester) { // Create a no-mesh using a DomainLayout and test. DomainLayout<2> layout1(physicalVertexDomain, gl); tester.out() << layout1 << std::endl; NoMesh<2> m(layout1); tester.check("NM.PVD", m.physicalVertexDomain(), physicalVertexDomain); tester.check("NM.TVD", m.totalVertexDomain(), totalVertexDomain); tester.check("NM.PCD", m.physicalCellDomain(), physicalCellDomain); tester.check("NM.TCD", m.totalCellDomain(), totalCellDomain); // Test a view. NoMesh<2> m2(m, viewDomain); tester.check("V.NM.PVD", m2.physicalVertexDomain(), viewPhysVertexDomain); tester.check("V.NM.TVD", m2.totalVertexDomain(), viewPhysVertexDomain); tester.check("V.NM.PCD", m2.physicalCellDomain(), viewPhysCellDomain); tester.check("V.NM.TCD", m2.totalCellDomain(), viewPhysCellDomain); } //----------------------------------------------------------------------------- // Main program //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { Pooma::initialize(argc,argv); Pooma::Tester tester(argc, argv); urmTest(tester); nmTest(tester); int ret = tester.results("MeshTest1"); Pooma::finalize(); return ret; } // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: MeshTest1.cpp,v $ $Author: richard $ // $Revision: 1.2 $ $Date: 2004/11/01 18:16:48 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Storage.Streams.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Networking.Sockets.3.h" #include "internal/Windows.Networking.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.Networking.Proximity.3.h" #include "Windows.Networking.h" WINRT_EXPORT namespace winrt { namespace Windows::Networking::Proximity { template <typename L> DeviceArrivedEventHandler::DeviceArrivedEventHandler(L lambda) : DeviceArrivedEventHandler(impl::make_delegate<impl_DeviceArrivedEventHandler<L>, DeviceArrivedEventHandler>(std::forward<L>(lambda))) {} template <typename F> DeviceArrivedEventHandler::DeviceArrivedEventHandler(F * function) : DeviceArrivedEventHandler([=](auto && ... args) { function(args ...); }) {} template <typename O, typename M> DeviceArrivedEventHandler::DeviceArrivedEventHandler(O * object, M method) : DeviceArrivedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); }) {} inline void DeviceArrivedEventHandler::operator()(const Windows::Networking::Proximity::ProximityDevice & sender) const { check_hresult((*(abi<DeviceArrivedEventHandler> **)this)->abi_Invoke(get_abi(sender))); } template <typename L> DeviceDepartedEventHandler::DeviceDepartedEventHandler(L lambda) : DeviceDepartedEventHandler(impl::make_delegate<impl_DeviceDepartedEventHandler<L>, DeviceDepartedEventHandler>(std::forward<L>(lambda))) {} template <typename F> DeviceDepartedEventHandler::DeviceDepartedEventHandler(F * function) : DeviceDepartedEventHandler([=](auto && ... args) { function(args ...); }) {} template <typename O, typename M> DeviceDepartedEventHandler::DeviceDepartedEventHandler(O * object, M method) : DeviceDepartedEventHandler([=](auto && ... args) { ((*object).*(method))(args ...); }) {} inline void DeviceDepartedEventHandler::operator()(const Windows::Networking::Proximity::ProximityDevice & sender) const { check_hresult((*(abi<DeviceDepartedEventHandler> **)this)->abi_Invoke(get_abi(sender))); } template <typename L> MessageReceivedHandler::MessageReceivedHandler(L lambda) : MessageReceivedHandler(impl::make_delegate<impl_MessageReceivedHandler<L>, MessageReceivedHandler>(std::forward<L>(lambda))) {} template <typename F> MessageReceivedHandler::MessageReceivedHandler(F * function) : MessageReceivedHandler([=](auto && ... args) { function(args ...); }) {} template <typename O, typename M> MessageReceivedHandler::MessageReceivedHandler(O * object, M method) : MessageReceivedHandler([=](auto && ... args) { ((*object).*(method))(args ...); }) {} inline void MessageReceivedHandler::operator()(const Windows::Networking::Proximity::ProximityDevice & sender, const Windows::Networking::Proximity::ProximityMessage & message) const { check_hresult((*(abi<MessageReceivedHandler> **)this)->abi_Invoke(get_abi(sender), get_abi(message))); } template <typename L> MessageTransmittedHandler::MessageTransmittedHandler(L lambda) : MessageTransmittedHandler(impl::make_delegate<impl_MessageTransmittedHandler<L>, MessageTransmittedHandler>(std::forward<L>(lambda))) {} template <typename F> MessageTransmittedHandler::MessageTransmittedHandler(F * function) : MessageTransmittedHandler([=](auto && ... args) { function(args ...); }) {} template <typename O, typename M> MessageTransmittedHandler::MessageTransmittedHandler(O * object, M method) : MessageTransmittedHandler([=](auto && ... args) { ((*object).*(method))(args ...); }) {} inline void MessageTransmittedHandler::operator()(const Windows::Networking::Proximity::ProximityDevice & sender, int64_t messageId) const { check_hresult((*(abi<MessageTransmittedHandler> **)this)->abi_Invoke(get_abi(sender), messageId)); } } namespace impl { template <typename D> struct produce<D, Windows::Networking::Proximity::IConnectionRequestedEventArgs> : produce_base<D, Windows::Networking::Proximity::IConnectionRequestedEventArgs> { HRESULT __stdcall get_PeerInformation(impl::abi_arg_out<Windows::Networking::Proximity::IPeerInformation> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeerInformation()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerFinderStatics> : produce_base<D, Windows::Networking::Proximity::IPeerFinderStatics> { HRESULT __stdcall get_AllowBluetooth(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AllowBluetooth()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_AllowBluetooth(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().AllowBluetooth(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AllowInfrastructure(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AllowInfrastructure()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_AllowInfrastructure(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().AllowInfrastructure(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AllowWiFiDirect(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AllowWiFiDirect()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_AllowWiFiDirect(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().AllowWiFiDirect(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DisplayName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DisplayName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_DisplayName(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DisplayName(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_SupportedDiscoveryTypes(Windows::Networking::Proximity::PeerDiscoveryTypes * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SupportedDiscoveryTypes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AlternateIdentities(impl::abi_arg_out<Windows::Foundation::Collections::IMap<hstring, hstring>> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AlternateIdentities()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_Start() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Start(); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_StartWithMessage(impl::abi_arg_in<hstring> peerMessage) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Start(*reinterpret_cast<const hstring *>(&peerMessage)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_Stop() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Stop(); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_TriggeredConnectionStateChanged(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs>> handler, event_token * cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); *cookie = detach_abi(this->shim().TriggeredConnectionStateChanged(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_TriggeredConnectionStateChanged(event_token cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().TriggeredConnectionStateChanged(cookie); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_ConnectionRequested(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs>> handler, event_token * cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); *cookie = detach_abi(this->shim().ConnectionRequested(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_ConnectionRequested(event_token cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ConnectionRequested(cookie); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_FindAllPeersAsync(impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Networking::Proximity::PeerInformation>>> asyncOp) noexcept override { try { typename D::abi_guard guard(this->shim()); *asyncOp = detach_abi(this->shim().FindAllPeersAsync()); return S_OK; } catch (...) { *asyncOp = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_ConnectAsync(impl::abi_arg_in<Windows::Networking::Proximity::IPeerInformation> peerInformation, impl::abi_arg_out<Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocket>> asyncOp) noexcept override { try { typename D::abi_guard guard(this->shim()); *asyncOp = detach_abi(this->shim().ConnectAsync(*reinterpret_cast<const Windows::Networking::Proximity::PeerInformation *>(&peerInformation))); return S_OK; } catch (...) { *asyncOp = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerFinderStatics2> : produce_base<D, Windows::Networking::Proximity::IPeerFinderStatics2> { HRESULT __stdcall get_Role(Windows::Networking::Proximity::PeerRole * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Role()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_Role(Windows::Networking::Proximity::PeerRole value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Role(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DiscoveryData(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DiscoveryData()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_DiscoveryData(impl::abi_arg_in<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DiscoveryData(*reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_CreateWatcher(impl::abi_arg_out<Windows::Networking::Proximity::IPeerWatcher> watcher) noexcept override { try { typename D::abi_guard guard(this->shim()); *watcher = detach_abi(this->shim().CreateWatcher()); return S_OK; } catch (...) { *watcher = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerInformation> : produce_base<D, Windows::Networking::Proximity::IPeerInformation> { HRESULT __stdcall get_DisplayName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DisplayName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerInformation3> : produce_base<D, Windows::Networking::Proximity::IPeerInformation3> { HRESULT __stdcall get_Id(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Id()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DiscoveryData(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DiscoveryData()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerInformationWithHostAndService> : produce_base<D, Windows::Networking::Proximity::IPeerInformationWithHostAndService> { HRESULT __stdcall get_HostName(impl::abi_arg_out<Windows::Networking::IHostName> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().HostName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_ServiceName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ServiceName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IPeerWatcher> : produce_base<D, Windows::Networking::Proximity::IPeerWatcher> { HRESULT __stdcall add_Added(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().Added(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_Added(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Added(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_Removed(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().Removed(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_Removed(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Removed(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_Updated(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().Updated(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_Updated(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Updated(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_EnumerationCompleted(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().EnumerationCompleted(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_EnumerationCompleted(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().EnumerationCompleted(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_Stopped(impl::abi_arg_in<Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable>> handler, event_token * token) noexcept override { try { typename D::abi_guard guard(this->shim()); *token = detach_abi(this->shim().Stopped(*reinterpret_cast<const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> *>(&handler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_Stopped(event_token token) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Stopped(token); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Status(Windows::Networking::Proximity::PeerWatcherStatus * status) noexcept override { try { typename D::abi_guard guard(this->shim()); *status = detach_abi(this->shim().Status()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_Start() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Start(); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_Stop() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Stop(); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IProximityDevice> : produce_base<D, Windows::Networking::Proximity::IProximityDevice> { HRESULT __stdcall abi_SubscribeForMessage(impl::abi_arg_in<hstring> messageType, impl::abi_arg_in<Windows::Networking::Proximity::MessageReceivedHandler> messageReceivedHandler, int64_t * subscriptionId) noexcept override { try { typename D::abi_guard guard(this->shim()); *subscriptionId = detach_abi(this->shim().SubscribeForMessage(*reinterpret_cast<const hstring *>(&messageType), *reinterpret_cast<const Windows::Networking::Proximity::MessageReceivedHandler *>(&messageReceivedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishMessage(impl::abi_arg_in<hstring> messageType, impl::abi_arg_in<hstring> message, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishMessage(*reinterpret_cast<const hstring *>(&messageType), *reinterpret_cast<const hstring *>(&message))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishMessageWithCallback(impl::abi_arg_in<hstring> messageType, impl::abi_arg_in<hstring> message, impl::abi_arg_in<Windows::Networking::Proximity::MessageTransmittedHandler> messageTransmittedHandler, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishMessage(*reinterpret_cast<const hstring *>(&messageType), *reinterpret_cast<const hstring *>(&message), *reinterpret_cast<const Windows::Networking::Proximity::MessageTransmittedHandler *>(&messageTransmittedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishBinaryMessage(impl::abi_arg_in<hstring> messageType, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> message, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishBinaryMessage(*reinterpret_cast<const hstring *>(&messageType), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&message))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishBinaryMessageWithCallback(impl::abi_arg_in<hstring> messageType, impl::abi_arg_in<Windows::Storage::Streams::IBuffer> message, impl::abi_arg_in<Windows::Networking::Proximity::MessageTransmittedHandler> messageTransmittedHandler, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishBinaryMessage(*reinterpret_cast<const hstring *>(&messageType), *reinterpret_cast<const Windows::Storage::Streams::IBuffer *>(&message), *reinterpret_cast<const Windows::Networking::Proximity::MessageTransmittedHandler *>(&messageTransmittedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishUriMessage(impl::abi_arg_in<Windows::Foundation::IUriRuntimeClass> message, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishUriMessage(*reinterpret_cast<const Windows::Foundation::Uri *>(&message))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_PublishUriMessageWithCallback(impl::abi_arg_in<Windows::Foundation::IUriRuntimeClass> message, impl::abi_arg_in<Windows::Networking::Proximity::MessageTransmittedHandler> messageTransmittedHandler, int64_t * messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); *messageId = detach_abi(this->shim().PublishUriMessage(*reinterpret_cast<const Windows::Foundation::Uri *>(&message), *reinterpret_cast<const Windows::Networking::Proximity::MessageTransmittedHandler *>(&messageTransmittedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_StopSubscribingForMessage(int64_t subscriptionId) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StopSubscribingForMessage(subscriptionId); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_StopPublishingMessage(int64_t messageId) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().StopPublishingMessage(messageId); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_DeviceArrived(impl::abi_arg_in<Windows::Networking::Proximity::DeviceArrivedEventHandler> arrivedHandler, event_token * cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); *cookie = detach_abi(this->shim().DeviceArrived(*reinterpret_cast<const Windows::Networking::Proximity::DeviceArrivedEventHandler *>(&arrivedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_DeviceArrived(event_token cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DeviceArrived(cookie); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall add_DeviceDeparted(impl::abi_arg_in<Windows::Networking::Proximity::DeviceDepartedEventHandler> departedHandler, event_token * cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); *cookie = detach_abi(this->shim().DeviceDeparted(*reinterpret_cast<const Windows::Networking::Proximity::DeviceDepartedEventHandler *>(&departedHandler))); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall remove_DeviceDeparted(event_token cookie) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().DeviceDeparted(cookie); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_MaxMessageBytes(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MaxMessageBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_BitsPerSecond(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().BitsPerSecond()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DeviceId()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IProximityDeviceStatics> : produce_base<D, Windows::Networking::Proximity::IProximityDeviceStatics> { HRESULT __stdcall abi_GetDeviceSelector(impl::abi_arg_out<hstring> selector) noexcept override { try { typename D::abi_guard guard(this->shim()); *selector = detach_abi(this->shim().GetDeviceSelector()); return S_OK; } catch (...) { *selector = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetDefault(impl::abi_arg_out<Windows::Networking::Proximity::IProximityDevice> proximityDevice) noexcept override { try { typename D::abi_guard guard(this->shim()); *proximityDevice = detach_abi(this->shim().GetDefault()); return S_OK; } catch (...) { *proximityDevice = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_FromId(impl::abi_arg_in<hstring> deviceId, impl::abi_arg_out<Windows::Networking::Proximity::IProximityDevice> proximityDevice) noexcept override { try { typename D::abi_guard guard(this->shim()); *proximityDevice = detach_abi(this->shim().FromId(*reinterpret_cast<const hstring *>(&deviceId))); return S_OK; } catch (...) { *proximityDevice = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::IProximityMessage> : produce_base<D, Windows::Networking::Proximity::IProximityMessage> { HRESULT __stdcall get_MessageType(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MessageType()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_SubscriptionId(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().SubscriptionId()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Data(impl::abi_arg_out<Windows::Storage::Streams::IBuffer> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Data()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_DataAsString(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DataAsString()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::Networking::Proximity::ITriggeredConnectionStateChangedEventArgs> : produce_base<D, Windows::Networking::Proximity::ITriggeredConnectionStateChangedEventArgs> { HRESULT __stdcall get_State(Windows::Networking::Proximity::TriggeredConnectState * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().State()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Id(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Id()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_Socket(impl::abi_arg_out<Windows::Networking::Sockets::IStreamSocket> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Socket()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; } namespace Windows::Networking::Proximity { template <typename D> hstring impl_IProximityMessage<D>::MessageType() const { hstring value; check_hresult(WINRT_SHIM(IProximityMessage)->get_MessageType(put_abi(value))); return value; } template <typename D> int64_t impl_IProximityMessage<D>::SubscriptionId() const { int64_t value {}; check_hresult(WINRT_SHIM(IProximityMessage)->get_SubscriptionId(&value)); return value; } template <typename D> Windows::Storage::Streams::IBuffer impl_IProximityMessage<D>::Data() const { Windows::Storage::Streams::IBuffer value; check_hresult(WINRT_SHIM(IProximityMessage)->get_Data(put_abi(value))); return value; } template <typename D> hstring impl_IProximityMessage<D>::DataAsString() const { hstring value; check_hresult(WINRT_SHIM(IProximityMessage)->get_DataAsString(put_abi(value))); return value; } template <typename D> int64_t impl_IProximityDevice<D>::SubscribeForMessage(hstring_view messageType, const Windows::Networking::Proximity::MessageReceivedHandler & messageReceivedHandler) const { int64_t subscriptionId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_SubscribeForMessage(get_abi(messageType), get_abi(messageReceivedHandler), &subscriptionId)); return subscriptionId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishMessage(hstring_view messageType, hstring_view message) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishMessage(get_abi(messageType), get_abi(message), &messageId)); return messageId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishMessage(hstring_view messageType, hstring_view message, const Windows::Networking::Proximity::MessageTransmittedHandler & messageTransmittedHandler) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishMessageWithCallback(get_abi(messageType), get_abi(message), get_abi(messageTransmittedHandler), &messageId)); return messageId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishBinaryMessage(hstring_view messageType, const Windows::Storage::Streams::IBuffer & message) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishBinaryMessage(get_abi(messageType), get_abi(message), &messageId)); return messageId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishBinaryMessage(hstring_view messageType, const Windows::Storage::Streams::IBuffer & message, const Windows::Networking::Proximity::MessageTransmittedHandler & messageTransmittedHandler) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishBinaryMessageWithCallback(get_abi(messageType), get_abi(message), get_abi(messageTransmittedHandler), &messageId)); return messageId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishUriMessage(const Windows::Foundation::Uri & message) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishUriMessage(get_abi(message), &messageId)); return messageId; } template <typename D> int64_t impl_IProximityDevice<D>::PublishUriMessage(const Windows::Foundation::Uri & message, const Windows::Networking::Proximity::MessageTransmittedHandler & messageTransmittedHandler) const { int64_t messageId {}; check_hresult(WINRT_SHIM(IProximityDevice)->abi_PublishUriMessageWithCallback(get_abi(message), get_abi(messageTransmittedHandler), &messageId)); return messageId; } template <typename D> void impl_IProximityDevice<D>::StopSubscribingForMessage(int64_t subscriptionId) const { check_hresult(WINRT_SHIM(IProximityDevice)->abi_StopSubscribingForMessage(subscriptionId)); } template <typename D> void impl_IProximityDevice<D>::StopPublishingMessage(int64_t messageId) const { check_hresult(WINRT_SHIM(IProximityDevice)->abi_StopPublishingMessage(messageId)); } template <typename D> event_token impl_IProximityDevice<D>::DeviceArrived(const Windows::Networking::Proximity::DeviceArrivedEventHandler & arrivedHandler) const { event_token cookie {}; check_hresult(WINRT_SHIM(IProximityDevice)->add_DeviceArrived(get_abi(arrivedHandler), &cookie)); return cookie; } template <typename D> event_revoker<IProximityDevice> impl_IProximityDevice<D>::DeviceArrived(auto_revoke_t, const Windows::Networking::Proximity::DeviceArrivedEventHandler & arrivedHandler) const { return impl::make_event_revoker<D, IProximityDevice>(this, &ABI::Windows::Networking::Proximity::IProximityDevice::remove_DeviceArrived, DeviceArrived(arrivedHandler)); } template <typename D> void impl_IProximityDevice<D>::DeviceArrived(event_token cookie) const { check_hresult(WINRT_SHIM(IProximityDevice)->remove_DeviceArrived(cookie)); } template <typename D> event_token impl_IProximityDevice<D>::DeviceDeparted(const Windows::Networking::Proximity::DeviceDepartedEventHandler & departedHandler) const { event_token cookie {}; check_hresult(WINRT_SHIM(IProximityDevice)->add_DeviceDeparted(get_abi(departedHandler), &cookie)); return cookie; } template <typename D> event_revoker<IProximityDevice> impl_IProximityDevice<D>::DeviceDeparted(auto_revoke_t, const Windows::Networking::Proximity::DeviceDepartedEventHandler & departedHandler) const { return impl::make_event_revoker<D, IProximityDevice>(this, &ABI::Windows::Networking::Proximity::IProximityDevice::remove_DeviceDeparted, DeviceDeparted(departedHandler)); } template <typename D> void impl_IProximityDevice<D>::DeviceDeparted(event_token cookie) const { check_hresult(WINRT_SHIM(IProximityDevice)->remove_DeviceDeparted(cookie)); } template <typename D> uint32_t impl_IProximityDevice<D>::MaxMessageBytes() const { uint32_t value {}; check_hresult(WINRT_SHIM(IProximityDevice)->get_MaxMessageBytes(&value)); return value; } template <typename D> uint64_t impl_IProximityDevice<D>::BitsPerSecond() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProximityDevice)->get_BitsPerSecond(&value)); return value; } template <typename D> hstring impl_IProximityDevice<D>::DeviceId() const { hstring value; check_hresult(WINRT_SHIM(IProximityDevice)->get_DeviceId(put_abi(value))); return value; } template <typename D> hstring impl_IProximityDeviceStatics<D>::GetDeviceSelector() const { hstring selector; check_hresult(WINRT_SHIM(IProximityDeviceStatics)->abi_GetDeviceSelector(put_abi(selector))); return selector; } template <typename D> Windows::Networking::Proximity::ProximityDevice impl_IProximityDeviceStatics<D>::GetDefault() const { Windows::Networking::Proximity::ProximityDevice proximityDevice { nullptr }; check_hresult(WINRT_SHIM(IProximityDeviceStatics)->abi_GetDefault(put_abi(proximityDevice))); return proximityDevice; } template <typename D> Windows::Networking::Proximity::ProximityDevice impl_IProximityDeviceStatics<D>::FromId(hstring_view deviceId) const { Windows::Networking::Proximity::ProximityDevice proximityDevice { nullptr }; check_hresult(WINRT_SHIM(IProximityDeviceStatics)->abi_FromId(get_abi(deviceId), put_abi(proximityDevice))); return proximityDevice; } template <typename D> Windows::Networking::Proximity::TriggeredConnectState impl_ITriggeredConnectionStateChangedEventArgs<D>::State() const { Windows::Networking::Proximity::TriggeredConnectState value {}; check_hresult(WINRT_SHIM(ITriggeredConnectionStateChangedEventArgs)->get_State(&value)); return value; } template <typename D> uint32_t impl_ITriggeredConnectionStateChangedEventArgs<D>::Id() const { uint32_t value {}; check_hresult(WINRT_SHIM(ITriggeredConnectionStateChangedEventArgs)->get_Id(&value)); return value; } template <typename D> Windows::Networking::Sockets::StreamSocket impl_ITriggeredConnectionStateChangedEventArgs<D>::Socket() const { Windows::Networking::Sockets::StreamSocket value { nullptr }; check_hresult(WINRT_SHIM(ITriggeredConnectionStateChangedEventArgs)->get_Socket(put_abi(value))); return value; } template <typename D> hstring impl_IPeerInformation<D>::DisplayName() const { hstring value; check_hresult(WINRT_SHIM(IPeerInformation)->get_DisplayName(put_abi(value))); return value; } template <typename D> Windows::Networking::HostName impl_IPeerInformationWithHostAndService<D>::HostName() const { Windows::Networking::HostName value { nullptr }; check_hresult(WINRT_SHIM(IPeerInformationWithHostAndService)->get_HostName(put_abi(value))); return value; } template <typename D> hstring impl_IPeerInformationWithHostAndService<D>::ServiceName() const { hstring value; check_hresult(WINRT_SHIM(IPeerInformationWithHostAndService)->get_ServiceName(put_abi(value))); return value; } template <typename D> hstring impl_IPeerInformation3<D>::Id() const { hstring value; check_hresult(WINRT_SHIM(IPeerInformation3)->get_Id(put_abi(value))); return value; } template <typename D> Windows::Storage::Streams::IBuffer impl_IPeerInformation3<D>::DiscoveryData() const { Windows::Storage::Streams::IBuffer value; check_hresult(WINRT_SHIM(IPeerInformation3)->get_DiscoveryData(put_abi(value))); return value; } template <typename D> Windows::Networking::Proximity::PeerInformation impl_IConnectionRequestedEventArgs<D>::PeerInformation() const { Windows::Networking::Proximity::PeerInformation value { nullptr }; check_hresult(WINRT_SHIM(IConnectionRequestedEventArgs)->get_PeerInformation(put_abi(value))); return value; } template <typename D> event_token impl_IPeerWatcher<D>::Added(const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPeerWatcher)->add_Added(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPeerWatcher> impl_IPeerWatcher<D>::Added(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { return impl::make_event_revoker<D, IPeerWatcher>(this, &ABI::Windows::Networking::Proximity::IPeerWatcher::remove_Added, Added(handler)); } template <typename D> void impl_IPeerWatcher<D>::Added(event_token token) const { check_hresult(WINRT_SHIM(IPeerWatcher)->remove_Added(token)); } template <typename D> event_token impl_IPeerWatcher<D>::Removed(const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPeerWatcher)->add_Removed(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPeerWatcher> impl_IPeerWatcher<D>::Removed(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { return impl::make_event_revoker<D, IPeerWatcher>(this, &ABI::Windows::Networking::Proximity::IPeerWatcher::remove_Removed, Removed(handler)); } template <typename D> void impl_IPeerWatcher<D>::Removed(event_token token) const { check_hresult(WINRT_SHIM(IPeerWatcher)->remove_Removed(token)); } template <typename D> event_token impl_IPeerWatcher<D>::Updated(const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPeerWatcher)->add_Updated(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPeerWatcher> impl_IPeerWatcher<D>::Updated(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Networking::Proximity::PeerInformation> & handler) const { return impl::make_event_revoker<D, IPeerWatcher>(this, &ABI::Windows::Networking::Proximity::IPeerWatcher::remove_Updated, Updated(handler)); } template <typename D> void impl_IPeerWatcher<D>::Updated(event_token token) const { check_hresult(WINRT_SHIM(IPeerWatcher)->remove_Updated(token)); } template <typename D> event_token impl_IPeerWatcher<D>::EnumerationCompleted(const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPeerWatcher)->add_EnumerationCompleted(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPeerWatcher> impl_IPeerWatcher<D>::EnumerationCompleted(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, IPeerWatcher>(this, &ABI::Windows::Networking::Proximity::IPeerWatcher::remove_EnumerationCompleted, EnumerationCompleted(handler)); } template <typename D> void impl_IPeerWatcher<D>::EnumerationCompleted(event_token token) const { check_hresult(WINRT_SHIM(IPeerWatcher)->remove_EnumerationCompleted(token)); } template <typename D> event_token impl_IPeerWatcher<D>::Stopped(const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> & handler) const { event_token token {}; check_hresult(WINRT_SHIM(IPeerWatcher)->add_Stopped(get_abi(handler), &token)); return token; } template <typename D> event_revoker<IPeerWatcher> impl_IPeerWatcher<D>::Stopped(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Networking::Proximity::PeerWatcher, Windows::Foundation::IInspectable> & handler) const { return impl::make_event_revoker<D, IPeerWatcher>(this, &ABI::Windows::Networking::Proximity::IPeerWatcher::remove_Stopped, Stopped(handler)); } template <typename D> void impl_IPeerWatcher<D>::Stopped(event_token token) const { check_hresult(WINRT_SHIM(IPeerWatcher)->remove_Stopped(token)); } template <typename D> Windows::Networking::Proximity::PeerWatcherStatus impl_IPeerWatcher<D>::Status() const { Windows::Networking::Proximity::PeerWatcherStatus status {}; check_hresult(WINRT_SHIM(IPeerWatcher)->get_Status(&status)); return status; } template <typename D> void impl_IPeerWatcher<D>::Start() const { check_hresult(WINRT_SHIM(IPeerWatcher)->abi_Start()); } template <typename D> void impl_IPeerWatcher<D>::Stop() const { check_hresult(WINRT_SHIM(IPeerWatcher)->abi_Stop()); } template <typename D> bool impl_IPeerFinderStatics<D>::AllowBluetooth() const { bool value {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_AllowBluetooth(&value)); return value; } template <typename D> void impl_IPeerFinderStatics<D>::AllowBluetooth(bool value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->put_AllowBluetooth(value)); } template <typename D> bool impl_IPeerFinderStatics<D>::AllowInfrastructure() const { bool value {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_AllowInfrastructure(&value)); return value; } template <typename D> void impl_IPeerFinderStatics<D>::AllowInfrastructure(bool value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->put_AllowInfrastructure(value)); } template <typename D> bool impl_IPeerFinderStatics<D>::AllowWiFiDirect() const { bool value {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_AllowWiFiDirect(&value)); return value; } template <typename D> void impl_IPeerFinderStatics<D>::AllowWiFiDirect(bool value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->put_AllowWiFiDirect(value)); } template <typename D> hstring impl_IPeerFinderStatics<D>::DisplayName() const { hstring value; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_DisplayName(put_abi(value))); return value; } template <typename D> void impl_IPeerFinderStatics<D>::DisplayName(hstring_view value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->put_DisplayName(get_abi(value))); } template <typename D> Windows::Networking::Proximity::PeerDiscoveryTypes impl_IPeerFinderStatics<D>::SupportedDiscoveryTypes() const { Windows::Networking::Proximity::PeerDiscoveryTypes value {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_SupportedDiscoveryTypes(&value)); return value; } template <typename D> Windows::Foundation::Collections::IMap<hstring, hstring> impl_IPeerFinderStatics<D>::AlternateIdentities() const { Windows::Foundation::Collections::IMap<hstring, hstring> value; check_hresult(WINRT_SHIM(IPeerFinderStatics)->get_AlternateIdentities(put_abi(value))); return value; } template <typename D> void impl_IPeerFinderStatics<D>::Start() const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->abi_Start()); } template <typename D> void impl_IPeerFinderStatics<D>::Start(hstring_view peerMessage) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->abi_StartWithMessage(get_abi(peerMessage))); } template <typename D> void impl_IPeerFinderStatics<D>::Stop() const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->abi_Stop()); } template <typename D> event_token impl_IPeerFinderStatics<D>::TriggeredConnectionStateChanged(const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> & handler) const { event_token cookie {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->add_TriggeredConnectionStateChanged(get_abi(handler), &cookie)); return cookie; } template <typename D> event_revoker<IPeerFinderStatics> impl_IPeerFinderStatics<D>::TriggeredConnectionStateChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> & handler) const { return impl::make_event_revoker<D, IPeerFinderStatics>(this, &ABI::Windows::Networking::Proximity::IPeerFinderStatics::remove_TriggeredConnectionStateChanged, TriggeredConnectionStateChanged(handler)); } template <typename D> void impl_IPeerFinderStatics<D>::TriggeredConnectionStateChanged(event_token cookie) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->remove_TriggeredConnectionStateChanged(cookie)); } template <typename D> event_token impl_IPeerFinderStatics<D>::ConnectionRequested(const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs> & handler) const { event_token cookie {}; check_hresult(WINRT_SHIM(IPeerFinderStatics)->add_ConnectionRequested(get_abi(handler), &cookie)); return cookie; } template <typename D> event_revoker<IPeerFinderStatics> impl_IPeerFinderStatics<D>::ConnectionRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs> & handler) const { return impl::make_event_revoker<D, IPeerFinderStatics>(this, &ABI::Windows::Networking::Proximity::IPeerFinderStatics::remove_ConnectionRequested, ConnectionRequested(handler)); } template <typename D> void impl_IPeerFinderStatics<D>::ConnectionRequested(event_token cookie) const { check_hresult(WINRT_SHIM(IPeerFinderStatics)->remove_ConnectionRequested(cookie)); } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Networking::Proximity::PeerInformation>> impl_IPeerFinderStatics<D>::FindAllPeersAsync() const { Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Networking::Proximity::PeerInformation>> asyncOp; check_hresult(WINRT_SHIM(IPeerFinderStatics)->abi_FindAllPeersAsync(put_abi(asyncOp))); return asyncOp; } template <typename D> Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocket> impl_IPeerFinderStatics<D>::ConnectAsync(const Windows::Networking::Proximity::PeerInformation & peerInformation) const { Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocket> asyncOp; check_hresult(WINRT_SHIM(IPeerFinderStatics)->abi_ConnectAsync(get_abi(peerInformation), put_abi(asyncOp))); return asyncOp; } template <typename D> Windows::Networking::Proximity::PeerRole impl_IPeerFinderStatics2<D>::Role() const { Windows::Networking::Proximity::PeerRole value {}; check_hresult(WINRT_SHIM(IPeerFinderStatics2)->get_Role(&value)); return value; } template <typename D> void impl_IPeerFinderStatics2<D>::Role(Windows::Networking::Proximity::PeerRole value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics2)->put_Role(value)); } template <typename D> Windows::Storage::Streams::IBuffer impl_IPeerFinderStatics2<D>::DiscoveryData() const { Windows::Storage::Streams::IBuffer value; check_hresult(WINRT_SHIM(IPeerFinderStatics2)->get_DiscoveryData(put_abi(value))); return value; } template <typename D> void impl_IPeerFinderStatics2<D>::DiscoveryData(const Windows::Storage::Streams::IBuffer & value) const { check_hresult(WINRT_SHIM(IPeerFinderStatics2)->put_DiscoveryData(get_abi(value))); } template <typename D> Windows::Networking::Proximity::PeerWatcher impl_IPeerFinderStatics2<D>::CreateWatcher() const { Windows::Networking::Proximity::PeerWatcher watcher { nullptr }; check_hresult(WINRT_SHIM(IPeerFinderStatics2)->abi_CreateWatcher(put_abi(watcher))); return watcher; } inline bool PeerFinder::AllowBluetooth() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowBluetooth(); } inline void PeerFinder::AllowBluetooth(bool value) { get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowBluetooth(value); } inline bool PeerFinder::AllowInfrastructure() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowInfrastructure(); } inline void PeerFinder::AllowInfrastructure(bool value) { get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowInfrastructure(value); } inline bool PeerFinder::AllowWiFiDirect() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowWiFiDirect(); } inline void PeerFinder::AllowWiFiDirect(bool value) { get_activation_factory<PeerFinder, IPeerFinderStatics>().AllowWiFiDirect(value); } inline hstring PeerFinder::DisplayName() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().DisplayName(); } inline void PeerFinder::DisplayName(hstring_view value) { get_activation_factory<PeerFinder, IPeerFinderStatics>().DisplayName(value); } inline Windows::Networking::Proximity::PeerDiscoveryTypes PeerFinder::SupportedDiscoveryTypes() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().SupportedDiscoveryTypes(); } inline Windows::Foundation::Collections::IMap<hstring, hstring> PeerFinder::AlternateIdentities() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().AlternateIdentities(); } inline void PeerFinder::Start() { get_activation_factory<PeerFinder, IPeerFinderStatics>().Start(); } inline void PeerFinder::Start(hstring_view peerMessage) { get_activation_factory<PeerFinder, IPeerFinderStatics>().Start(peerMessage); } inline void PeerFinder::Stop() { get_activation_factory<PeerFinder, IPeerFinderStatics>().Stop(); } inline event_token PeerFinder::TriggeredConnectionStateChanged(const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> & handler) { return get_activation_factory<PeerFinder, IPeerFinderStatics>().TriggeredConnectionStateChanged(handler); } inline factory_event_revoker<IPeerFinderStatics> PeerFinder::TriggeredConnectionStateChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> & handler) { auto factory = get_activation_factory<PeerFinder, IPeerFinderStatics>(); return { factory, &ABI::Windows::Networking::Proximity::IPeerFinderStatics::remove_TriggeredConnectionStateChanged, factory.TriggeredConnectionStateChanged(handler) }; } inline void PeerFinder::TriggeredConnectionStateChanged(event_token cookie) { get_activation_factory<PeerFinder, IPeerFinderStatics>().TriggeredConnectionStateChanged(cookie); } inline event_token PeerFinder::ConnectionRequested(const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs> & handler) { return get_activation_factory<PeerFinder, IPeerFinderStatics>().ConnectionRequested(handler); } inline factory_event_revoker<IPeerFinderStatics> PeerFinder::ConnectionRequested(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Foundation::IInspectable, Windows::Networking::Proximity::ConnectionRequestedEventArgs> & handler) { auto factory = get_activation_factory<PeerFinder, IPeerFinderStatics>(); return { factory, &ABI::Windows::Networking::Proximity::IPeerFinderStatics::remove_ConnectionRequested, factory.ConnectionRequested(handler) }; } inline void PeerFinder::ConnectionRequested(event_token cookie) { get_activation_factory<PeerFinder, IPeerFinderStatics>().ConnectionRequested(cookie); } inline Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Networking::Proximity::PeerInformation>> PeerFinder::FindAllPeersAsync() { return get_activation_factory<PeerFinder, IPeerFinderStatics>().FindAllPeersAsync(); } inline Windows::Foundation::IAsyncOperation<Windows::Networking::Sockets::StreamSocket> PeerFinder::ConnectAsync(const Windows::Networking::Proximity::PeerInformation & peerInformation) { return get_activation_factory<PeerFinder, IPeerFinderStatics>().ConnectAsync(peerInformation); } inline Windows::Networking::Proximity::PeerRole PeerFinder::Role() { return get_activation_factory<PeerFinder, IPeerFinderStatics2>().Role(); } inline void PeerFinder::Role(Windows::Networking::Proximity::PeerRole value) { get_activation_factory<PeerFinder, IPeerFinderStatics2>().Role(value); } inline Windows::Storage::Streams::IBuffer PeerFinder::DiscoveryData() { return get_activation_factory<PeerFinder, IPeerFinderStatics2>().DiscoveryData(); } inline void PeerFinder::DiscoveryData(const Windows::Storage::Streams::IBuffer & value) { get_activation_factory<PeerFinder, IPeerFinderStatics2>().DiscoveryData(value); } inline Windows::Networking::Proximity::PeerWatcher PeerFinder::CreateWatcher() { return get_activation_factory<PeerFinder, IPeerFinderStatics2>().CreateWatcher(); } inline hstring ProximityDevice::GetDeviceSelector() { return get_activation_factory<ProximityDevice, IProximityDeviceStatics>().GetDeviceSelector(); } inline Windows::Networking::Proximity::ProximityDevice ProximityDevice::GetDefault() { return get_activation_factory<ProximityDevice, IProximityDeviceStatics>().GetDefault(); } inline Windows::Networking::Proximity::ProximityDevice ProximityDevice::FromId(hstring_view deviceId) { return get_activation_factory<ProximityDevice, IProximityDeviceStatics>().FromId(deviceId); } } } template<> struct std::hash<winrt::Windows::Networking::Proximity::IConnectionRequestedEventArgs> { size_t operator()(const winrt::Windows::Networking::Proximity::IConnectionRequestedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerFinderStatics> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerFinderStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerFinderStatics2> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerFinderStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerInformation> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerInformation & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerInformation3> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerInformation3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerInformationWithHostAndService> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerInformationWithHostAndService & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IPeerWatcher> { size_t operator()(const winrt::Windows::Networking::Proximity::IPeerWatcher & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IProximityDevice> { size_t operator()(const winrt::Windows::Networking::Proximity::IProximityDevice & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IProximityDeviceStatics> { size_t operator()(const winrt::Windows::Networking::Proximity::IProximityDeviceStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::IProximityMessage> { size_t operator()(const winrt::Windows::Networking::Proximity::IProximityMessage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::ITriggeredConnectionStateChangedEventArgs> { size_t operator()(const winrt::Windows::Networking::Proximity::ITriggeredConnectionStateChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs> { size_t operator()(const winrt::Windows::Networking::Proximity::ConnectionRequestedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::PeerInformation> { size_t operator()(const winrt::Windows::Networking::Proximity::PeerInformation & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::PeerWatcher> { size_t operator()(const winrt::Windows::Networking::Proximity::PeerWatcher & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::ProximityDevice> { size_t operator()(const winrt::Windows::Networking::Proximity::ProximityDevice & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::ProximityMessage> { size_t operator()(const winrt::Windows::Networking::Proximity::ProximityMessage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs> { size_t operator()(const winrt::Windows::Networking::Proximity::TriggeredConnectionStateChangedEventArgs & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
#include "wizpopupwidget.h" #include <QtGui> #include "wizmisc.h" #ifdef Q_OS_WIN //#include "wizwindowshelper.h" #endif CWizPopupWidget::CWizPopupWidget(QWidget* parent) : QWidget(parent, Qt::Popup | Qt::FramelessWindowHint) , m_leftAlign(false) { setContentsMargins(8, 20, 8, 8); QPalette pal = palette(); pal.setColor(QPalette::Window, "#DCDCDC"); // (215, 215, 215) setPalette(pal); } QSize CWizPopupWidget::sizeHint() const { return QSize(300, 400); } QRect CWizPopupWidget::getClientRect() const { QMargins margins = contentsMargins(); return QRect(margins.left(), margins.top(), width() - margins.left() - margins.right(), height() - margins.top() - margins.bottom()); } void CWizPopupWidget::paintEvent(QPaintEvent* event) { Q_UNUSED(event); setMask(maskRegion()); } void CWizPopupWidget::showAtPoint(const QPoint& pt) { int xOffset = m_leftAlign ? 21 : sizeHint().width() - 21; int yOffset = 4; int left = pt.x() - xOffset; int top = pt.y() - yOffset; m_pos.setX(left); m_pos.setY(top); QPropertyAnimation* anim1 = new QPropertyAnimation(this, "geometry"); anim1->setDuration(200); anim1->setKeyValueAt(0, QRect(QPoint(m_pos.x() + sizeHint().width(), m_pos.y()), QSize(0, 0))); anim1->setKeyValueAt(0.5, QRect(QPoint(m_pos.x() - 50, m_pos.y()), QSize(sizeHint().width() + 100, sizeHint().height() + 100))); anim1->setKeyValueAt(1, QRect(QPoint(m_pos.x(), m_pos.y()), QSize(sizeHint().width(), sizeHint().height()))); QPropertyAnimation* anim2 = new QPropertyAnimation(this, "windowOpacity"); anim2->setStartValue(0.1); anim2->setEndValue(1.0); QParallelAnimationGroup *group = new QParallelAnimationGroup; group->addAnimation(anim1); group->addAnimation(anim2); group->start(); show(); } QRegion CWizPopupWidget::maskRegion() { QSize sz = size(); m_pointsRegion.clear(); if (m_leftAlign) { m_pointsRegion.push_back(QPoint(1, 10)); m_pointsRegion.push_back(QPoint(11, 10)); m_pointsRegion.push_back(QPoint(21, 0)); m_pointsRegion.push_back(QPoint(31, 10)); m_pointsRegion.push_back(QPoint(sz.width() - 1, 10)); m_pointsRegion.push_back(QPoint(sz.width(), 11)); m_pointsRegion.push_back(QPoint(sz.width(), sz.height())); m_pointsRegion.push_back(QPoint(0, sz.height())); m_pointsRegion.push_back(QPoint(0, 11)); m_pointsPolygon.push_back(QPoint(1, 10)); m_pointsPolygon.push_back(QPoint(11, 10)); for (int i = 0; i < 9; i++) { m_pointsPolygon.push_back(QPoint(11 + i, 10 - i)); m_pointsPolygon.push_back(QPoint(11 + i + 1, 10 - i)); } m_pointsPolygon.push_back(QPoint(20, 1)); m_pointsPolygon.push_back(QPoint(21, 1)); for (int i = 0; i < 9; i++) { m_pointsPolygon.push_back(QPoint(21 + i, 2 + i)); m_pointsPolygon.push_back(QPoint(21 + i + 1, 2 + i)); } m_pointsPolygon.push_back(QPoint(31, 10)); m_pointsPolygon.push_back(QPoint(sz.width() - 2, 10)); m_pointsPolygon.push_back(QPoint(sz.width() - 1, 11)); m_pointsPolygon.push_back(QPoint(sz.width() - 1, sz.height() - 1)); m_pointsPolygon.push_back(QPoint(0, sz.height() - 1)); m_pointsPolygon.push_back(QPoint(0, 11)); m_pointsPolygon.push_back(QPoint(1, 11)); } else { m_pointsRegion.push_back(QPoint(1, 10)); m_pointsRegion.push_back(QPoint(sz.width() - 31, 10)); m_pointsRegion.push_back(QPoint(sz.width() - 21, 0)); m_pointsRegion.push_back(QPoint(sz.width() - 11, 10)); m_pointsRegion.push_back(QPoint(sz.width() - 1, 10)); m_pointsRegion.push_back(QPoint(sz.width(), 11)); m_pointsRegion.push_back(QPoint(sz.width(), sz.height())); m_pointsRegion.push_back(QPoint(0, sz.height())); m_pointsRegion.push_back(QPoint(0, 11)); m_pointsPolygon.push_back(QPoint(1, 10)); m_pointsPolygon.push_back(QPoint(sz.width() - 31, 10)); for (int i = 0; i < 9; i++) { m_pointsPolygon.push_back(QPoint(sz.width() - 31 + i, 10 - i)); m_pointsPolygon.push_back(QPoint(sz.width() - 31 + i + 1, 10 - i)); } m_pointsPolygon.push_back(QPoint(sz.width() - 22, 1)); m_pointsPolygon.push_back(QPoint(sz.width() - 21, 1)); for (int i = 0; i < 9; i++) { m_pointsPolygon.push_back(QPoint(sz.width() - 21 + i, 2 + i)); m_pointsPolygon.push_back(QPoint(sz.width() - 21 + i + 1, 2 + i)); } m_pointsPolygon.push_back(QPoint(sz.width() - 12, 10)); m_pointsPolygon.push_back(QPoint(sz.width() - 2, 10)); m_pointsPolygon.push_back(QPoint(sz.width() - 2, 11)); m_pointsPolygon.push_back(QPoint(sz.width() - 1, 11)); m_pointsPolygon.push_back(QPoint(sz.width() - 1, sz.height() - 1)); m_pointsPolygon.push_back(QPoint(0, sz.height() - 1)); m_pointsPolygon.push_back(QPoint(0, 11)); m_pointsPolygon.push_back(QPoint(1, 11)); } QPolygon polygon(m_pointsRegion); return QRegion(polygon); }
#include "AngraMCMixer.h" AngraMCMixer::AngraMCMixer() : currentPrimary(0), currentEvent(0), currentTime(0), outFile(), theTree(), pulseDB(), rates(), pulseBuffer(), bufferSize(0) { } void AngraMCMixer::AddPrimary(PulseTree * aPulseTree, double rate) { std::cout << " AngraMCMixer: Adding a generator" << std::endl; rates.push_back(rate); std::vector<std::vector< AngraMCPulse > > aTree; pulseDB.push_back(aTree); int lastGen = pulseDB.size(); //loop over tree and add pulses std::vector< AngraMCPulse > theEvent; AngraMCPulse aPulse; Long64_t pt1_ne = aPulseTree->fChain->GetEntriesFast(); for (Long64_t pt1_j=0; pt1_j<pt1_ne;pt1_j++) { theEvent.clear(); Long64_t ientry = aPulseTree->LoadTree(pt1_j); if (ientry < 0) break; aPulseTree->fChain->GetEntry(pt1_j); for(int ip=0; ip<aPulseTree->Pulses_; ip++) { LoadPulse(ip, aPulse, aPulseTree); theEvent.push_back(aPulse); } pulseDB[lastGen-1].push_back(theEvent); } std::cout << " AngraMCMixer: added " << pulseDB[lastGen-1].size() << " events to generator " << (lastGen-1) << std::endl; } void AngraMCMixer::LoadPulse(int ip, AngraMCPulse &aPulse, PulseTree * aPulseTree){ for(int i=0; i<TOT_PMTS; i++){ aPulse.hits[i]=aPulseTree->Pulses_hits[ip][i]; aPulse.times[i]=aPulseTree->Pulses_times[ip][i]; } aPulse.startPmt=aPulseTree->Pulses_startPmt[ip]; aPulse.startTime=aPulseTree->Pulses_startTime[ip]; aPulse.globalTime1=aPulseTree->Pulses_globalTime1[ip]; aPulse.globalTime2=aPulseTree->Pulses_globalTime2[ip]; aPulse.run1=aPulseTree->Pulses_run1[ip]; aPulse.run2=aPulseTree->Pulses_run2[ip]; aPulse.event1=aPulseTree->Pulses_event1[ip]; aPulse.event2=aPulseTree->Pulses_event2[ip]; } int AngraMCMixer::GetNPrimaries(){ return pulseDB.size(); } int AngraMCMixer::GetNEvents(int primary){ return pulseDB[primary].size(); } int AngraMCMixer::GetNPulses(int primary, int event){ return pulseDB[primary][event].size(); } AngraMCPulse AngraMCMixer::GetAPulse(int primary, int event, int pulse){ return pulseDB[primary][event][pulse]; } void AngraMCMixer::Init(std::string fileName, int seed){ std::cout << " AngraMCMixer: Init " << std::endl; outFile.Open(fileName.c_str(),"recreate"); theTree = new TTree("MixerTree", "Mixed Pulses"); thePulseP=new AngraMCPulse(); theTree->Branch("Pulse","AngraMCPulse",&thePulseP,32000,99); theTimer=new AngraMixerTimer(seed); std::vector< double >::iterator ratesIt; for(ratesIt=rates.begin();ratesIt!=rates.end();++ratesIt){ theTimer->PushBack(*ratesIt); } theTimer->Init( ); theRGenerator = new TRandom2(seed); } void AngraMCMixer::Finalize(){ std::cout << " AngraMCMixer: Finalize " << std::endl; theTree->Write(); outFile.Close(); thePulseP->Delete(); theTree->Delete(); theRGenerator->Delete(); delete theTimer; } void AngraMCMixer::FillSequentially(){ std::cout << " AngraMCMixer: Filling sequentially " << std::endl; std::vector<std::vector< std::vector< AngraMCPulse > > >::iterator it1; std::vector< std::vector< AngraMCPulse > >::iterator it2; std::vector< AngraMCPulse >::iterator it3; int cycle = 0; for(it1=pulseDB.begin();it1!=pulseDB.end();++it1){ std::cout << " primary " << cycle << std::endl; for(it2=it1->begin();it2!=it1->end();++it2){ for(it3=it2->begin();it3!=it2->end();++it3){ (*thePulseP)=(*it3); theTree->Fill(); } } cycle++; } } void AngraMCMixer::Fill(double time){ std::cout << " AngraMCMixer: Filling for " << time << " seconds " << std::endl; currentPrimary=theTimer->GetCurrentGenerator(); currentEvent=theRGenerator->Integer(pulseDB[currentPrimary].size()); currentTime=theTimer->GetCurrentTime(); while(theTimer->Next()<time){ StoreEvent(); if( pulseBuffer.size() > buffersize) Flush(); currentPrimary=theTimer->GetCurrentGenerator(); currentEvent=theRGenerator->Integer(pulseDB[currentPrimary].size()); currentTime=theTimer->GetCurrentTime(); } FlushAll(); for(unsigned int i=0; i<rates.size();++i) std::cout << " timer: total events generator " << i << " " << theTimer->GetEvents(i) << std::endl; } void AngraMCMixer::StoreEvent(){ AngraMCPulse aPulse; std::vector< AngraMCPulse >::iterator itPulse; for(itPulse=pulseDB[currentPrimary][currentEvent].begin();itPulse!=pulseDB[currentPrimary][currentEvent].end();++itPulse){ aPulse=(*itPulse); aPulse.globalTime1=currentTime; pulseBuffer.push_back(aPulse); bufferSize++; } } void AngraMCMixer::Flush(){ pulseBuffer.sort(); while( bufferSize > minbuffersize) { (*thePulseP)=pulseBuffer.front(); theTree->Fill(); pulseBuffer.pop_front(); bufferSize--; } } void AngraMCMixer::FlushAll(){ pulseBuffer.sort(); while( bufferSize > 0) { (*thePulseP)=pulseBuffer.front(); theTree->Fill(); pulseBuffer.pop_front(); bufferSize--; } }
#pragma once #include "Algorithm.h" #include "Timer.h" #include <time.h> class AlgorithmRunningTime { Algorithm algorithm; Timer timer; public: AlgorithmRunningTime(); time_t getInterchangeSortRunningTime(std::vector<int> data); // O(n^2) time_t getLinearSeachRunningTime(std::vector<int> data, int searchValue); // O(n) time_t getBinarySearchRunningTime(std::vector<int> data, int searchValue); // O(log(n)) };
#ifndef _I2C_DEVICE_H_ #define _I2C_DEVICE_H_ #include <string> #include "sim_avr.h" #include "sim_irq.h" #include "avr_twi.h" #include "device.h" class i2c_device : public device{ public: i2c_device(uint8_t address, const char* name); ~i2c_device(); virtual uint8_t read() = 0; virtual void write(uint8_t data) = 0; void attach(struct avr_t * avr); int get_type(){ return I2C_TYPE; } uint8_t address; uint8_t selected; struct avr_t* avr; struct avr_irq_t* irq_list; const char* c_names[2]; }; #endif
#include "ros/ros.h" #include "ball_chaser/DriveToTarget.h" #include <sensor_msgs/Image.h> // Define a global client that can request services ros::ServiceClient client; // This function calls the command_robot service to drive the robot in the specified direction void drive_robot(float lin_x, float ang_z) { // TODO: Request a service and pass the velocities to it to drive the robot ball_chaser::DriveToTarget vel_cmd; vel_cmd.request.linear_x = lin_x; vel_cmd.request.angular_z = ang_z; if (!client.call(vel_cmd)){ ROS_ERROR("Failed to execute command"); } } // This callback function continuously executes and reads the image data void process_image_callback(const sensor_msgs::Image img) { int white_pixel = 255; // TODO: Loop through each pixel in the image and check if there's a bright white one // Then, identify if this pixel falls in the left, mid, or right side of the image // Depending on the white ball position, call the drive_bot function and pass velocities to it // Request a stop when there's no white ball seen by the camera int pos_sum = 0; int tot_white_pixels = 0; float mean_ball_position; float x, z; // ROS_INFO("image width %d height %d step_size %d",img.width,img.height,img.step); for(int i=0; i<img.height; ++i){ for (int j=0; j<img.width; ++j){ if (img.data[(i*img.step)+(j*3)] == white_pixel && img.data[(i*img.step)+(j*3)+1] == white_pixel && img.data[(i*img.step)+(j*3)+2] == white_pixel){ ++tot_white_pixels; pos_sum = pos_sum + j; mean_ball_position = pos_sum/tot_white_pixels; } } } // ROS_INFO("%d white pixels found. mean_ball_position is %1.2f ", tot_white_pixels,mean_ball_position); if (tot_white_pixels == 0) { drive_robot(0,0); } else { if (mean_ball_position < img.width / 3) { drive_robot(0.2, 0.5); } else if (mean_ball_position > img.width * 2 / 3) { drive_robot(0.2, -0.5); } else { drive_robot(0.2, 0.0); } } } int main(int argc, char** argv) { // Initialize the process_image node and create a handle to it ros::init(argc, argv, "process_image"); ros::NodeHandle n; // Define a client service capable of requesting services from command_robot client = n.serviceClient<ball_chaser::DriveToTarget>("/ball_chaser/command_robot"); // Subscribe to /camera/rgb/image_raw topic to read the image data inside the process_image_callback function ros::Subscriber sub1 = n.subscribe("/camera/rgb/image_raw", 10, process_image_callback); // Handle ROS communication events ros::spin(); return 0; }
#ifndef PARTICLEBOX_H #define PARTICLEBOX_H #define TRUNC 3.0 //Truncate forces after this distance #define EPS1 0.001 //minimum distance will calculate forces #define CONST1 24.0 #define CONST2 4.0 #define SIG13 1.0 #define SIG12 1.0 #define SIG7 1.0 #define SIG6 1.0 typedef struct{ double xp0, xp1; //x position, now=1, previous=0 int xcrosses; //times crossed the x boundary double xv; //x velocity double yp0, yp1; //y position double yv; //y velocity int ycrosses; }particle; //Particle Box class for particles interacting in // 2D. Potential used is Leonard-Jones with // toroidal boundary conditions and potential // boundary condtions encircling the box, i.e. // boxes on the corners allowed to influence, // not just ones at right angles. class particleBox { public: particleBox(int size, int length, double timestep); ~particleBox(); //Stat-getting functions double getVel2(int i); //get individual square velocity double getTVel(); //get total velocity double getXVel(int i); double getYVel(int i); double getTVel2(); //get total square velocity double getDisp2(int i); //get individual square displacement double getTDisp(); //get total displacement double getTXDisp(); double getTYDisp(); double getTDisp2(); //get total square displacement double getTPot(); //get total potential energy //setup and stepping functions void step(); //take a step void initVel(double min, double max); //initialize velocities void initPos(bool random); //initialize posisitions void firstStep(); //start first step void copy(particle source, particle *dest); //read the name genius //printing functions void printInitPos(); //print intial position void printPos(); //print positions and motion vectors void printForces(double *f, int n); //print once force matrix void printVels(particle *p, int n); //print all velocities //find forces between all particles, also fills in potentials double *findForces(double *n, double *x, double *y); double findForce(double rn1); //get force for a given inverse distance r^-1 double findPot(double rn1); //get potential for a given inverse distance //Update particle positions and velocity (Verlet) void updateParts(); //find min distance between two particles double minDist(int i1, int i2, double *x, double *y); double findDist(particle p1, particle p2); //Move a particle by x and y then return that moved particle particle move(particle p, double x, double y); //heat box by increasing velocities by a factor > 1.0 (<1.0 == cooling) void heatBox(double factor); //private: particle *parts; //the particles being tracked particle *oparts; //original particle states @ t=0 int n; //num of particles being tracked int l; //length of side of box double delt; //delta t, time-step double delt2; //delta t**2 (save time) double *xforces; //x forces (n*n size) double *yforces; //y forces (n*n size) double *nforces; //net forces (n*n size) double *potentials; //potential energies between particles (n*n) }; #endif
#include <Servo.h> Servo servo1; void setup() { servo1.attach(2); servo1.write(125); delay(5000); servo1.write(90); delay(200); servo1.write(125); delay(710); } void loop() { servo1.write(90); //1 delay(200); servo1.write(125); delay(600); }
//Copyright 2015-2016 Tomas Mikalauskas. All rights reserved. #pragma once //forward declared class GLLineDrawer; struct srfTriangles_t; struct glconfig_st; struct gl_params; #include "IRenderer.h" struct glconfig_st { const char * renderer_string; const char * vendor_string; const char * version_string; const char * extensions_string; const char * wgl_extensions_string; const char * shading_language_string; float fGLVersion; float fMaxTextureAnisotropy; uint32_t iNumbOfSuppExt; //number of supported extensions uint32_t iMaxTextureSize; // queried from GL uint32_t iMaxTextureCoords; uint32_t iMaxTextureImageUnits; uint32_t iUniformBufferOffsetAlignment; uint32_t iColorBits; uint32_t iDepthBits; uint32_t iStencilBits; uint32_t iNativeScreenWidth; // this is the native screen width resolution of the renderer uint32_t iNativeScreenHeight; // this is the native screen height resolution of the renderer uint32_t iDisplayFrequency; uint32_t iMultiSamples; uint32_t iNumbMonitor; // monitor number bool bIsStereoPixelFormat; bool bStereoPixelFormatAvailable; bool bSyncAvailable; bool bSwapControlTearAvailable; //adaptive vsync bool bTimerQueryAvailable; bool bIsFullScreen; }; #pragma pack(push, 1) struct gl_params { uint32_t iXCoord; //screen position in x uint32_t iYCoord; //screen position in y uint32_t iWidth; uint32_t iHeight; uint32_t iDisplayHz; // -1 = borderless window for spanning multiple display // 0 = windowed, otherwise 1 based monitor number to go full screen on uint16_t iFullScreen; uint16_t iMultiSamples; uint16_t iSwapInterval; // 0 - no vsync | 1 - vsync on | 2 - adaptive vsync bool bStereo; }; #pragma pack(pop) #include "WindowsGLRendererInitializer.h" class TYWRENDERER_API GLRenderer final: public IRenderer { public: GLRenderer(); ~GLRenderer(); void VShutdown(); bool VInitRenderer(uint32_t height, uint32_t widht, bool isFullscreen, LRESULT(CALLBACK MainWindowProc)(HWND, UINT, WPARAM, LPARAM)); void VSetBackgroundColor(BYTE bgA, BYTE bgR, BYTE bgG, BYTE bgB) { m_backgroundColor[0] = float(bgA) / 255.0f; m_backgroundColor[1] = float(bgR) / 255.0f; m_backgroundColor[2] = float(bgG) / 255.0f; m_backgroundColor[3] = float(bgB) / 255.0f; } bool VPreRender(); bool VPostRender(); HRESULT VOnRestore(); void VCalcLighting(Lights *lights, int maximumLights); // These three functions are done for each shader, not as a part of beginning the render - so they do nothing in D3D11. void VSetWorldTransform(const glx::mat4<float> *m); void VSetViewTransform(const glx::mat4<float> *m); void VSetProjectionTransform(const glx::mat4<float> *m); void VDrawLine(const glx::vec3<float>& from, const glx::vec3<float>& to, const glx::vec4<float>& color); std::shared_ptr<IRenderState> VPrepareAlphaPass(); std::shared_ptr<IRenderState> VPrepareSkyBoxPass(); //Creates files for logging void VSetLogPath(); //Clears screens and swaps buffers //void SwapCommandsFinnishRendering(uint64_t* gpuMicroSec); void StartFrame(); void EndFrame(uint64_t* gpuMicroSec); public: //Log Renderer void Logv(const char* format, ...); //Log Rendering Streaming void LogStrv(char* format, ...); //Log Renderer Shaders void LogShv(char* format, ...); //Prints directly log info to screen void Log(char* str,...); protected: //Calculates swap command and calculates how much time gpu took to process requests void SwapCommandBuffers_FinnishRendering(uint64_t* gpuMicroSec); void GLCheckErrors(); void inline GLClearScreen(); void inline GLClearDepthBuffer(); void inline GLEnable(); protected: //Log Renderer FILE* m_LogFile; //Log Rendering Streaming FILE* m_LogFileStr; //Log Renderer Shaders FILE* m_LogFileSh; protected: bool m_bIsOpenglRunning; bool m_bLogRenderer; uint32_t m_iTimerQueryId; float m_backgroundColor[4]; glconfig_st m_glConfigs; gl_params m_glParams; GLLineDrawer *m_pLineDrawer; IRendererInitializer *m_pWRenderer; }; extern GLRenderer g_RendGL; extern TYWRENDERER_API IRenderer * g_pRendGL; struct TYWRENDERER_API ConstantBuffer_Lighting { glx::vec4<float> m_vLightDiffuse[MAXIMUM_LIGHTS_SUPPORTED]; glx::vec4<float> m_vLightDir[MAXIMUM_LIGHTS_SUPPORTED]; glx::vec4<float> m_vLightAmbient; UINT m_nNumLights; glx::vec3<float> m_vUnused; }; class TYWRENDERER_API GLLineDrawer { public: GLLineDrawer() :m_pVertexBuffer(nullptr) {} ~GLLineDrawer() { m_pVertexBuffer->FreeBufferObject(); SAFE_DELETE(m_pVertexBuffer); } void DrawLine(const glx::vec3<float>& from, const glx::vec3<float>& to, const glx::vec4<float>& color) {} HRESULT OnRestore() { return 0; } protected: glx::vec3<float> m_Verts[2]; VertexBuffer* m_pVertexBuffer; }; /* ============================================================ TR_TRISURF ============================================================ */ srfTriangles_t * R_AllocStaticTriSurf(); void R_AllocStaticTriSurfVerts(srfTriangles_t *tri, int numVerts); void R_AllocStaticTriSurfIndexes(srfTriangles_t *tri, int numIndexes); void R_FreeStaticTriSurfSilIndexes(srfTriangles_t *tri); void R_FreeStaticTriSurf(srfTriangles_t *tri); void R_FreeStaticTriSurfVerts(srfTriangles_t *tri); void R_CreateStaticBuffersForTri(srfTriangles_t & tri); //============================================= /* TESTING */ TYWRENDERER_API bool ImGui_ImplGlfwGL3_Init(IRendererInitializer *m_pWRenderer, bool install_callbacks); TYWRENDERER_API void ImGui_ImplGlfwGL3_Shutdown(); TYWRENDERER_API void ImGui_ImplGlfwGL3_NewFrame(double dCurrentTime, struct Win32vars & winVars); // Use if you want to reset your rendering device without losing ImGui state. TYWRENDERER_API void ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); TYWRENDERER_API bool ImGui_ImplGlfwGL3_CreateDeviceObjects(); TYWRENDERER_API bool ImGui_ImplGlfwGL3_CreateFontsTexture(); TYWRENDERER_API bool ImguiRender(); //
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ string s; bool match(string s, string t) { if (s.length() != t.length()) return false; rep(i,s.length()) { if (t[i]=='*')continue; if (t[i]!=s[i]) return false; } return true; } void solve(vector<string> good , vector<string> ngWords) { rep(i,good.size()) { rep(j, ngWords.size()) { if (match(good[i], ngWords[j])) { good[i] = string(ngWords[j].length(), '*'); } } } cout << good[0]; rep(i,good.size()-1) cout << ' ' << good[i+1]; cout << endl; } int main() { getline(cin, s); int n; cin >>n; s+= ' '; vector<string> ngWords(n); vector<string> good; int start = 0; rep(i, s.length()) { if (s[i] == ' ') { good.push_back(s.substr(start, i-start)); start = i+1; i++; } } rep (_,n) { cin >> ngWords[_]; } solve(good,ngWords); return 0; }
#include <iostream> #include <string> #include <fstream> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <algorithm> #include <new> #include <ctype.h> #include <stdlib.h> #include <sstream> using namespace std; //**************************** LISTA EQU ******************************************************* class no { string rot; //Rotulo associado pela diretiva EQU string val_rotulo; //Valor associado ao rotulo no *prox_rot; //Posicao do proximo rotulo public: no() {}; void Def_Rotulo (string rotulo) {rot = rotulo;} //Define o rotulo de um no void Def_Valor (string valor) {val_rotulo = valor;} //Define o valor associado a um rotulo void Def_prox_rot (no *prox) {prox_rot = prox;} //Define proximo no string Return_rot() {return rot;} string Return_val() {return val_rotulo;} no* Return_prox_rot () {return prox_rot;} }; class EQU_List { //Lista para as definicoes das diretivas EQU public: no *head; EQU_List() { head = NULL; } void insere_final (string,string); //Insere no no final da lista string busca_no (string,bool&); //Busca no na lista a partir do rotulo void limpa_lista(); }; void EQU_List::insere_final (string rotulo, string val) { no *novo_no = new no(); novo_no->Def_Rotulo(rotulo); novo_no->Def_Valor(val); novo_no->Def_prox_rot(NULL); no *tmp = head; if(tmp != NULL) { //Se existem nos na lista, ir para o final while(tmp->Return_prox_rot() != NULL) { tmp = tmp->Return_prox_rot(); } tmp->Def_prox_rot(novo_no); } else { head = novo_no; } } string EQU_List::busca_no (string label, bool& exist) { //Busca no na lista bool *aux = &exist; no *tmp = head; string tmpval; while(tmp != NULL) { if(tmp->Return_rot() == label) { //Se tiver rotulo == label, retornar valor associado e coloca flag exist em true tmpval = tmp->Return_val(); *aux = true; break; } tmp = tmp->Return_prox_rot(); } if(tmp == NULL) { *aux = false; return ""; } return tmpval; } void EQU_List::limpa_lista () { no *tmp = head; if (tmp == NULL) return; no *aux; do { aux = head->Return_prox_rot(); head = aux; delete tmp; tmp = head; } while(tmp != NULL); } //*********************************************** FIM DA LISTA EQU ******************************************************* //********************************************* INICIO DA STRUCT BSS ***************************************************** typedef struct BSS { string variavel; string size; }BSS; //************************************************************************************************************************ void Preprocessamento(istream&,string); void diretivas(istream&,ostream&,BSS*); void instrucoes(istream&,ostream&); string InttoString(int); int main(int argc, char *argv[]) { BSS *var_bss; //Abertura do arquivo var_bss = (BSS*)malloc(sizeof(BSS)); if(argc != 2) { cout << "O programa deve receber apenas o arquivo .asm!" << endl; exit(EXIT_FAILURE); } std::string str1(argv[1],strlen(argv[1])); //Abrindo arquivo para Pre-processamento fstream entrada (argv[1],ios::in); if(entrada.is_open()) Preprocessamento(entrada,str1); //Realizando Preprocessamento entrada.close(); // Fechando arquivo de entrada entrada.clear(); str1.erase(str1.length()-4,4); str1 += ".s"; fstream saida (str1.c_str(),ios::out); //Criando arquivo de saida .s str1.erase (str1.length()-2,2); //Abrindo arquivo Preprocessado str1 += "_Preproc.asm"; fstream entradapreproc (str1.c_str(),ios::in); //Fim da abertura do arquivo //Chamada das funções de traducao diretivas(entradapreproc,saida,var_bss); //Imprimindo section .data e section .bss no arquivo de saida entradapreproc.clear(); //Retornando para o inicio do arquivo de entrada entradapreproc.seekg(0,ios::beg); saida.clear(); instrucoes(entradapreproc,saida); entradapreproc.close(); saida.close(); return 0; } void Preprocessamento(istream &file, string nome_arq) { EQU_List no; //Objeto da lista da diretiva EQU string str, linha, strtemp; string token, token1, token2, dir, linhaout, linhain, aux, aux2, aux3; string rotulo, valorstr; //strings para abrir arquivo, guardar linhas, verificacoes de linhas e diretivas unsigned int i, j, k, tam2, tam3; //Contadores e variaveis para tamanho de linha int flagIF1 = 0, flagIF2 = 0;//Flag para verificar erros, se existe rotulo, flags para diretiva IF, flag para verificar se o programa esta na ordem correta bool eh_rotulo = false; //Variavel para definir se pertence a lista da diretiva EQU int posit = 0; //Inteiro para pegar posicao das diretivas IF, CONST e SPACE size_t pos; //Necessario para funcao str.find() nome_arq.erase(nome_arq.length()-4,4); nome_arq += "_Preproc.asm"; fstream out (nome_arq.c_str(),ios::out); if(out.is_open()) { while(getline(file,linha)) { pos = linha.find("\t"); posit = pos; if(posit > -1) { while(posit > -1) { aux = linha.substr(0,pos); aux2 = linha.substr(pos+1,string::npos); linha.clear(); linha += aux; linha += ' '; linha += aux2; aux.clear(); aux2.clear(); pos = linha.find("\t"); posit = pos; } } if(flagIF1 == 0 && flagIF2 == 1) { //Se achou a diretiva IF mas seu operando foi zero, ignorar linha flagIF2 = 0; continue; } token.clear(); //Limpando strings valorstr.clear(); rotulo.clear(); aux.clear(); linhain.clear(); eh_rotulo = false; //Colocando variavel em false para o caso de nova verificacao if(linha.length() == 0) { //Se a linha estiver em branco, ir para a proxima linha continue; } if(linha.at(0) == ';') { //Se for uma linha de comentario, ir para a proxima linha continue; } tam2 = linha.length(); transform(linha.begin(), linha.end(), linha.begin(), ptr_fun<int, int>(toupper)); //Colocando em maiusculo for(i=0;i<tam2;i++) { //Verifica espacos no inicio da linha if(linha.at(i) != ' ') { k = i; break; } } //************************************** LEITURA DA LINHA DO ARQUIVO DE ENTRADA ************************************************** k = 0; i = 0; while(i < linha.length()) { for(i=k;i<tam2;i++) { //Verifica espacos na linha if(linha.at(i) != ' ') { k = i; break; } } if(i == tam2 || linha.at(i) == ';') { //Se houver apenas comentarios no final da linha, ir para a proxima break; } for(i=k;i<tam2;i++) {//Pega token if(linha.at(i) == ' ') { k = i; break; } if(linha.at(i) == ':') { token += linha.at(i); k = i+1; break; } token += linha.at(i); } aux = no.busca_no(token,eh_rotulo); if(eh_rotulo == true) { linhain += aux; linhain += ' '; } else { linhain += token; linhain += ' '; } token.clear(); } linhain.erase(linhain.length()-1,1); //Apagando espaço restante no final da linha if(flagIF1 == 1) { //Se achou a diretiva IF e seu operando foi diferente de 0, imprimir linha no arquivo de saida out << linhain; out << endl; linhain.clear(); flagIF1 = 0; flagIF2 = 0; continue; } tam3 = linhain.length(); k = 0; //Zerando contadores i = 0; //************************** Verificacao da Diretiva EQU ****************************************** pos = linhain.find("EQU"); posit = pos; if(posit > -1) { k = 0; for(i=k;i<tam3;i++) { if(linhain.at(i) == ':') { //Armazenando rotulo, como esperado para a diretiva EQU for(j=0;j<i;j++) { rotulo += linha.at(j); } k = i+2; break; } } for(i=k;i<tam3;i++) { //Pegando proximo operando, que deve ser a diretiva EQU if(linhain.at(i) == ' ') { k = i+1; break; } } for(i=k;i<tam3;i++) { //Pega numero apos o EQU valorstr += linhain.at(i); } no.insere_final(rotulo, valorstr); //Criando no na lista de rotulos da diretiva EQU continue; } //*********************** Fim da verificacao da diretiva EQU ********************************** pos = linhain.find("IF"); //Procura diretiva IF, para verificacao posit = pos; if(posit > -1) { for(j=pos+3;j<linhain.length();j++) { aux += linhain.at(j); } if(atoi(aux.c_str()) != 0) { flagIF1 = 1; } flagIF2 = 1; //Indica que entrou na diretiva IF, servindo para que nao se imprima a proxima linha continue; } out << linhain; out << endl; linhain.clear(); } } //******************************************************************************************************************************* no.limpa_lista(); out.close(); out.clear(); } //****************************************************** FIM DO PRE PROCESSADOR *********************************************** void diretivas(istream &entrada, ostream &saida, BSS *var_bss) { //Procura pela SECTION DATA e Diretivas SPACE e CONST, gerando a section .data e section .bss string linha, var, dir, valor; bool flag_DATA = false, flag_SPACE = false; //Flag para indicar SECTION DATA e para indicar diretiva SPACE unsigned int i=0, k=0, j=0; while(getline(entrada,linha)) { if(linha == "SECTION DATA") { //Se a linha do arquivo for igual a SECTION DATA, colocar flag_DATA em true e pegar proxima linha flag_DATA = true; saida << "section .data" << endl; saida << "msg1 db 'Numero Invalido! Digite Novamente.',0ah" << endl; saida << "msg0 db 'Numero Invalido!',0ah" << endl; saida << "msg2 db 'Digite um caracter.',0ah" << endl; saida << endl; continue; } if(linha == "SECTION TEXT") { //Se encontrou a SECTION TEXT, colocar flag_data em false (Caso esta venha depois da SECTION DATA) flag_DATA = false; } if(flag_DATA == false) { //Se nao chegou na SECTION DATA, pegar proxima linha continue; } else { var.clear(); valor.clear(); dir.clear(); k = 0; i = 0; for(i=0;i<linha.length();i++) { //Procurando rotulo, o qual sera o nome da variavel if(linha.at(i) == ':') { k = i+2; break; } var += linha.at(i); } while(linha.at(k) != ' ') { //Verificando diretiva (CONST ou SPACE) dir += linha.at(k); k++; } k++; //Indo para o proximo token if(k > linha.length()) { if(dir == "SPACE") { if(flag_SPACE == true) var_bss = (BSS*)realloc(var_bss,(j+1)*sizeof(BSS)); //Alocando espaco var_bss[j].variavel = var; var_bss[j].size = 1; flag_SPACE = true; j++; continue; } } for(i=k;i<linha.length();i++) { //Pegando valor apos diretiva valor += linha.at(i); } if(dir == "CONST") { //Se for a diretiva CONST, gravar no arquivo de saida saida << var; saida << " dd "; saida << valor; saida << endl; } if(dir == "SPACE") { //Se for a diretiva SPACE, salvar dados para posterior gravacao if(flag_SPACE == true) var_bss = (BSS*)realloc(var_bss,(j+1)*sizeof(BSS)); //Alocando espaco var_bss[j].variavel = var; //Salvando dados no elemento j do vetor var_bss[j].size = valor; flag_SPACE = true; j++; //Incrementando contador de elementos } } } if(flag_SPACE == true) { //Se entrou na diretiva SPACE tera section .bss saida << endl; saida << "section .bss" << endl; for(i=0;i<=j-1;i++) { //Imprimindo no arquivo de saida os elementos definidos pela diretiva SPACE na section .bss saida << var_bss[i].variavel; saida << " resd "; saida << var_bss[i].size; saida << endl; } } free(var_bss); } void instrucoes(istream &entrada,ostream &saida) { //Faz a traducao das instrucoes do assembly inventado string line, rotulo, inst, op1, op2; unsigned int i1=0,k1=0,num=0; bool flag_TEXT=false, flag_rotulo; //Flag para indicar que se esta na SECTION TEXT e flag para indicar que ha rotulo saida << endl; saida << "section .text" << endl; //Iniciando section .text saida << "global _start" << endl; //Colocando variavel global _start saida << "_start:" << endl; saida << " mov ebx,0" << endl; //Zerando contador escolhido (ebx) while(getline(entrada,line)) { if(line == "SECTION TEXT") { flag_TEXT = true; } if(line == "SECTION DATA") { flag_TEXT = false; } if(!flag_TEXT) { continue; } else { //Se ja chegou na SECTION TEXT rotulo.clear(); inst.clear(); op1.clear(); op2.clear(); flag_rotulo = false; k1=0; for(i1=0;i1<line.length();i1++) { if(line.at(i1) == ':') { //Se a linha possuir rotulo rotulo += line.at(i1); saida << " " << rotulo; k1 = i1+2; flag_rotulo = true; break; } rotulo += line.at(i1); } for(i1=k1;i1<line.length();i1++) { //Pegando instrucao if(line.at(i1) == ' ') { k1 = i1+1; break; } inst += line.at(i1); } //Inicio da traducao da instrucao if(inst == "ADD") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } saida << " add ebx," << '[' << op1 << ']' << endl; //Gravando codigo IA32 correspondente na saida } else if(inst == "SUB") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } saida << " sub ebx," << '[' << op1 << ']' << endl; //Gravando codigo IA32 correspondente na saida } else if(inst == "MUL") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push eax" << endl; //Gravando codigo IA32 correspondente na saida saida << " mov eax,ebx" << endl; saida << " imul dword " << '[' << op1 << ']' << endl; saida << " mov ebx,eax" << endl; saida << " pop eax" << endl; } else { saida << " push eax" << endl; //Gravando codigo IA32 correspondente na saida saida << " mov eax,ebx" << endl; saida << " imul dword " << '[' << op1 << ']' << endl; saida << " mov ebx,eax" << endl; saida << " pop eax" << endl; } } else if(inst == "DIV") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push eax" << endl; //Gravando codigo IA32 correspondente na saida saida << " push edx" << endl; saida << " mov eax,ebx" << endl; saida << " cdq" << endl; saida << " idiv dword " << '[' << op1 << ']' << endl; saida << " mov ebx,eax" << endl; saida << " pop edx"; saida << " pop eax" << endl; } else { saida << " push eax" << endl; //Gravando codigo IA32 correspondente na saida saida << " push edx" << endl; saida << " mov eax,ebx" << endl; saida << " cdq" << endl; saida << " idiv dword " << '[' << op1 << ']' << endl; saida << " mov ebx,eax" << endl; saida << " pop edx" << endl; saida << " pop eax" << endl; } } else if(inst == "JMP") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } saida << " jmp " << op1 << endl; } else if(inst == "JMPN") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " cmp ebx,0" << endl; saida << " jl " << op1 << endl; } else { saida << " cmp ebx,0" << endl; saida << " jl " << op1 << endl; } } else if(inst == "JMPP") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " cmp ebx,0" << endl; saida << " jg " << op1 << endl; } else { saida << " cmp ebx,0" << endl; saida << " jg " << op1 << endl; } } else if(inst == "JMPZ") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " cmp ebx,0" << endl; saida << " je " << op1 << endl; } else { saida << " cmp ebx,0" << endl; saida << " je " << op1 << endl; } } else if (inst == "LOAD") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } saida << " mov ebx," << '[' << op1 << ']' << endl; } else if (inst == "STORE") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } saida << " mov " << '[' << op1 << ']' << ",ebx" << endl; } else if (inst == "STOP") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " mov eax,1" << endl; saida << " mov ebx,0" << endl; saida << " int 80h" << endl; } else { saida << " mov eax,1" << endl; saida << " mov ebx,0" << endl; saida << " int 80h" << endl; } } else if (inst == "COPY") { for(i1=k1;i1<line.length();i1++) { //Pegando operando if(line.at(i1) == ',') { k1 = i1 + 1; break; } op1 += line.at(i1); } for(i1=k1;i1<line.length();i1++) { op2 += line.at(i1); } if(flag_rotulo == false) { saida << " push eax" << endl; saida << " mov eax,[" << op1 << ']' << endl; saida << " mov [" << op2 << "],eax" << endl; saida << " pop eax" << endl; } else { saida << " push eax" << endl; saida << " mov eax,[" << op1 << ']' << endl; saida << " mov [" << op2 << "],eax" << endl; saida << " pop eax" << endl; } } else if (inst == "INPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push " << op1 << endl; saida << " call LeerInteiro" << endl; } else { saida << " push" << op1 << endl; saida << " call LeerInteiro" << endl; } } else if (inst == "OUTPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push " << op1 << endl; saida << " call EscreverInteiro" << endl; } else { saida << " push" << op1 << endl; saida << " call EscreverInteiro" << endl; } } else if (inst == "S_INPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando if(line.at(i1) == ',') { k1 = i1 + 1; break; } op1 += line.at(i1); } for(i1=k1;i1<line.length();i1++) { op2 += line.at(i1); } num = atoi(op2.c_str()); num++; op2 = InttoString(num); if(flag_rotulo == false) { saida << " push DWORD " << op2 << endl; saida << " push " << op1 << endl; saida << " call LeerString" << endl; } else { saida << " push DWORD " << op2 << endl; saida << " push " << op1 << endl; saida << " call LeerString" << endl; } } else if (inst == "S_OUTPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando if(line.at(i1) == ',') { k1 = i1 + 1; break; } op1 += line.at(i1); } for(i1=k1;i1<line.length();i1++) { op2 += line.at(i1); } num = atoi(op2.c_str()); num++; op2 = InttoString(num); if(flag_rotulo == false) { saida << " push DWORD " << op2 << endl; saida << " push " << op1 << endl; saida << " call EscreverString" << endl; } else { saida << " push DWORD " << op2 << endl; saida << " push " << op1 << endl; saida << " call EscreverString" << endl; } } else if (inst == "H_INPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push " << op1 << endl; saida << " call LeerHexa" << endl; } else { saida << " push " << op1 << endl; saida << " call LeerHexa" << endl; } } else if (inst == "H_OUTPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push dword [" << op1 << ']' << endl; saida << " call EscreverHexa" << endl; } else { saida << " push dword [" << op1 << ']' << endl; saida << " call EscreverHexa" << endl; } } else if (inst == "C_INPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push " << op1 << endl; saida << " call LeerChar" << endl; } else { saida << " push" << op1 << endl; saida << " call LeerChar" << endl; } } else if (inst == "C_OUTPUT") { for(i1=k1;i1<line.length();i1++) { //Pegando operando op1 += line.at(i1); } if(flag_rotulo == false) { saida << " push " << op1 << endl; saida << " call EscreverChar" << endl; } else { saida << " push" << op1 << endl; saida << " call EscreverChar" << endl; } } //Fim da traducao da instrucao } } //Impressao das rotinas //LeerInteiro saida << " LeerInteiro: enter 24,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov esi,0" << endl; saida << " mov word [EBP-20],0" << endl; saida << " Get_Int: mov eax,3" << endl; saida << " mov ebx,0" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,18" << endl; saida << " mov edx,12" << endl; saida << " int 80h" << endl; saida << " mov ecx,eax" << endl; saida << " mov [EBP-24],eax" << endl; saida << " sub ecx,1" << endl; saida << " mov eax,0" << endl; saida << " mov edi,10" << endl; saida << " mov ebx,0" << endl; saida << " cmp byte [EBP-18],0x2D" << endl; saida << " je Negativo" << endl; saida << " Convert_Int: cmp byte [EBP-18+esi],0x30" << endl; saida << " jl Invalido" << endl; saida << " cmp byte [EBP-18+esi],0x39" << endl; saida << " jg Invalido" << endl; saida << " mov BL,[EBP-18+esi]" << endl; saida << " cmp esi,0" << endl; saida << " je First_Digit" << endl; saida << " cmp word [EBP-20],1" << endl; saida << " je Verif_Digit" << endl; saida << " Mult: mul edi" << endl; saida << " First_Digit: add eax,ebx" << endl; saida << " sub eax,0x30" << endl; saida << " inc esi" << endl; saida << " loop Convert_Int" << endl; saida << " jmp Armazena_Num" << endl; saida << " Verif_Digit: cmp esi,1" << endl; saida << " je First_Digit" << endl; saida << " jmp Mult" << endl; saida << " Negativo: inc esi" << endl; saida << " dec ecx" << endl; saida << " mov word [EBP-20],1" << endl; saida << " jmp Convert_Int" << endl; saida << " Invalido: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,msg1" << endl; saida << " mov edx,35" << endl; saida << " int 80h" << endl; saida << " jmp Get_Int" << endl; saida << " Armazena_Num: cmp word [EBP-20],1" << endl; saida << " je Nega_Num" << endl; saida << " mov ebx,[EBP+8]" << endl; saida << " mov dword [ebx],eax" << endl; saida << " jmp FIM" << endl; saida << " Nega_Num: neg eax" << endl; saida << " mov word [EBP-20],0" << endl; saida << " jmp Armazena_Num" << endl; saida << " FIM: mov eax,[EBP-24]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 4" << endl; //EscreverInteiro saida << " EscreverInteiro: enter 16,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov dword [EBP-16],0" << endl; saida << " mov ebx,0" << endl; saida << " mov esi,0" << endl; saida << " mov ecx,10" << endl; saida << " mov edi,[EBP+8]" << endl; saida << " mov eax,[edi]" << endl; saida << " cmp eax,0" << endl; saida << " je Zero" << endl; saida << " cmp dword [edi],0" << endl; saida << " jl Neg" << endl; saida << " Positivo: cdq" << endl; saida << " cmp eax,0" << endl; saida << " je Imprime" << endl; saida << " div ecx" << endl; saida << " add edx,0x30" << endl; saida << " cmp edx,0x30" << endl; saida << " jl Numero_Inv" << endl; saida << " cmp edx,0x39" << endl; saida << " jg Numero_Inv" << endl; saida << " mov [EBP-12+esi],edx" << endl; saida << " inc esi" << endl; saida << " jmp Positivo" << endl; saida << " Neg: mov ebx,1" << endl; saida << " neg eax" << endl; saida << " Neg_Loop: cdq" << endl; saida << " cmp eax,0" << endl; saida << " je Imprime" << endl; saida << " div ecx" << endl; saida << " add edx,0x30" << endl; saida << " cmp edx,0x30" << endl; saida << " jl Numero_Inv" << endl; saida << " cmp edx,0x39" << endl; saida << " jg Numero_Inv" << endl; saida << " mov [EBP-12+esi],DL" << endl; saida << " inc esi" << endl; saida << " jmp Neg_Loop" << endl; saida << " Zero: add eax,0x30" << endl; saida << " mov [EBP-12+esi],eax" << endl; saida << " inc esi" << endl; saida << " jmp Imprime" << endl; saida << " Numero_Inv: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,msg0" << endl; saida << " mov edx,17" << endl; saida << " int 80h" << endl; saida << " jmp Exit_Func" << endl; saida << " Imprime: cmp ebx,1" << endl; saida << " je Insert_sign" << endl; saida << " mov byte [EBP-12+esi],0ah" << endl; saida << " mov edi,esi" << endl; saida << " mov eax,12" << endl; saida << " sub eax,esi" << endl; saida << " mov edi,eax" << endl; saida << " mov esi,eax" << endl; saida << " inc esi" << endl; saida << " Sys_Write: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,esi" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " inc esi" << endl; saida << " inc dword [EBP-16]" << endl; saida << " cmp esi,13" << endl; saida << " jne Sys_Write" << endl; saida << " mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,edi" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " inc dword [EBP-16]" << endl; saida << " jmp Exit_Func" << endl; saida << " Insert_sign: mov byte [EBP-12+esi],0x2D" << endl; saida << " inc esi" << endl; saida << " inc dword [EBP-16]" << endl; saida << " mov ebx,0" << endl; saida << " jmp Imprime" << endl; saida << " Exit_Func: mov eax,[EBP-16]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " pop eax" << endl; saida << " leave" << endl; saida << " ret 4" << endl; //LeerString saida << " LeerString: enter 4,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov edi,[EBP+8]" << endl; saida << " mov dword [EBP-4],0" << endl; saida << " mov esi,[EBP+12]" << endl; saida << " Leitura: mov eax,3" << endl; saida << " mov ebx,0" << endl; saida << " mov ecx,edi" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " cmp byte [edi],0ah" << endl; saida << " je Fim_Leitura" << endl; saida << " add edi,1" << endl; saida << " inc dword [EBP-4]" << endl; saida << " cmp [EBP-4],esi" << endl; saida << " je Fim_Leitura" << endl; saida << " jmp Leitura" << endl; saida << " Fim_Leitura: mov eax,[EBP-4]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 8" << endl; //EscreverString saida << " EscreverString: enter 4,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov edi,[EBP+8]" << endl; saida << " mov dword [EBP-4],0" << endl; saida << " mov esi,[EBP+12]" << endl; saida << " Escrita: mov eax,4" << endl; saida << " mov ebx,0" << endl; saida << " mov ecx,edi" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " cmp byte [edi],0ah" << endl; saida << " je Fim_Escrita" << endl; saida << " add edi,1" << endl; saida << " inc dword [EBP-4]" << endl; saida << " cmp [EBP-4],esi" << endl; saida << " je Fim_Escrita" << endl; saida << " jmp Escrita" << endl; saida << " Fim_Escrita: mov eax,[EBP-4]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 8" << endl; //LeerHexa saida << " LeerHexa: enter 21,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov dword [EBP-21],0" << endl; saida << " mov dword [EBP-13],0" << endl; saida << " Input_HEX: mov eax,3" << endl; saida << " mov ebx,0" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,9" << endl; saida << " mov edx,9" << endl; saida << " int 80h" << endl; saida << " cmp byte [EBP-9],0x2D" << endl; saida << " je Invalido_HEX" << endl; saida << " mov edi,eax" << endl; saida << " mov [EBP-21],eax" << endl; saida << " sub edi,2" << endl; saida << " mov esi,0" << endl; saida << " xor edx,edx" << endl; saida << " Verifica_Char: cmp byte [EBP-9+esi],0x30" << endl; saida << " jl Invalido_HEX" << endl; saida << " cmp byte [EBP-9+esi],0x39" << endl; saida << " jg Verifica_Char_HEX" << endl; saida << " xor ebx,ebx" << endl; saida << " mov BL,[EBP-9+esi]" << endl; saida << " sub ebx,0x30" << endl; saida << " jmp Convert_to_Num" << endl; saida << " Verifica_Char_HEX: cmp byte [EBP-9+esi],0x41" << endl; saida << " jl Invalido_HEX" << endl; saida << " cmp byte [EBP-9+esi],0x46" << endl; saida << " jg Invalido_HEX" << endl; saida << " xor ebx,ebx" << endl; saida << " mov BL,[EBP-9+esi]" << endl; saida << " sub ebx,0x41" << endl; saida << " add ebx,10" << endl; saida << " Convert_to_Num: cmp edi,0" << endl; saida << " je Last_Digit" << endl; saida << " mov ecx,edi" << endl; saida << " mov eax,1" << endl; saida << " mov [EBP-17],ebx" << endl; saida << " mov ebx,16" << endl; saida << " Loop_Convert: mul ebx" << endl; saida << " loop Loop_Convert" << endl; saida << " mov ebx,[EBP-17]" << endl; saida << " dec edi" << endl; saida << " mul ebx" << endl; saida << " add [EBP-13],eax" << endl; saida << " inc esi" << endl; saida << " jmp Verifica_Char" << endl; saida << " Last_Digit: add [EBP-13],ebx" << endl; saida << " jmp FIM_HEX" << endl; saida << " Invalido_HEX: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,msg1" << endl; saida << " mov edx,35" << endl; saida << " int 80h" << endl; saida << " jmp Input_HEX" << endl; saida << " FIM_HEX: mov eax,[EBP-13]" << endl; saida << " mov ebx,[EBP+8]" << endl; saida << " mov [ebx],eax" << endl; saida << " mov eax,[EBP-21]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 4" << endl; //EscreverHexa saida << " EscreverHexa: enter 13,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " push esi" << endl; saida << " push edi" << endl; saida << " mov dword [EBP-13],0" << endl; saida << " mov eax,[EBP+8]" << endl; saida << " mov esi,-2" << endl; saida << " xor ebx,ebx" << endl; saida << " mov edi,16" << endl; saida << " cmp eax,0" << endl; saida << " jl Inv_HEX" << endl; saida << " Div_Loop: cdq" << endl; saida << " div edi" << endl; saida << " cmp DL,10" << endl; saida << " jge ASCII_HEX" << endl; saida << " add DL,0x30" << endl; saida << " Store_HEX: mov byte [EBP+esi],DL" << endl; saida << " mov BL,[EBP+esi]" << endl; saida << " dec esi" << endl; saida << " cmp eax,0" << endl; saida << " je Print_HEX" << endl; saida << " jmp Div_Loop" << endl; saida << " ASCII_HEX: add DL,0x37" << endl; saida << " jmp Store_HEX" << endl; saida << " Inv_HEX: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,msg0" << endl; saida << " mov edx,17" << endl; saida << " int 80h" << endl; saida << " jmp F_HEX" << endl; saida << " Print_HEX: mov byte [EBP-1],0ah" << endl; saida << " neg esi" << endl; saida << " dec esi" << endl; saida << " mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,esi" << endl; saida << " mov edx,esi" << endl; saida << " int 80h" << endl; saida << " mov [EBP-13],eax" << endl; saida << " F_HEX: mov eax,[EBP-13]" << endl; saida << " pop edi" << endl; saida << " pop esi" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 4" << endl; //LeerChar saida << " LeerChar: enter 2,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " InputC: mov eax,3" << endl; saida << " mov ebx,0" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,2" << endl; saida << " mov edx,2" << endl; saida << " int 80h" << endl; saida << " cmp byte [EBP-2],0ah" << endl; saida << " je Espaco" << endl; saida << " mov CL,[EBP-2]" << endl; saida << " mov edx,[EBP+8]" << endl; saida << " mov [edx],CL" << endl; saida << " jmp FIM_C" << endl; saida << " Espaco: mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,msg2" << endl; saida << " mov edx,20" << endl; saida << " int 80h" << endl; saida << " jmp InputC" << endl; saida << " FIM_C: pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 4" << endl; //EscreverChar saida << " EscreverChar: enter 4,0" << endl; saida << " push ebx" << endl; saida << " push ecx" << endl; saida << " push edx" << endl; saida << " mov dword [EBP-4],0" << endl; saida << " mov byte [EBP-4],0ah" << endl; saida << " mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,[EBP+8]" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " mov eax,4" << endl; saida << " mov ebx,1" << endl; saida << " mov ecx,EBP" << endl; saida << " sub ecx,4" << endl; saida << " mov edx,1" << endl; saida << " int 80h" << endl; saida << " pop edx" << endl; saida << " pop ecx" << endl; saida << " pop ebx" << endl; saida << " leave" << endl; saida << " ret 4"; //Fim da Impressão das rotinas } string InttoString (int Num) { ostringstream str; str << Num; return str.str(); }
#ifndef HTTPS_CLIENT_HPP_ //并不是通用的,只是获取网络资源并保存到文件 #define HTTPS_CLIENT_HPP_ #include <cstdlib> #include <boost/bind/bind.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <string> #include <fstream> #include <iostream> #include <istream> #include <ostream> #include "util.h" class HttpsClient { public: ~HttpsClient(){ outfile_.close(); } HttpsClient(boost::asio::io_context& io_context, boost::asio::ssl::context& context, const std::string &server,const std::string &path,size_t resource_id, std::string &file_name,size_t *size ) : socket_(io_context, context),server_(server),path_(path),resource_id_(resource_id),file_name_(file_name) { *size = static_cast<size_t>(0); size_ = size; boost::asio::ip::tcp::resolver resolver(io_context); boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(server_, "443"); socket_.set_verify_mode(boost::asio::ssl::verify_peer); socket_.set_verify_callback(boost::bind(&HttpsClient::verify_certificate, this,boost::placeholders::_1, boost::placeholders::_2)); boost::asio::async_connect(socket_.lowest_layer(), endpoints,boost::bind(&HttpsClient::handle_connect, this,boost::asio::placeholders::error)); } bool verify_certificate(bool preverified,boost::asio::ssl::verify_context& ctx) { return true; } void handle_connect(const boost::system::error_code& error) { if (!error) { socket_.async_handshake(boost::asio::ssl::stream_base::client, boost::bind(&HttpsClient::handle_handshake, this, boost::asio::placeholders::error)); } else { std::cout << "Connect failed: " << error.message() << "\n"; } } void handle_handshake(const boost::system::error_code& error) { if (!error) { std::ostream request_stream(&request_); request_stream << "GET " << path_ << " HTTP/1.0\r\n"; request_stream << "Host: " << server_ << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n\r\n"; boost::asio::async_write( socket_, request_, boost::bind(&HttpsClient::handle_write, this ,boost::asio::placeholders::error)); } else { std::cout << "Handshake failed: " << error.message() << "\n"; } } void handle_write(const boost::system::error_code& error) { if (!error) { boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&HttpsClient::handle_read_headers, this, boost::asio::placeholders::error)); } else { std::cout << "Write failed: " << error.message() << "\n"; } } void handle_read_headers(const boost::system::error_code &err) { if (!err) { std::istream response_stream(&response_); std::string header; while (std::getline(response_stream, header) && header != "\r") { //get Content-Type if(header.substr(0,12)=="Content-Type"){ file_name_ =std::to_string(resource_id_)+"."+ header.substr(header.find_last_of('/') + 1); deleteAllMark(file_name_,"\r"); outfile_.open("data/" + file_name_, std::ios::app | std::ios::binary);//path.substr(path.find_last_of('/') + 1) if (!outfile_) { std::cout << "打开文件失败,文件名:" <<file_name_<<"\n"; } } } // Start reading remaining data until EOF. boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&HttpsClient::handle_read_content, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_content(const boost::system::error_code &err) { if (!err) { // Write all of the data that has been read so far. // std::cout << std::endl << "-------" << std::endl; // std::cout << &response_; *size_+=response_.size(); outfile_ << &response_; // Continue reading remaining data until EOF. boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1), boost::bind(&HttpsClient::handle_read_content, this, boost::asio::placeholders::error)); } else if (err != boost::asio::error::eof) { std::cout << "Error: " << err << "\n"; } } private: boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_; boost::asio::streambuf request_; boost::asio::streambuf response_; std::string server_; std::string path_; std::ofstream outfile_; size_t* size_; size_t resource_id_; std::string &file_name_; }; #endif // HTTPS_CLIENT_HPP_
class Solution { public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int cover = 0; int a = max(A, E); int b = min(C, G); int c = max(B, F); int d = min(D, H); if(b > a && d > c) cover = (b - a) * (d - c); return abs(G - E) * abs(H - F) + abs(A - C) * abs(B - D) - cover; } };
#ifndef CEVENTSTATS_H #define CEVENTSTATS_H #include "TObject.h" #include <map> #include <string> #include "TTree.h" class TFile; class CEventStats { public: TFile *rootFile; TTree *simTree; TTree *geoTree; TFile *outputFile; TTree *outputTree; std::map<int, std::string> decayMode; enum State { MAXTRACK = 100, MAXPMT = 20000, MAXHIT = 50000, }; float cylRadius; float cylLength; int totalPMTs; float pmt_x[MAXPMT]; float pmt_y[MAXPMT]; float pmt_z[MAXPMT]; int eventNumber; int nTrigger; int mode; int nTrack; int track_pdg[MAXTRACK]; int track_parent[MAXTRACK]; float track_t[MAXTRACK]; // time [ns] float track_e[MAXTRACK]; // KE [ns] float track_ee[MAXTRACK]; // Total Energy [ns] float track_x[MAXTRACK]; float track_y[MAXTRACK]; float track_z[MAXTRACK]; float track_dx[MAXTRACK]; float track_dy[MAXTRACK]; float track_dz[MAXTRACK]; int nPMT; // # hit PMTs int nHit; // # total hits == total PEs int hit_pmtID[MAXHIT]; float hit_t[MAXHIT]; float hit_tc[MAXHIT]; float hit_wl[MAXHIT]; // stats variables float kaon_decay_t; // ns // ch1: kaon -> mu + nu float ch1_muon_e; float ch1_michele_t; float ch1_michele_e; float ch1_kaon_npe; // with clean time separation float ch1_muon_npe; // with clean time separation float ch1_muon_npe_recon; // with clean time separation // float ch1_prompt_npe; // within 100 ns // float ch1_rising_dt; // rising time of the hittime shape // float ch1_early_charge_ratio; // early charge / all charge (in the first 100ns) float prompt_npe; // within 100 ns float rising_dt; // rising time of the hittime shape float rising_dt_vis; // rising time of the hittime shape, adding smear float early_charge_ratio; // early charge / all charge (in the first 100ns) float bg1_muon_e; float bg1_muon_npe_recon; float bg1_michele_t; CEventStats(); CEventStats(const char* filename, const char* outname); virtual ~CEventStats(); // methods void Loop(int maxEntry=-1); void SaveOutput(); void SetDefault(); void InspectShape(); void InspectVisShape(); TTree* Tree() { return simTree; } void GetEntry(int i) { simTree->GetEntry(i); } void PrintInfo(); void PrintInfo(int i); // std::vector< std::vector<float> > FindRing(int track_id, int resolution = 200); // std::vector<float> ProjectToTankSurface_C(float *vtx, float *dir); float GetRandomMuonPE(float e); private: void InitBranchAddress(); void InitDecayMode(); void InitOutput(const char* filename); // void InitGeometry(); }; #endif
/* SOLUTION OF LINEAR EQUATION CODE BY PRABHAT KUAMR (RIT2010043) INPUT FORMAT 3 1 3 -2 3 5 6 2 4 3 5 7 8 */ #include<iostream> #include<math.h> using namespace std; void cof(int *arr,int *tarr,int s,int x,int y) { int l=0,m; for(int i=0;i<s;i++) { if(i!=x) { m=0; for(int j=0;j<s;j++) if(j!=y) { *(tarr+l*(s-1)+m)=*(arr+i*s+j); //cout<<*(tarr+l*(s-1)+m); m++; } l++; } } } int mode(int *arr,int s) { if(s==2) return *arr**(arr+3)-*(arr+1)**(arr+2); int sum=0; for(int i=0;i<s;i++) { int tarr[s-1][s-1]; cof(arr,&tarr[0][0],s,0,i); sum+=pow(-1,i)**(arr+i)*mode(&tarr[0][0],s-1); //cout<<mode(&tarr[0][0],s-1)<<endl; } return sum; } int main() { int s,k=0; cin>>s; //NUMBER OF VARIABLES int arr[s][s],barr[s],sarr[s],tarr[s-1][s-1]; float save[s][s]; for(int i=0;i<s;i++) for(int j=0;j<s;j++) cin>>arr[i][j]; //INPUT COEFFICIENT MATRIX for(int i=0;i<s;i++) cin>>barr[i]; //B MATRIX int m=mode(&arr[0][0],s); for(int i=0;i<s;i++) for(int j=0;j<s;j++) { cof(&arr[0][0],&tarr[0][0],s,i,j); save[j][i]=float(pow(-1,i+j)*mode(&tarr[0][0],s-1))/float(m); } /*for(int i=0;i<s;i++) {for(int j=0;j<s;j++) cout<<save[i][j]<<" "; cout<<endl; }*/ for(int i=0;i<s;i++) { float sum=0.0; for(int j=0;j<s;j++) sum+=float(save[i][j])*float(barr[j]); sarr[k]=sum; k++; } for(int i=0;i<s;i++) cout<<sarr[i]<<" "; return 0; }
#include<iostream> #include<iomanip> using namespace std; int main() { //int a = 3, b=78, c = 1254; //cout<<"the value of a is :"<<setw(4)<<a<<endl; //cout<<"the value of b is :"<<b<<endl; //cout<<"the value of c is :"<<c<<endl; /* OPERATOR PRECEDENCE */ int a = 3, b=4; int c = (a*5)+b-44+65; cout<<c; return 0; }
#include<bits/stdc++.h> using namespace std; #define debug(x) cerr << #x << ": " << x << endl; #define iosbase ios_base::sync_with_stdio(false) #define tie cin.tie();cout.tie(); #define endl '\n' typedef pair<int, int> ii; typedef long long ll; #define cima 1 #define esq 2 #define dir 3 #define baixo 4 string m[2]; int n; int main(){ iosbase; tie; int t; cin >> t; while( t--){ int n; cin >> n; cin >> m[0]; cin >> m[1]; int ult = esq; int x = 0, y = 0; while(true){ // debug(x); // debug(y); // cerr << endl; if(x == 1 && y == n){ cout << "YES" << endl; break; } if(x > 1 || x < 0 || y > n || y < 0) { cout << "NO" << endl; break; } if(m[x][y] <= '2' && ult == esq){ y++; ult = esq; } else if(m[x][y] > '2' && ult == esq){ x = (x+1) % 2; ult = baixo; } else if(m[x][y] > '2' && (ult == cima || ult == baixo) ){ ult = esq; y++; } else{ cout << "NO" << endl; break; } } } }