hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
041a516d01a56bcdd3e1b489aac74754a7a8f12d
12,552
hpp
C++
ios/Pods/boost-for-react-native/boost/polygon/detail/rectangle_formation.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/polygon/detail/rectangle_formation.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/polygon/detail/rectangle_formation.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
/* Copyright 2008 Intel Corporation Use, modification and distribution are subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt). */ #ifndef BOOST_POLYGON_RECTANGLE_FORMATION_HPP #define BOOST_POLYGON_RECTANGLE_FORMATION_HPP namespace boost { namespace polygon{ namespace rectangle_formation { template <class T> class ScanLineToRects { public: typedef T rectangle_type; typedef typename rectangle_traits<T>::coordinate_type coordinate_type; typedef rectangle_data<coordinate_type> scan_rect_type; private: typedef std::set<scan_rect_type, less_rectangle_concept<scan_rect_type, scan_rect_type> > ScanData; ScanData scanData_; bool haveCurrentRect_; scan_rect_type currentRect_; orientation_2d orient_; typename rectangle_traits<T>::coordinate_type currentCoordinate_; public: inline ScanLineToRects() : scanData_(), haveCurrentRect_(), currentRect_(), orient_(), currentCoordinate_() {} inline ScanLineToRects(orientation_2d orient, rectangle_type model) : scanData_(orientation_2d(orient.to_int() ? VERTICAL : HORIZONTAL)), haveCurrentRect_(false), currentRect_(), orient_(orient), currentCoordinate_() { assign(currentRect_, model); currentCoordinate_ = (std::numeric_limits<coordinate_type>::max)(); } template <typename CT> inline ScanLineToRects& processEdge(CT& rectangles, const interval_data<coordinate_type>& edge); inline ScanLineToRects& nextMajorCoordinate(coordinate_type currentCoordinate) { if(haveCurrentRect_) { scanData_.insert(scanData_.end(), currentRect_); haveCurrentRect_ = false; } currentCoordinate_ = currentCoordinate; return *this; } }; template <class CT, class ST, class rectangle_type, typename interval_type, typename coordinate_type> inline CT& processEdge_(CT& rectangles, ST& scanData, const interval_type& edge, bool& haveCurrentRect, rectangle_type& currentRect, coordinate_type currentCoordinate, orientation_2d orient) { typedef typename CT::value_type result_type; bool edgeProcessed = false; if(!scanData.empty()) { //process all rectangles in the scanData that touch the edge typename ST::iterator dataIter = scanData.lower_bound(rectangle_type(edge, edge)); //decrement beginIter until its low is less than edge's low while((dataIter == scanData.end() || (*dataIter).get(orient).get(LOW) > edge.get(LOW)) && dataIter != scanData.begin()) { --dataIter; } //process each rectangle until the low end of the rectangle //is greater than the high end of the edge while(dataIter != scanData.end() && (*dataIter).get(orient).get(LOW) <= edge.get(HIGH)) { const rectangle_type& rect = *dataIter; //if the rectangle data intersects the edge at all if(rect.get(orient).get(HIGH) >= edge.get(LOW)) { if(contains(rect.get(orient), edge, true)) { //this is a closing edge //we need to write out the intersecting rectangle and //insert between 0 and 2 rectangles into the scanData //write out rectangle rectangle_type tmpRect = rect; if(rect.get(orient.get_perpendicular()).get(LOW) < currentCoordinate) { //set the high coordinate perpedicular to slicing orientation //to the current coordinate of the scan event tmpRect.set(orient.get_perpendicular().get_direction(HIGH), currentCoordinate); result_type result; assign(result, tmpRect); rectangles.insert(rectangles.end(), result); } //erase the rectangle from the scan data typename ST::iterator nextIter = dataIter; ++nextIter; scanData.erase(dataIter); if(tmpRect.get(orient).get(LOW) < edge.get(LOW)) { //insert a rectangle for the overhang of the bottom //of the rectangle back into scan data rectangle_type lowRect(tmpRect); lowRect.set(orient.get_perpendicular(), interval_data<coordinate_type>(currentCoordinate, currentCoordinate)); lowRect.set(orient.get_direction(HIGH), edge.get(LOW)); scanData.insert(nextIter, lowRect); } if(tmpRect.get(orient).get(HIGH) > edge.get(HIGH)) { //insert a rectangle for the overhang of the top //of the rectangle back into scan data rectangle_type highRect(tmpRect); highRect.set(orient.get_perpendicular(), interval_data<coordinate_type>(currentCoordinate, currentCoordinate)); highRect.set(orient.get_direction(LOW), edge.get(HIGH)); scanData.insert(nextIter, highRect); } //we are done with this edge edgeProcessed = true; break; } else { //it must be an opening edge //assert that rect does not overlap the edge but only touches //write out rectangle rectangle_type tmpRect = rect; //set the high coordinate perpedicular to slicing orientation //to the current coordinate of the scan event if(tmpRect.get(orient.get_perpendicular().get_direction(LOW)) < currentCoordinate) { tmpRect.set(orient.get_perpendicular().get_direction(HIGH), currentCoordinate); result_type result; assign(result, tmpRect); rectangles.insert(rectangles.end(), result); } //erase the rectangle from the scan data typename ST::iterator nextIter = dataIter; ++nextIter; scanData.erase(dataIter); dataIter = nextIter; if(haveCurrentRect) { if(currentRect.get(orient).get(HIGH) >= edge.get(LOW)){ if(!edgeProcessed && currentRect.get(orient.get_direction(HIGH)) > edge.get(LOW)){ rectangle_type tmpRect2(currentRect); tmpRect2.set(orient.get_direction(HIGH), edge.get(LOW)); scanData.insert(nextIter, tmpRect2); if(currentRect.get(orient.get_direction(HIGH)) > edge.get(HIGH)) { currentRect.set(orient, interval_data<coordinate_type>(edge.get(HIGH), currentRect.get(orient.get_direction(HIGH)))); } else { haveCurrentRect = false; } } else { //extend the top of current rect currentRect.set(orient.get_direction(HIGH), (std::max)(edge.get(HIGH), tmpRect.get(orient.get_direction(HIGH)))); } } else { //insert current rect into the scanData scanData.insert(nextIter, currentRect); //create a new current rect currentRect.set(orient.get_perpendicular(), interval_data<coordinate_type>(currentCoordinate, currentCoordinate)); currentRect.set(orient, interval_data<coordinate_type>((std::min)(tmpRect.get(orient).get(LOW), edge.get(LOW)), (std::max)(tmpRect.get(orient).get(HIGH), edge.get(HIGH)))); } } else { haveCurrentRect = true; currentRect.set(orient.get_perpendicular(), interval_data<coordinate_type>(currentCoordinate, currentCoordinate)); currentRect.set(orient, interval_data<coordinate_type>((std::min)(tmpRect.get(orient).get(LOW), edge.get(LOW)), (std::max)(tmpRect.get(orient).get(HIGH), edge.get(HIGH)))); } //skip to nextIter position edgeProcessed = true; continue; } //edgeProcessed = true; } ++dataIter; } //end while edge intersects rectangle data } if(!edgeProcessed) { if(haveCurrentRect) { if(currentRect.get(orient.get_perpendicular().get_direction(HIGH)) == currentCoordinate && currentRect.get(orient.get_direction(HIGH)) >= edge.get(LOW)) { if(currentRect.get(orient.get_direction(HIGH)) > edge.get(LOW)){ rectangle_type tmpRect(currentRect); tmpRect.set(orient.get_direction(HIGH), edge.get(LOW)); scanData.insert(scanData.end(), tmpRect); if(currentRect.get(orient.get_direction(HIGH)) > edge.get(HIGH)) { currentRect.set(orient, interval_data<coordinate_type>(edge.get(HIGH), currentRect.get(orient.get_direction(HIGH)))); return rectangles; } else { haveCurrentRect = false; return rectangles; } } //extend current rect currentRect.set(orient.get_direction(HIGH), edge.get(HIGH)); return rectangles; } scanData.insert(scanData.end(), currentRect); haveCurrentRect = false; } rectangle_type tmpRect(currentRect); tmpRect.set(orient.get_perpendicular(), interval_data<coordinate_type>(currentCoordinate, currentCoordinate)); tmpRect.set(orient, edge); scanData.insert(tmpRect); return rectangles; } return rectangles; } template <class T> template <class CT> inline ScanLineToRects<T>& ScanLineToRects<T>::processEdge(CT& rectangles, const interval_data<coordinate_type>& edge) { processEdge_(rectangles, scanData_, edge, haveCurrentRect_, currentRect_, currentCoordinate_, orient_); return *this; } } //namespace rectangle_formation template <typename T, typename T2> struct get_coordinate_type_for_rectangles { typedef typename polygon_traits<T>::coordinate_type type; }; template <typename T> struct get_coordinate_type_for_rectangles<T, rectangle_concept> { typedef typename rectangle_traits<T>::coordinate_type type; }; template <typename output_container, typename iterator_type, typename rectangle_concept> void form_rectangles(output_container& output, iterator_type begin, iterator_type end, orientation_2d orient, rectangle_concept ) { typedef typename output_container::value_type rectangle_type; typedef typename get_coordinate_type_for_rectangles<rectangle_type, typename geometry_concept<rectangle_type>::type>::type Unit; rectangle_data<Unit> model; Unit prevPos = (std::numeric_limits<Unit>::max)(); rectangle_formation::ScanLineToRects<rectangle_data<Unit> > scanlineToRects(orient, model); for(iterator_type itr = begin; itr != end; ++ itr) { Unit pos = (*itr).first; if(pos != prevPos) { scanlineToRects.nextMajorCoordinate(pos); prevPos = pos; } Unit lowy = (*itr).second.first; iterator_type tmp_itr = itr; ++itr; Unit highy = (*itr).second.first; scanlineToRects.processEdge(output, interval_data<Unit>(lowy, highy)); if(std::abs((*itr).second.second) > 1) itr = tmp_itr; //next edge begins from this vertex } } } } #endif
47.011236
140
0.57449
rudylee
041bd28ad892a32c4a33ad031711b79f8358ec9b
4,378
cc
C++
paddle/pten/tests/api/test_tensor_utils.cc
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
2
2021-07-25T06:47:03.000Z
2021-12-17T04:27:26.000Z
paddle/pten/tests/api/test_tensor_utils.cc
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
null
null
null
paddle/pten/tests/api/test_tensor_utils.cc
HydrogenSulfate/Paddle
42cfd15e672e1ed7ad0242c1ae9e492f197599d6
[ "Apache-2.0" ]
1
2021-10-09T10:57:17.000Z
2021-10-09T10:57:17.000Z
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gtest/gtest.h" #include "paddle/pten/api/lib/utils/tensor_utils.h" #include "paddle/pten/core/tensor_meta.h" namespace paddle { namespace tests { using DDim = paddle::framework::DDim; using DataType = paddle::experimental::DataType; using DataLayout = paddle::experimental::DataLayout; using DenseTensor = pten::DenseTensor; using DenseTensorMeta = pten::DenseTensorMeta; TEST(tensor_utils, dense_tensor_to_lod_tensor) { const DDim dims({2, 1}); const DataType dtype{DataType::FLOAT32}; const DataLayout layout{DataLayout::NCHW}; const pten::LoD lod{{0, 2}}; DenseTensorMeta meta(dtype, dims, layout, lod); auto alloc = std::make_shared<experimental::DefaultAllocator>(platform::CPUPlace()); DenseTensor dense_tensor(alloc, meta); float* data = dense_tensor.mutable_data<float>(); data[0] = 1.0f; data[1] = 2.1f; framework::LoDTensor lod_tensor; experimental::MovesStorage(&dense_tensor, &lod_tensor); CHECK(dense_tensor.lod().size() == lod_tensor.lod().size()); CHECK(dense_tensor.lod()[0] == static_cast<paddle::framework::Vector<size_t>>((lod_tensor.lod()[0]))); CHECK(dense_tensor.dtype() == pten::TransToPtenDataType(lod_tensor.type())); CHECK(dense_tensor.layout() == lod_tensor.layout()); CHECK(platform::is_cpu_place(lod_tensor.place())); CHECK(lod_tensor.data<float>()[0] == 1.0f); CHECK(lod_tensor.data<float>()[1] == 2.1f); auto dense_tensor_1 = experimental::MakePtenDenseTensor(lod_tensor); CHECK(dense_tensor_1->dims() == dims); CHECK(dense_tensor_1->dtype() == dtype); CHECK(dense_tensor_1->layout() == layout); CHECK(dense_tensor_1->lod().size() == lod.size()); CHECK(dense_tensor_1->lod()[0] == lod[0]); const float* data_1 = dense_tensor_1->data<float>(); CHECK(data_1[0] == 1.0f); CHECK(data_1[1] == 2.1f); } TEST(tensor_utils, dense_tensor_to_tensor) { const DDim dims({2, 1}); const DataType dtype{DataType::FLOAT32}; const DataLayout layout{DataLayout::NCHW}; DenseTensorMeta meta(dtype, dims, layout); auto alloc = std::make_shared<experimental::DefaultAllocator>(platform::CPUPlace()); DenseTensor dense_tensor(alloc, meta); float* data = dense_tensor.mutable_data<float>(); data[0] = 1.0f; data[1] = 2.1f; framework::Tensor tensor; experimental::MovesStorage(&dense_tensor, &tensor); CHECK(dense_tensor.dtype() == pten::TransToPtenDataType(tensor.type())); CHECK(dense_tensor.layout() == tensor.layout()); CHECK(platform::is_cpu_place(tensor.place())); CHECK(tensor.data<float>()[0] == 1.0f); CHECK(tensor.data<float>()[1] == 2.1f); auto dense_tensor_1 = experimental::MakePtenDenseTensor(tensor); CHECK(dense_tensor_1->dims() == dims); CHECK(dense_tensor_1->dtype() == dtype); CHECK(dense_tensor_1->layout() == layout); const float* data_1 = dense_tensor_1->data<float>(); CHECK(data_1[0] == 1.0f); CHECK(data_1[1] == 2.1f); } TEST(PtenUtils, VarToPtTensor) { // 1. create Variable paddle::framework::Variable v; auto selected_rows = v.GetMutable<paddle::framework::SelectedRows>(); paddle::framework::Tensor* value = selected_rows->mutable_value(); auto* data = value->mutable_data<int>(paddle::framework::make_ddim({1, 1}), paddle::platform::CPUPlace()); data[0] = 123; pten::Backend expect_backend = pten::Backend::CPU; #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) expect_backend = pten::Backend::GPU; #endif auto tensor_def = pten::TensorArgDef( expect_backend, pten::DataLayout::NCHW, pten::DataType::INT32); // 2. test API auto tensor_x = experimental::MakePtenTensorBaseFromVar(v, tensor_def); // 3. check result ASSERT_EQ(tensor_x->dtype(), pten::DataType::INT32); } } // namespace tests } // namespace paddle
35.024
79
0.711284
HydrogenSulfate
042199996e136c4076f552e7e928272b94ec1ecc
16,917
cpp
C++
physically-based-cloud-rendering/clouds/main.cpp
markomijolovic/physically-based-cloud-rendering
a8f9b3e11d6c2f744a45a598b872afb45ff8756c
[ "BSD-3-Clause" ]
3
2021-05-25T13:58:22.000Z
2022-02-21T11:53:26.000Z
physically-based-cloud-rendering/clouds/main.cpp
markomijolovic/physically-based-cloud-rendering
a8f9b3e11d6c2f744a45a598b872afb45ff8756c
[ "BSD-3-Clause" ]
null
null
null
physically-based-cloud-rendering/clouds/main.cpp
markomijolovic/physically-based-cloud-rendering
a8f9b3e11d6c2f744a45a598b872afb45ff8756c
[ "BSD-3-Clause" ]
null
null
null
#define GLFW_INCLUDE_NONE #include "GLFW/glfw3.h" #include "camera.hpp" #include "framebuffer.hpp" #include "glbinding/gl/gl.h" #include "glbinding/glbinding.h" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" #include "input.hpp" #include "mesh.hpp" #include "preetham.hpp" #include "shader.hpp" #include "stb_image.h" #include "transforms.hpp" #include <chrono> #include <string_view> struct configuration_t { std::string_view weather_map{}; float base_scale{}; float detail_scale{}; float weather_scale{}; float detail_factor{}; glm::vec3 min{}; glm::vec3 max{}; float a{}; float b{}; float c{}; float extinction{}; float scattering{}; float global_coverage{}; }; auto main() -> int { constexpr auto screen_width = 1280; constexpr auto screen_height = 720; const auto full_screen_quad_positions = std::vector{ glm::vec3{-1.0F, -1.0F, 0.0F}, glm::vec3{1.0F, -1.0F, 0.0F}, glm::vec3{1.0F, 1.0F, 0.0F}, glm::vec3{-1.0F, 1.0F, 0.0F}}; const auto full_screen_quad_uvs = std::vector{ glm::vec2{0.0F, 0.0F}, glm::vec2{1.0F, 0.0F}, glm::vec2{1.0F, 1.0F}, glm::vec2{0.0F, 1.0F}}; const auto full_screen_quad_indices = std::vector{0U, 1U, 2U, 2U, 3U, 0U}; auto camera = camera_t{ perspective(90.0F, static_cast<float>(screen_width) / screen_height, 0.01F, 100000.0F), {{0.0F, 10.0F, 0.0F, 1.0F}, {}, {1.0F, 1.0F, 1.0F}}}; auto configurations = std::array{ configuration_t{ "perlin_test_cumulus", 60000, 1500, 60000, 0.5F, {-30000, 1000, -30000}, {30000, 4000, 30000}, 0.55F, 0.7F, 0.00F, 0.06F, 0.06F, 0.0F}, configuration_t{ "perlin_test_stratocumulus", 40000, 2000, 60000, 0.5F, {-30000, 1000, -30000}, {30000, 4000, 30000}, 0.6F, 0.75, 0.0F, 0.033F, 0.033F, 0.0F}, configuration_t{ "perlin_test_stratus", 60000, 3000, 60000, 0.33F, {-30000, 1000, -30000}, {30000, 4000, 30000}, 0.6F, 0.75F, 0.0F, 0.02F, 0.02F, 1.0F}, configuration_t{ "custom_cumulus", 15000, 1500, 60000, 0.5F, {-6000, 1000, -6000}, {6000, 4000, 6000}, 0.6F, 0.75F, 0.0F, 0.06F, 0.06F, 1.0F}, }; auto weather_maps = std::unordered_map<std::string_view, texture_t<2U>>{}; const auto arr_up = std::array{ normalize(glm::vec3{0, 1, 0}), normalize(glm::vec3{1, 0.01, 0}), glm::vec3{-1, 0.01, 0}, glm::vec3{0, 0.01, 1}, glm::vec3{0, 0.01, -1}}; const auto arr_down = std::array{ normalize(glm::vec3{0, -1, 0}), normalize(glm::vec3{1, -0.01, 0}), glm::vec3{-1, -0.01, 0}, glm::vec3{0, -0.01, 1}, glm::vec3{0, -0.01, -1}}; auto radio_button_value{3}; auto cfg_value{0}; auto sun_intensity{1.0F}; auto anvil_bias{0.0F}; auto coverage_multiplier{1.0F}; auto exposure_factor{0.000015F}; auto turbidity{5.0F}; auto multiple_scattering_approximation{true}; auto blue_noise{false}; auto blur{false}; auto ambient{true}; auto n{16}; auto primary_ray_steps{64}; auto secondary_ray_steps{16}; auto cloud_speed{0.0F}; auto density_multiplier{1.0F}; auto wind_direction{glm::vec3{1.0F, 0.0F, 0.0F}}; auto wind_direction_normalized{glm::vec3{}}; auto sun_direction{glm::vec3{0.0F, -1.0F, 0.0F}}; auto sun_direction_normalized{glm::vec3{}}; // init glfw if (glfwInit() == 0) { std::exit(-1); } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, 0); const auto window = glfwCreateWindow(screen_width, screen_height, "clouds", nullptr, nullptr); if (window == nullptr) { std::exit(-1); } glfwSetCursorPosCallback(window, mouse_callback); glfwSetKeyCallback(window, key_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(window); glfwSwapInterval(0); // disable v-sync glbinding::initialize(glfwGetProcAddress); gl::glViewport(0, 0, screen_width, screen_height); //init imgui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGui::StyleColorsLight(); ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init("#version 460"); // load textures stbi_set_flip_vertically_on_load(1); const auto cloud_base_texture = texture_t<3U>{128U, 128U, 128U, "textures/noise_shape.tga"}; const auto cloud_erosion_texture = texture_t<3U>{64U, 64U, 64U, "textures/noise_erosion_hd.tga"}; const auto mie_texture = texture_t<1U>{ 1800U, 0U, 0U, "textures/mie_phase_function_normalized.hdr", gl::GLenum::GL_RGB32F, gl::GLenum::GL_RGB, gl::GLenum::GL_FLOAT}; weather_maps["perlin_test_stratus"] = texture_t<2U>{512U, 512U, 0U, "textures/perlin_test_stratus.tga"}; weather_maps["perlin_test_stratocumulus"] = texture_t<2U>{512U, 512U, 0U, "textures/perlin_test_stratocumulus.tga"}; weather_maps["perlin_test_cumulus"] = texture_t<2U>{512U, 512U, 0U, "textures/perlin_test_cumulus.tga"}; weather_maps["custom_cumulus"] = texture_t<2U>{512U, 512U, 0U, "textures/custom_cumulus.tga"}; const auto blue_noise_texture = texture_t<2U>(512U, 512U, 0U, "textures/blue_noise.png"); const auto quad = mesh_t{full_screen_quad_positions, full_screen_quad_uvs, full_screen_quad_indices}; const auto raymarching_shader = shader_t{"shaders/raymarch.vert", "shaders/raymarch.frag"}; const auto blur_shader = shader_t{"shaders/raymarch.vert", "shaders/blur.frag"}; const auto tonemap_shader = shader_t{"shaders/raymarch.vert", "shaders/tonemap.frag"}; gl::glClearColor(0.0F, 0.0F, 0.0F, 1.0F); // create framebuffers auto framebuffer{framebuffer_t{screen_width, screen_height, 1, true}}; auto framebuffer2{framebuffer_t{screen_width, screen_height, 1, true}}; auto framebuffer3{framebuffer_t{screen_width, screen_height, 1, true}}; auto delta_time = 1.0F / 60.0F; auto cumulative_time{0.0F}; auto now = std::chrono::high_resolution_clock::now(); while (glfwWindowShouldClose(window) == 0) { glfwPollEvents(); delta_time = std::chrono::duration<float, std::milli>(std::chrono::high_resolution_clock::now() - now).count(); now = std::chrono::high_resolution_clock::now(); cumulative_time += delta_time; process_input(delta_time, camera); //std::cout << "Delta time: " << delta_time << std::endl; // raymarching auto &cfg = configurations[cfg_value]; framebuffer2.bind(); glClear(gl::ClearBufferMask::GL_COLOR_BUFFER_BIT | gl::ClearBufferMask::GL_DEPTH_BUFFER_BIT); raymarching_shader.use(); cloud_base_texture.bind(1); cloud_erosion_texture.bind(2); weather_maps[cfg.weather_map].bind(3); raymarching_shader.set_uniform("cloud_base", 1); raymarching_shader.set_uniform("cloud_erosion", 2); raymarching_shader.set_uniform("weather_map", 3); raymarching_shader.set_uniform("use_blue_noise", blue_noise); if (blue_noise) { blue_noise_texture.bind(4); raymarching_shader.set_uniform("blue_noise", 4); } mie_texture.bind(5); raymarching_shader.set_uniform("mie_texture", 5); raymarching_shader.set_uniform("projection", camera.projection); raymarching_shader.set_uniform("view", get_view_matrix(camera.transform)); raymarching_shader.set_uniform("camera_pos", glm::vec3{camera.transform.position}); raymarching_shader.set_uniform("low_frequency_noise_visualization", static_cast<int>(radio_button_value == 2)); raymarching_shader.set_uniform("high_frequency_noise_visualization", static_cast<int>(radio_button_value == 3)); raymarching_shader.set_uniform("multiple_scattering_approximation", multiple_scattering_approximation); raymarching_shader.set_uniform("low_freq_noise_scale", cfg.base_scale); raymarching_shader.set_uniform("weather_map_scale", cfg.weather_scale); raymarching_shader.set_uniform("high_freq_noise_scale", cfg.detail_scale); raymarching_shader.set_uniform("scattering_factor", cfg.scattering); raymarching_shader.set_uniform("extinction_factor", cfg.extinction); raymarching_shader.set_uniform("sun_intensity", sun_intensity); raymarching_shader.set_uniform("high_freq_noise_factor", cfg.detail_factor); raymarching_shader.set_uniform("N", n); raymarching_shader.set_uniform("a", cfg.a); raymarching_shader.set_uniform("b", cfg.b); raymarching_shader.set_uniform("c", cfg.c); raymarching_shader.set_uniform("primary_ray_steps", primary_ray_steps); raymarching_shader.set_uniform("secondary_ray_steps", secondary_ray_steps); raymarching_shader.set_uniform("time", cumulative_time); raymarching_shader.set_uniform("cloud_speed", cloud_speed); raymarching_shader.set_uniform("global_cloud_coverage", cfg.global_coverage); raymarching_shader.set_uniform("anvil_bias", anvil_bias); wind_direction_normalized = normalize(wind_direction); raymarching_shader.set_uniform("wind_direction", wind_direction_normalized); sun_direction_normalized = normalize(sun_direction); raymarching_shader.set_uniform("sun_direction", sun_direction_normalized); raymarching_shader.set_uniform("use_ambient", ambient); raymarching_shader.set_uniform("turbidity", turbidity); raymarching_shader.set_uniform("coverage_mult", coverage_multiplier); raymarching_shader.set_uniform("density_mult", density_multiplier); raymarching_shader.set_uniform("aabb_max", cfg.max); raymarching_shader.set_uniform("aabb_min", cfg.min); // use average of 5 samples as ambient radiance // this could really be improved (and done on the GPU as well) auto ambient_luminance_up{glm::vec3{}}; for (const auto &el: arr_up) { ambient_luminance_up += 1000.0F * calculate_sky_luminance_RGB(-sun_direction_normalized, el, turbidity); } ambient_luminance_up /= 5.0F; raymarching_shader.set_uniform("ambient_luminance_up", ambient_luminance_up); auto ambient_luminance_down{glm::vec3{}}; for (const auto &el: arr_down) { ambient_luminance_down += 1000.0F * calculate_sky_luminance_RGB(-sun_direction_normalized, el, turbidity); } ambient_luminance_down /= 5.0F; raymarching_shader.set_uniform("ambient_luminance_down", ambient_luminance_down); quad.draw(); if (blur) { // gaussian blur auto horizontal = true; auto amount = 4; blur_shader.use(); blur_shader.set_uniform("full_screen", 0); for (auto i = 0; i < amount; i++) { if (horizontal) { framebuffer3.bind(); framebuffer2.colour_attachments().front().bind(0); } else { framebuffer2.bind(); framebuffer3.colour_attachments().front().bind(0); } blur_shader.set_uniform("horizontal", horizontal); quad.draw(); horizontal = !horizontal; } } framebuffer_t::unbind(); glClear(gl::ClearBufferMask::GL_COLOR_BUFFER_BIT | gl::ClearBufferMask::GL_DEPTH_BUFFER_BIT); tonemap_shader.use(); framebuffer2.colour_attachments().front().bind(0); tonemap_shader.set_uniform("full_screen", 0); tonemap_shader.set_uniform("exposure_factor", exposure_factor); quad.draw(); // render gui if (options()) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGui::Begin("clouds"); ImGui::Text("average fps: %.2f fps", ImGui::GetIO().Framerate); ImGui::Text("average frametime: %.2f ms", 1000.0F / ImGui::GetIO().Framerate); ImGui::Text("time elapsed: %.2f ms", cumulative_time); ImGui::Text("camera world position: x=%f, y=%f, z=%f", camera.transform.position.x, camera.transform.position.y, camera.transform.position.z); ImGui::Text("press 'o' to toggle options"); ImGui::End(); ImGui::Begin("options"); ImGui::SliderInt("number of primary ray steps", &primary_ray_steps, 1, 500, "%d"); ImGui::SliderInt("number of secondary ray steps", &secondary_ray_steps, 1, 100, "%d"); ImGui::NewLine(); ImGui::RadioButton("low frequency noise", &radio_button_value, 2); ImGui::RadioButton("high frequency noise", &radio_button_value, 3); ImGui::NewLine(); ImGui::RadioButton("cumulus map", &cfg_value, 0); ImGui::RadioButton("stratocumulus map", &cfg_value, 1); ImGui::RadioButton("stratus map", &cfg_value, 2); ImGui::RadioButton("one cumulus map", &cfg_value, 3); ImGui::NewLine(); ImGui::Checkbox("blue noise jitter", &blue_noise); ImGui::Checkbox("gaussian blur", &blur); ImGui::NewLine(); ImGui::SliderFloat("low frequency noise scale", &cfg.base_scale, 10.0F, 200000.0F, "%.5f"); ImGui::SliderFloat("high frequency noise scale", &cfg.detail_scale, 10.0F, 10000.0F, "%.5f"); ImGui::SliderFloat("weather map scale", &cfg.weather_scale, 3000.0F, 300000.0F, "%.5f"); ImGui::NewLine(); ImGui::SliderFloat("high frequency noise factor", &cfg.detail_factor, 0.0F, 1.0F, "%.5f"); ImGui::SliderFloat("anvil bias", &anvil_bias, 0.0F, 1.0F, "%.5f"); ImGui::SliderFloat("scattering factor", &cfg.scattering, 0.01F, 1.0F, "%.5f"); ImGui::SliderFloat("extinction factor", &cfg.extinction, 0.01F, 1.0F, "%.5f"); ImGui::SliderFloat3("wind direction", &wind_direction[0], -1.0F, 1.0F, "%.5f"); ImGui::SliderFloat3("aabb max", &cfg.max[0], -30000.0F, 30000.0F, "%.5f"); ImGui::SliderFloat3("aabb min", &cfg.min[0], -30000.0F, 30000.0F, "%.5f"); ImGui::SliderFloat("sun direction x", &sun_direction[0], -1.0F, 1.0F, "%.5f"); ImGui::SliderFloat("sun direction y", &sun_direction[1], -1.0F, -0.001F, "%.5f"); ImGui::SliderFloat("sun direction z", &sun_direction[2], -1.0F, 1.0F, "%.5f"); ImGui::SliderFloat("cloud speed", &cloud_speed, 0.0F, 10.0F, "%.5f"); ImGui::SliderFloat("exposure factor", &exposure_factor, 0.00001F, 0.0001F, "%.8f"); ImGui::SliderFloat("global cloud coverage", &cfg.global_coverage, 0.0F, 1.0F, "%.5f"); ImGui::SliderFloat("turbidity", &turbidity, 2.0F, 20.0F); ImGui::SliderFloat("coverage_mult", &coverage_multiplier, 0.0F, 1.0F); ImGui::SliderFloat("density_mult", &density_multiplier, 0.0F, 5.0F); ImGui::NewLine(); ImGui::Checkbox("approximate ambient light", &ambient); ImGui::Checkbox("multiple scattering approximation", &multiple_scattering_approximation); ImGui::SliderInt("octaves count", &n, 1, 16, "%d"); ImGui::SliderFloat("attenuation", &cfg.a, 0.01F, 1.0F, "%.2f"); ImGui::SliderFloat("contribution", &cfg.b, 0.01F, 1.0F, "%.2f"); ImGui::SliderFloat("eccentricity attenuation", &cfg.c, 0.01F, 1.0F, "%.2f"); ImGui::End(); ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } glfwSwapBuffers(window); } ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); glfwDestroyWindow(window); glfwTerminate(); }
40.471292
120
0.612106
markomijolovic
0425fa69f4e3ac728927b93c3e082eaefc45c651
867
cpp
C++
tools/clang/test/CoverageMapping/header.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/clang/test/CoverageMapping/header.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
tools/clang/test/CoverageMapping/header.cpp
seanbaxter/DirectXShaderCompiler
6d02c8d43ff3fdeb9963acaf3af00c62aaa01f44
[ "NCSA" ]
null
null
null
// RUN: %clang_cc1 -fprofile-instr-generate -fcoverage-mapping -dump-coverage-mapping -emit-llvm37-only -main-file-name header.cpp %s > %tmapping // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-FUNC // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-STATIC-FUNC // RUN: FileCheck -input-file %tmapping %s --check-prefix=CHECK-STATIC-FUNC2 #include "Inputs/header1.h" int main() { func(1); static_func(2); } // CHECK-FUNC: func // CHECK-FUNC: File 0, 4:25 -> 11:2 = #0 // CHECK-FUNC: File 0, 6:15 -> 8:4 = #1 // CHECK-FUNC: File 0, 8:10 -> 10:4 = (#0 - #1) // CHECK-STATIC-FUNC: static_func // CHECK-STATIC-FUNC: File 0, 12:32 -> 20:2 = #0 // CHECK-STATIC-FUNC: File 0, 14:15 -> 16:4 = #1 // CHECK-STATIC-FUNC: File 0, 16:10 -> 18:4 = (#0 - #1) // CHECK-STATIC-FUNC2: static_func2 // CHECK-STATIC-FUNC2: File 0, 21:33 -> 29:2 = 0
34.68
145
0.650519
seanbaxter
54b61352b50aca0111335157616a19b65c267ed1
1,265
hpp
C++
client_utils/include/hawktracer/client_utils/tcp_client_stream.hpp
jandom/hawktracer
e53b07bc812c4cfe8f6253ddb48ac43de8fa74a8
[ "MIT" ]
116
2018-05-04T14:51:58.000Z
2022-02-08T23:47:28.000Z
client_utils/include/hawktracer/client_utils/tcp_client_stream.hpp
jandom/hawktracer
e53b07bc812c4cfe8f6253ddb48ac43de8fa74a8
[ "MIT" ]
58
2018-05-04T15:00:15.000Z
2020-11-06T11:34:11.000Z
client_utils/include/hawktracer/client_utils/tcp_client_stream.hpp
beila/hawktracer
d427c6a66097787f4e5431e1cae0278f1f03ca4c
[ "MIT" ]
32
2018-05-05T12:05:56.000Z
2021-12-06T02:18:05.000Z
#ifndef HAWKTRACER_CLIENT_UTILS_TCP_CLIENT_STREAM_HPP #define HAWKTRACER_CLIENT_UTILS_TCP_CLIENT_STREAM_HPP #include <hawktracer/parser/stream.hpp> #include <queue> #include <mutex> #include <condition_variable> #include <atomic> #include <thread> namespace HawkTracer { namespace ClientUtils { class TCPClientStream : public parser::Stream { public: TCPClientStream(const std::string& ip_address, uint16_t port, bool wait_for_server = true); ~TCPClientStream(); bool start() override; void stop() override; bool is_connected() const; int read_byte() override; bool read_data(char* buff, size_t size) override; bool is_continuous() override { return true; } private: void _run(); bool _wait_for_data(std::unique_lock<std::mutex>& l); void _pop_if_used() { if (_datas.front().second.size() == _datas.front().first) { _datas.pop(); } } std::queue<std::pair<size_t, std::vector<char>>> _datas; std::mutex _datas_mtx; std::condition_variable _datas_cv; std::thread _thread; std::atomic<int> _sock_fd; std::string _ip_address; uint16_t _port; bool _wait_for_server; }; } // namespace ClientUtils } // namespace HawkTracer #endif // HAWKTRACER_CLIENT_UTILS_TCP_CLIENT_STREAM_HPP
22.589286
103
0.72332
jandom
54bd7b9f769501f46b5c842b931f46d1f551a22f
911
cpp
C++
built_in_translation-31533019/main.cpp
kay54068/qt-snippets
1af5b41599d469cf3e9ccce267f4721fad1e169e
[ "Apache-2.0" ]
10
2016-04-07T07:10:42.000Z
2021-12-08T19:57:45.000Z
built_in_translation-31533019/main.cpp
kay54068/qt-snippets
1af5b41599d469cf3e9ccce267f4721fad1e169e
[ "Apache-2.0" ]
null
null
null
built_in_translation-31533019/main.cpp
kay54068/qt-snippets
1af5b41599d469cf3e9ccce267f4721fad1e169e
[ "Apache-2.0" ]
3
2017-01-26T13:58:20.000Z
2020-02-04T22:12:19.000Z
#include <QDebug> #include <QtWidgets/QApplication> #include <QMessageBox> #include <QTranslator> #include <QLibraryInfo> int main(int argc, char *argv[]) { QApplication app(argc, argv); QTranslator qtTranslator; if (qtTranslator.load(QLocale::system(), "qt", "_", QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << "qtTranslator ok"; app.installTranslator(&qtTranslator); } QTranslator qtBaseTranslator; if (qtBaseTranslator.load("qtbase_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath))) { qDebug() << "qtBaseTranslator ok"; app.installTranslator(&qtBaseTranslator); } QTranslator translator; translator.load("myapp_es", ":/"); app.installTranslator(&translator); QMessageBox::question(0, QObject::tr("Sure want to quit?"), QObject::tr("Sure?"), QMessageBox::Yes | QMessageBox::No); return app.exec(); }
23.358974
64
0.711306
kay54068
54bf8f716cc6ef9e5331c44b3e06e1537f53f941
10,375
hpp
C++
src/dtl/bitmap/uah_skip.hpp
harald-lang/tree-encoded-bitmaps
a4ab056f2cefa7843b27c736833b08977b56649c
[ "Apache-2.0" ]
29
2020-06-18T12:51:42.000Z
2022-02-22T07:38:24.000Z
src/dtl/bitmap/uah_skip.hpp
marcellus-saputra/Thuja
8443320a6d0e9a20bb6b665f0befc6988978cafd
[ "Apache-2.0" ]
null
null
null
src/dtl/bitmap/uah_skip.hpp
marcellus-saputra/Thuja
8443320a6d0e9a20bb6b665f0befc6988978cafd
[ "Apache-2.0" ]
2
2021-04-07T13:43:34.000Z
2021-06-09T04:49:39.000Z
#pragma once //===----------------------------------------------------------------------===// #include "uah.hpp" #include <dtl/bitmap/util/plain_bitmap.hpp> #include <dtl/bitmap/util/plain_bitmap_iter.hpp> #include <dtl/dtl.hpp> #include <boost/dynamic_bitset.hpp> #include <algorithm> #include <cstddef> #include <type_traits> #include <vector> //===----------------------------------------------------------------------===// namespace dtl { //===----------------------------------------------------------------------===// /// Un-Aligned Hybrid: An RLE compressed representation of a bitmap of length N. /// Unlike WAH or BBC, the encoding is not word or byte aligned. /// This implementation maintains a small index that allows for faster skips. template<typename _word_type = u32, std::size_t _skip_distance = 1024> class uah_skip : public uah<_word_type> { using super = uah<_word_type>; using word_type = typename super::word_type; using uah<_word_type>::uah; using uah<_word_type>::is_fill_word; using uah<_word_type>::extract_fill_value; using uah<_word_type>::extract_fill_length; using uah<_word_type>::word_bitlength; using uah<_word_type>::payload_bit_cnt; std::vector<$u32> offsets_; /// Initialize the skip offsets. void init_skip_offsets() { const auto word_cnt = this->data_.size(); offsets_.reserve((word_cnt + (_skip_distance - 1)) / _skip_distance); std::size_t i = 0; if (word_cnt > 1) { for (std::size_t word_idx = 0; word_idx < word_cnt - 1; ++word_idx) { if (word_idx % _skip_distance == 0) { offsets_.push_back(i); } const auto w = this->data_[word_idx]; i += super::is_fill_word(w) ? super::extract_fill_length(w) : super::payload_bit_cnt; } } if (offsets_.empty()) { offsets_.push_back(0); } } public: uah_skip() = default; explicit uah_skip(const boost::dynamic_bitset<$u32>& in) : super(in), offsets_() { init_skip_offsets(); } ~uah_skip() = default; uah_skip(const uah_skip& other) = default; uah_skip(uah_skip&& other) noexcept = default; uah_skip& operator=(const uah_skip& other) = default; uah_skip& operator=(uah_skip&& other) noexcept = default; /// Return the size in bytes. std::size_t __forceinline__ size_in_bytes() const { return super::size_in_bytes() + offsets_.size() * sizeof(u32); } static std::string name() { return "uah_skip" + std::to_string(super::word_bitlength); } /// Returns the value of the bit at the position pos. u1 __forceinline__ test(const std::size_t pos) const { std::size_t word_idx = 0; std::size_t i = 0; auto search = std::upper_bound(offsets_.begin(), offsets_.end(), $u32(pos)); const std::size_t offset_idx = std::distance(offsets_.begin(), search) - 1; word_idx = offset_idx * _skip_distance; i = offsets_[offset_idx]; // Find the corresponding word. for (; word_idx < this->data_.size(); ++word_idx) { auto& w = this->data_[word_idx]; if (this->is_literal_word(w)) { if (pos >= i + super::payload_bit_cnt) { i += super::payload_bit_cnt; continue; } else { return dtl::bits::bit_test(w, pos - i + 1); // TODO optimize } } else { auto fill_len = this->extract_fill_length(w); if (pos >= i + fill_len) { i += fill_len; continue; } else { return this->extract_fill_value(w); } } } return false; } /// Try to reduce the memory consumption. This function is supposed to be /// called after the bitmap has been modified. __forceinline__ void shrink() { super::shrink(); offsets_.shrink_to_fit(); } //===--------------------------------------------------------------------===// /// 1-run iterator class iter { const uah_skip& outer_; std::size_t word_idx_; std::size_t in_word_idx_; //===------------------------------------------------------------------===// // Iterator state //===------------------------------------------------------------------===// /// Points to the beginning of a 1-run. $u64 pos_; /// The length of the current 1-run. $u64 length_; //===------------------------------------------------------------------===// public: explicit __forceinline__ iter(const uah_skip& outer) : outer_(outer), word_idx_(0), in_word_idx_(0), pos_(0), length_(0) { const auto word_cnt = outer_.data_.size(); word_type w; while (word_idx_ < word_cnt) { w = outer_.data_[word_idx_]; if (is_fill_word(w)) { if (extract_fill_value(w) == false) { pos_ += extract_fill_length(w); } else { length_ = extract_fill_length(w); in_word_idx_ = 0; break; } } else { const word_type payload = w >> 1; if (payload == 0) { pos_ += payload_bit_cnt; } else { const std::size_t b = dtl::bits::tz_count(payload); std::size_t e = b + 1; for (; e < payload_bit_cnt; ++e) { u1 is_set = dtl::bits::bit_test(payload, e); if (!is_set) break; } pos_ += b; length_ = e - b; in_word_idx_ = e; break; } } ++word_idx_; } if (word_idx_ == word_cnt) { pos_ = outer_.encoded_bitmap_length_; length_ = 0; } else { if (is_fill_word(w)) { ++word_idx_; in_word_idx_ = 0; } } } /// Forward the iterator to the next 1-run. void __forceinline__ next() { pos_ += length_; length_ = 0; const auto word_cnt = outer_.data_.size(); word_type w; while (word_idx_ < word_cnt) { w = outer_.data_[word_idx_]; if (is_fill_word(w)) { if (extract_fill_value(w) == false) { pos_ += extract_fill_length(w); } else { length_ = extract_fill_length(w); break; } } else { if (in_word_idx_ < payload_bit_cnt) { // TODO decode the entire literal word at once. const word_type payload = w >> (1 + in_word_idx_); if (payload == 0) { pos_ += payload_bit_cnt - in_word_idx_; } else { const std::size_t b = dtl::bits::tz_count(payload); std::size_t e = b + 1; for (; e < (payload_bit_cnt - in_word_idx_); ++e) { u1 is_set = dtl::bits::bit_test(payload, e); if (!is_set) break; } pos_ += b; length_ = e - b; in_word_idx_ += e; break; } } } ++word_idx_; in_word_idx_ = 0; } if (word_idx_ == word_cnt) { pos_ = outer_.encoded_bitmap_length_; length_ = 0; } else { if (is_fill_word(w)) { ++word_idx_; in_word_idx_ = 0; } } } /// Forward the iterator to the desired position. void __forceinline__ skip_to(const std::size_t to_pos) { assert(pos_ <= to_pos); if (to_pos >= outer_.encoded_bitmap_length_) { pos_ = outer_.encoded_bitmap_length_; length_ = 0; return; } // Skip close to the desired position. auto search = std::upper_bound( outer_.offsets_.begin(), outer_.offsets_.end(), $u32(to_pos)); const std::size_t offset_idx = std::distance(outer_.offsets_.begin(), search) - 1; word_idx_ = offset_idx * _skip_distance; in_word_idx_ = 0; pos_ = outer_.offsets_[offset_idx]; length_ = 0; // Call next until the desired position has been reached. while (!end() && pos() + length() <= to_pos) { next(); } // Adjust the current position and run length. if (!end() && pos() < to_pos) { length_ -= to_pos - pos_; pos_ = to_pos; } } u1 __forceinline__ end() const noexcept { return pos_ >= outer_.encoded_bitmap_length_; } u64 __forceinline__ pos() const noexcept { return pos_; } u64 __forceinline__ length() const noexcept { return length_; } }; //===--------------------------------------------------------------------===// using skip_iter_type = iter; using scan_iter_type = iter; /// Returns a 1-run iterator. skip_iter_type __forceinline__ it() const { return skip_iter_type(*this); } /// Returns a 1-run iterator. scan_iter_type __forceinline__ scan_it() const { return scan_iter_type(*this); } /// Returns the name of the instance including the most important parameters /// in JSON. std::string info() const { return "{\"name\":\"" + name() + "\"" + ",\"n\":" + std::to_string(this->size()) + ",\"size\":" + std::to_string(size_in_bytes()) + ",\"word_size\":" + std::to_string(sizeof(_word_type)) + ",\"skip_distance\":" + std::to_string(_skip_distance) + ",\"skip_offsets_size\":" + std::to_string(offsets_.size() * sizeof($u32)) + "}"; } // For debugging purposes. void print(std::ostream& os) const { super::print(os); os << " idx | offset " << std::endl; for (std::size_t i = 0; i < offsets_.size(); ++i) { os << std::setw(8) << i << " | "; os << std::setw(8) << offsets_[i]; os << std::endl; } } }; //===----------------------------------------------------------------------===// /// UAH compressed representation of a bitmap of length N using 8-bit words. using uah8_skip = uah_skip<u8>; /// UAH compressed representation of a bitmap of length N using 16-bit words. using uah16_skip = uah_skip<u16>; /// UAH compressed representation of a bitmap of length N using 32-bit words. using uah32_skip = uah_skip<u32>; /// UAH compressed representation of a bitmap of length N using 64-bit words. using uah64_skip = uah_skip<u64>; //===----------------------------------------------------------------------===// } // namespace dtl
29.30791
95
0.525783
harald-lang
54c0c3aeee1752643ec38d00020ae44d6ee4a79f
325
cpp
C++
All_code/73.cpp
jnvshubham7/cpp-programming
7d00f4a3b97b9308e337c5d3547fd3edd47c5e0b
[ "Apache-2.0" ]
1
2021-12-22T12:37:36.000Z
2021-12-22T12:37:36.000Z
All_code/73.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
All_code/73.cpp
jnvshubham7/CPP_Programming
a17c4a42209556495302ca305b7c3026df064041
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int N; cin>>N; for(int i=0;i<N;i++){ cin>>i; if(i%2!=0){ cout<<i<<" "<<endl; } } // YOUR CODE GOES HERE return 0; }
12.5
38
0.443077
jnvshubham7
54c35c93dac2804d9b04f7392759251ee6147a8d
654
hpp
C++
source/parser/parser_content.hpp
octopus-prime/hessian_x3
f0cf0f7a334efb8ba434ac87370814561e033ea0
[ "BSL-1.0" ]
3
2016-12-10T15:01:11.000Z
2019-11-25T14:03:49.000Z
source/parser/parser_content.hpp
octopus-prime/hessian_x3
f0cf0f7a334efb8ba434ac87370814561e033ea0
[ "BSL-1.0" ]
null
null
null
source/parser/parser_content.hpp
octopus-prime/hessian_x3
f0cf0f7a334efb8ba434ac87370814561e033ea0
[ "BSL-1.0" ]
null
null
null
/* * parser_content.hpp * * Created on: 25.02.2016 * Author: mike_gresens */ #pragma once using namespace std::literals; namespace hessian { namespace parser { namespace content { const x3::rule<class content_rule, content_t> content_rule; const x3::rule<class reply_rule, reply_t> reply_rule; const x3::rule<class fault_rule, fault_t> fault_rule; const auto content_rule_def = x3::lit("H\x02\x00"s) >> (reply_rule | fault_rule); const auto reply_rule_def = x3::lit('R') >> value_rule; const auto fault_rule_def = x3::lit('F') >> map_rule; BOOST_SPIRIT_DEFINE(content_rule, reply_rule, fault_rule); } using content::content_rule; } }
20.4375
81
0.730887
octopus-prime
54c36342fc5f6ea3a2409e052aebff2f11da5f12
6,164
cpp
C++
indra/newview/fsmoneytracker.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/fsmoneytracker.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/fsmoneytracker.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file fsmoneytracker.cpp * @brief Tip Tracker Window * * $LicenseInfo:firstyear=2011&license=viewerlgpl$ * Copyright (c) 2011 Arrehn Oberlander * Copyright (c) 2015 Ansariel Hiller * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * The Phoenix Firestorm Project, Inc., 1831 Oakwood Drive, Fairmont, Minnesota 56031-3225 USA * http://www.firestormviewer.org * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "fsmoneytracker.h" #include "llclipboard.h" #include "llfloaterreg.h" #include "llnamelistctrl.h" #include "lltextbox.h" #include "lltrans.h" #include "llviewercontrol.h" FSMoneyTracker::FSMoneyTracker(const LLSD& key) : LLFloater(key), mAmountPaid(0), mAmountReceived(0) { } BOOL FSMoneyTracker::postBuild() { mSummary = getChild<LLTextBox>("summary"); mTransactionHistory = getChild<LLNameListCtrl>("payment_list"); mTransactionHistory->setContextMenu(&gFSMoneyTrackerListMenu); clear(); // Button Actions childSetAction("Clear", boost::bind(&FSMoneyTracker::clear, this)); return TRUE; } void FSMoneyTracker::onClose(bool app_quitting) { if (!gSavedSettings.getBOOL("FSAlwaysTrackPayments")) { clear(); } } void FSMoneyTracker::addPayment(const LLUUID other_id, bool is_group, S32 amount, bool incoming) { time_t utc_time = time_corrected(); S32 scroll_pos = mTransactionHistory->getScrollPos(); bool at_end = mTransactionHistory->getScrollbar()->isAtEnd(); LLNameListCtrl::NameItem item_params; item_params.value = other_id; item_params.name = LLTrans::getString("AvatarNameWaiting"); item_params.target = is_group ? LLNameListCtrl::GROUP : LLNameListCtrl::INDIVIDUAL; item_params.columns.add().column("time").value(getTime(utc_time)); item_params.columns.add().column("name"); item_params.columns.add().column("amount") .value((incoming ? amount : -amount)) .color(LLUIColorTable::instance().getColor((incoming ? "MoneyTrackerIncrease" : "MoneyTrackerDecrease"))); item_params.columns.add().column("time_sort_column").value(getDate(utc_time)); mTransactionHistory->addNameItemRow(item_params); if (at_end) { mTransactionHistory->setScrollPos(scroll_pos + 1); } if (incoming) { mAmountReceived += amount; mSummary->setTextArg("RECEIVED", llformat("%d", mAmountReceived)); } else { mAmountPaid += amount; mSummary->setTextArg("PAID", llformat("%d", mAmountPaid)); } } std::string FSMoneyTracker::getTime(time_t utc_time) { std::string timeStr = "[" + LLTrans::getString("TimeHour") + "]:[" + LLTrans::getString("TimeMin") + "]:[" + LLTrans::getString("TimeSec") + "]"; LLSD substitution; substitution["datetime"] = (S32)utc_time; LLStringUtil::format(timeStr, substitution); return timeStr; } std::string FSMoneyTracker::getDate(time_t utc_time) { LLDate curdate = LLDate(utc_time); return curdate.asString(); } void FSMoneyTracker::clear() { LL_INFOS() << "Cleared." << LL_ENDL; mAmountPaid = 0; mAmountReceived = 0; mTransactionHistory->clearRows(); mSummary->setTextArg("RECEIVED", llformat("%d", mAmountReceived)); mSummary->setTextArg("PAID", llformat("%d", mAmountPaid)); } ////////////////////////////////////////////////////////////////////////////// // FSMoneyTrackerListMenu ////////////////////////////////////////////////////////////////////////////// LLContextMenu* FSMoneyTrackerListMenu::createMenu() { LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar; LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar; registrar.add("MoneyTrackerList.Action", boost::bind(&FSMoneyTrackerListMenu::onContextMenuItemClick, this, _2)); enable_registrar.add("MoneyTrackerList.Enable", boost::bind(&FSMoneyTrackerListMenu::onContextMenuItemEnable, this, _2)); return createFromFile("menu_fs_moneytracker_list.xml"); } void FSMoneyTrackerListMenu::onContextMenuItemClick(const LLSD& userdata) { std::string option = userdata.asString(); if (option == "copy") { FSMoneyTracker* floater = LLFloaterReg::findTypedInstance<FSMoneyTracker>("money_tracker"); if (floater) { std::string copy_text; LLNameListCtrl* list = floater->getChild<LLNameListCtrl>("payment_list"); std::vector<LLScrollListItem*> selected = list->getAllSelected(); for (std::vector<LLScrollListItem*>::iterator it = selected.begin(); it != selected.end(); ++it) { const LLScrollListItem* item = *it; copy_text += ( (copy_text.empty() ? "" : "\n") + item->getColumn(0)->getValue().asString() + ";" + item->getColumn(1)->getValue().asString() + ";" + item->getColumn(2)->getValue().asString() ); } if (!copy_text.empty()) { LLClipboard::instance().copyToClipboard(utf8str_to_wstring(copy_text), 0, copy_text.size() ); } } } else if (option == "delete") { FSMoneyTracker* floater = LLFloaterReg::findTypedInstance<FSMoneyTracker>("money_tracker"); if (floater) { LLNameListCtrl* list = floater->getChild<LLNameListCtrl>("payment_list"); list->operateOnSelection(LLCtrlListInterface::OP_DELETE); } } } bool FSMoneyTrackerListMenu::onContextMenuItemEnable(const LLSD& userdata) { std::string item = userdata.asString(); if (item == "can_copy" || item == "can_delete") { FSMoneyTracker* floater = LLFloaterReg::findTypedInstance<FSMoneyTracker>("money_tracker"); if (floater) { LLNameListCtrl* list = floater->getChild<LLNameListCtrl>("payment_list"); return (list->getNumSelected() > 0); } } return false; } FSMoneyTrackerListMenu gFSMoneyTrackerListMenu;
30.215686
146
0.711551
SaladDais
54c45bc46cce1b65b021b01bfa42d8b83b5c86cf
10,722
cpp
C++
src/mod/visualize/flamethrower.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
7
2021-03-02T02:27:18.000Z
2022-02-18T00:56:28.000Z
src/mod/visualize/flamethrower.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
3
2021-11-29T15:53:02.000Z
2022-02-21T13:09:22.000Z
src/mod/visualize/flamethrower.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2021-03-04T20:26:11.000Z
2021-11-26T07:09:24.000Z
#include "mod.h" #include "stub/entities.h" #include "stub/tfplayer.h" // adapted from Debug:Flamethrower_Mojo namespace Mod::Visualize::Flamethrower { Color RainbowGenerator() { static long i = 0; switch ((i++) % 8) { case 0: return Color(0xff, 0x00, 0x00, 0xff); // red case 1: return Color(0xff, 0x80, 0x00, 0xff); // orange case 2: return Color(0xff, 0xff, 0x00, 0xff); // yellow case 3: return Color(0x00, 0xff, 0x00, 0xff); // green case 4: return Color(0x00, 0xff, 0xff, 0xff); // cyan case 5: return Color(0x00, 0x00, 0xff, 0xff); // blue case 6: return Color(0x80, 0x00, 0xff, 0xff); // violet case 7: return Color(0xff, 0x00, 0xff, 0xff); // magenta default: return Color(0x00, 0x00, 0x00, 0x00); // black } } Color MakeColorLighter(Color c) { c[0] += (0xff - c[0]) / 2; c[1] += (0xff - c[1]) / 2; c[2] += (0xff - c[2]) / 2; return c; } struct FlameInfo { FlameInfo(CTFFlameEntity *flame) { init_origin = flame->GetAbsOrigin(); init_curtime = gpGlobals->curtime; init_realtime = Plat_FloatTime(); init_tick = gpGlobals->tickcount; // col = RainbowGenerator(); // // CBaseEntity *flamethrower = flame->GetOwnerEntity(); // if (flamethrower != nullptr) { // CTFPlayer *player = ToTFPlayer(flamethrower->GetOwnerEntity()); // if (player != nullptr) { // // // if (player->IsMiniBoss()) { // // } else { // // } // // // } // } col = Color(0xff, 0xff, 0xff, 0xff); col_lt = MakeColorLighter(col); num_thinks = 0; missed_thinks = 0; hit_an_entity = false; spawned_this_tick = true; thought_this_tick = false; removed_this_tick = false; } FlameInfo(const FlameInfo&) = delete; Vector init_origin; float init_curtime; float init_realtime; int init_tick; Color col; Color col_lt; int num_thinks; int missed_thinks; bool hit_an_entity; bool spawned_this_tick; bool thought_this_tick; bool removed_this_tick; }; std::map<CHandle<CBaseEntity>, FlameInfo> flames; std::vector<decltype(flames)::iterator> dead_flames; DETOUR_DECL_STATIC(CTFFlameEntity *, CTFFlameEntity_Create, const Vector& origin, const QAngle& angles, CBaseEntity *owner, float f1, int i1, float f2, bool b1, bool b2) { auto result = DETOUR_STATIC_CALL(CTFFlameEntity_Create)(origin, angles, owner, f1, i1, f2, b1, b2); if (result != nullptr) { flames.emplace(std::make_pair(result, result)); } return result; } ConVar cvar_dead_flame_duration("sig_visualize_flamethrower_dead_flame_duration", "1.0", FCVAR_NOTIFY, "Visualization: How long to show boxes for flame entities after they've been removed"); DETOUR_DECL_MEMBER(void, CTFFlameEntity_RemoveFlame) { auto flame = reinterpret_cast<CTFFlameEntity *>(this); auto it = flames.find(flame); if (it != flames.end()) { FlameInfo& info = (*it).second; const Vector& pos_start = info.init_origin; const Vector& pos_end = flame->GetAbsOrigin(); float dist = (pos_end - pos_start).Length(); int delta_tick = gpGlobals->tickcount - info.init_tick; float delta_curtime = gpGlobals->curtime - info.init_curtime; float delta_realtime = Plat_FloatTime() - info.init_realtime; // NDebugOverlay::EntityTextAtPosition(pos_end, 0, CFmtStrN<64>("%.0f", dist), cvar_dead_flame_duration.GetFloat(), 0xff, 0xff, 0xff, 0xff); // NDebugOverlay::EntityTextAtPosition(pos_end, 0, CFmtStrN<64>("%dt", delta_tick), cvar_dead_flame_duration.GetFloat(), 0xff, 0xff, 0xff, 0xff); // NDebugOverlay::EntityTextAtPosition(pos_end, 1, CFmtStrN<64>("%.3fs", delta_realtime), cvar_dead_flame_duration.GetFloat(), 0xff, 0xff, 0xff, 0xff); NDebugOverlay::EntityBounds(flame, 0xff, 0xff, 0xff, 0x10, cvar_dead_flame_duration.GetFloat()); // NDebugOverlay::Cross3D(flame->WorldSpaceCenter(), 3.0f, 0xff, 0xff, 0xff, false, cvar_dead_flame_duration.GetFloat()); info.removed_this_tick = true; dead_flames.push_back(it); } // DevMsg("[CTFFlameEntity::RemoveFlame] [%+6.1f %+6.1f %+6.1f]\n", // flame->GetAbsOrigin().x, flame->GetAbsOrigin().y, flame->GetAbsOrigin().z); DETOUR_MEMBER_CALL(CTFFlameEntity_RemoveFlame)(); } DETOUR_DECL_MEMBER(void, CTFFlameEntity_FlameThink) { auto flame = reinterpret_cast<CTFFlameEntity *>(this); auto it = flames.find(flame); if (it != flames.end()) { FlameInfo& info = (*it).second; info.thought_this_tick = true; int num_thinks = info.num_thinks++; } DETOUR_MEMBER_CALL(CTFFlameEntity_FlameThink)(); } DETOUR_DECL_MEMBER(void, CTFFlameEntity_OnCollide, CBaseEntity *pOther) { auto flame = reinterpret_cast<CTFFlameEntity *>(this); auto it = flames.find(flame); if (it != flames.end()) { FlameInfo& info = (*it).second; info.hit_an_entity = true; // NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), -2, "HIT", 0.10f, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } DETOUR_MEMBER_CALL(CTFFlameEntity_OnCollide)(pOther); } ConVar cvar_show_thinks("sig_visualize_flamethrower_show_thinks", "0", FCVAR_NOTIFY, "Visualization: show think overlays on active flame entities"); void PostThink_DrawFlames() { for (int i = 0; i < ITFFlameEntityAutoList::AutoList().Count(); ++i) { auto flame = rtti_cast<CTFFlameEntity *>(ITFFlameEntityAutoList::AutoList()[i]); if (flame == nullptr) continue; auto it = flames.find(flame); if (it != flames.end()) { FlameInfo& info = (*it).second; NDebugOverlay::EntityBounds(flame, info.col.r(), info.col.g(), info.col.b(), 0x10, gpGlobals->interval_per_tick); // NDebugOverlay::Cross3D(flame->WorldSpaceCenter(), 3.0f, 0xff, 0xff, 0xff, false, gpGlobals->interval_per_tick); if (cvar_show_thinks.GetBool()) { if (info.thought_this_tick) { NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), -1, "THINK", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), 0, CFmtStrN<64>("#%d", info.num_thinks), gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } else { if (info.spawned_this_tick) { NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), -1, "SPAWN", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } else if (info.removed_this_tick) { NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), -1, "DEAD", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } else { ++info.missed_thinks; NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), -1, "MISSED", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), 0, "THINK!", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } } if (info.missed_thinks != 0) { NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), 5, CFmtStrN<64>("%d MISSED", info.missed_thinks), gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); NDebugOverlay::EntityTextAtPosition(flame->WorldSpaceCenter(), 6, "THINKS!!", gpGlobals->interval_per_tick, info.col_lt.r(), info.col_lt.g(), info.col_lt.b(), 0xff); } } } } } void PostThink_PyroOverlay() { static CountdownTimer ctPyroOverlay; if (ctPyroOverlay.IsElapsed()) { ctPyroOverlay.Start(1.00f); for (int i = 1; i <= gpGlobals->maxClients; ++i) { CTFPlayer *player = ToTFPlayer(UTIL_PlayerByIndex(i)); if (player == nullptr) continue; if (player->IsPlayerClass(TF_CLASS_PYRO)) { NDebugOverlay::EntityBounds(player, 0xff, 0xff, 0xff, 0x00, 1.00f); Vector vecFwd; player->EyeVectors(&vecFwd); Vector vecStart = player->EyePosition() + Vector(0.0f, 0.0f, 50.0f); vecFwd.z = 0.0f; vecFwd.NormalizeInPlace(); // NDebugOverlay::Line(vecStart, vecStart + (1000.0f * vecFwd), 0x80, 0x80, 0x80, true, 1.00f); NDebugOverlay::EntityTextAtPosition(vecStart + (-30.0f * vecFwd) + Vector(0.0f, 0.0f, 15.0f), 0, "HAMMER", 1.00f, 0xc0, 0xc0, 0xc0, 0xff); NDebugOverlay::EntityTextAtPosition(vecStart + (-30.0f * vecFwd) + Vector(0.0f, 0.0f, 15.0f), 1, " UNITS", 1.00f, 0xc0, 0xc0, 0xc0, 0xff); for (float x = 0.0f; x <= 1000.0f; x += 50.0f) { Vector vecHash1 = vecStart + (x * vecFwd) + Vector(0.0f, 0.0f, 10.0f); Vector vecHash2 = vecStart + (x * vecFwd) + Vector(0.0f, 0.0f, -50.0f); Vector vecHash3 = vecStart + ((x - 3.0f) * vecFwd) + Vector(0.0f, 0.0f, 15.0f); NDebugOverlay::Line(vecHash1, vecHash2, 0x80, 0x80, 0x80, true, 1.00f); NDebugOverlay::EntityTextAtPosition(vecHash3, 0, CFmtStrN<64>("%.0f", x), 1.00f, 0xc0, 0xc0, 0xc0, 0xff); } } } } } class CMod : public IMod, public IFrameUpdatePostEntityThinkListener, public IFrameUpdatePreEntityThinkListener { public: CMod() : IMod("Visualize:Flamethrower") { MOD_ADD_DETOUR_STATIC(CTFFlameEntity_Create, "CTFFlameEntity::Create"); MOD_ADD_DETOUR_MEMBER(CTFFlameEntity_RemoveFlame, "CTFFlameEntity::RemoveFlame"); MOD_ADD_DETOUR_MEMBER(CTFFlameEntity_FlameThink, "CTFFlameEntity::FlameThink"); MOD_ADD_DETOUR_MEMBER(CTFFlameEntity_OnCollide, "CTFFlameEntity::OnCollide"); } virtual bool ShouldReceiveCallbacks() const override { return this->IsEnabled(); } virtual void FrameUpdatePreEntityThink() override { for (auto& pair : flames) { pair.second.spawned_this_tick = false; pair.second.thought_this_tick = false; } } virtual void FrameUpdatePostEntityThink() override { PostThink_DrawFlames(); // PostThink_PyroOverlay(); for (auto it : dead_flames) { flames.erase(it); } dead_flames.clear(); } }; CMod s_Mod; ConVar cvar_enable("sig_visualize_flamethrower", "0", FCVAR_NOTIFY, "Visualization: show flame entity boxes, distances, etc.", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); }
34.475884
207
0.650159
fugueinheels
54c5674d3497c353587118936250be8331eb1d14
3,785
cpp
C++
src/blinkit/blink/renderer/core/loader/CookieJar.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
13
2020-04-21T13:14:00.000Z
2021-11-13T14:55:12.000Z
src/blinkit/blink/renderer/core/loader/CookieJar.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
null
null
null
src/blinkit/blink/renderer/core/loader/CookieJar.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
4
2020-04-21T13:15:43.000Z
2021-11-13T14:55:00.000Z
// ------------------------------------------------- // BlinKit - BlinKit Library // ------------------------------------------------- // File Name: CookieJar.cpp // Description: CookieJar Class // Author: Ziming Li // Created: 2021-07-26 // ------------------------------------------------- // Copyright (C) 2021 MingYang Software Technology. // ------------------------------------------------- /* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "core/loader/CookieJar.h" #include "core/dom/Document.h" #include "core/frame/LocalFrame.h" #include "core/loader/FrameLoaderClient.h" #include "public/platform/Platform.h" #if 0 // BKTODO: #include "public/platform/WebCookieJar.h" #include "public/platform/WebURL.h" #endif #ifdef BLINKIT_CRAWLER_ENABLED # include "blinkit/crawler/crawler_impl.h" #endif namespace blink { static WebCookieJar* toCookieJar(const Document* document) { if (!document || !document->frame()) return 0; ASSERT(false); // BKTODO: return document->frame()->loader().client()->cookieJar(); return nullptr; } String cookies(const Document* document, const KURL& url) { WebCookieJar* cookieJar = toCookieJar(document); if (!cookieJar) return String(); ASSERT(false); // BKTODO: return cookieJar->cookies(url, document->firstPartyForCookies()); return String(); } void setCookies(Document* document, const KURL& url, const String& cookieString) { WebCookieJar* cookieJar = toCookieJar(document); if (!cookieJar) return; ASSERT(false); // BKTODO: cookieJar->setCookie(url, document->firstPartyForCookies(), cookieString); } bool cookiesEnabled(const Document *document) { #ifdef BLINKIT_CRAWLER_ENABLED if (document->isCrawlerNode()) { CrawlerImpl *crawler = CrawlerImpl::From(*document); if (nullptr != crawler->GetCookieJar(false)) return true; } #endif return false; } String cookieRequestHeaderFieldValue(const Document* document, const KURL& url) { WebCookieJar* cookieJar = toCookieJar(document); if (!cookieJar) return String(); ASSERT(false); // BKTODO: return cookieJar->cookieRequestHeaderFieldValue(url, document->firstPartyForCookies()); return String(); } } // namespace blink
36.047619
117
0.689828
titilima
54c5714add2bb96b302e54b6841d006eb13a76f3
1,412
cpp
C++
Talg/Test/testErase.cpp
doside/Tiny-C---Template-Algorithm-Library
9aea047659fedb273abca960b8501a4297829a2b
[ "MIT" ]
null
null
null
Talg/Test/testErase.cpp
doside/Tiny-C---Template-Algorithm-Library
9aea047659fedb273abca960b8501a4297829a2b
[ "MIT" ]
null
null
null
Talg/Test/testErase.cpp
doside/Tiny-C---Template-Algorithm-Library
9aea047659fedb273abca960b8501a4297829a2b
[ "MIT" ]
null
null
null
#include <Talg/core.h> #include "test_suits.h" #include <tuple> #include <Talg/seqop.h> #include <Talg/find_val.h> using namespace Talg; namespace { void f() { testSame( Seq<int,double,char>, Reverse<std::tuple<char,double,int>>, Seq<int, int, int, int>, Erase_front<Seq<int, double, float>, Seq<int, int, int, int, int>>, Seq<int, double, float>, Erase_front<Seq<bool, char>, Seq<int, char, double, float>>, Seq<>, Erase_front<Seq<int, double>, Seq<int>>, Seq<float>, Erase_front<Seq<int, double>, std::tuple<float>>, Seq<int, int, int, int>, Erase_front_s<Seq<int, double, float>, Seq<int, int, int, int, int>>, Seq<int, double, float>, Erase_front_s<Seq<bool, char>, Seq<int, char, double, float>>, Seq<>, Erase_front_s<Seq<int, double>, Seq<int>>, Seq<float>, Erase_front_s<Seq<int, double>, Seq<float>>, Erase_back<Seq<int,double>,Seq<bool,bool,bool>>, Seq<bool, bool, bool>, Erase_back<Seq<int,double>, Seq<bool, bool, bool,double>>, Seq<bool, bool, bool>, Erase_back<Seq<int, double>, Seq<bool, bool, bool,int,double>>, Seq<bool, bool, bool>, Seq<char,char>, Erase_back<Seq<>,Seq<char,char>>, Seq<char>, Erase_back<Seq<char>,Seq<char,char>>, Seq<char>, Erase_back<Seq<>,Seq<char>>, Seq<int,float,int,double>, EraseAt_s<2,Seq<int,float,float,int,double>> ); } }
17.65
72
0.628187
doside
54c8d87c22a2d2d0f4c418b7e79e3135505f72d4
2,153
cpp
C++
src/mode/network_config.cpp
FissionAndFusion/FnFnMvWallet-Pre
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
[ "MIT" ]
22
2018-08-17T07:05:56.000Z
2019-09-16T09:22:32.000Z
src/mode/network_config.cpp
FissionAndFusion/FnFnMvWallet-Pre
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
[ "MIT" ]
23
2018-08-18T11:09:42.000Z
2019-04-22T10:02:02.000Z
src/mode/network_config.cpp
FissionAndFusion/FnFnMvWallet-Pre
80d3d5b2c6a4c25ebb6c25dc111bb65d7105d032
[ "MIT" ]
13
2018-08-17T01:12:58.000Z
2019-09-16T09:05:31.000Z
// Copyright (c) 2017-2019 The Multiverse developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "mode/network_config.h" #include "mode/config_macro.h" namespace multiverse { namespace po = boost::program_options; CMvNetworkConfig::CMvNetworkConfig() { po::options_description desc("LoMoNetwork"); CMvNetworkConfigOption::AddOptionsImpl(desc); AddOptions(desc); } CMvNetworkConfig::~CMvNetworkConfig() {} bool CMvNetworkConfig::PostLoad() { if (fHelp) { return true; } if (nPortInt <= 0 || nPortInt > 0xFFFF) { nPort = (fTestNet ? DEFAULT_TESTNET_P2PPORT : DEFAULT_P2PPORT); } else { nPort = (unsigned short)nPortInt; } nMaxOutBounds = DEFAULT_MAX_OUTBOUNDS; if (nMaxConnection <= DEFAULT_MAX_OUTBOUNDS) { nMaxInBounds = (fListen || fListen4 || fListen6) ? 1 : 0; } else { nMaxInBounds = nMaxConnection - DEFAULT_MAX_OUTBOUNDS; } if (nConnectTimeout == 0) { nConnectTimeout = 1; } if (!fTestNet) { // vDNSeed.push_back("118.193.83.220"); } if (nThreadNumber <= 0) { nThreadNumber = 1; } vector<uint8> vecMac; if (!walleve::GetAnIFMacAddress(vecMac)) { return false; } string strPath = pathRoot.string(); vecMac.insert(vecMac.end(), strPath.begin(), strPath.end()); uint256 seed = crypto::CryptoHash(&vecMac[0], vecMac.size()); crypto::CryptoImportKey(nodeKey, seed); return true; } std::string CMvNetworkConfig::ListConfig() const { std::ostringstream oss; oss << CMvNetworkConfigOption::ListConfigImpl(); oss << "port: " << nPort << "\n"; oss << "maxOutBounds: " << nMaxOutBounds << "\n"; oss << "maxInBounds: " << nMaxInBounds << "\n"; oss << "dnseed: "; for (auto& s: vDNSeed) { oss << s << " "; } oss << "\n"; return oss.str(); } std::string CMvNetworkConfig::Help() const { return CMvNetworkConfigOption::HelpImpl(); } } // namespace multiverse
21.53
71
0.619601
FissionAndFusion
54c9ef8bf0099d1ee734be0129b5affc826504eb
3,997
cc
C++
server/modules/routing/pinloki/gtid.cc
2733284198/MaxScale
b921dddbf06fcce650828ca94a3d715012b7072f
[ "BSD-3-Clause" ]
1
2020-10-29T07:39:00.000Z
2020-10-29T07:39:00.000Z
server/modules/routing/pinloki/gtid.cc
2733284198/MaxScale
b921dddbf06fcce650828ca94a3d715012b7072f
[ "BSD-3-Clause" ]
null
null
null
server/modules/routing/pinloki/gtid.cc
2733284198/MaxScale
b921dddbf06fcce650828ca94a3d715012b7072f
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2024-10-14 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #define BOOST_ERROR_CODE_HEADER_ONLY 1 #include "gtid.hh" #include <maxbase/string.hh> #include <maxscale/log.hh> #include <maxbase/log.hh> #include <boost/fusion/adapted/std_tuple.hpp> #include <boost/spirit/home/x3.hpp> #include <algorithm> #include <sstream> #include <mysql.h> #include <mariadb_rpl.h> #include <iostream> #include <iomanip> namespace maxsql { Gtid::Gtid(st_mariadb_gtid* mgtid) : m_domain_id(mgtid->domain_id) , m_server_id(mgtid->server_id) , m_sequence_nr(mgtid->sequence_nr) , m_is_valid(true) { } std::string Gtid::to_string() const { return MAKE_STR(m_domain_id << '-' << m_server_id << '-' << m_sequence_nr); } Gtid Gtid::from_string(const std::string& gtid_str) { if (gtid_str.empty()) { return Gtid(); } namespace x3 = boost::spirit::x3; const auto gtid_parser = x3::uint32 >> '-' >> x3::uint32 >> '-' >> x3::uint64; std::tuple<uint32_t, uint32_t, uint64_t> result; // intermediary to avoid boost-fusionizing Gtid. auto first = begin(gtid_str); auto success = parse(first, end(gtid_str), gtid_parser, result); if (success && first == end(gtid_str)) { return Gtid(result); } else { MXS_SERROR("Invalid gtid string: '" << gtid_str); return Gtid(); } } Gtid Gtid::previous() const { if (m_is_valid && m_sequence_nr > 1) { return Gtid(m_domain_id, m_server_id, m_sequence_nr - 1); } else { return Gtid(); } } std::ostream& operator<<(std::ostream& os, const Gtid& gtid) { os << gtid.to_string(); return os; } GtidList::GtidList(const std::vector<Gtid>&& gtids) : m_gtids(std::move(gtids)) { sort(); m_is_valid = std::all_of(begin(m_gtids), end(m_gtids), [](const Gtid& gtid) { return gtid.is_valid(); }); } void GtidList::clear() { m_gtids.clear(); m_is_valid = false; } void GtidList::replace(const Gtid& gtid) { auto ite = std::find_if(begin(m_gtids), end(m_gtids), [&gtid](const Gtid& rhs) { return gtid.domain_id() == rhs.domain_id(); }); if (ite != end(m_gtids) && ite->domain_id() == gtid.domain_id()) { *ite = gtid; } else { m_gtids.push_back(gtid); sort(); } m_is_valid = std::all_of(begin(m_gtids), end(m_gtids), [](const Gtid& gtid) { return gtid.is_valid(); }); } std::string GtidList::to_string() const { return maxbase::join(m_gtids); } GtidList GtidList::from_string(const std::string& str) { std::vector<Gtid> gvec; auto gtid_strs = maxbase::strtok(str, ","); for (auto& s : gtid_strs) { gvec.push_back(Gtid::from_string(s)); } return GtidList(std::move(gvec)); } void GtidList::sort() { std::sort(begin(m_gtids), end(m_gtids), [](const Gtid& lhs, const Gtid& rhs) { return lhs.domain_id() < rhs.domain_id(); }); } bool GtidList::is_included(const GtidList& other) const { for (const auto& gtid : other.gtids()) { auto it = std::find_if( m_gtids.begin(), m_gtids.end(), [&](const Gtid& g) { return g.domain_id() == gtid.domain_id(); }); if (it == m_gtids.end() || it->sequence_nr() < gtid.sequence_nr()) { return false; } } return true; } std::ostream& operator<<(std::ostream& os, const GtidList& lst) { os << lst.to_string(); return os; } }
22.84
104
0.585689
2733284198
54cb8da02e65d1ad7fa65c1d58dcd1114f576909
280
cpp
C++
cpcli/templates/template.cpp
EricLiclair/CPCLI
0b03a5f07348c4522e06bd77d5579fa6321277ff
[ "MIT" ]
null
null
null
cpcli/templates/template.cpp
EricLiclair/CPCLI
0b03a5f07348c4522e06bd77d5579fa6321277ff
[ "MIT" ]
7
2021-12-21T10:50:28.000Z
2022-01-01T20:08:59.000Z
cpcli/templates/template.cpp
EricLiclair/CPCLI
0b03a5f07348c4522e06bd77d5579fa6321277ff
[ "MIT" ]
1
2022-03-31T10:34:27.000Z
2022-03-31T10:34:27.000Z
#include <bits/stdc++.h> typedef long long ll; using namespace std; int main() { cout << "[Algorithm Name] - Algorithm for [Algorithm Usage]\n" << "Time Complexity - O(1)\n" << "Space Complexity - O(1)\n" << "Ref Link - [LINK]\n"; return 0; }
20
66
0.553571
EricLiclair
54cdc3fc3d06c3b29ac643bc6f2e9d4e57758dbd
19,734
cpp
C++
src/gse/src/gs_serializer.cpp
RichLogan/gse
9243166142d8f1500df13b57ca0985105d334d83
[ "BSD-2-Clause" ]
null
null
null
src/gse/src/gs_serializer.cpp
RichLogan/gse
9243166142d8f1500df13b57ca0985105d334d83
[ "BSD-2-Clause" ]
null
null
null
src/gse/src/gs_serializer.cpp
RichLogan/gse
9243166142d8f1500df13b57ca0985105d334d83
[ "BSD-2-Clause" ]
1
2022-03-28T15:37:40.000Z
2022-03-28T15:37:40.000Z
/* * gs_serializer.cpp * * Copyright (C) 2022 * Cisco Systems, Inc. * All Rights Reserved * * Description: * The Game State Serializer is an object used by the Game State Encoder * to serialize data into a given buffer. * * Portability Issues: * The C++ float and double types are assumed to be implemented following * IEEE-754 specification. * * License: * BSD 2-Clause License * * Copyright (c) 2022, Cisco Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstring> #include "gs_serializer.h" #include "half_float.h" namespace gs { /* * Serializer::Write * * Description: * This function will write the unsigned integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Uint8 value) const { if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); return sizeof(Uint8); } /* * Serializer::Write * * Description: * This function will write the unsigned integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Uint16 value) const { if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); return sizeof(Uint16); } /* * Serializer::Write * * Description: * This function will write the unsigned integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Uint32 value) const { if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); return sizeof(Uint32); } /* * Serializer::Write * * Description: * This function will write the unsigned integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Uint64 value) const { if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); return sizeof(Uint64); } /* * Serializer::Write * * Description: * This function will write the signed integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Int8 value) const { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<Uint8>(value)); } return sizeof(Int8); } /* * Serializer::Write * * Description: * This function will write the signed integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Int16 value) const { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<Uint16>(value)); } return sizeof(Int16); } /* * Serializer::Write * * Description: * This function will write the signed integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Int32 value) const { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<Uint32>(value)); } return sizeof(Int32); } /* * Serializer::Write * * Description: * This function will write the signed integer of fixed-size to * the data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The unsigned integer value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Int64 value) const { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<Uint64>(value)); } return sizeof(Int64); } /* * Serializer::WriteVarUint * * Description: * This function will write the unsigned integer as a variable-length * integer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The 64-bit VarUint value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * VarUint is encoded as follows: * [a] 0b + 7 bits for unsigned integer in the range 0 to 127 * [b] 10b + 14 bits for unsigned integer in the range 0 to 16383 * [c] 110b + 21 bits for unsigned integer 0 to 2097151 * [d] 11100001b + 4 octets for a 32-bit unsigned integer * [e] 11100010b + 8 octets for a 64-bit unsigned integer */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, const VarUint &value) const { // [a] Produce a 7-bit unsigned integer if (value.value <= 0x7f) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(value.value)); } return sizeof(std::uint8_t); } // [b] Produce a 14-bit unsigned integer if (value.value <= 0x3fff) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue( static_cast<std::uint16_t>(value.value | 0x8000)); } return sizeof(std::uint16_t); } // [c] Produce a 21-bit unsigned integer if (value.value <= 0x001f'ffff) { std::uint32_t i = static_cast<std::uint32_t>(value.value) | 0x00c0'0000; if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(i >> 16)); data_buffer.AppendValue(static_cast<std::uint16_t>(i & 0xffff)); } return sizeof(std::uint8_t) + sizeof(std::uint16_t); } // [d] Prduce a 32-bit unsigned integer if (value.value <= 0xffff'ffff) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(0b1110'0001)); data_buffer.AppendValue(static_cast<std::uint32_t>(value.value)); } return sizeof(std::uint8_t) + sizeof(std::uint32_t); } // [e] Produce a 64-bit unsigned integer if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(0b1110'0010)); data_buffer.AppendValue(static_cast<std::uint64_t>(value.value)); } return sizeof(std::uint8_t) + sizeof(std::uint64_t); } /* * Serializer::WriteVarInt * * Description: * This function will write the signed integer as a variable-length * integer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The 64-bit VarInt value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * VarInt is encoded as follows: * [a] 0b + 7 bits for signed integer in the range -64 to +63 * [b] 10b + 14 bits for signed integer in the range -8192 to 8191 * [c] 110b + 21 bits for signed integer -1048576 to 1048575 * [d] 11100001b + 4 octets for a 32-bit signed integer * [e] 11100010b + 8 octets for a 64-bit signed integer */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, const VarInt &value) const { // [a] Produce a 7-bit signed integer if (((value.value & 0xffff'ffff'ffff'ffc0) == 0xffff'ffff'ffff'ffc0) || ((value.value & 0xffff'ffff'ffff'ffc0) == 0x0000'0000'0000'0000)) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue( static_cast<std::uint8_t>(value.value & 0x7f)); } return sizeof(std::uint8_t); } // [b] Produce a 14-bit signed integer if (((value.value & 0xffff'ffff'ffff'e000) == 0xffff'ffff'ffff'e000) || ((value.value & 0xffff'ffff'ffff'e000) == 0x0000'0000'0000'0000)) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue( static_cast<std::uint16_t>((value.value & 0x3fff) | 0x8000)); } return sizeof(std::uint16_t); } // [c] Produce a 21-bit signed integer if (((value.value & 0xffff'ffff'fff0'0000) == 0xffff'ffff'fff0'0000) || ((value.value & 0xffff'ffff'fff0'0000) == 0x0000'0000'0000'0000)) { if (data_buffer.GetBufferSize()) { std::uint32_t i = (value.value & 0x001f'ffff) | 0x00c0'0000; data_buffer.AppendValue(static_cast<std::uint8_t>(i >> 16)); data_buffer.AppendValue(static_cast<std::uint16_t>(i & 0xffff)); } return sizeof(std::uint8_t) + sizeof(std::uint16_t); } // [d] Prduce a 32-bit signed integer if (((value.value & 0xffff'ffff'8000'0000) == 0xffff'ffff'8000'0000) || ((value.value & 0xffff'ffff'8000'0000) == 0x0000'0000'0000'0000)) { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(0b1110'0001)); data_buffer.AppendValue( static_cast<std::uint32_t>(value.value & 0xffff'ffff)); } return sizeof(std::uint8_t) + sizeof(std::uint32_t); } // [e] Produce a 64-bit signed integer if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(static_cast<std::uint8_t>(0b1110'0010)); data_buffer.AppendValue(static_cast<std::uint64_t>(value.value)); } return sizeof(std::uint8_t) + sizeof(std::uint64_t); } /* * Serializer::Write * * Description: * This function will take a 32-bit floating point value and serialize it * as a 16-bit half floating point value per IEEE 754 at the end of the * given data buffer. See * https://en.wikipedia.org/wiki/Half-precision_floating-point_format. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The floating point value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, const Float16 &value) const { if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(FloatToHalfFloat(value.value)); } return sizeof(std::uint16_t); } /* * Serializer::Write * * Description: * This function will take a 32-bit floating point value and serialize it * at the end of the given data buffer. The floating point value is * assumed to conform to IEEE 754. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The single-precision floating point value to write to the data * buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Float32 value) const { static_assert(sizeof(value) == 4, "expected Float32 to be 32 bits"); if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(value); } return sizeof(std::uint32_t); } /* * Serializer::Write * * Description: * This function will take a 64-bit floating point value and serialize it * at the end of the given data buffer. The floating point value is * assumed to conform to IEEE 754. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The double-precision floating point value to write to the data * buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Float64 value) const { static_assert(sizeof(value) == 8, "expected Float64 to be 64 bits"); if (data_buffer.GetBufferSize()) { data_buffer.AppendValue(value); } return sizeof(std::uint64_t); } /* * Serializer::Write * * Description: * This function will write a Boolean value to the end of the specified * data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The Boolean value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, Boolean value) const { if (data_buffer.GetBufferSize()) { if (value) { data_buffer.AppendValue(static_cast<std::uint8_t>(1)); } else { data_buffer.AppendValue(static_cast<std::uint8_t>(0)); } } return sizeof(std::uint8_t); } /* * Write * * Description: * This function will write a String to the end of the specified data * buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The String value to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, const String &value) const { std::size_t total_length{}; // Write out the buffer length as a VarUint total_length = Write(data_buffer, VarUint{value.size()}); // If the string is empty, just return if (value.empty()) return total_length; // Write out the actual string content if there is a string if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); // Update the octet count total_length += value.length(); return total_length; } /* * Serializer::Write * * Description: * This function will write a vector of elements to the end of the * specified data buffer. * * Parameters: * data_buffer [in] * The data buffer into which the value shall be written. * * value [in] * The vector of values to write to the data buffer. * * Returns: * The number of octets appended to the data buffer or would have been * appended if the data_buffer contains a zero-sized buffer. * * Comments: * None. */ std::size_t Serializer::Write(DataBuffer<> &data_buffer, const Blob &value) const { std::size_t total_length{}; // Write out the number of Blob bytes that follow total_length = Write(data_buffer, VarUint{value.size()}); // If the string is empty, just return if (value.empty()) return total_length; // Write out the actual string content if there is a string if (data_buffer.GetBufferSize()) data_buffer.AppendValue(value); // Update the octet count total_length += value.size(); return total_length; } } // namespace gs
28.435159
80
0.631144
RichLogan
54ce006bcd60790abd004d54f9519e18031b5fed
2,098
cc
C++
tensorstore/index_space/dim_expression_nc_test.cc
stuarteberg/tensorstore
2c22a3c9f798b0fbf023031633c58cc7c644235d
[ "Apache-2.0" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/index_space/dim_expression_nc_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/index_space/dim_expression_nc_test.cc
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2020 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorstore/index.h" #include "tensorstore/index_space/dim_expression.h" #include "tensorstore/index_space/index_transform.h" #include "tensorstore/util/span.h" namespace { void NoOpTest() { tensorstore::Dims(0, 2) .TranslateBy(5)(tensorstore::IdentityTransform<3>()) .value(); EXPECT_NON_COMPILE( "no matching function", tensorstore::Dims(0, 2)(tensorstore::IdentityTransform<3>())); } void TranslateRankMismatchTest() { tensorstore::AllDims() .TranslateBy({5, 2})(tensorstore::IdentityTransform<2>()) .value(); EXPECT_NON_COMPILE("no matching function", tensorstore::AllDims().TranslateBy({5, 2})( tensorstore::IdentityTransform<3>())); } void DimensionSelectionRankMismatchTest() { tensorstore::Dims(0, 1, 2) .TranslateBy(5)(tensorstore::IdentityTransform<3>()) .value(); EXPECT_NON_COMPILE("no matching function", tensorstore::Dims(0, 1, 2).TranslateBy({5, 3, 2})( tensorstore::IdentityTransform<2>())); } void AddNewLabeledDimensions() { tensorstore::Dims(0).AddNew()(tensorstore::IdentityTransform({"x"})).value(); EXPECT_NON_COMPILE( "New dimensions must be specified by index.", tensorstore::Dims("x").AddNew()(tensorstore::IdentityTransform({"x"}))); } } // namespace int main() { NoOpTest(); TranslateRankMismatchTest(); DimensionSelectionRankMismatchTest(); AddNewLabeledDimensions(); }
30.852941
79
0.685415
stuarteberg
54ce01688c93bc76dcbc66d229cf6c5a6dd60dce
1,307
cpp
C++
7/E.cpp
CovarianceMomentum/dm-itmo
b87b65727d376895e23f9f2317c8e930dd420c5a
[ "MIT" ]
null
null
null
7/E.cpp
CovarianceMomentum/dm-itmo
b87b65727d376895e23f9f2317c8e930dd420c5a
[ "MIT" ]
null
null
null
7/E.cpp
CovarianceMomentum/dm-itmo
b87b65727d376895e23f9f2317c8e930dd420c5a
[ "MIT" ]
null
null
null
// // Created by covariance on 26.12.2020. // #include <bits/stdc++.h> using namespace std; unordered_set<bitset<20>> dependent; void bitmask_dfs(bitset<20> mask) { dependent.insert(mask); if (mask.count() != 20) { for (uint32_t i = 0; i != 20u; ++i) { if (!mask.test(i)) { mask.set(i); if (dependent.find(mask) == dependent.end()) { bitmask_dfs(mask); } mask.reset(i); } } } } int main() { #ifndef DEBUG freopen("cycles.in", "r", stdin); freopen("cycles.out", "w", stdout); #endif uint32_t n, m; cin >> n >> m; vector<pair<uint32_t, uint32_t>> weights(n); for (uint32_t i = 0; i != n; ++i) { cin >> weights[i].first; weights[i].second = i; } uint32_t cnt, tmp; bitset<20> set; while (m--) { set.reset(); cin >> cnt; while (cnt--) { cin >> tmp; set.set(tmp - 1); } bitmask_dfs(set); } sort(weights.begin(), weights.end()); set.reset(); uint32_t weight = 0; while (!weights.empty()) { weight += weights.rbegin()->first; set.set(weights.rbegin()->second); if (dependent.find(set) != dependent.end()) { weight -= weights.rbegin()->first; set.reset(weights.rbegin()->second); } weights.pop_back(); } cout << weight; return 0; }
19.80303
54
0.54935
CovarianceMomentum
54d08a888ae124a9b2fb0f7acdd84b2019606de3
816
cpp
C++
13- Linked Lists/findmidPoint.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
21
2020-10-03T03:57:19.000Z
2022-03-25T22:41:05.000Z
13- Linked Lists/findmidPoint.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
40
2020-10-02T07:02:34.000Z
2021-10-30T16:00:07.000Z
13- Linked Lists/findmidPoint.cpp
ShreyashRoyzada/C-plus-plus-Algorithms
9db89faf0a9b9e636aece3e7289f21ab6a1e3748
[ "MIT" ]
90
2020-10-02T07:06:22.000Z
2022-03-25T22:41:17.000Z
#include<iostream> using namespace std; class node{ public: int data; node*next; node(int d){ data=d; node*next=NULL; } }; void insertAtBeginning(node*&head, int data){ node*n= new node(data); n->next= head; head=n; } void printNode(node*head){ while(head!=NULL){ cout<<head->data<<"->"; head= head->next; } } node*middle(node*head){ if(head->next==NULL and head==NULL){ return head; } else{ node*slow; node*fast; while(fast->next!=NULL and fast!=NULL){ fast= head->next->next; slow= head->next; } return slow; } } int main() { node*head=NULL; insertAtBeginning(head,4); insertAtBeginning(head,3); insertAtBeginning(head,2); insertAtBeginning(head,1); insertAtBeginning(head,8); printNode(head); cout<<endl; node*m= middle(head); cout<<m->data<<endl; return 0; }
15.396226
45
0.655637
ShreyashRoyzada
54d22e29fabfff883297742c415d9a11e5a1862b
932
cpp
C++
Engine/src/model.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
Engine/src/model.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
Engine/src/model.cpp
julienbernat/dmri-explorer
32639916b0a95ecc2ae7484f9e1a084f84c3035a
[ "MIT" ]
null
null
null
#include <model.h> #include <utils.hpp> #include <iostream> namespace Slicer { Model::Model(const std::shared_ptr<ApplicationState>& state) :mState(state) ,mTransformGPUData(GPU::Binding::modelTransform) ,mCoordinateSystem() ,mIsInit(false) { } Model::~Model() { } void Model::initializeModel() { updateApplicationStateAtInit(); registerStateCallbacks(); initProgramPipeline(); mIsInit = true; } void Model::Draw() { if(!mIsInit) { throw std::runtime_error("Model::Draw() called before initializeModel()"); } mProgramPipeline.Bind(); uploadTransformToGPU(); drawSpecific(); } void Model::uploadTransformToGPU() { glm::mat4 transform = mCoordinateSystem->ToWorld(); mTransformGPUData.Update(0, sizeof(glm::mat4), &transform); mTransformGPUData.ToGPU(); } void Model::resetCS(std::shared_ptr<CoordinateSystem> cs) { mCoordinateSystem = cs; } } // namespace Slicer
18.64
82
0.698498
julienbernat
54d3a3eb3e6202b452e200ad5ccdbc9e4bc865b5
581
cpp
C++
Kawakawa/PhysicTest/Physic/ForceGenerator/ParticleForceGenerator/ForceGenerationRegistry.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/PhysicTest/Physic/ForceGenerator/ParticleForceGenerator/ForceGenerationRegistry.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/PhysicTest/Physic/ForceGenerator/ParticleForceGenerator/ForceGenerationRegistry.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
#include "../PrecompiledHeader.h" #include "ForceGenerationRegistry.h" namespace Physic { void ForceGenerationRegistry::RemoveForceGenerator(const IParticleForceGenerator* forceGenerator) { for (auto iter = forceGenerators.begin(); iter != forceGenerators.end(); ++iter) { if (*iter == forceGenerator) { forceGenerators.erase(iter); break; } } } void ForceGenerationRegistry::UpdateForceGenerators(Particle* particle) { for (auto iter = forceGenerators.begin(); iter != forceGenerators.end(); ++iter) { (*iter)->UpdateForces(particle); } } }
23.24
98
0.707401
JiaqiJin
54d521b3fe10fa2cd5a115f25348ec29ee237a8a
852
cpp
C++
201703/2.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
23
2021-03-01T07:07:48.000Z
2022-03-19T12:49:14.000Z
201703/2.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
null
null
null
201703/2.cpp
qzylalala/CSP
8bd474b0cb70b90c41e3fb87452724c5a2bc14fa
[ "Apache-2.0" ]
2
2021-08-30T09:35:17.000Z
2021-09-10T12:26:13.000Z
#include <iostream> #include <cstring> #include <algorithm> using namespace std; int n, m; int a[1010]; int main() { cin >> n; cin >> m; for (int i = 1; i <= n; i++) a[i] = i; while(m --) { int p, q; cin >> p >> q; int idx; for (int i = 1; i <= n; i++) { if (a[i] == p) idx = i; } if (q > 0) { for (int i = 1; i <= q; i++) { int cur = idx + i - 1; a[cur] = a[cur + 1]; } a[idx + q] = p; } else { q = -1 * q; for (int i = 1; i <= q; i++) { int cur = idx - i + 1; a[cur] = a[cur - 1]; } a[idx - q] = p; } } for (int i = 1; i <= n; i++) cout << a[i] << " "; cout << endl; return 0; }
18.933333
53
0.308685
qzylalala
54d9ae8506716c18fe87a0bf54e72ca2a7538d32
9,391
cc
C++
rina-stack/rinad/src/ipcp/plugins/nsm-address-change/nsm-address-change-plugin.cc
kr1stj0n/pep-dna
17136ca8c16238423bf1ca1ab4302d51d2fc8e57
[ "RSA-MD", "Linux-OpenIB", "FTL", "TCP-wrappers", "CECILL-B" ]
3
2021-11-12T13:01:51.000Z
2022-02-19T09:06:23.000Z
rina-stack/rinad/src/ipcp/plugins/nsm-address-change/nsm-address-change-plugin.cc
kr1stj0n/pep-dna
17136ca8c16238423bf1ca1ab4302d51d2fc8e57
[ "RSA-MD", "Linux-OpenIB", "FTL", "TCP-wrappers", "CECILL-B" ]
null
null
null
rina-stack/rinad/src/ipcp/plugins/nsm-address-change/nsm-address-change-plugin.cc
kr1stj0n/pep-dna
17136ca8c16238423bf1ca1ab4302d51d2fc8e57
[ "RSA-MD", "Linux-OpenIB", "FTL", "TCP-wrappers", "CECILL-B" ]
null
null
null
// // Address change policy set for Namespace Manager // // Eduard Grasa <eduard.grasa@i2cat.net> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301 USA // #define IPCP_MODULE "namespace-manager-ps-address-change" #include "../../ipcp-logging.h" #include <string> #include <stdlib.h> #include "ipcp/components.h" namespace rinad { class AddressChangeNamespaceManagerPs: public INamespaceManagerPs { public: AddressChangeNamespaceManagerPs(INamespaceManager * nsm); bool isValidAddress(unsigned int address, const std::string& ipcp_name, const std::string& ipcp_instance); unsigned int getValidAddress(const std::string& ipcp_name, const std::string& ipcp_instance); int set_policy_set_param(const std::string& name, const std::string& value); void set_dif_configuration(const rina::DIFConfiguration& dif_configuration); virtual ~AddressChangeNamespaceManagerPs() {} void change_address(void); static const std::string POLICY_PARAM_USE_NEW_TIMEOUT; static const std::string POLICY_PARAM_DEPRECATE_OLD_TIMEOUT; static const std::string POLICY_PARAM_CHANGE_PERIOD; static const std::string POLICY_PARAM_ADDRESS_RANGE; static const std::string POLICY_PARAM_START_DELAY; private: unsigned int getIPCProcessAddress(const std::string& process_name, const std::string& process_instance, const rina::AddressingConfiguration& address_conf); bool isAddressInUse(unsigned int address, const std::string& ipcp_name); // Data model of the namespace manager component. INamespaceManager * nsm; rina::Timer timer; unsigned int use_new_timeout; unsigned int deprecate_old_timeout; unsigned int change_period; unsigned int min_address; unsigned int max_address; unsigned int current_address; unsigned int start_delay; bool first_time; }; class NSMChangeAddressTimerTask : public rina::TimerTask { public: NSMChangeAddressTimerTask(AddressChangeNamespaceManagerPs *ps); ~NSMChangeAddressTimerTask() throw(){}; void run(); std::string name() const { return "nsm-change-address"; } private: AddressChangeNamespaceManagerPs* nsm_ps; }; NSMChangeAddressTimerTask::NSMChangeAddressTimerTask(AddressChangeNamespaceManagerPs *ps) { nsm_ps = ps; } void NSMChangeAddressTimerTask::run() { nsm_ps->change_address(); } const std::string AddressChangeNamespaceManagerPs::POLICY_PARAM_USE_NEW_TIMEOUT = "useNewTimeout"; const std::string AddressChangeNamespaceManagerPs::POLICY_PARAM_DEPRECATE_OLD_TIMEOUT = "deprecateOldTimeout"; const std::string AddressChangeNamespaceManagerPs::POLICY_PARAM_CHANGE_PERIOD = "changePeriod"; const std::string AddressChangeNamespaceManagerPs::POLICY_PARAM_ADDRESS_RANGE = "addressRange"; const std::string AddressChangeNamespaceManagerPs::POLICY_PARAM_START_DELAY = "startDelay"; AddressChangeNamespaceManagerPs::AddressChangeNamespaceManagerPs(INamespaceManager * nsm_) : nsm(nsm_) { use_new_timeout = 0; deprecate_old_timeout = 0; change_period = 0; min_address = 0; max_address = 0; current_address = 0; start_delay = 0; first_time = true; } void AddressChangeNamespaceManagerPs::set_dif_configuration(const rina::DIFConfiguration& dif_configuration) { NSMChangeAddressTimerTask * task; long delay = 0; unsigned int address_range = 0; try { current_address = getIPCProcessAddress(nsm->ipcp->get_name(), nsm->ipcp->get_instance(), dif_configuration.nsm_configuration_.addressing_configuration_); use_new_timeout = dif_configuration.nsm_configuration_.policy_set_. get_param_value_as_uint(POLICY_PARAM_USE_NEW_TIMEOUT); deprecate_old_timeout = dif_configuration.nsm_configuration_.policy_set_. get_param_value_as_uint(POLICY_PARAM_DEPRECATE_OLD_TIMEOUT); change_period = dif_configuration.nsm_configuration_.policy_set_. get_param_value_as_uint(POLICY_PARAM_CHANGE_PERIOD); address_range = dif_configuration.nsm_configuration_.policy_set_. get_param_value_as_uint(POLICY_PARAM_ADDRESS_RANGE); start_delay = dif_configuration.nsm_configuration_.policy_set_. get_param_value_as_uint(POLICY_PARAM_START_DELAY); min_address = current_address * address_range; max_address = min_address + address_range - 1; } catch (rina::Exception &e) { LOG_IPCP_ERR("Could not properly initialize address change NSM policy, will not change addresses: %s", e.what()); return; } LOG_IPCP_DBG("Use new timeout (ms): %u", use_new_timeout); LOG_IPCP_DBG("Deprecate old timeout (ms): %u", deprecate_old_timeout); LOG_IPCP_DBG("Change period (ms): %u", change_period); LOG_IPCP_DBG("Minimum address: %u", min_address); LOG_IPCP_DBG("Maximum address: %u", max_address); LOG_IPCP_DBG("Start delay: %u", start_delay); task = new NSMChangeAddressTimerTask(this); delay = start_delay + deprecate_old_timeout + use_new_timeout + (rand() % (change_period + 1)); LOG_IPCP_DBG("Will update address again in %ld ms", delay); timer.scheduleTask(task, delay); } void AddressChangeNamespaceManagerPs::change_address(void) { NSMChangeAddressTimerTask * task; unsigned int new_address = 0; long delay = 0; // 1 Compute new address if (current_address + 1 > max_address || first_time) { new_address = min_address; first_time = false; } else { new_address = current_address + 1; } //2 Deliver address changed event LOG_IPCP_INFO("Computed new address: %u, disseminating the event!", new_address); rina::AddressChangeEvent * event = new rina::AddressChangeEvent(new_address, current_address, use_new_timeout, deprecate_old_timeout); current_address = new_address; nsm->ipcp->internal_event_manager_->deliverEvent(event); //3 Re-schedule timer task = new NSMChangeAddressTimerTask(this); delay = deprecate_old_timeout + use_new_timeout + (rand() % (change_period + 1)); LOG_IPCP_DBG("Will update address again in %ld ms", delay); timer.scheduleTask(task, delay); } bool AddressChangeNamespaceManagerPs::isValidAddress(unsigned int address, const std::string& ipcp_name, const std::string& ipcp_instance) { if (address == 0) return false; return true; } unsigned int AddressChangeNamespaceManagerPs::getValidAddress(const std::string& ipcp_name, const std::string& ipcp_instance) { rina::AddressingConfiguration configuration = nsm->ipcp->get_dif_information(). dif_configuration_.nsm_configuration_.addressing_configuration_; unsigned int candidateAddress = getIPCProcessAddress(ipcp_name, ipcp_instance, configuration); if (candidateAddress != 0) { return candidateAddress; } return 0; } unsigned int AddressChangeNamespaceManagerPs::getIPCProcessAddress(const std::string& process_name, const std::string& process_instance, const rina::AddressingConfiguration& address_conf) { std::list<rina::StaticIPCProcessAddress>::const_iterator it; for (it = address_conf.static_address_.begin(); it != address_conf.static_address_.end(); ++it) { if (it->ap_name_.compare(process_name) == 0 && it->ap_instance_.compare(process_instance) == 0) { return it->address_; } } return 0; } bool AddressChangeNamespaceManagerPs::isAddressInUse(unsigned int address, const std::string& ipcp_name) { std::list<rina::Neighbor> neighbors = nsm->ipcp->get_neighbors(); for (std::list<rina::Neighbor>::const_iterator it = neighbors.begin(); it != neighbors.end(); ++it) { if (it->address_ == address) { if (it->name_.processName.compare(ipcp_name) == 0) { return false; } else { return true; } } } return false; } int AddressChangeNamespaceManagerPs::set_policy_set_param(const std::string& name, const std::string& value) { LOG_IPCP_DBG("No policy-set-specific parameters to set (%s, %s)", name.c_str(), value.c_str()); return -1; } extern "C" rina::IPolicySet * createAddressChangeNamespaceManagerPs(rina::ApplicationEntity * ctx) { INamespaceManager * nsm = dynamic_cast<INamespaceManager *>(ctx); if (!nsm) { return NULL; } return new AddressChangeNamespaceManagerPs(nsm); } extern "C" void destroyAddressChangeNamespaceManagerPs(rina::IPolicySet * ps) { if (ps) { delete ps; } } extern "C" int get_factories(std::vector<struct rina::PsFactory>& factories) { struct rina::PsFactory factory; int ret; factory.info.name = "address-change"; factory.info.app_entity = INamespaceManager::NAMESPACE_MANAGER_AE_NAME; factory.create = createAddressChangeNamespaceManagerPs; factory.destroy = destroyAddressChangeNamespaceManagerPs; factories.push_back(factory); return 0; } }
32.835664
110
0.749654
kr1stj0n
54d9e7f398668d333cbf3b75dd008d7a596b4a01
335
cpp
C++
Chapter06/Qt Core Essentials/xmlreader/playerinfo.cpp
PacktPublishing/Game-Programming-using-Qt-5-Beginners-Guide-Second-Edition
4c95eecd43024e385344ec13f19842fd8b3855ed
[ "MIT" ]
124
2018-04-24T22:39:02.000Z
2022-03-31T10:40:14.000Z
Chapter06/Qt Core Essentials/xmlreader/playerinfo.cpp
PacktPublishing/Game-Programming-using-Qt-5-Beginners-Guide-Second-Edition
4c95eecd43024e385344ec13f19842fd8b3855ed
[ "MIT" ]
null
null
null
Chapter06/Qt Core Essentials/xmlreader/playerinfo.cpp
PacktPublishing/Game-Programming-using-Qt-5-Beginners-Guide-Second-Edition
4c95eecd43024e385344ec13f19842fd8b3855ed
[ "MIT" ]
45
2018-05-11T05:56:55.000Z
2022-03-23T19:09:17.000Z
#include "playerinfo.h" #include <QMetaEnum> InventoryItem::Type InventoryItem::typeByName(const QStringRef &r) { QMetaEnum metaEnum = QMetaEnum::fromType<InventoryItem::Type>(); QByteArray latin1 = r.toLatin1(); int result = metaEnum.keyToValue(latin1.constData()); return static_cast<InventoryItem::Type>(result); }
33.5
68
0.740299
PacktPublishing
54de68a0ba2a5cb767507d12925fd930b9eaf435
3,780
cc
C++
src/Modules/Legacy/DataIO/ReadMatrix.cc
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/ReadMatrix.cc
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/ReadMatrix.cc
benjaminlarson/SCIRunGUIPrototype
ed34ee11cda114e3761bd222a71a9f397517914d
[ "Unlicense" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2009 Scientific Computing and Imaging Institute, University of Utah. 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. */ /// /// @file ReadMatrix.cc /// /// @author /// Steven G. Parker /// Department of Computer Science /// University of Utah /// @date July 1994 /// #include <Dataflow/Network/Ports/MatrixPort.h> #include <Dataflow/Modules/DataIO/GenericReader.h> #include <Core/ImportExport/Matrix/MatrixIEPlugin.h> namespace SCIRun { template class GenericReader<MatrixHandle>; /// @class ReadMatrix /// @brief This module reads a matrix from file /// /// (a SCIRun .mat file and various other file formats using a plugin system). class ReadMatrix : public GenericReader<MatrixHandle> { protected: GuiString gui_types_; GuiString gui_filetype_; virtual bool call_importer(const std::string &filename, MatrixHandle &fHandle); public: ReadMatrix(GuiContext* ctx); virtual ~ReadMatrix() {} virtual void execute(); }; DECLARE_MAKER(ReadMatrix) ReadMatrix::ReadMatrix(GuiContext* ctx) : GenericReader<MatrixHandle>("ReadMatrix", ctx, "DataIO", "SCIRun"), gui_types_(get_ctx()->subVar("types", false)), gui_filetype_(get_ctx()->subVar("filetype")) { MatrixIEPluginManager mgr; std::vector<std::string> importers; mgr.get_importer_list(importers); std::string importtypes = "{"; importtypes += "{{SCIRun Matrix File} {.mat} } "; for (unsigned int i = 0; i < importers.size(); i++) { MatrixIEPlugin *pl = mgr.get_plugin(importers[i]); if (pl->fileExtension_ != "") { importtypes += "{{" + importers[i] + "} {" + pl->fileExtension_ + "} } "; } else { importtypes += "{{" + importers[i] + "} {.*} } "; } } importtypes += "}"; gui_types_.set(importtypes); } bool ReadMatrix::call_importer(const std::string &filename, MatrixHandle &mHandle) { const std::string ftpre = gui_filetype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); MatrixIEPluginManager mgr; MatrixIEPlugin *pl = mgr.get_plugin(ft); if (pl) { mHandle = pl->fileReader_(this, filename.c_str()); return mHandle.get_rep(); } return false; } void ReadMatrix::execute() { if (gui_types_.changed() || gui_filetype_.changed()) inputs_changed_ = true; const std::string ftpre = gui_filetype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); importing_ = !(ft == "" || ft == "SCIRun Matrix File" || ft == "SCIRun Matrix Any"); GenericReader<MatrixHandle>::execute(); } } // End namespace SCIRun
28.421053
83
0.692328
benjaminlarson
54e001bb8984467c6e695ea4fb4b844c42bb16fd
59,348
tcc
C++
include/solvers/mpm_base.tcc
jgiven100/mpm-1
adc83ab57782874d4dce1ac13be46bca1754a0fe
[ "MIT" ]
null
null
null
include/solvers/mpm_base.tcc
jgiven100/mpm-1
adc83ab57782874d4dce1ac13be46bca1754a0fe
[ "MIT" ]
null
null
null
include/solvers/mpm_base.tcc
jgiven100/mpm-1
adc83ab57782874d4dce1ac13be46bca1754a0fe
[ "MIT" ]
null
null
null
//! Constructor template <unsigned Tdim> mpm::MPMBase<Tdim>::MPMBase(const std::shared_ptr<IO>& io) : mpm::MPM(io) { //! Logger console_ = spdlog::get("MPMBase"); // Create a mesh with global id 0 const mpm::Index id = 0; // Set analysis step to start at 0 step_ = 0; // Set mesh as isoparametric bool isoparametric = is_isoparametric(); mesh_ = std::make_shared<mpm::Mesh<Tdim>>(id, isoparametric); // Create constraints constraints_ = std::make_shared<mpm::Constraints<Tdim>>(mesh_); // Empty all materials materials_.clear(); // Variable list tsl::robin_map<std::string, VariableType> variables = { // Scalar variables {"mass", VariableType::Scalar}, {"volume", VariableType::Scalar}, {"mass_density", VariableType::Scalar}, // Vector variables {"displacements", VariableType::Vector}, {"velocities", VariableType::Vector}, {"normals", VariableType::Vector}, // Tensor variables {"strains", VariableType::Tensor}, {"stresses", VariableType::Tensor}}; try { analysis_ = io_->analysis(); // Time-step size dt_ = analysis_["dt"].template get<double>(); // Number of time steps nsteps_ = analysis_["nsteps"].template get<mpm::Index>(); // nload balance if (analysis_.find("nload_balance_steps") != analysis_.end()) nload_balance_steps_ = analysis_["nload_balance_steps"].template get<mpm::Index>(); // Locate particles if (analysis_.find("locate_particles") != analysis_.end()) locate_particles_ = analysis_["locate_particles"].template get<bool>(); // Stress update method (USF/USL/MUSL/Newmark) try { if (analysis_.find("mpm_scheme") != analysis_.end()) stress_update_ = analysis_["mpm_scheme"].template get<std::string>(); } catch (std::exception& exception) { console_->warn( "{} #{}: {}. Stress update method is not specified, using USF as " "default", __FILE__, __LINE__, exception.what()); } // Velocity update try { velocity_update_ = analysis_["velocity_update"].template get<bool>(); } catch (std::exception& exception) { console_->warn( "{} #{}: Velocity update parameter is not specified, using default " "as false", __FILE__, __LINE__, exception.what()); velocity_update_ = false; } // Damping try { if (analysis_.find("damping") != analysis_.end()) { if (!initialise_damping(analysis_.at("damping"))) throw std::runtime_error("Damping parameters are not defined"); } } catch (std::exception& exception) { console_->warn("{} #{}: Damping is not specified, using none as default", __FILE__, __LINE__, exception.what()); } // Math functions try { // Get materials properties auto math_functions = io_->json_object("math_functions"); if (!math_functions.empty()) this->initialise_math_functions(math_functions); } catch (std::exception& exception) { console_->warn("{} #{}: No math functions are defined", __FILE__, __LINE__, exception.what()); } post_process_ = io_->post_processing(); // Output steps output_steps_ = post_process_["output_steps"].template get<mpm::Index>(); } catch (std::domain_error& domain_error) { console_->error("{} {} Get analysis object: {}", __FILE__, __LINE__, domain_error.what()); abort(); } // VTK particle variables // Initialise container with empty vector vtk_vars_.insert( std::make_pair(mpm::VariableType::Scalar, std::vector<std::string>())); vtk_vars_.insert( std::make_pair(mpm::VariableType::Vector, std::vector<std::string>())); vtk_vars_.insert( std::make_pair(mpm::VariableType::Tensor, std::vector<std::string>())); if ((post_process_.find("vtk") != post_process_.end()) && post_process_.at("vtk").is_array() && post_process_.at("vtk").size() > 0) { // Iterate over vtk for (unsigned i = 0; i < post_process_.at("vtk").size(); ++i) { std::string attribute = post_process_["vtk"][i].template get<std::string>(); if (variables.find(attribute) != variables.end()) vtk_vars_[variables.at(attribute)].emplace_back(attribute); else { console_->warn( "{} #{}: VTK variable '{}' was specified, but is not available " "in variable list", __FILE__, __LINE__, attribute); } } } else { console_->warn( "{} #{}: No VTK variables were specified, none will be generated", __FILE__, __LINE__); } // VTK state variables bool vtk_statevar = false; if ((post_process_.find("vtk_statevars") != post_process_.end()) && post_process_.at("vtk_statevars").is_array() && post_process_.at("vtk_statevars").size() > 0) { // Iterate over state_vars for (const auto& svars : post_process_["vtk_statevars"]) { // Phase id unsigned phase_id = 0; if (svars.contains("phase_id")) phase_id = svars.at("phase_id").template get<unsigned>(); // State variables if (svars.at("statevars").is_array() && svars.at("statevars").size() > 0) { // Insert vtk_statevars_ const std::vector<std::string> state_var = svars["statevars"]; vtk_statevars_.insert(std::make_pair(phase_id, state_var)); vtk_statevar = true; } else { vtk_statevar = false; break; } } } if (!vtk_statevar) console_->warn( "{} #{}: No VTK statevariable were specified, none will be generated", __FILE__, __LINE__); } // Initialise mesh template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_mesh() { // Initialise MPI rank and size int mpi_rank = 0; int mpi_size = 1; #ifdef USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); #endif // Get mesh properties auto mesh_props = io_->json_object("mesh"); // Get Mesh reader from JSON object const std::string io_type = mesh_props["io_type"].template get<std::string>(); bool check_duplicates = true; try { check_duplicates = mesh_props["check_duplicates"].template get<bool>(); } catch (std::exception& exception) { console_->warn( "{} #{}: Check duplicates, not specified setting default as true", __FILE__, __LINE__, exception.what()); check_duplicates = true; } // Create a mesh reader auto mesh_io = Factory<mpm::IOMesh<Tdim>>::instance()->create(io_type); auto nodes_begin = std::chrono::steady_clock::now(); // Global Index mpm::Index gid = 0; // Node type const auto node_type = mesh_props["node_type"].template get<std::string>(); // Mesh file std::string mesh_file = io_->file_name(mesh_props["mesh"].template get<std::string>()); // Create nodes from file bool node_status = mesh_->create_nodes(gid, // global id node_type, // node type mesh_io->read_mesh_nodes(mesh_file), // coordinates check_duplicates); // check dups if (!node_status) throw std::runtime_error( "mpm::base::init_mesh(): Addition of nodes to mesh failed"); auto nodes_end = std::chrono::steady_clock::now(); console_->info("Rank {} Read nodes: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( nodes_end - nodes_begin) .count()); // Read and assign node sets this->node_entity_sets(mesh_props, check_duplicates); // Read nodal euler angles and assign rotation matrices this->node_euler_angles(mesh_props, mesh_io); // Read and assign velocity constraints this->nodal_velocity_constraints(mesh_props, mesh_io); // Read and assign velocity constraints for implicit solver this->nodal_displacement_constraints(mesh_props, mesh_io); // Read and assign friction constraints this->nodal_frictional_constraints(mesh_props, mesh_io); // Read and assign pressure constraints this->nodal_pressure_constraints(mesh_props, mesh_io); // Initialise cell auto cells_begin = std::chrono::steady_clock::now(); // Shape function name const auto cell_type = mesh_props["cell_type"].template get<std::string>(); // Shape function std::shared_ptr<mpm::Element<Tdim>> element = Factory<mpm::Element<Tdim>>::instance()->create(cell_type); // Create cells from file bool cell_status = mesh_->create_cells(gid, // global id element, // element type mesh_io->read_mesh_cells(mesh_file), // Node ids check_duplicates); // Check dups if (!cell_status) throw std::runtime_error( "mpm::base::init_mesh(): Addition of cells to mesh failed"); // Compute cell neighbours mesh_->find_cell_neighbours(); // Read and assign cell sets this->cell_entity_sets(mesh_props, check_duplicates); // Use Nonlocal basis if (cell_type.back() == 'B') { this->initialise_nonlocal_mesh(mesh_props); } auto cells_end = std::chrono::steady_clock::now(); console_->info("Rank {} Read cells: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( cells_end - cells_begin) .count()); } // Initialise particle types template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_particle_types() { // Get particles properties auto json_particles = io_->json_object("particles"); for (const auto& json_particle : json_particles) { // Gather particle types auto particle_type = json_particle["generator"]["particle_type"].template get<std::string>(); particle_types_.insert(particle_type); } } // Initialise particles template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_particles() { // Initialise MPI rank and size int mpi_rank = 0; int mpi_size = 1; #ifdef USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); #endif // Get mesh properties auto mesh_props = io_->json_object("mesh"); // Get Mesh reader from JSON object const std::string io_type = mesh_props["io_type"].template get<std::string>(); // Check duplicates default set to true bool check_duplicates = true; if (mesh_props.find("check_duplicates") != mesh_props.end()) check_duplicates = mesh_props["check_duplicates"].template get<bool>(); auto particles_gen_begin = std::chrono::steady_clock::now(); // Get particles properties auto json_particles = io_->json_object("particles"); for (const auto& json_particle : json_particles) { // Generate particles bool gen_status = mesh_->generate_particles(io_, json_particle["generator"]); if (!gen_status) std::runtime_error( "mpm::base::init_particles() Generate particles failed"); } // Gather particle types this->initialise_particle_types(); auto particles_gen_end = std::chrono::steady_clock::now(); console_->info("Rank {} Generate particles: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( particles_gen_end - particles_gen_begin) .count()); auto particles_locate_begin = std::chrono::steady_clock::now(); // Create a mesh reader auto particle_io = Factory<mpm::IOMesh<Tdim>>::instance()->create(io_type); // Read and assign particles cells this->particles_cells(mesh_props, particle_io); // Locate particles in cell auto unlocatable_particles = mesh_->locate_particles_mesh(); if (!unlocatable_particles.empty()) throw std::runtime_error( "mpm::base::init_particles() Particle outside the mesh domain"); // Write particles and cells to file particle_io->write_particles_cells( io_->output_file("particles-cells", ".txt", uuid_, 0, 0).string(), mesh_->particles_cells()); auto particles_locate_end = std::chrono::steady_clock::now(); console_->info("Rank {} Locate particles: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( particles_locate_end - particles_locate_begin) .count()); auto particles_volume_begin = std::chrono::steady_clock::now(); // Compute volume mesh_->iterate_over_particles(std::bind( &mpm::ParticleBase<Tdim>::compute_volume, std::placeholders::_1)); // Read and assign particles volumes this->particles_volumes(mesh_props, particle_io); // Read and assign particles stresses this->particles_stresses(mesh_props, particle_io); // Read and assign particles initial pore pressure this->particles_pore_pressures(mesh_props, particle_io); auto particles_volume_end = std::chrono::steady_clock::now(); console_->info("Rank {} Read volume, velocity and stresses: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( particles_volume_end - particles_volume_begin) .count()); // Particle entity sets this->particle_entity_sets(check_duplicates); // Read and assign particles velocity constraints this->particle_velocity_constraints(); console_->info("Rank {} Create particle sets: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( particles_volume_end - particles_volume_begin) .count()); // Material id update using particle sets try { auto material_sets = io_->json_object("material_sets"); if (!material_sets.empty()) { for (const auto& material_set : material_sets) { unsigned material_id = material_set["material_id"].template get<unsigned>(); unsigned phase_id = mpm::ParticlePhase::Solid; if (material_set.contains("phase_id")) phase_id = material_set["phase_id"].template get<unsigned>(); unsigned pset_id = material_set["pset_id"].template get<unsigned>(); // Update material_id for particles in each pset mesh_->iterate_over_particle_set( pset_id, std::bind(&mpm::ParticleBase<Tdim>::assign_material, std::placeholders::_1, materials_.at(material_id), phase_id)); } } } catch (std::exception& exception) { console_->warn("{} #{}: Material sets are not specified", __FILE__, __LINE__, exception.what()); } } // Initialise materials template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_materials() { // Get materials properties auto materials = io_->json_object("materials"); for (const auto material_props : materials) { // Get material type const std::string material_type = material_props["type"].template get<std::string>(); // Get material id auto material_id = material_props["id"].template get<unsigned>(); // Create a new material from JSON object auto mat = Factory<mpm::Material<Tdim>, unsigned, const Json&>::instance()->create( material_type, std::move(material_id), material_props); // Add material to list auto result = materials_.insert(std::make_pair(mat->id(), mat)); // If insert material failed if (!result.second) throw std::runtime_error( "mpm::base::init_materials(): New material cannot be added, " "insertion failed"); } // Copy materials to mesh mesh_->initialise_material_models(this->materials_); } //! Checkpoint resume template <unsigned Tdim> bool mpm::MPMBase<Tdim>::checkpoint_resume() { bool checkpoint = true; try { int mpi_rank = 0; #ifdef USE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); #endif // Gather particle types this->initialise_particle_types(); if (!analysis_["resume"]["resume"].template get<bool>()) throw std::runtime_error("Resume analysis option is disabled!"); // Get unique analysis id this->uuid_ = analysis_["resume"]["uuid"].template get<std::string>(); // Get step this->step_ = analysis_["resume"]["step"].template get<mpm::Index>(); // Input particle h5 file for resume for (const auto ptype : particle_types_) { std::string attribute = mpm::ParticlePODTypeName.at(ptype); std::string extension = ".h5"; auto particles_file = io_->output_file(attribute, extension, uuid_, step_, this->nsteps_) .string(); // Load particle information from file mesh_->read_particles_hdf5(particles_file, attribute, ptype); } // Clear all particle ids mesh_->iterate_over_cells( std::bind(&mpm::Cell<Tdim>::clear_particle_ids, std::placeholders::_1)); // Locate particles auto unlocatable_particles = mesh_->locate_particles_mesh(); if (!unlocatable_particles.empty()) throw std::runtime_error("Particle outside the mesh domain"); console_->info("Checkpoint resume at step {} of {}", this->step_, this->nsteps_); } catch (std::exception& exception) { console_->info("{} {} Resume failed, restarting analysis: {}", __FILE__, __LINE__, exception.what()); this->step_ = 0; checkpoint = false; } return checkpoint; } //! Write HDF5 files template <unsigned Tdim> void mpm::MPMBase<Tdim>::write_hdf5(mpm::Index step, mpm::Index max_steps) { // Write hdf5 file for single phase particle for (const auto ptype : particle_types_) { std::string attribute = mpm::ParticlePODTypeName.at(ptype); std::string extension = ".h5"; auto particles_file = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); // Load particle information from file if (attribute == "particles" || attribute == "fluid_particles") mesh_->write_particles_hdf5(particles_file); else if (attribute == "twophase_particles") mesh_->write_particles_hdf5_twophase(particles_file); } } #ifdef USE_VTK //! Write VTK files template <unsigned Tdim> void mpm::MPMBase<Tdim>::write_vtk(mpm::Index step, mpm::Index max_steps) { // VTK PolyData writer auto vtk_writer = std::make_unique<VtkWriter>(mesh_->particle_coordinates()); // Write mesh on step 0 // Get active node pairs use true if (step % nload_balance_steps_ == 0) vtk_writer->write_mesh( io_->output_file("mesh", ".vtp", uuid_, step, max_steps).string(), mesh_->nodal_coordinates(), mesh_->node_pairs(true)); // Write input geometry to vtk file const std::string extension = ".vtp"; const std::string attribute = "geometry"; auto meshfile = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); vtk_writer->write_geometry(meshfile); // MPI parallel vtk file int mpi_rank = 0; int mpi_size = 1; bool write_mpi_rank = false; #ifdef USE_MPI // Get MPI rank MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); #endif //! VTK scalar variables for (const auto& attribute : vtk_vars_.at(mpm::VariableType::Scalar)) { // Write scalar auto file = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); vtk_writer->write_scalar_point_data( file, mesh_->particles_scalar_data(attribute), attribute); // Write a parallel MPI VTK container file #ifdef USE_MPI if (mpi_rank == 0 && mpi_size > 1) { auto parallel_file = io_->output_file(attribute, ".pvtp", uuid_, step, max_steps, write_mpi_rank) .string(); vtk_writer->write_parallel_vtk(parallel_file, attribute, mpi_size, step, max_steps, 1); } #endif } //! VTK vector variables for (const auto& attribute : vtk_vars_.at(mpm::VariableType::Vector)) { // Write vector auto file = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); vtk_writer->write_vector_point_data( file, mesh_->particles_vector_data(attribute), attribute); // Write a parallel MPI VTK container file #ifdef USE_MPI if (mpi_rank == 0 && mpi_size > 1) { auto parallel_file = io_->output_file(attribute, ".pvtp", uuid_, step, max_steps, write_mpi_rank) .string(); vtk_writer->write_parallel_vtk(parallel_file, attribute, mpi_size, step, max_steps, 3); } #endif } //! VTK tensor variables for (const auto& attribute : vtk_vars_.at(mpm::VariableType::Tensor)) { // Write vector auto file = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); vtk_writer->write_tensor_point_data( file, mesh_->template particles_tensor_data<6>(attribute), attribute); // Write a parallel MPI VTK container file #ifdef USE_MPI if (mpi_rank == 0 && mpi_size > 1) { auto parallel_file = io_->output_file(attribute, ".pvtp", uuid_, step, max_steps, write_mpi_rank) .string(); vtk_writer->write_parallel_vtk(parallel_file, attribute, mpi_size, step, max_steps, 9); } #endif } // VTK state variables for (auto const& vtk_statevar : vtk_statevars_) { unsigned phase_id = vtk_statevar.first; for (const auto& attribute : vtk_statevar.second) { std::string phase_attribute = "phase" + std::to_string(phase_id) + attribute; // Write state variables auto file = io_->output_file(phase_attribute, extension, uuid_, step, max_steps) .string(); vtk_writer->write_scalar_point_data( file, mesh_->particles_statevars_data(attribute, phase_id), phase_attribute); // Write a parallel MPI VTK container file #ifdef USE_MPI if (mpi_rank == 0 && mpi_size > 1) { auto parallel_file = io_->output_file(phase_attribute, ".pvtp", uuid_, step, max_steps, write_mpi_rank) .string(); unsigned ncomponents = 1; vtk_writer->write_parallel_vtk(parallel_file, phase_attribute, mpi_size, step, max_steps, ncomponents); } #endif } } } #endif #ifdef USE_PARTIO //! Write Partio files template <unsigned Tdim> void mpm::MPMBase<Tdim>::write_partio(mpm::Index step, mpm::Index max_steps) { // MPI parallel partio file int mpi_rank = 0; int mpi_size = 1; #ifdef USE_MPI // Get MPI rank MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); #endif // Get Partio file extensions const std::string extension = ".bgeo"; const std::string attribute = "partio"; // Create filename auto file = io_->output_file(attribute, extension, uuid_, step, max_steps).string(); // Write partio file mpm::partio::write_particles(file, mesh_->particles_hdf5()); } #endif // USE_PARTIO //! Output results template <unsigned Tdim> void mpm::MPMBase<Tdim>::write_outputs(mpm::Index step) { if (step % this->output_steps_ == 0) { // HDF5 outputs this->write_hdf5(step, this->nsteps_); #ifdef USE_VTK // VTK outputs this->write_vtk(step, this->nsteps_); #endif #ifdef USE_PARTIO // Partio outputs this->write_partio(step, this->nsteps_); #endif } } //! Return if a mesh is isoparametric template <unsigned Tdim> bool mpm::MPMBase<Tdim>::is_isoparametric() { bool isoparametric = true; try { const auto mesh_props = io_->json_object("mesh"); isoparametric = mesh_props.at("isoparametric").template get<bool>(); } catch (std::exception& exception) { console_->warn( "{} {} Isoparametric status of mesh: {}\n Setting mesh as " "isoparametric.", __FILE__, __LINE__, exception.what()); isoparametric = true; } return isoparametric; } //! Initialise loads template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_loads() { auto loads = io_->json_object("external_loading_conditions"); // Initialise gravity loading gravity_.setZero(); if (loads.at("gravity").is_array() && loads.at("gravity").size() == gravity_.size()) { for (unsigned i = 0; i < gravity_.size(); ++i) { gravity_[i] = loads.at("gravity").at(i); } // Assign initial particle acceleration as gravity mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::assign_acceleration, std::placeholders::_1, gravity_)); } else { throw std::runtime_error("Specified gravity dimension is invalid"); } // Create a file reader const std::string io_type = io_->json_object("mesh")["io_type"].template get<std::string>(); auto reader = Factory<mpm::IOMesh<Tdim>>::instance()->create(io_type); // Read and assign particles surface tractions if (loads.find("particle_surface_traction") != loads.end()) { for (const auto& ptraction : loads["particle_surface_traction"]) { // Get the math function std::shared_ptr<FunctionBase> tfunction = nullptr; // If a math function is defined set to function or use scalar if (ptraction.find("math_function_id") != ptraction.end()) tfunction = math_functions_.at( ptraction.at("math_function_id").template get<unsigned>()); // Set id int pset_id = ptraction.at("pset_id").template get<int>(); // Direction unsigned dir = ptraction.at("dir").template get<unsigned>(); // Traction double traction = ptraction.at("traction").template get<double>(); // Create particle surface tractions bool particles_tractions = mesh_->create_particles_tractions(tfunction, pset_id, dir, traction); if (!particles_tractions) throw std::runtime_error( "Particles tractions are not properly assigned"); } } else console_->warn("No particle surface traction is defined for the analysis"); // Read and assign nodal concentrated forces if (loads.find("concentrated_nodal_forces") != loads.end()) { for (const auto& nforce : loads["concentrated_nodal_forces"]) { // Forces are specified in a file if (nforce.find("file") != nforce.end()) { std::string force_file = nforce.at("file").template get<std::string>(); bool nodal_forces = mesh_->assign_nodal_concentrated_forces( reader->read_forces(io_->file_name(force_file))); if (!nodal_forces) throw std::runtime_error( "Nodal force file is invalid, forces are not properly " "assigned"); set_node_concentrated_force_ = true; } else { // Get the math function std::shared_ptr<FunctionBase> ffunction = nullptr; if (nforce.find("math_function_id") != nforce.end()) ffunction = math_functions_.at( nforce.at("math_function_id").template get<unsigned>()); // Set id int nset_id = nforce.at("nset_id").template get<int>(); // Direction unsigned dir = nforce.at("dir").template get<unsigned>(); // Traction double force = nforce.at("force").template get<double>(); // Read and assign nodal concentrated forces bool nodal_force = mesh_->assign_nodal_concentrated_forces( ffunction, nset_id, dir, force); if (!nodal_force) throw std::runtime_error( "Concentrated nodal forces are not properly assigned"); set_node_concentrated_force_ = true; } } } else console_->warn("No concentrated nodal force is defined for the analysis"); } //! Initialise math functions template <unsigned Tdim> bool mpm::MPMBase<Tdim>::initialise_math_functions(const Json& math_functions) { bool status = true; try { // Get materials properties for (const auto& function_props : math_functions) { // Get math function id auto function_id = function_props["id"].template get<unsigned>(); // Get function type const std::string function_type = function_props["type"].template get<std::string>(); // Create a new function from JSON object auto function = Factory<mpm::FunctionBase, unsigned, const Json&>::instance()->create( function_type, std::move(function_id), function_props); // Add material to list auto insert_status = math_functions_.insert(std::make_pair(function->id(), function)); // If insert material failed if (!insert_status.second) { status = false; throw std::runtime_error( "Invalid properties for new math function, fn insertion failed"); } } } catch (std::exception& exception) { console_->error("#{}: Reading math functions: {}", __LINE__, exception.what()); status = false; } return status; } //! Node entity sets template <unsigned Tdim> void mpm::MPMBase<Tdim>::node_entity_sets(const Json& mesh_props, bool check_duplicates) { try { if (mesh_props.find("entity_sets") != mesh_props.end()) { std::string entity_sets = mesh_props["entity_sets"].template get<std::string>(); if (!io_->file_name(entity_sets).empty()) { bool node_sets = mesh_->create_node_sets( (io_->entity_sets(io_->file_name(entity_sets), "node_sets")), check_duplicates); if (!node_sets) throw std::runtime_error("Node sets are not properly assigned"); } } else throw std::runtime_error("Entity set JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Entity sets are undefined {} ", __LINE__, exception.what()); } } //! Node Euler angles template <unsigned Tdim> void mpm::MPMBase<Tdim>::node_euler_angles( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& mesh_io) { try { if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find("nodal_euler_angles") != mesh_props["boundary_conditions"].end()) { std::string euler_angles = mesh_props["boundary_conditions"]["nodal_euler_angles"] .template get<std::string>(); if (!io_->file_name(euler_angles).empty()) { bool rotation_matrices = mesh_->compute_nodal_rotation_matrices( mesh_io->read_euler_angles(io_->file_name(euler_angles))); if (!rotation_matrices) throw std::runtime_error( "Euler angles are not properly assigned/computed"); } } else throw std::runtime_error("Euler angles JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Euler angles are undefined {} ", __LINE__, exception.what()); } } // Nodal velocity constraints template <unsigned Tdim> void mpm::MPMBase<Tdim>::nodal_velocity_constraints( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& mesh_io) { try { // Read and assign velocity constraints if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find("velocity_constraints") != mesh_props["boundary_conditions"].end()) { // Iterate over velocity constraints for (const auto& constraints : mesh_props["boundary_conditions"]["velocity_constraints"]) { // Velocity constraints are specified in a file if (constraints.find("file") != constraints.end()) { std::string velocity_constraints_file = constraints.at("file").template get<std::string>(); bool velocity_constraints = constraints_->assign_nodal_velocity_constraints( mesh_io->read_velocity_constraints( io_->file_name(velocity_constraints_file))); if (!velocity_constraints) throw std::runtime_error( "Velocity constraints are not properly assigned"); } else { // Set id int nset_id = constraints.at("nset_id").template get<int>(); // Direction unsigned dir = constraints.at("dir").template get<unsigned>(); // Velocity double velocity = constraints.at("velocity").template get<double>(); // Add velocity constraint to mesh auto velocity_constraint = std::make_shared<mpm::VelocityConstraint>(nset_id, dir, velocity); bool velocity_constraints = constraints_->assign_nodal_velocity_constraint( nset_id, velocity_constraint); if (!velocity_constraints) throw std::runtime_error( "Nodal velocity constraint is not properly assigned"); } } } else throw std::runtime_error("Velocity constraints JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Velocity constraints are undefined {} ", __LINE__, exception.what()); } } // Nodal displacement constraints for implicit solver template <unsigned Tdim> void mpm::MPMBase<Tdim>::nodal_displacement_constraints( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& mesh_io) { try { // Read and assign displacement constraints if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find("displacement_constraints") != mesh_props["boundary_conditions"].end()) { // Iterate over displacement constraints for (const auto& constraints : mesh_props["boundary_conditions"]["displacement_constraints"]) { // Displacement constraints are specified in a file if (constraints.find("file") != constraints.end()) { std::string displacement_constraints_file = constraints.at("file").template get<std::string>(); bool displacement_constraints = constraints_->assign_nodal_displacement_constraints( mesh_io->read_displacement_constraints( io_->file_name(displacement_constraints_file))); if (!displacement_constraints) throw std::runtime_error( "Displacement constraints are not properly assigned"); } else { // Get the math function std::shared_ptr<FunctionBase> dfunction = nullptr; if (constraints.find("math_function_id") != constraints.end()) dfunction = math_functions_.at( constraints.at("math_function_id").template get<unsigned>()); // Set id int nset_id = constraints.at("nset_id").template get<int>(); // Direction unsigned dir = constraints.at("dir").template get<unsigned>(); // Displacement double displacement = constraints.at("displacement").template get<double>(); // Add displacement constraint to mesh auto displacement_constraint = std::make_shared<mpm::DisplacementConstraint>(nset_id, dir, displacement); bool displacement_constraints = constraints_->assign_nodal_displacement_constraint( dfunction, nset_id, displacement_constraint); if (!displacement_constraints) throw std::runtime_error( "Nodal displacement constraint is not properly assigned"); } } } else throw std::runtime_error("Displacement constraints JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Displacement constraints are undefined {} ", __LINE__, exception.what()); } } // Nodal frictional constraints template <unsigned Tdim> void mpm::MPMBase<Tdim>::nodal_frictional_constraints( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& mesh_io) { try { // Read and assign friction constraints if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find("friction_constraints") != mesh_props["boundary_conditions"].end()) { // Iterate over velocity constraints for (const auto& constraints : mesh_props["boundary_conditions"]["friction_constraints"]) { // Friction constraints are specified in a file if (constraints.find("file") != constraints.end()) { std::string friction_constraints_file = constraints.at("file").template get<std::string>(); bool friction_constraints = constraints_->assign_nodal_friction_constraints( mesh_io->read_friction_constraints( io_->file_name(friction_constraints_file))); if (!friction_constraints) throw std::runtime_error( "Friction constraints are not properly assigned"); } else { // Set id int nset_id = constraints.at("nset_id").template get<int>(); // Direction unsigned dir = constraints.at("dir").template get<unsigned>(); // Sign n int sign_n = constraints.at("sign_n").template get<int>(); // Friction double friction = constraints.at("friction").template get<double>(); // Add friction constraint to mesh auto friction_constraint = std::make_shared<mpm::FrictionConstraint>( nset_id, dir, sign_n, friction); bool friction_constraints = constraints_->assign_nodal_frictional_constraint( nset_id, friction_constraint); if (!friction_constraints) throw std::runtime_error( "Nodal friction constraint is not properly assigned"); } } } else throw std::runtime_error("Friction constraints JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Friction conditions are undefined {} ", __LINE__, exception.what()); } } // Nodal pressure constraints template <unsigned Tdim> void mpm::MPMBase<Tdim>::nodal_pressure_constraints( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& mesh_io) { try { // Read and assign pressure constraints if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find("pressure_constraints") != mesh_props["boundary_conditions"].end()) { // Iterate over pressure constraints for (const auto& constraints : mesh_props["boundary_conditions"]["pressure_constraints"]) { // Pore pressure constraint phase indice unsigned constraint_phase = constraints["phase_id"]; // Pore pressure constraints are specified in a file if (constraints.find("file") != constraints.end()) { std::string pressure_constraints_file = constraints.at("file").template get<std::string>(); bool ppressure_constraints = constraints_->assign_nodal_pressure_constraints( constraint_phase, mesh_io->read_pressure_constraints( io_->file_name(pressure_constraints_file))); if (!ppressure_constraints) throw std::runtime_error( "Pore pressure constraints are not properly assigned"); } else { // Get the math function std::shared_ptr<FunctionBase> pfunction = nullptr; if (constraints.find("math_function_id") != constraints.end()) pfunction = math_functions_.at( constraints.at("math_function_id").template get<unsigned>()); // Set id int nset_id = constraints.at("nset_id").template get<int>(); // Pressure double pressure = constraints.at("pressure").template get<double>(); // Add pressure constraint to mesh constraints_->assign_nodal_pressure_constraint( pfunction, nset_id, constraint_phase, pressure); } } } else throw std::runtime_error("Pressure constraints JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Nodal pressure constraints are undefined {} ", __LINE__, exception.what()); } } //! Cell entity sets template <unsigned Tdim> void mpm::MPMBase<Tdim>::cell_entity_sets(const Json& mesh_props, bool check_duplicates) { try { if (mesh_props.find("entity_sets") != mesh_props.end()) { // Read and assign cell sets std::string entity_sets = mesh_props["entity_sets"].template get<std::string>(); if (!io_->file_name(entity_sets).empty()) { bool cell_sets = mesh_->create_cell_sets( (io_->entity_sets(io_->file_name(entity_sets), "cell_sets")), check_duplicates); if (!cell_sets) throw std::runtime_error("Cell sets are not properly assigned"); } } else throw std::runtime_error("Cell entity sets JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Cell entity sets are undefined {} ", __LINE__, exception.what()); } } // Particles cells template <unsigned Tdim> void mpm::MPMBase<Tdim>::particles_cells( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& particle_io) { try { if (mesh_props.find("particle_cells") != mesh_props.end()) { std::string fparticles_cells = mesh_props["particle_cells"].template get<std::string>(); if (!io_->file_name(fparticles_cells).empty()) { bool particles_cells = mesh_->assign_particles_cells(particle_io->read_particles_cells( io_->file_name(fparticles_cells))); if (!particles_cells) throw std::runtime_error( "Particle cells are not properly assigned to particles"); } } else throw std::runtime_error("Particle cells JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle cells are undefined {} ", __LINE__, exception.what()); } } // Particles volumes template <unsigned Tdim> void mpm::MPMBase<Tdim>::particles_volumes( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& particle_io) { try { if (mesh_props.find("particles_volumes") != mesh_props.end()) { std::string fparticles_volumes = mesh_props["particles_volumes"].template get<std::string>(); if (!io_->file_name(fparticles_volumes).empty()) { bool particles_volumes = mesh_->assign_particles_volumes(particle_io->read_particles_volumes( io_->file_name(fparticles_volumes))); if (!particles_volumes) throw std::runtime_error( "Particles volumes are not properly assigned"); } } else throw std::runtime_error("Particle volumes JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle volumes are undefined {} ", __LINE__, exception.what()); } } // Particle velocity constraints template <unsigned Tdim> void mpm::MPMBase<Tdim>::particle_velocity_constraints() { auto mesh_props = io_->json_object("mesh"); // Create a file reader const std::string io_type = io_->json_object("mesh")["io_type"].template get<std::string>(); auto reader = Factory<mpm::IOMesh<Tdim>>::instance()->create(io_type); try { if (mesh_props.find("boundary_conditions") != mesh_props.end() && mesh_props["boundary_conditions"].find( "particles_velocity_constraints") != mesh_props["boundary_conditions"].end()) { // Iterate over velocity constraints for (const auto& constraints : mesh_props["boundary_conditions"] ["particles_velocity_constraints"]) { // Set id int pset_id = constraints.at("pset_id").template get<int>(); // Direction unsigned dir = constraints.at("dir").template get<unsigned>(); // Velocity double velocity = constraints.at("velocity").template get<double>(); // Add velocity constraint to mesh auto velocity_constraint = std::make_shared<mpm::VelocityConstraint>(pset_id, dir, velocity); mesh_->create_particle_velocity_constraint(pset_id, velocity_constraint); } } else throw std::runtime_error("Particle velocity constraints JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle velocity constraints are undefined {} ", __LINE__, exception.what()); } } // Particles stresses template <unsigned Tdim> void mpm::MPMBase<Tdim>::particles_stresses( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& particle_io) { try { if (mesh_props.find("particles_stresses") != mesh_props.end()) { // Get generator type const std::string type = mesh_props["particles_stresses"]["type"].template get<std::string>(); if (type == "file") { std::string fparticles_stresses = mesh_props["particles_stresses"]["location"] .template get<std::string>(); if (!io_->file_name(fparticles_stresses).empty()) { // Get stresses of all particles const auto all_particles_stresses = particle_io->read_particles_stresses( io_->file_name(fparticles_stresses)); // Read and assign particles stresses if (!mesh_->assign_particles_stresses(all_particles_stresses)) throw std::runtime_error( "Particles stresses are not properly assigned"); } } else if (type == "isotropic") { Eigen::Matrix<double, 6, 1> in_stress; in_stress.setZero(); if (mesh_props["particles_stresses"]["values"].is_array() && mesh_props["particles_stresses"]["values"].size() == in_stress.size()) { for (unsigned i = 0; i < in_stress.size(); ++i) { in_stress[i] = mesh_props["particles_stresses"]["values"].at(i); } mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::initial_stress, std::placeholders::_1, in_stress)); } else { throw std::runtime_error("Initial stress dimension is invalid"); } } } else throw std::runtime_error("Particle stresses JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle stresses are undefined {} ", __LINE__, exception.what()); } } // Particles pore pressures template <unsigned Tdim> void mpm::MPMBase<Tdim>::particles_pore_pressures( const Json& mesh_props, const std::shared_ptr<mpm::IOMesh<Tdim>>& particle_io) { try { if (mesh_props.find("particles_pore_pressures") != mesh_props.end()) { // Get generator type const std::string type = mesh_props["particles_pore_pressures"]["type"] .template get<std::string>(); // Assign initial pore pressure by file if (type == "file") { std::string fparticles_pore_pressures = mesh_props["particles_pore_pressures"]["location"] .template get<std::string>(); if (!io_->file_name(fparticles_pore_pressures).empty()) { // Read and assign particles pore pressures if (!mesh_->assign_particles_pore_pressures( particle_io->read_particles_scalar_properties( io_->file_name(fparticles_pore_pressures)))) throw std::runtime_error( "Particles pore pressures are not properly assigned"); } else throw std::runtime_error("Particle pore pressures JSON not found"); } else if (type == "water_table") { // Initialise water tables std::map<double, double> reference_points; // Vertical direction const unsigned dir_v = mesh_props["particles_pore_pressures"]["dir_v"] .template get<unsigned>(); // Horizontal direction const unsigned dir_h = mesh_props["particles_pore_pressures"]["dir_h"] .template get<unsigned>(); // Iterate over water tables for (const auto& water_table : mesh_props["particles_pore_pressures"]["water_tables"]) { // Position coordinate double position = water_table.at("position").template get<double>(); // Direction double h0 = water_table.at("h0").template get<double>(); // Add reference points to mesh reference_points.insert(std::make_pair<double, double>( static_cast<double>(position), static_cast<double>(h0))); } // Initialise particles pore pressures by watertable mesh_->iterate_over_particles(std::bind( &mpm::ParticleBase<Tdim>::initialise_pore_pressure_watertable, std::placeholders::_1, dir_v, dir_h, this->gravity_, reference_points)); } else if (type == "isotropic") { const double pore_pressure = mesh_props["particles_pore_pressures"]["values"] .template get<double>(); mesh_->iterate_over_particles(std::bind( &mpm::ParticleBase<Tdim>::assign_pressure, std::placeholders::_1, pore_pressure, mpm::ParticlePhase::Liquid)); } else throw std::runtime_error( "Particle pore pressures generator type is not properly " "specified"); } else throw std::runtime_error("Particle pore pressure JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle pore pressures are undefined {} ", __LINE__, exception.what()); } } //! Particle entity sets template <unsigned Tdim> void mpm::MPMBase<Tdim>::particle_entity_sets(bool check_duplicates) { // Get mesh properties auto mesh_props = io_->json_object("mesh"); // Read and assign particle sets try { if (mesh_props.find("entity_sets") != mesh_props.end()) { std::string entity_sets = mesh_props["entity_sets"].template get<std::string>(); if (!io_->file_name(entity_sets).empty()) { bool particle_sets = mesh_->create_particle_sets( (io_->entity_sets(io_->file_name(entity_sets), "particle_sets")), check_duplicates); if (!particle_sets) throw std::runtime_error("Particle set creation failed"); } } else throw std::runtime_error("Particle entity set JSON not found"); } catch (std::exception& exception) { console_->warn("#{}: Particle sets are undefined {} ", __LINE__, exception.what()); } } // Initialise Damping template <unsigned Tdim> bool mpm::MPMBase<Tdim>::initialise_damping(const Json& damping_props) { // Read damping JSON object bool status = true; try { // Read damping type std::string type = damping_props.at("type").template get<std::string>(); if (type == "Cundall") damping_type_ = mpm::Damping::Cundall; // Read damping factor damping_factor_ = damping_props.at("damping_factor").template get<double>(); } catch (std::exception& exception) { console_->warn("#{}: Damping parameters are undefined {} ", __LINE__, exception.what()); status = false; } return status; } //! Domain decomposition template <unsigned Tdim> void mpm::MPMBase<Tdim>::mpi_domain_decompose(bool initial_step) { #ifdef USE_MPI // Initialise MPI rank and size int mpi_rank = 0; int mpi_size = 1; // Get MPI rank MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); if (mpi_size > 1 && mesh_->ncells() > 1) { // Initialize MPI MPI_Comm comm; MPI_Comm_dup(MPI_COMM_WORLD, &comm); auto mpi_domain_begin = std::chrono::steady_clock::now(); console_->info("Rank {}, Domain decomposition started\n", mpi_rank); #ifdef USE_GRAPH_PARTITIONING // Create graph object if empty if (initial_step || graph_ == nullptr) graph_ = std::make_shared<Graph<Tdim>>(mesh_->cells()); // Find number of particles in each cell across MPI ranks mesh_->find_nglobal_particles_cells(); // Construct a weighted DAG graph_->construct_graph(mpi_size, mpi_rank); // Graph partitioning mode int mode = 4; // FAST // Create graph partition graph_->create_partitions(&comm, mode); // Collect the partitions auto exchange_cells = graph_->collect_partitions(mpi_size, mpi_rank, &comm); // Identify shared nodes across MPI domains mesh_->find_domain_shared_nodes(); // Identify ghost boundary cells mesh_->find_ghost_boundary_cells(); // Delete all the particles which is not in local task parititon if (initial_step) mesh_->remove_all_nonrank_particles(); // Transfer non-rank particles to appropriate cells else mesh_->transfer_nonrank_particles(exchange_cells); #endif auto mpi_domain_end = std::chrono::steady_clock::now(); console_->info("Rank {}, Domain decomposition: {} ms", mpi_rank, std::chrono::duration_cast<std::chrono::milliseconds>( mpi_domain_end - mpi_domain_begin) .count()); } #endif // MPI } //! MPM pressure smoothing template <unsigned Tdim> void mpm::MPMBase<Tdim>::pressure_smoothing(unsigned phase) { // Assign pressure to nodes mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::map_pressure_to_nodes, std::placeholders::_1, phase)); // Apply pressure constraint mesh_->iterate_over_nodes_predicate( std::bind(&mpm::NodeBase<Tdim>::apply_pressure_constraint, std::placeholders::_1, phase, this->dt_, this->step_), std::bind(&mpm::NodeBase<Tdim>::status, std::placeholders::_1)); #ifdef USE_MPI int mpi_size = 1; // Get number of MPI ranks MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); // Run if there is more than a single MPI task if (mpi_size > 1) { // MPI all reduce nodal pressure mesh_->template nodal_halo_exchange<double, 1>( std::bind(&mpm::NodeBase<Tdim>::pressure, std::placeholders::_1, phase), std::bind(&mpm::NodeBase<Tdim>::assign_pressure, std::placeholders::_1, phase, std::placeholders::_2)); } #endif // Smooth pressure over particles mesh_->iterate_over_particles( std::bind(&mpm::ParticleBase<Tdim>::compute_pressure_smoothing, std::placeholders::_1, phase)); } //! MPM implicit solver initialization template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_linear_solver( const Json& lin_solver_props, tsl::robin_map< std::string, std::shared_ptr<mpm::SolverBase<Eigen::SparseMatrix<double>>>>& linear_solver) { // Iterate over specific solver settings for (const auto& solver : lin_solver_props) { std::string dof = solver["dof"].template get<std::string>(); std::string solver_type = solver["solver_type"].template get<std::string>(); // NOTE: Only KrylovPETSC solver is supported for MPI #ifdef USE_MPI // Get number of MPI ranks int mpi_size = 1; MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); if (solver_type != "KrylovPETSC" && mpi_size > 1) { console_->warn( "The linear solver for DOF:\'{}\' in MPI setting is " "automatically set to default: \'KrylovPETSC\'. Only " "\'KrylovPETSC\' solver is supported for MPI.", dof); solver_type = "KrylovPETSC"; } #endif unsigned max_iter = solver["max_iter"].template get<unsigned>(); double tolerance = solver["tolerance"].template get<double>(); auto lin_solver = Factory<mpm::SolverBase<Eigen::SparseMatrix<double>>, unsigned, double>::instance() ->create(solver_type, std::move(max_iter), std::move(tolerance)); // Specific settings if (solver.contains("sub_solver_type")) lin_solver->set_sub_solver_type( solver["sub_solver_type"].template get<std::string>()); if (solver.contains("preconditioner_type")) lin_solver->set_preconditioner_type( solver["preconditioner_type"].template get<std::string>()); if (solver.contains("abs_tolerance")) lin_solver->set_abs_tolerance( solver["abs_tolerance"].template get<double>()); if (solver.contains("div_tolerance")) lin_solver->set_div_tolerance( solver["div_tolerance"].template get<double>()); if (solver.contains("verbosity")) lin_solver->set_verbosity(solver["verbosity"].template get<unsigned>()); // Add solver set to map linear_solver.insert( std::pair< std::string, std::shared_ptr<mpm::SolverBase<Eigen::SparseMatrix<double>>>>( dof, lin_solver)); } } //! Initialise nonlocal mesh template <unsigned Tdim> void mpm::MPMBase<Tdim>::initialise_nonlocal_mesh(const Json& mesh_props) { //! Shape function name const auto cell_type = mesh_props["cell_type"].template get<std::string>(); try { if (cell_type.back() == 'B') { // Cell and node neighbourhood for quadratic B-Spline cell_neighbourhood_ = 1; node_neighbourhood_ = 3; // Initialise nonlocal node mesh_->iterate_over_nodes( std::bind(&mpm::NodeBase<Tdim>::initialise_nonlocal_node, std::placeholders::_1)); //! Read nodal type from entity sets if (mesh_props.find("nonlocal_mesh_properties") != mesh_props.end() && mesh_props["nonlocal_mesh_properties"].find("node_types") != mesh_props["nonlocal_mesh_properties"].end()) { // Iterate over node type for (const auto& node_type : mesh_props["nonlocal_mesh_properties"]["node_types"]) { // Set id int nset_id = node_type.at("nset_id").template get<int>(); // Direction unsigned dir = node_type.at("dir").template get<unsigned>(); // Type unsigned type = node_type.at("type").template get<unsigned>(); // Assign nodal nonlocal type mesh_->assign_nodal_nonlocal_type(nset_id, dir, type); } } //! Update number of nodes in cell mesh_->upgrade_cells_to_nonlocal(cell_type, cell_neighbourhood_); } } catch (std::exception& exception) { console_->warn("{} #{}: initialising nonlocal mesh failed! ", __FILE__, __LINE__, exception.what()); } }
37.255493
80
0.634967
jgiven100
54e372d63f2884a1d9cc555ce2b3aa6387125a89
2,190
cpp
C++
bbs/exec_os2.cpp
RPTST/wwiv_dietpi
202177393778e809ffe657095c1f77aa8f404651
[ "Apache-2.0" ]
157
2015-07-08T18:29:22.000Z
2022-03-10T10:22:58.000Z
bbs/exec_os2.cpp
RPTST/wwiv_dietpi
202177393778e809ffe657095c1f77aa8f404651
[ "Apache-2.0" ]
1,037
2015-07-18T03:09:12.000Z
2022-03-13T17:39:55.000Z
bbs/exec_os2.cpp
RPTST/wwiv_dietpi
202177393778e809ffe657095c1f77aa8f404651
[ "Apache-2.0" ]
74
2015-07-08T19:42:19.000Z
2021-12-22T06:15:46.000Z
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)1998-2021, WWIV Software Services */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, */ /* software distributed under the License is distributed on an */ /* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */ /* either express or implied. See the License for the specific */ /* language governing permissions and limitations under the License. */ /* */ /**************************************************************************/ #include "bbs/exec.h" #include "bbs/application.h" #include "bbs/bbs.h" #include "bbs/stuffin.h" #include "common/output.h" #include "common/remote_io.h" #include "core/log.h" #include "fmt/format.h" #include <cctype> #include <process.h> #include <string> int exec_cmdline(wwiv::bbs::CommandLine& cmdline, int flags) { if (a()->sess().ok_modem_stuff() && a()->sess().using_modem()) { VLOG(1) <<"Closing remote IO"; bout.remoteIO()->close(true); } const auto cmd = cmdline.cmdline(); auto res = system(cmd.c_str()); if (a()->sess().ok_modem_stuff() && a()->sess().using_modem()) { VLOG(1) << "Reopening comm (on createprocess error)"; bout.remoteIO()->open(); } if (res != 0) { LOG(ERROR) << "error on system: " << res << "; errno: " << errno; } return res; }
41.320755
76
0.440639
RPTST
54e38f30c7799eef7faf904fc518e163b9eed972
25,671
cpp
C++
src/ed_genome_aligner.cpp
BioGeek/BrumiR
c4a8f58411399c86ed73a190445f180f7ed4fbf1
[ "MIT" ]
7
2020-08-06T15:31:15.000Z
2022-01-12T16:59:46.000Z
src/ed_genome_aligner.cpp
BioGeek/BrumiR
c4a8f58411399c86ed73a190445f180f7ed4fbf1
[ "MIT" ]
2
2020-09-07T16:12:43.000Z
2022-02-21T08:31:06.000Z
src/ed_genome_aligner.cpp
BioGeek/BrumiR
c4a8f58411399c86ed73a190445f180f7ed4fbf1
[ "MIT" ]
2
2020-08-14T01:39:28.000Z
2020-11-05T12:28:04.000Z
#include <unistd.h> #include <cstdlib> #include <cstring> #include <cstdio> #include <vector> #include <ctime> #include <string> #include <climits> #include <queue> #include <map> #include <unordered_map> #include <iterator> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <cassert> #include <algorithm> #include "edlib.h" using namespace std; //struct for seqs typedef struct seq{ int id=-1; string name=""; string seq="";//contigs are string rseq=""; } seq; //save the match of miRNAs in the genome sequence typedef struct mihit{ int qid;// internal microRNA id string qname;//name of the miRNA int rid;//internal reference id int qstart;//miStart int qend;//Mi end int tstart;//ref start int tend;//ref name int edit_distance;//actual edit distance bool strand;//0 means forward, 1 means reverse int alnlen;//length of alignment int qlen;//miRNA lenght int cov;//aln coverage of the miRNA }mihit; string revcomp(string kmer); void map_in_genome_window(string wgenome, int wstart, vector<seq> &queries, vector<mihit> &mihits, int k, bool log,int t); int read_fasta(string filename, vector<seq> &seqs); void print_hit(mihit &mh); //function that get the sequence of the potencial precursors void get_potential_precursors(vector<mihit> &mihits, vector<seq> &qry, vector<seq> &ref, int bestn); //function that get the sequence of the potencial precursors for plants void get_potential_precursors_plants(vector<mihit> &mihits, vector<seq> &qry, vector<seq> &ref, int bestn); void printAlignment(const char* query, const char* target, const unsigned char* alignment, const int alignmentLength, const int position, const EdlibAlignMode modeCode); // For debugging void printSeq(const vector<char> &seq) { for (int i = 0; i < (int) seq.size(); i++) printf("%d ", seq[i]); printf("\n"); } int main(int argc, char * const argv[]) { //----------------------------- PARSE COMMAND LINE ------------------------// // If true, there will be no output. bool silent = false; // Alignment mode. char mode[16] = "NW"; // How many best sequences (those with smallest score) do we want. // If 0, then we want them all. int numBestSeqs = 0; bool findAlignment = false; bool findStartLocations = false; bool plantmode = false; int option; int kArg = -1; // If "STD" or "EXT", cigar string will be printed. if "NICE" nice representation // of alignment will be printed. char alignmentFormat[16] = "NICE"; bool invalidOption = false; while ((option = getopt(argc, argv, "m:n:k:f:spla")) >= 0) { switch (option) { case 'm': strcpy(mode, optarg); break; case 'n': numBestSeqs = atoi(optarg); break; case 'k': kArg = atoi(optarg); break; case 'f': strcpy(alignmentFormat, optarg); break; case 's': silent = true; break; case 'p': plantmode = true; break; case 'a': findAlignment = true; break; case 'l': findStartLocations = true; break; default: invalidOption = true; } } if (optind + 2 != argc || invalidOption) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s [options...] <queries.fasta> <target.fasta>\n", argv[0]); fprintf(stderr, "Options:\n"); fprintf(stderr, "\t-s If specified, there will be no score or alignment output (silent mode).\n"); fprintf(stderr, "\t-m HW|NW|SHW Alignment mode that will be used. [default: NW]\n"); fprintf(stderr, "\t-n N Score will be calculated only for N best sequences (best = with smallest score)." " If N = 0 then all sequences will be calculated." " Specifying small N can make total calculation much faster. [default: 0]\n"); fprintf(stderr, "\t-k K Sequences with score > K will be discarded." " Smaller k, faster calculation. If -1, no sequences will be discarded. [default: -1]\n"); fprintf(stderr, "\t-p If specified, active the plante mode of the genome based mapping.\n "); fprintf(stderr, "\t-a If specified, alignment path will be found and printed. " "This may significantly slow down the calculation.\n"); fprintf(stderr, "\t-l If specified, start locations will be found and printed. " "Each start location corresponds to one end location. This may somewhat slow down " "the calculation, but is still faster then finding alignment path and does not consume " "any extra memory.\n"); fprintf(stderr, "\t-f NICE|CIG_STD|CIG_EXT Format that will be used to print alignment path," " can be used only with -p. NICE will give visually attractive format, CIG_STD will " " give standard cigar format and CIG_EXT will give extended cigar format. [default: NICE]\n"); return 1; } //-------------------------------------------------------------------------// if (strcmp(alignmentFormat, "NICE") && strcmp(alignmentFormat, "CIG_STD") && strcmp(alignmentFormat, "CIG_EXT")) { printf("Invalid alignment path format (-f)!\n"); return 1; } EdlibAlignMode modeCode; if (!strcmp(mode, "SHW")) modeCode = EDLIB_MODE_SHW; else if (!strcmp(mode, "HW")) modeCode = EDLIB_MODE_HW; else if (!strcmp(mode, "NW")) modeCode = EDLIB_MODE_NW; else { printf("Invalid mode (-m)!\n"); return 1; } printf("Using %s alignment mode.\n", mode); EdlibAlignTask alignTask = EDLIB_TASK_DISTANCE; if (findStartLocations) alignTask = EDLIB_TASK_LOC; if (findAlignment) alignTask = EDLIB_TASK_PATH; int readResult; // Read queries char* queriesFilepath = argv[optind]; vector <seq> queries; printf("Reading queries...\n"); readResult = read_fasta(queriesFilepath, queries); if (readResult) { printf("Error: There is no file with name %s\n", queriesFilepath); return 1; } int numQueries = queries.size(); printf("NQ=%d\n",numQueries); int queriesTotalLength = 0; for (int i = 0; i < numQueries; i++) { queries[i].rseq=revcomp(queries[i].seq); queriesTotalLength += queries[i].seq.length(); printf("id=%d name=%s seq1=%s rseq1=%s\n",i, queries[i].name.c_str() ,queries[i].seq.c_str(),queries[i].rseq.c_str()); } printf("Read %d queries, %d residues total.\n", numQueries, queriesTotalLength); // Read target char* targetFilepath = argv[optind+1]; printf("Reading target fasta file...\n"); vector<seq> targets; readResult = read_fasta(targetFilepath, targets); if (readResult) { printf("Error: There is no file with name %s\n", targetFilepath); return 1; } clock_t start = clock(); printf("\nComparing queries to targets...\n"); //for quering all agains all vector<mihit> mihits; int window=200; for(auto t=0; t < targets.size(); t++){ //we split target in windows of length 500bp auto starget=targets[t].seq; printf("Scanning seq:%s %d\n",targets[t].name.c_str(),targets[t].seq.length()); for(auto j=0; j<starget.length()-window; j+=window) { auto wgenome = starget.substr(j, window); //we map the microRNA in the window map_in_genome_window(wgenome, j, queries, mihits, 2, false, t); } /* const char* target = targets[t].seq.c_str(); const char* ntarget = targets[t].name.c_str(); int targetLength = targets[t].seq.length();*/ //printf("Read target name=%s id=%d,L=%d residues.\n",ntarget,t, targetLength); } //closing the free printf("Total hits stored %d\n",mihits.size()); //for(auto h:mihits) //sort(mihits.begin(),mihits.end()) // for(auto mh:mihits) // print_hit(mh); //Step 2, we sort the array of positions by minimizer,seq and pos sort( mihits.begin( ), mihits.end( ), [ ]( const mihit a, const mihit b) { //return tie(a.qid,a.edit_distance,a.rid,a.tstart) < tie(b.qid,b.edit_distance,b.rid,b.tstart); //return tie(a.qid,a.edit_distance,a.cov*-1) < tie(a.qid,b.edit_distance,b.cov*-1); return (a.qid < b.qid) || ((a.qid == b.qid) && (a.edit_distance < b.edit_distance)) || ((a.qid == b.qid) && (a.edit_distance == b.edit_distance) && (a.cov > b.cov)); }); //we select the best N hits per miRNA location int MAX_HITS_PER_MIRNA=100; printf("Selecting the best %d per miRNA\n",MAX_HITS_PER_MIRNA); vector<mihit> best_mihits; unordered_map<int, int> hitcounter; //we innit the hitcounter hash for( auto mi:queries){ hitcounter[mi.id]=0; } //we select the best MAX_HITS_PER_MIRNA for(auto mh:mihits){ if(hitcounter[mh.qid] < MAX_HITS_PER_MIRNA){ best_mihits.push_back(mh); hitcounter[mh.qid]++; }else{ hitcounter[mh.qid]++; } } //we print the total HITS per miRNA for(auto cc:hitcounter) printf("H_TOTAL_COUNT: id=%d total=%d\n",cc.first,cc.second); //we print the best hit selected for(auto mh:best_mihits) print_hit(mh); //get the sequece from the hits if(plantmode){ //plante mode //get_potential_precursors_plants(mihits,queries,targets,10); get_potential_precursors_plants(best_mihits,queries,targets,10); }else{ //default mode for vertebrates genomes //get_potential_precursors(mihits,queries,targets,10); get_potential_precursors(best_mihits,queries,targets,10); } clock_t finish = clock(); double cpuTime = ((double)(finish-start))/CLOCKS_PER_SEC; printf("\nCpu time of searching: %lf\n", cpuTime); return 0; } //global array for to compute revcomp char const comp_tab2[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O', 'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', 91, 92, 93, 94, 95, 64, 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o', 'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', 123, 124, 125, 126, 127 }; //heng li revcomp this is for printing only string revcomp(string kmer) { int c0, c1; int klen=kmer.length(); for (int i = 0; i < klen>>1; ++i) { // reverse complement sequence c0 = comp_tab2[(int)kmer[i]]; c1 = comp_tab2[(int)kmer[klen - 1 - i]]; kmer[i] = c1; kmer[klen - 1 - i] = c0; } if (klen & 1) // complement the remaining base kmer[klen>>1] = comp_tab2[(int)kmer[klen>>1]]; return kmer; } void print_hit(mihit &mh){ printf("HIT Qid=%d Rid=%d rs=%d re=%d ed=%d aln=%d qlen=%d cov=%d strand=%d\n",mh.qid,mh.rid,mh.tstart,mh.tend,mh.edit_distance,mh.alnlen,mh.qlen,mh.cov,mh.strand); } //mirDeep2 take the sequences like this //todo: check RNAfold command of mirDeep2 //ViennaRNA-2.4.9/RNA/bin/RNAfold -j3 --noPS -i ara.hits.fa --outfile=ara.hits.rnafold, three is the number of cores //command from mirDeep2 RNAfold < $dir_tmp/precursors.fa -noPS > $dir_tmp/precursors.str 2>>error_${time}.log //at this point the array of hits is sorted by miRNA and we want to create the fasta file for the precursor void get_potential_precursors(vector<mihit> &mihits, vector<seq> &qry, vector<seq> &ref, int bestn){ for (auto mh:mihits) { //print_hit(mh); //we print the foward sequence int excise_beg= mh.tstart-70; int excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) //printf("hsp_%d_%d_%d_%d %s\n",mh.qid,mh.rid,excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+70; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) //printf("hsp_%d_%d_%d_%d %s\n",mh.qid,mh.rid,excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); } } //print precursor sequence for plants void get_potential_precursors_plants(vector<mihit> &mihits, vector<seq> &qry, vector<seq> &ref, int bestn){ for (auto mh:mihits) { //print_hit(mh); //create a precursor sequence of ~110bp //we print the foward sequence int excise_beg= mh.tstart-70; int excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+70; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //create a precursor sequence of ~150bp excise_beg= mh.tstart-120; excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+120; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //create a precursor sequence of ~200bp excise_beg= mh.tstart-160; excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+160; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //create a precursor sequence of ~250bp excise_beg= mh.tstart-210; excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+210; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //create a precursor sequence of ~300bp excise_beg= mh.tstart-260; excise_end= mh.tend+20; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); //we print the rev sequence excise_beg= mh.tstart-20; excise_end= mh.tend+260; if(excise_beg >=0 and excise_end <=ref[mh.rid].seq.length()) printf("hsp::%s::%s::%d::%d %s\n",mh.qname.c_str(),ref[mh.rid].name.c_str(),excise_beg,excise_end,ref[mh.rid].seq.substr(excise_beg,abs(excise_beg-excise_end)).c_str()); } } /* * https://github.com/rajewsky-lab/mirdeep2/blob/master/src/excise_precursors.pl * lines: 251-261 * #else excise to sequences, corresponding to the read stack being the mature sequence #in the 5' arm or the 3' arm of the precursor hairpin my $excise_beg=$db_beg-70; my $excise_end=$db_end+20; #print out in fasta format print_positions($db,\$strand,$db_seq,\$db_lng,\$excise_beg,\$excise_end); $excise_beg=$db_beg-20; $excise_end=$db_end+70; print_positions($db,\$strand,$db_seq,\$db_lng,\$excise_beg,\$excise_end); #the most 3' position that has yet been excised $db_limit=$excise_end; */ void map_in_genome_window(string wgenome, int wstart, vector<seq> &queries, vector<mihit> &mihits,int k, bool log, int t){ EdlibAlignTask alignTask = EDLIB_TASK_LOC; //if (findStartLocations) alignTask = EDLIB_TASK_LOC; if (log) alignTask = EDLIB_TASK_PATH; EdlibAlignMode modeCode; modeCode=EDLIB_MODE_HW; const char* target = wgenome.c_str(); //hay que hacer lo mismo para el reverse int kmersize=12;//seed size miRNAs mihit mh; //indexando los 10-mers de la ventana unordered_map<string, bool> hashqq; for(int j=0; j< wgenome.length()-kmersize; j++) hashqq[wgenome.substr(j,kmersize)]=true; //printf("%d %s\n",queries.size(),target); for (int i = 0; i < queries.size(); ++i) { //printf("%s %s\n",queries[i].seq.c_str(),target); //char* query = queries[i].seq.c_str(); //int queryLength = queries[i].seq.length(); bool aln=false; for(int k=0; k<queries[i].seq.length()-kmersize; k++) if(hashqq.find(queries[i].seq.substr(k,kmersize)) !=hashqq.end() ){ aln=true; break; } if(aln){ // Calculate score EdlibAlignResult result = edlibAlign(queries[i].seq.c_str(), queries[i].seq.length(), target, wgenome.length(), edlibNewAlignConfig(-1, modeCode, alignTask, NULL, 0)); if (result.status == EDLIB_STATUS_OK){ if(result.editDistance <= k) { /*printf("HIT %s %s %d %d %d %d %d %d\n", queries[i].name.c_str(), rname.c_str(), wstart, result.editDistance, result.alignmentLength, result.startLocations[0], result.endLocations[0], 0);*/ //mh.qname = queries[i].name; mh.qid=i; mh.qname=queries[i].name; mh.rid=t; //mh.rname = rname; mh.tstart = wstart + result.startLocations[0];//pos for the target mh.tend = wstart + result.endLocations[0]; mh.qstart = result.startLocations[0]; mh.qend = result.endLocations[0]; mh.edit_distance = result.editDistance; mh.strand = 0;//strand foward for the miRNA //mh.alnlen = result.alignmentLength; mh.alnlen = abs(result.startLocations[0]-result.endLocations[0])+1;//is 0-based mh.qlen=queries[i].seq.length(); mh.cov=((float)mh.alnlen/mh.qlen)*100; //print_hit(mh); mihits.push_back(mh);//we store the hit in the vector } } edlibFreeAlignResult(result); } //reverse strand aln=false; for(int k=0; k<queries[i].rseq.length()-kmersize; k++) if(hashqq.find(queries[i].rseq.substr(k,kmersize)) !=hashqq.end() ){ aln=true; break; } if(aln){ // Calculate score EdlibAlignResult result = edlibAlign(queries[i].rseq.c_str(), queries[i].rseq.length(), target, wgenome.length(), edlibNewAlignConfig(-1, modeCode, alignTask, NULL, 0)); if (result.status == EDLIB_STATUS_OK){ if(result.editDistance <= k) { /* printf("HIT %s %s %d %d %d %d %d %d\n", queries[i].name.c_str(), rname.c_str(), wstart, result.editDistance, result.alignmentLength, result.startLocations[0], result.endLocations[0], 1); */ //mh.qname = queries[i].name; mh.qid=i; mh.qname=queries[i].name; mh.rid=t; //mh.rname = rname; mh.tstart = wstart + result.startLocations[0];//pos for the target mh.tend = wstart + result.endLocations[0]; mh.qstart = result.startLocations[0]; mh.qend = result.endLocations[0]; mh.edit_distance = result.editDistance; mh.strand = 1;//strand reverse of the miRNA mh.alnlen = abs(result.startLocations[0]-result.endLocations[0])+1; mh.qlen=queries[i].seq.length(); mh.cov=((float)mh.alnlen/mh.qlen)*100; //print_hit(mh); mihits.push_back(mh);//we store the hit in the vector } } edlibFreeAlignResult(result); } } } void printAlignment(const char* query, const char* target, const unsigned char* alignment, const int alignmentLength, const int position, const EdlibAlignMode modeCode) { int tIdx = -1; int qIdx = -1; if (modeCode == EDLIB_MODE_HW) { tIdx = position; for (int i = 0; i < alignmentLength; i++) { if (alignment[i] != EDLIB_EDOP_INSERT) tIdx--; } } for (int start = 0; start < alignmentLength; start += 50) { // target printf("T: "); int startTIdx; for (int j = start; j < start + 50 && j < alignmentLength; j++) { if (alignment[j] == EDLIB_EDOP_INSERT) printf("-"); else printf("%c", target[++tIdx]); if (j == start) startTIdx = tIdx; } printf(" (%d - %d)\n", max(startTIdx, 0), tIdx); // match / mismatch printf(" "); for (int j = start; j < start + 50 && j < alignmentLength; j++) { printf(alignment[j] == EDLIB_EDOP_MATCH ? "|" : " "); } printf("\n"); // query printf("Q: "); int startQIdx = qIdx; for (int j = start; j < start + 50 && j < alignmentLength; j++) { if (alignment[j] == EDLIB_EDOP_DELETE) printf("-"); else printf("%c", query[++qIdx]); if (j == start) startQIdx = qIdx; } printf(" (%d - %d)\n\n", max(startQIdx, 0), qIdx); } } //Construct contigs from FASTA file int read_fasta(string filename, vector<seq> &seqs){ std::ifstream input(filename); if(!input.good()){ std::cerr << "Error opening '"<<filename<<"'. Bailing out." << std::endl; return 1; } int id=0; std::string line, name, content; while(getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ // Identifier marker if( !name.empty() ){ // Print out what we read from the last entry //std::cout << name << ":" << content << std::endl; //cout << name << ":" <<id<<":"<< content << std::endl; //todo: improve the parsing of contig name for the moment we expect and space seq tmp; tmp.id=id; tmp.name=name.find(' ') ? name.substr(0, name.find(' ')):name.substr(0, name.find('\n')); tmp.seq=content; seqs.push_back(tmp); id++; name.clear(); } if( !line.empty() ){ name = line.substr(1);//pick name before the end; } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ // Print out what we read from the last entry seq tmp; tmp.id=id; tmp.name=name.substr(0, name.find(' ')); tmp.seq=content; seqs.push_back(tmp); //cout << name << ":" <<id<<":"<< content << std::endl; } return 0; }
41.471729
189
0.572007
BioGeek
54e5083094578c7207e73424e3b59db29e542ee5
443
cpp
C++
llvm/lib/TableGen/TableGenAction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
3
2019-02-12T04:14:39.000Z
2020-11-05T08:46:20.000Z
llvm/lib/TableGen/TableGenAction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
1
2020-02-22T09:59:21.000Z
2020-02-22T09:59:21.000Z
llvm/lib/TableGen/TableGenAction.cpp
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
1
2020-11-04T06:38:51.000Z
2020-11-04T06:38:51.000Z
//===- TableGenAction.cpp - defines TableGenAction --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/TableGen/TableGenAction.h" using namespace llvm; void TableGenAction::anchor() { }
27.6875
80
0.525959
clairechingching
54ea97f3430ae0025343fcfbbe1561cd21a83131
353
cpp
C++
ext2/open.cpp
danielzy95/fuse-ext2
3148484fce13768c307a8ca33ba46d8f524e247c
[ "MIT" ]
null
null
null
ext2/open.cpp
danielzy95/fuse-ext2
3148484fce13768c307a8ca33ba46d8f524e247c
[ "MIT" ]
null
null
null
ext2/open.cpp
danielzy95/fuse-ext2
3148484fce13768c307a8ca33ba46d8f524e247c
[ "MIT" ]
null
null
null
#include "operations.h" #include "inode.h" #include <string> #include <errno.h> #include <stdio.h> using namespace std; int open(const char *path, struct fuse_file_info *fi) { printf("OPERATION: open(path=%s)\n", path); if((fi->flags & 3) != O_RDONLY) return -EACCES; fi->fh = getInodeIndexByPath(string(path)); return 0; }
19.611111
55
0.645892
danielzy95
54eacb1a4fec0709cf83e0c3afb20b4640ac97a1
92,945
cpp
C++
enduser/sakit/sak/plugins/iisprov/globdata.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/sakit/sak/plugins/iisprov/globdata.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/sakit/sak/plugins/iisprov/globdata.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "iisprov.h" #define ALL_BITS_ON 0xFFFFFFFF /// // initialize METABASE_PROPERTY_DATA // METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessExecute = { L"AccessExecute",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_EXECUTE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessFlags = { L"AccessFlags",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessNoRemoteExecute = { L"AccessNoRemoteExecute",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_NO_REMOTE_EXECUTE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessNoRemoteRead = { L"AccessNoRemoteRead",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_NO_REMOTE_READ, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessNoRemoteScript = { L"AccessNoRemoteScript",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_NO_REMOTE_SCRIPT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessNoRemoteWrite = { L"AccessNoRemoteWrite",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_NO_REMOTE_WRITE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessRead = { L"AccessRead",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_READ, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSource = { L"AccessSource",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_SOURCE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessScript = { L"AccessScript",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_SCRIPT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSL = { L"AccessSSL",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_SSL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSL128 = { L"AccessSSL128",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_SSL128, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSLFlags = { L"AccessSSLFlags",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_SSL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSLMapCert = { L"AccessSSLMapCert",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_MAP_CERT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSLNegotiateCert = { L"AccessSSLNegotiateCert",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_NEGO_CERT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessSSLRequireCert = { L"AccessSSLRequireCert",MD_SSL_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_REQUIRE_CERT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AccessWrite = { L"AccessWrite",MD_ACCESS_PERM, IIS_MD_UT_FILE, DWORD_METADATA, MD_ACCESS_WRITE, METADATA_INHERIT, FALSE }; //METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AdminACL = // { L"AdminACL",MD_ADMIN_ACL, IIS_MD_UT_FILE, BINARY_METADATA, NULL, METADATA_INHERIT | METADATA_SECURE, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AdminServer = { L"AdminServer",MD_ADMIN_INSTANCE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AllowAnonymous = { L"AllowAnonymous",MD_ALLOW_ANONYMOUS, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AllowKeepAlive = { L"AllowKeepAlive",MD_ALLOW_KEEPALIVES, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AllowPathInfoForScriptMappings = { L"AllowPathInfoForScriptMappings",MD_ALLOW_PATH_INFO_FOR_SCRIPT_MAPPINGS, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AnonymousOnly = { L"AnonymousOnly",MD_ANONYMOUS_ONLY, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AnonymousPasswordSync = { L"AnonymousPasswordSync",MD_ANONYMOUS_USE_SUBAUTH, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AnonymousUserName = { L"AnonymousUserName",MD_ANONYMOUS_USER_NAME, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AnonymousUserPass = { L"AnonymousUserPass",MD_ANONYMOUS_PWD, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT | METADATA_SECURE, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppAllowClientDebug = { L"AppAllowClientDebug",MD_ASP_ENABLECLIENTDEBUG, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppAllowDebugging = { L"AppAllowDebugging",MD_ASP_ENABLESERVERDEBUG, IIS_MD_UT_WAM, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppFriendlyName = { L"AppFriendlyName",MD_APP_FRIENDLY_NAME, IIS_MD_UT_WAM, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppIsolated = { L"AppIsolated",MD_APP_ISOLATED, IIS_MD_UT_WAM, DWORD_METADATA, NULL, METADATA_INHERIT, TRUE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppOopRecoverLimit = { L"AppOopRecoverLimit",MD_APP_OOP_RECOVER_LIMIT, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppPackageID = { L"AppPackageId",MD_APP_PACKAGE_ID, IIS_MD_UT_WAM, STRING_METADATA, NULL, METADATA_INHERIT, TRUE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppPackageName = { L"AppPackageName",MD_APP_PACKAGE_NAME, IIS_MD_UT_WAM, STRING_METADATA, NULL, METADATA_INHERIT, TRUE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppRoot = { L"AppRoot",MD_APP_ROOT, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, TRUE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AppWamClsid = { L"AppWamClsID",MD_APP_WAM_CLSID, IIS_MD_UT_WAM, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspAllowOutOfProcComponents = { L"AspAllowOutOfProcComponents",MD_ASP_ALLOWOUTOFPROCCOMPONENTS, IIS_MD_UT_WAM, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspAllowSessionState = { L"AspAllowSessionState",MD_ASP_ALLOWSESSIONSTATE, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspBufferingOn = { L"AspBufferingOn",MD_ASP_BUFFERINGON, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspCodepage = { L"AspCodepage",MD_ASP_CODEPAGE, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspEnableApplicationRestart = { L"AspEnableApplicationRestart",MD_ASP_ENABLEAPPLICATIONRESTART, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspEnableAspHtmlFallback = { L"AspEnableAspHtmlFallback",MD_ASP_ENABLEASPHTMLFALLBACK, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspEnableChunkedEncoding = { L"AspEnableChunkedEncoding",MD_ASP_ENABLECHUNKEDENCODING, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspEnableParentPaths = { L"AspEnableParentPaths",MD_ASP_ENABLEPARENTPATHS, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspEnableTypelibCache = { L"AspEnableTypelibCache",MD_ASP_ENABLETYPELIBCACHE, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspErrorsToNTLog = { L"AspErrorsToNTLog",MD_ASP_ERRORSTONTLOG, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspExceptionCatchEnable = { L"AspExceptionCatchEnable", MD_ASP_EXCEPTIONCATCHENABLE, IIS_MD_UT_WAM, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspLogErrorRequests = { L"AspLogErrorRequests",MD_ASP_LOGERRORREQUESTS, IIS_MD_UT_WAM, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspProcessorThreadMax = { L"AspProcessorThreadMax",MD_ASP_PROCESSORTHREADMAX, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspQueueConnectionTestTime = { L"AspQueueConnectionTestTime",MD_ASP_QUEUECONNECTIONTESTTIME, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspQueueTimeout = { L"AspQueueTimeout", MD_ASP_QUEUETIMEOUT, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspRequestQueueMax = { L"AspRequestQueueMax", MD_ASP_REQEUSTQUEUEMAX, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptEngineCacheMax = { L"AspScriptEngineCacheMax", MD_ASP_SCRIPTENGINECACHEMAX, IIS_MD_UT_WAM, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptErrorMessage = { L"AspScriptErrorMessage", MD_ASP_SCRIPTERRORMESSAGE, IIS_MD_UT_WAM, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptErrorSentToBrowser = { L"AspScriptErrorSentToBrowser", MD_ASP_SCRIPTERRORSSENTTOBROWSER, IIS_MD_UT_WAM, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptFileCacheSize = { L"AspScriptFileCacheSize",MD_ASP_SCRIPTFILECACHESIZE, IIS_MD_UT_WAM, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptLanguage = { L"AspScriptLanguage", MD_ASP_SCRIPTLANGUAGE, ASP_MD_UT_APP, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspScriptTimeout = { L"AspScriptTimeout", MD_ASP_SCRIPTTIMEOUT, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspSessionMax = { L"AspSessionMax", MD_ASP_SESSIONMAX, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspSessionTimeout = { L"AspSessionTimeout", MD_ASP_SESSIONTIMEOUT, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateEnabled = { L"AspThreadGateEnabled", MD_ASP_THREADGATEENABLED, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateLoadHigh = { L"AspThreadGateLoadHigh", MD_ASP_THREADGATELOADHIGH, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateLoadLow = { L"AspThreadGateLoadLow", MD_ASP_THREADGATELOADLOW, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateSleepDelay = { L"AspThreadGateSleepDelay", MD_ASP_THREADGATESLEEPDELAY, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateSleepMax = { L"AspThreadGateSleepMax", MD_ASP_THREADGATESLEEPMAX, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspThreadGateTimeSlice = { L"AspThreadGateTimeSlice", MD_ASP_THREADGATETIMESLICE, ASP_MD_UT_APP, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AspTrackThreadingModel = { L"AspTrackThreadingModel", MD_ASP_TRACKTHREADINGMODEL, ASP_MD_UT_APP, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthAnonymous = { L"AuthAnonymous",MD_AUTHORIZATION, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_ANONYMOUS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthBasic = { L"AuthBasic",MD_AUTHORIZATION, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_BASIC, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthFlags = { L"AuthFlags",MD_AUTHORIZATION, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthNTLM = { L"AuthNTLM",MD_AUTHORIZATION, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_NT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthPersistence = { L"AuthPersistence",MD_AUTHORIZATION_PERSISTENCE, IIS_MD_UT_FILE, DWORD_METADATA, NULL}; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthPersistSingleRequest = { L"AuthPersistSingleRequest",MD_AUTHORIZATION_PERSISTENCE, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_SINGLEREQUEST}; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthPersistSingleRequestIfProxy = { L"AuthPersistSingleRequestIfProxy",MD_AUTHORIZATION_PERSISTENCE, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_SINGLEREQUESTIFPROXY}; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_AuthPersistSingleRequestAlwaysIfProxy = { L"AuthPersistSingleRequestAlwaysIfProxy",MD_AUTHORIZATION_PERSISTENCE, IIS_MD_UT_FILE, DWORD_METADATA, MD_AUTH_SINGLEREQUESTALWAYSIFPROXY}; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CacheControlCustom = { L"CacheControlCustom",MD_CC_OTHER, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CacheControlMaxAge = { L"CacheControlMaxAge",MD_CC_MAX_AGE, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CacheControlNoCache = { L"CacheControlNoCache",MD_CC_NO_CACHE, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CacheISAPI = { L"CacheISAPI",MD_CACHE_EXTENSIONS, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CGITimeout = { L"CGITimeout",MD_SCRIPT_TIMEOUT, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ConnectionTimeout = { L"ConnectionTimeout",MD_CONNECTION_TIMEOUT, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ContentIndexed = { L"ContentIndexed", MD_IS_CONTENT_INDEXED, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuAppEnabled = { L"CpuAppenabled",MD_CPU_APP_ENABLED, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuCgiEnabled = { L"CpuCgiEnabled",MD_CPU_CGI_ENABLED, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLoggingMask = { L"CpuLoggingMask",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableActiveProcs = { L"CpuEnableActiveProcs",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_ACTIVE_PROCS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableAllProcLogging = { L"CpuEnableAllProcLogging",MD_CPU_LOGGING_OPTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_ALL_PROC_LOGGING, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableApplicationLogging = { L"CpuEnableApplicationLogging",MD_CPU_LOGGING_OPTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_APP_LOGGING, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableCgiLogging = { L"CpuEnableCgiLogging",MD_CPU_LOGGING_OPTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_CGI_LOGGING, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableEvent = { L"CpuEnableEvent",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_EVENT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableKernelTime = { L"CpuEnableKernelTime",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_KERNEL_TIME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableLogging = { L"CpuEnableLogging",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_LOGGING, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnablePageFaults = { L"CpuEnablePageFaults",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_PAGE_FAULTS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableProcType = { L"CpuEnableProcType",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_PROC_TYPE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableTerminatedProcs = { L"CpuEnableTerminatedProcs",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_TERMINATED_PROCS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableTotalProcs = { L"CpuEnableTotalProcs",MD_CPU_LOGGING_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_TOTAL_PROCS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuEnableUserTime = { L"CpuEnableUserTime",MD_CPU_ENABLE_USER_TIME, IIS_MD_UT_SERVER, DWORD_METADATA, MD_CPU_ENABLE_USER_TIME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLimitLogEvent = { L"CpuLimitLogEvent",MD_CPU_LIMIT_LOGEVENT, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLimitPause = { L"CpuLimitPause",MD_CPU_LIMIT_PAUSE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLimitPriority = { L"CpuLimitPriority",MD_CPU_LIMIT_PRIORITY, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLimitProcStop = { L"CpuLimitProcStop",MD_CPU_LIMIT_PROCSTOP, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLimitsEnabled = { L"CpuLimitsEnabled",MD_CPU_LIMITS_ENABLED, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLoggingInterval = { L"CpuLoggingInterval",MD_CPU_LOGGING_INTERVAL, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuLoggingOptions = { L"CpuLoggingOptions",MD_CPU_LOGGING_OPTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CpuResetInterval = { L"CpuResetInterval",MD_CPU_RESET_INTERVAL, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CreateCGIWithNewConsole = { L"CreateCGIWithNewConsole",MD_CREATE_PROC_NEW_CONSOLE, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CreateProcessAsUser = { L"CreateProcessAsUser",MD_CREATE_PROCESS_AS_USER, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_CustomErrorDescriptions = { L"CustomErrorDescriptions", MD_CUSTOM_ERROR_DESC, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DefaultDoc = { L"DefaultDoc",MD_DEFAULT_LOAD_FILE, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DefaultDocFooter = { L"DefaultDocFooter",MD_FOOTER_DOCUMENT, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DefaultLogonDomain = { L"DefaultLogonDomain",MD_DEFAULT_LOGON_DOMAIN, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseFlags = { L"DirBrowseFlags", MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseShowDate = { L"DirBrowseShowDate",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_SHOW_DATE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseShowExtension = { L"DirBrowseShowExtension",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_SHOW_EXTENSION, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseShowLongDate = { L"DirBrowseShowLongDate",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_LONG_DATE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseShowSize = { L"DirBrowseShowSize",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_SHOW_SIZE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirBrowseShowTime = { L"DirBrowseShowTime",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_SHOW_TIME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DirectoryLevelsToScan = { L"DirectoryLevelsToScan",MD_LEVELS_TO_SCAN, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DisableSocketPooling = { L"DisableSocketPooling",MD_DISABLE_SOCKET_POOLING, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DontLog = { L"DontLog",MD_DONT_LOG, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_DownlevelAdminInstance = { L"DownlevelAdminInstance",MD_DOWNLEVEL_ADMIN_INSTANCE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_EnableDefaultDoc = { L"EnableDefaultDoc",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_LOADDEFAULT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_EnableDirBrowsing = { L"EnableDirBrowsing",MD_DIRECTORY_BROWSING, IIS_MD_UT_FILE, DWORD_METADATA, MD_DIRBROW_ENABLED, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_EnableDocFooter = { L"EnableDocFooter",MD_FOOTER_ENABLED, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_EnableReverseDns = { L"EnableReverseDns",MD_DO_REVERSE_DNS, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ExitMessage = { L"ExitMessage",MD_EXIT_MESSAGE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterDescription = { L"FilterDescription",MD_FILTER_DESCRIPTION, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterEnabled = { L"FilterEnabled",MD_FILTER_ENABLED, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterFlags = { L"FilterFlags",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterLoadOrder = { L"FilterLoadOrder",MD_FILTER_LOAD_ORDER, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterPath = { L"FilterPath",MD_FILTER_IMAGE_PATH, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FilterState = { L"FilterState",MD_FILTER_STATE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FrontPageWeb = { L"FrontPageWeb",MD_FRONTPAGE_WEB, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_GreetingMessage = { L"GreetingMessage",MD_GREETING_MESSAGE, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcCompressionDll = { L"HcCompressionDll",MD_HC_COMPRESSION_DLL, IIS_MD_UT_SERVER, EXPANDSZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcCreateFlags = { L"HcCreateFlags",MD_HC_CREATE_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcDoDynamicCompression = { L"HcDoDynamicCompression",MD_HC_DO_DYNAMIC_COMPRESSION, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcDoOnDemandCompression = { L"HcDoOnDemandCompression",MD_HC_DO_ON_DEMAND_COMPRESSION, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcDoStaticCompression = { L"HcDoStaticCompression",MD_HC_DO_STATIC_COMPRESSION, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcDynamicCompressionLevel = { L"HcDynamicCompressionLevel",MD_HC_DYNAMIC_COMPRESSION_LEVEL, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcFileExtensions = { L"HcFileExtensions",MD_HC_FILE_EXTENSIONS, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcMimeType = { L"HcMimeType",MD_HC_MIME_TYPE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcOnDemandCompLevel = { L"HcOnDemandCompLevel",MD_HC_ON_DEMAND_COMP_LEVEL, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcPriority = { L"HcPriority",MD_HC_PRIORITY, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HcScriptFileExtensions = { L"HcScriptFileExtensions",MD_HC_SCRIPT_FILE_EXTENSIONS, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HttpCustomHeaders = { L"HttpCustomHeaders",MD_HTTP_CUSTOM, IIS_MD_UT_FILE, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HttpErrors = { L"HttpErrors",MD_CUSTOM_ERROR, IIS_MD_UT_FILE, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HttpExpires = { L"HttpExpires",MD_HTTP_EXPIRES, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HttpPics = { L"HttpPics",MD_HTTP_PICS, IIS_MD_UT_FILE, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_HttpRedirect = { L"HttpRedirect",MD_HTTP_REDIRECT, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_InProcessIsapiApps = { L"InProcessIsapiApps",MD_SERVER_STATE, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; //METABASE_PROPERTY METABASE_PROPERTY_DATA::s_IPSecurity = // { L"IPSecurity",MD_IP_SEC, IIS_MD_UT_FILE, BINARY_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogAnonymous = { L"LogAnonymous",MD_LOG_ANONYMOUS, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyDataType = { L"LogCustomPropertyDataType",MD_LOGCUSTOM_PROPERTY_DATATYPE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyHeader = { L"LogCustomPropertyHeader",MD_LOGCUSTOM_PROPERTY_HEADER, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyID = { L"LogCustomPropertyID",MD_LOGCUSTOM_PROPERTY_ID, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyMask = { L"LogCustomPropertyMask",MD_LOGCUSTOM_PROPERTY_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyName = { L"LogCustomPropertyName",MD_LOGCUSTOM_PROPERTY_NAME, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogCustomPropertyServicesString = { L"LogCustomPropertyServicesString",MD_LOGCUSTOM_SERVICES_STRING, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileBytesRecv = { L"LogExtFileBytesRecv",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_BYTES_RECV, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileBytesSent = { L"LogExtFileBytesSent",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_BYTES_SENT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileClientIp = {L"LogExtFileClientIp",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_CLIENT_IP, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileComputerName = { L"LogExtFileComputerName",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_COMPUTER_NAME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileCookie = { L"LogExtFileCookie",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_COOKIE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileDate = { L"LogExtFileDate",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_DATE, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileFlags = { L"LogExtFileFlags",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileHttpStatus = { L"LogExtFileHttpStatus",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_HTTP_STATUS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileMethod = { L"LogExtFileMethod",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_METHOD, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileProtocolVersion = { L"LogExtFileProtocolVersion",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_PROTOCOL_VERSION, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileReferer = { L"LogExtFileReferer",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_REFERER, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileServerIp = { L"LogExtFileServerIp",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_SERVER_IP, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileServerPort = { L"LogExtFileServerPort",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_SERVER_PORT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileSiteName = { L"LogExtFileSiteName",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_SITE_NAME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileTime = { L"LogExtFileTime",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_TIME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileTimeTaken = { L"LogExtFileTimeTaken",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_TIME_TAKEN, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileUriQuery = { L"LogExtFileUriquery",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_URI_QUERY, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileUriStem = { L"LogExtFileUriStem",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_URI_STEM, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileUserAgent = { L"LogExtFileUserAgent",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_USER_AGENT, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileUserName = { L"LogExtFileUserName",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_USERNAME, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogExtFileWin32Status = { L"LogExtFileWin32Status",MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, DWORD_METADATA, MD_EXTLOG_WIN32_STATUS, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogFileDirectory = { L"LogFileDirectory",MD_LOGFILE_DIRECTORY, IIS_MD_UT_SERVER, EXPANDSZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogFileLocaltimeRollover = { L"LogFileLocaltimeRollover",MD_LOGFILE_LOCALTIME_ROLLOVER, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogFilePeriod = { L"LogFilePeriod",MD_LOGFILE_PERIOD, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogFileTruncateSize = { L"LogFileTruncateSize",MD_LOGFILE_TRUNCATE_SIZE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogModuleId = { L"LogModuleId", MD_LOG_PLUGIN_MOD_ID, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogModuleUiId = { L"LogModuleUiId", MD_LOG_PLUGIN_UI_ID, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogModuleList = { L"LogModuleList", MD_LOG_PLUGINS_AVAILABLE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogNonAnonymous = { L"LogNonAnonymous",MD_LOG_NONANONYMOUS, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogOdbcDataSource = { L"LogOdbcDataSource",MD_LOGSQL_DATA_SOURCES, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogOdbcPassword = { L"LogOdbcPassword",MD_LOGSQL_PASSWORD, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT | METADATA_SECURE, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogOdbcTableName = { L"LogOdbcTableName",MD_LOGSQL_TABLE_NAME, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogOdbcUserName = { L"LogOdbcUserName",MD_LOGSQL_USER_NAME, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogonMethod = { L"LogonMethod",MD_LOGON_METHOD, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogPluginClsId = { L"LogPluginClsId",MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_LogType = { L"LogType",MD_LOG_TYPE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MaxBandwidth = { L"MaxBandwidth",MD_MAX_BANDWIDTH, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MaxBandwidthBlocked = { L"MaxBandwidthBlocked",MD_MAX_BANDWIDTH_BLOCKED, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MaxClientsMessage = { L"MaxClientsMessage",MD_MAX_CLIENTS_MESSAGE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MaxConnections = { L"MaxConnections",MD_MAX_CONNECTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MaxEndpointConnections = { L"MaxEndpointConnections",MD_MAX_ENDPOINT_CONNECTIONS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MimeMap = { L"MimeMap",MD_MIME_MAP, IIS_MD_UT_FILE, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_MSDOSDirOutput = { L"MSDOSDirOutput",MD_MSDOS_DIR_OUTPUT, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NetLogonWorkstation = { L"NetLogonWorkstation",MD_NET_LOGON_WKS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotDeletable = { L"NotDeletable",MD_NOT_DELETABLE, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyAccessDenied = { L"NotifyAccessDenied",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_ACCESS_DENIED, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyAuthentication = { L"NotifyAuthentication",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_AUTHENTICATION, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyEndOfNetSession = { L"NotifyEndOfNetSession",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_END_OF_NET_SESSION, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyEndOfRequest = { L"NotifyEndOfRequest",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_END_OF_REQUEST, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyLog = { L"NotifyLog",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_LOG, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyNonSecurePort = { L"NotifyNonSecurePort",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_NONSECURE_PORT, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyOrderHigh = { L"NotifyOrderHigh",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_ORDER_HIGH, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyOrderLow = { L"NotifyOrderLow",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_ORDER_LOW, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyOrderMedium = { L"NotifyOrderMedium",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_ORDER_MEDIUM, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyPreProcHeaders = { L"NotifyPreProcHeaders",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_PREPROC_HEADERS, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyReadRawData = { L"NotifyReadRawData",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_READ_RAW_DATA, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifySecurePort = { L"NotifySecurePort",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_SECURE_PORT, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifySendRawData = { L"NotifySendRawData",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_SEND_RAW_DATA, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifySendResponse = { L"NotifySendResponse",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_SEND_RESPONSE, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NotifyUrlMap = { L"NotifyUrlMap",MD_FILTER_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, MD_NOTIFY_URL_MAP, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_NTAuthenticationProviders = { L"NTAuthenticationProviders",MD_NTAUTHENTICATION_PROVIDERS, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_PasswordCacheTTL = { L"PasswordCacheTTL", MD_ADV_CACHE_TTL, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_PasswordChangeFlags = { L"PasswordChangeFlags", MD_AUTH_CHANGE_FLAGS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_PasswordExpirePrenotifyDays = { L"PasswordExpirePrenotifyDays", MD_ADV_NOTIFY_PWD_EXP_IN_DAYS, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_Path = { L"Path", MD_VR_PATH, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_PoolIDCTimeout = { L"PoolIDCTimeout", MD_POOL_IDC_TIMEOUT, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ProcessNTCRIfLoggedOn = { L"ProcessNTCRIfLoggedOn", MD_PROCESS_NTCR_IF_LOGGED_ON, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_PutReadSize = { L"PutReadSize", MD_PUT_READ_SIZE, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_Realm = { L"Realm", MD_REALM, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_RedirectHeaders = { L"RedirectHeaders", MD_REDIRECT_HEADERS, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ScriptMaps = { L"ScriptMaps", MD_SCRIPT_MAPS, IIS_MD_UT_FILE, MULTISZ_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerAutoStart = { L"ServerAutoStart", MD_SERVER_AUTOSTART, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_SecureBindings = { L"SecureBindings",MD_SECURE_BINDINGS, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerBindings = { L"ServerBindings",MD_SERVER_BINDINGS, IIS_MD_UT_SERVER, MULTISZ_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerComment = { L"ServerComment",MD_SERVER_COMMENT, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerConfigAutoPWSync = { L"ServerConfigAutoPWSync",MD_SERVER_CONFIGURATION_INFO, IIS_MD_UT_SERVER, DWORD_METADATA, MD_SERVER_CONFIG_AUTO_PW_SYNC, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerConfigFlags = { L"ServerConfigFlags",MD_SERVER_CONFIGURATION_INFO, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerConfigSSL128 = { L"ServerConfigSSL128",MD_SERVER_CONFIGURATION_INFO, IIS_MD_UT_SERVER, DWORD_METADATA, MD_SERVER_CONFIG_SSL_128, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerConfigSSL40 = { L"ServerConfigSSL40",MD_SERVER_CONFIGURATION_INFO, IIS_MD_UT_SERVER, DWORD_METADATA, MD_SERVER_CONFIG_SSL_40, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerConfigSSLAllowEncrypt = { L"ServerConfigSSLAllowEncrypt",MD_SERVER_CONFIGURATION_INFO, IIS_MD_UT_SERVER, DWORD_METADATA, MD_SERVER_CONFIG_ALLOW_ENCRYPT, METADATA_NO_ATTRIBUTES, FALSE }; // custom property: ServerID METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerID = { L"ServerID",0, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerListenBacklog = { L"ServerListenBacklog",MD_SERVER_LISTEN_BACKLOG, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerListenTimeout = { L"ServerListenTimeout",MD_SERVER_LISTEN_TIMEOUT, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerSize = { L"ServerSize",MD_SERVER_SIZE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_ServerState = { L"ServerState",MD_SERVER_STATE, IIS_MD_UT_SERVER, DWORD_METADATA, NULL, METADATA_NO_ATTRIBUTES, TRUE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_SSIExecDisable = { L"SSIExecDisable",MD_SSI_EXEC_DISABLED, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_UNCAuthenticationPassthrough = { L"UNCAuthenticationPassthrough", MD_VR_PASSTHROUGH, IIS_MD_UT_FILE, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_UNCPassword = { L"UNCPassword", MD_VR_PASSWORD, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT | METADATA_SECURE, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_UNCUserName = { L"UNCUserName", MD_VR_USERNAME, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_FtpDirBrowseShowLongDate = { L"FtpDirBrowseShowLongDate", MD_SHOW_4_DIGIT_YEAR, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_UploadReadAheadSize = { L"UploadReadAheadSize", MD_UPLOAD_READAHEAD_SIZE, IIS_MD_UT_FILE, DWORD_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_UseHostName = { L"UseHostName", MD_USE_HOST_NAME, IIS_MD_UT_SERVER, DWORD_METADATA, ALL_BITS_ON, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_WAMUserName = { L"WamUserName", MD_WAM_USER_NAME, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_WAMUserPass = { L"WamUserPass", MD_WAM_PWD, IIS_MD_UT_FILE, STRING_METADATA, NULL, METADATA_INHERIT | METADATA_SECURE, FALSE }; METABASE_PROPERTY METABASE_PROPERTY_DATA::s_KeyType = { L"", MD_KEY_TYPE, IIS_MD_UT_SERVER, STRING_METADATA, NULL, METADATA_NO_ATTRIBUTES, FALSE }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpComputerSettings[] = { &s_MaxBandwidth, &s_MaxBandwidthBlocked, &s_MimeMap, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpComputer[] = { NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpMimeMapSetting[] = { &s_MimeMap, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpLogModuleSetting[] = { &s_LogModuleId, &s_LogModuleUiId, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpCustomLogModuleSetting[] = { &s_LogCustomPropertyDataType, &s_LogCustomPropertyHeader, &s_LogCustomPropertyID, &s_LogCustomPropertyMask, &s_LogCustomPropertyName, &s_LogCustomPropertyServicesString, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpCompressionSchemeSetting[] = { &s_HcCompressionDll, &s_HcCreateFlags, &s_HcDoDynamicCompression, &s_HcDoOnDemandCompression, &s_HcDoStaticCompression, &s_HcDynamicCompressionLevel, &s_HcFileExtensions, &s_HcMimeType, &s_HcOnDemandCompLevel, &s_HcPriority, &s_HcScriptFileExtensions, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpService[] = { NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpInfoSetting[] = { &s_LogModuleList, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpServer[] = { &s_ServerState, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpVirtualDir[] = { NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpVirtualDirSettings[] = { &s_AccessFlags, &s_AccessRead, &s_AccessWrite, &s_DontLog, &s_FtpDirBrowseShowLongDate, &s_Path, &s_UNCPassword, &s_UNCUserName, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpServiceSettings[] = { &s_LogExtFileFlags, &s_AccessFlags, &s_AccessRead, &s_AccessWrite, &s_DontLog, &s_FtpDirBrowseShowLongDate, &s_AllowAnonymous, &s_AnonymousOnly, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_ConnectionTimeout, &s_DefaultLogonDomain, &s_DisableSocketPooling, &s_ExitMessage, &s_GreetingMessage, &s_LogAnonymous, &s_LogExtFileBytesRecv, &s_LogExtFileBytesSent, &s_LogExtFileClientIp, &s_LogExtFileComputerName, &s_LogExtFileCookie, &s_LogExtFileDate, &s_LogExtFileHttpStatus, &s_LogExtFileMethod, &s_LogExtFileProtocolVersion, &s_LogExtFileReferer, &s_LogExtFileServerIp, &s_LogExtFileServerPort, &s_LogExtFileSiteName, &s_LogExtFileTime, &s_LogExtFileTimeTaken, &s_LogExtFileUriQuery, &s_LogExtFileUriStem, &s_LogExtFileUserAgent, &s_LogExtFileUserName, &s_LogExtFileWin32Status, &s_LogFileDirectory, &s_LogFileLocaltimeRollover, &s_LogFilePeriod, &s_LogFileTruncateSize, &s_LogNonAnonymous, &s_LogOdbcDataSource, &s_LogOdbcPassword, &s_LogOdbcTableName, &s_LogOdbcUserName, &s_LogPluginClsId, &s_LogType, &s_MaxClientsMessage, &s_MaxConnections, &s_MaxEndpointConnections, &s_MSDOSDirOutput, &s_Realm, &s_ServerAutoStart, &s_ServerBindings, &s_ServerComment, &s_ServerListenBacklog, &s_ServerListenTimeout, &s_ServerSize, &s_DirectoryLevelsToScan, &s_DownlevelAdminInstance, // &s_AdminACL, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpFtpServerSettings[] = { &s_LogExtFileFlags, &s_AccessFlags, &s_AccessRead, &s_AccessWrite, &s_DontLog, &s_FtpDirBrowseShowLongDate, &s_AllowAnonymous, &s_AnonymousOnly, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_ConnectionTimeout, &s_DefaultLogonDomain, &s_DisableSocketPooling, &s_ExitMessage, &s_GreetingMessage, &s_LogAnonymous, &s_LogExtFileBytesRecv, &s_LogExtFileBytesSent, &s_LogExtFileClientIp, &s_LogExtFileComputerName, &s_LogExtFileCookie, &s_LogExtFileDate, &s_LogExtFileHttpStatus, &s_LogExtFileMethod, &s_LogExtFileProtocolVersion, &s_LogExtFileReferer, &s_LogExtFileServerIp, &s_LogExtFileServerPort, &s_LogExtFileSiteName, &s_LogExtFileTime, &s_LogExtFileTimeTaken, &s_LogExtFileUriQuery, &s_LogExtFileUriStem, &s_LogExtFileUserAgent, &s_LogExtFileUserName, &s_LogExtFileWin32Status, &s_LogFileDirectory, &s_LogFileLocaltimeRollover, &s_LogFilePeriod, &s_LogFileTruncateSize, &s_LogNonAnonymous, &s_LogOdbcDataSource, &s_LogOdbcPassword, &s_LogOdbcTableName, &s_LogOdbcUserName, &s_LogPluginClsId, &s_LogType, &s_MaxClientsMessage, &s_MaxConnections, &s_MaxEndpointConnections, &s_MSDOSDirOutput, &s_Realm, &s_ServerAutoStart, &s_ServerBindings, &s_ServerComment, &s_ServerListenBacklog, &s_ServerListenTimeout, &s_ServerSize, // &s_AdminACL, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebService[] = { &s_AdminServer, &s_AppPackageName, &s_AppIsolated, &s_AppWamClsid, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebInfoSetting[] = { &s_ServerConfigFlags, &s_CustomErrorDescriptions, &s_LogModuleList, &s_ServerConfigAutoPWSync, &s_ServerConfigSSL128, &s_ServerConfigSSL40, &s_ServerConfigSSLAllowEncrypt, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebFilter[] = { &s_FilterFlags, &s_FilterDescription, &s_FilterEnabled, &s_FilterPath, &s_FilterState, &s_NotifyAuthentication, &s_NotifyEndOfNetSession, &s_NotifyEndOfRequest, &s_NotifyLog, &s_NotifyNonSecurePort, &s_NotifyOrderHigh, &s_NotifyOrderLow, &s_NotifyOrderMedium, &s_NotifyPreProcHeaders, &s_NotifyReadRawData, &s_NotifySecurePort, &s_NotifySendRawData, &s_NotifySendResponse, &s_NotifyUrlMap, &s_NotifyAccessDenied, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebServer[] = { &s_ServerState, &s_AppPackageName, &s_AppIsolated, &s_AppWamClsid, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebCertMapper[] = { NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebVirtualDir[] = { &s_AppIsolated, &s_AppPackageName, &s_AppWamClsid, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebDirectory[] = { &s_AppIsolated, &s_AppPackageName, &s_AppWamClsid, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebFile[] = { NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebServiceSettings[] = { &s_CpuLoggingOptions, &s_CpuLoggingMask, &s_LogExtFileFlags, &s_AuthFlags, &s_AuthPersistence, &s_AccessFlags, &s_AccessSSLFlags, &s_DirBrowseFlags, &s_AccessExecute, &s_AccessNoRemoteExecute, &s_AccessNoRemoteRead, &s_AccessNoRemoteScript, &s_AccessNoRemoteWrite, &s_AccessRead, &s_AccessScript, &s_AccessSSL, &s_AccessSSL128, &s_AccessSSLMapCert, &s_AccessSSLNegotiateCert, &s_AccessSSLRequireCert, &s_AccessWrite, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_AuthAnonymous, &s_AuthBasic, &s_AuthNTLM, &s_AuthPersistSingleRequest, &s_AuthPersistSingleRequestAlwaysIfProxy, &s_AuthPersistSingleRequestIfProxy, &s_CacheControlCustom, &s_CacheControlMaxAge, &s_CacheControlNoCache, &s_CGITimeout, &s_CpuAppEnabled, &s_CpuCgiEnabled, &s_CreateCGIWithNewConsole, &s_CreateProcessAsUser, &s_DefaultDocFooter, &s_DefaultLogonDomain, &s_DontLog, &s_EnableDocFooter, &s_EnableReverseDns, &s_HttpCustomHeaders, &s_HttpErrors, &s_HttpExpires, &s_HttpPics, &s_HttpRedirect, &s_LogonMethod, &s_MimeMap, &s_PoolIDCTimeout, &s_PutReadSize, &s_Realm, &s_RedirectHeaders, &s_ScriptMaps, &s_SSIExecDisable, &s_UNCAuthenticationPassthrough, &s_UploadReadAheadSize, &s_AppAllowClientDebug, &s_AppAllowDebugging, &s_AppFriendlyName, &s_AppPackageID, &s_AppRoot, &s_AspAllowOutOfProcComponents, &s_AspAllowSessionState, &s_AspBufferingOn, &s_AspCodepage, &s_AspEnableApplicationRestart, &s_AspEnableAspHtmlFallback, &s_AspEnableChunkedEncoding, &s_AspEnableParentPaths, &s_AspEnableTypelibCache, &s_AspErrorsToNTLog, &s_AspExceptionCatchEnable, &s_AspLogErrorRequests, &s_AspProcessorThreadMax, &s_AspQueueConnectionTestTime, &s_AspQueueTimeout, &s_AspRequestQueueMax, &s_AspScriptEngineCacheMax, &s_AspScriptErrorMessage, &s_AspScriptErrorSentToBrowser, &s_AspScriptFileCacheSize, &s_AspScriptLanguage, &s_AspScriptTimeout, &s_AspSessionMax, &s_AspSessionTimeout, &s_AspThreadGateEnabled, &s_AspThreadGateLoadHigh, &s_AspThreadGateLoadLow, &s_AspThreadGateSleepDelay, &s_AspThreadGateSleepMax, &s_AspThreadGateTimeSlice, &s_AspTrackThreadingModel, &s_CacheISAPI, &s_ContentIndexed, &s_DefaultDoc, &s_DirBrowseShowDate, &s_DirBrowseShowExtension, &s_DirBrowseShowLongDate, &s_DirBrowseShowSize, &s_DirBrowseShowTime, &s_EnableDefaultDoc, &s_EnableDirBrowsing, &s_AccessSource, &s_AllowKeepAlive, &s_AllowPathInfoForScriptMappings, &s_CGITimeout, &s_ConnectionTimeout, &s_CpuEnableActiveProcs, &s_CpuEnableAllProcLogging, &s_CpuEnableApplicationLogging, &s_CpuEnableCgiLogging, &s_CpuEnableEvent, &s_CpuEnableKernelTime, &s_CpuEnableLogging, &s_CpuEnablePageFaults, &s_CpuEnableProcType, &s_CpuEnableTerminatedProcs, &s_CpuEnableTotalProcs, &s_CpuEnableUserTime, &s_CpuLimitLogEvent, &s_CpuLimitPause, &s_CpuLimitPriority, &s_CpuLimitProcStop, &s_CpuLimitsEnabled, &s_CpuLoggingInterval, &s_CpuResetInterval, &s_LogExtFileBytesRecv, &s_LogExtFileBytesSent, &s_LogExtFileClientIp, &s_LogExtFileComputerName, &s_LogExtFileCookie, &s_LogExtFileDate, &s_LogExtFileHttpStatus, &s_LogExtFileMethod, &s_LogExtFileProtocolVersion, &s_LogExtFileReferer, &s_LogExtFileServerIp, &s_LogExtFileServerPort, &s_LogExtFileSiteName, &s_LogExtFileTime, &s_LogExtFileTimeTaken, &s_LogExtFileUriQuery, &s_LogExtFileUriStem, &s_LogExtFileUserAgent, &s_LogExtFileUserName, &s_LogExtFileWin32Status, &s_LogFileDirectory, &s_LogFileLocaltimeRollover, &s_LogFilePeriod, &s_LogFileTruncateSize, &s_LogOdbcDataSource, &s_LogOdbcPassword, &s_LogOdbcTableName, &s_LogOdbcUserName, &s_LogPluginClsId, &s_LogType, &s_MaxConnections, &s_MaxEndpointConnections, &s_NetLogonWorkstation, &s_NTAuthenticationProviders, &s_PasswordCacheTTL, &s_PasswordChangeFlags, &s_PasswordExpirePrenotifyDays, &s_ProcessNTCRIfLoggedOn, &s_ServerAutoStart, &s_ServerBindings, &s_ServerComment, &s_ServerListenBacklog, &s_ServerListenTimeout, &s_ServerSize, &s_UseHostName, &s_InProcessIsapiApps, &s_WAMUserName, &s_WAMUserPass, &s_DirectoryLevelsToScan, &s_DownlevelAdminInstance, // &s_AdminACL, // &s_IPSecurity, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebServerSettings[] = { &s_CpuLoggingOptions, &s_CpuLoggingMask, &s_LogExtFileFlags, &s_AuthFlags, &s_AuthPersistence, &s_AccessFlags, &s_AccessSSLFlags, &s_DirBrowseFlags, &s_AccessExecute, &s_AccessNoRemoteExecute, &s_AccessNoRemoteRead, &s_AccessNoRemoteScript, &s_AccessNoRemoteWrite, &s_AccessRead, &s_AccessScript, &s_AccessSSL, &s_AccessSSL128, &s_AccessSSLMapCert, &s_AccessSSLNegotiateCert, &s_AccessSSLRequireCert, &s_AccessWrite, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_AuthAnonymous, &s_AuthBasic, &s_AuthNTLM, &s_AuthPersistSingleRequest, &s_AuthPersistSingleRequestAlwaysIfProxy, &s_AuthPersistSingleRequestIfProxy, &s_CacheControlCustom, &s_CacheControlMaxAge, &s_CacheControlNoCache, &s_CGITimeout, &s_CpuAppEnabled, &s_CpuCgiEnabled, &s_CreateCGIWithNewConsole, &s_CreateProcessAsUser, &s_DefaultDocFooter, &s_DefaultLogonDomain, &s_DontLog, &s_EnableDocFooter, &s_EnableReverseDns, &s_HttpCustomHeaders, &s_HttpErrors, &s_HttpExpires, &s_HttpPics, &s_HttpRedirect, &s_LogonMethod, &s_MimeMap, &s_PoolIDCTimeout, &s_PutReadSize, &s_Realm, &s_RedirectHeaders, &s_ScriptMaps, &s_SSIExecDisable, &s_UNCAuthenticationPassthrough, &s_UploadReadAheadSize, &s_AppAllowClientDebug, &s_AppAllowDebugging, &s_AppFriendlyName, &s_AppPackageID, &s_AppRoot, &s_AspAllowOutOfProcComponents, &s_AspAllowSessionState, &s_AspBufferingOn, &s_AspCodepage, &s_AspEnableApplicationRestart, &s_AspEnableAspHtmlFallback, &s_AspEnableChunkedEncoding, &s_AspEnableParentPaths, &s_AspEnableTypelibCache, &s_AspErrorsToNTLog, &s_AspExceptionCatchEnable, &s_AspLogErrorRequests, &s_AspProcessorThreadMax, &s_AspQueueConnectionTestTime, &s_AspQueueTimeout, &s_AspRequestQueueMax, &s_AspScriptEngineCacheMax, &s_AspScriptErrorMessage, &s_AspScriptErrorSentToBrowser, &s_AspScriptFileCacheSize, &s_AspScriptLanguage, &s_AspScriptTimeout, &s_AspSessionMax, &s_AspSessionTimeout, &s_AspThreadGateEnabled, &s_AspThreadGateLoadHigh, &s_AspThreadGateLoadLow, &s_AspThreadGateSleepDelay, &s_AspThreadGateSleepMax, &s_AspThreadGateTimeSlice, &s_AspTrackThreadingModel, &s_CacheISAPI, &s_ContentIndexed, &s_DefaultDoc, &s_DirBrowseShowDate, &s_DirBrowseShowExtension, &s_DirBrowseShowLongDate, &s_DirBrowseShowSize, &s_DirBrowseShowTime, &s_EnableDefaultDoc, &s_EnableDirBrowsing, &s_AccessSource, &s_AllowKeepAlive, &s_AllowPathInfoForScriptMappings, &s_CGITimeout, &s_ConnectionTimeout, &s_CpuEnableActiveProcs, &s_CpuEnableAllProcLogging, &s_CpuEnableApplicationLogging, &s_CpuEnableCgiLogging, &s_CpuEnableEvent, &s_CpuEnableKernelTime, &s_CpuEnableLogging, &s_CpuEnablePageFaults, &s_CpuEnableProcType, &s_CpuEnableTerminatedProcs, &s_CpuEnableTotalProcs, &s_CpuEnableUserTime, &s_CpuLimitLogEvent, &s_CpuLimitPause, &s_CpuLimitPriority, &s_CpuLimitProcStop, &s_CpuLimitsEnabled, &s_CpuLoggingInterval, &s_CpuResetInterval, &s_LogExtFileBytesRecv, &s_LogExtFileBytesSent, &s_LogExtFileClientIp, &s_LogExtFileComputerName, &s_LogExtFileCookie, &s_LogExtFileDate, &s_LogExtFileHttpStatus, &s_LogExtFileMethod, &s_LogExtFileProtocolVersion, &s_LogExtFileReferer, &s_LogExtFileServerIp, &s_LogExtFileServerPort, &s_LogExtFileSiteName, &s_LogExtFileTime, &s_LogExtFileTimeTaken, &s_LogExtFileUriQuery, &s_LogExtFileUriStem, &s_LogExtFileUserAgent, &s_LogExtFileUserName, &s_LogExtFileWin32Status, &s_LogFileDirectory, &s_LogFileLocaltimeRollover, &s_LogFilePeriod, &s_LogFileTruncateSize, &s_LogOdbcDataSource, &s_LogOdbcPassword, &s_LogOdbcTableName, &s_LogOdbcUserName, &s_LogPluginClsId, &s_LogType, &s_MaxConnections, &s_MaxEndpointConnections, &s_NetLogonWorkstation, &s_NTAuthenticationProviders, &s_PasswordCacheTTL, &s_PasswordChangeFlags, &s_PasswordExpirePrenotifyDays, &s_ProcessNTCRIfLoggedOn, &s_ServerAutoStart, &s_ServerBindings, &s_ServerComment, &s_ServerListenBacklog, &s_ServerListenTimeout, &s_ServerSize, &s_UseHostName, &s_AppOopRecoverLimit, &s_MaxBandwidth, &s_MaxBandwidthBlocked, &s_NotDeletable, &s_SecureBindings, &s_ServerID, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebVirtualDirSettings[] = { &s_AuthFlags, &s_AuthPersistence, &s_AccessFlags, &s_AccessSSLFlags, &s_DirBrowseFlags, &s_AccessExecute, &s_AccessNoRemoteExecute, &s_AccessNoRemoteRead, &s_AccessNoRemoteScript, &s_AccessNoRemoteWrite, &s_AccessRead, &s_AccessScript, &s_AccessSSL, &s_AccessSSL128, &s_AccessSSLMapCert, &s_AccessSSLNegotiateCert, &s_AccessSSLRequireCert, &s_AccessWrite, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_AuthAnonymous, &s_AuthBasic, &s_AuthNTLM, &s_AuthPersistSingleRequest, &s_AuthPersistSingleRequestAlwaysIfProxy, &s_AuthPersistSingleRequestIfProxy, &s_CacheControlCustom, &s_CacheControlMaxAge, &s_CacheControlNoCache, &s_CGITimeout, &s_CpuAppEnabled, &s_CpuCgiEnabled, &s_CreateCGIWithNewConsole, &s_CreateProcessAsUser, &s_DefaultDocFooter, &s_DefaultLogonDomain, &s_DontLog, &s_EnableDocFooter, &s_EnableReverseDns, &s_HttpCustomHeaders, &s_HttpErrors, &s_HttpExpires, &s_HttpPics, &s_HttpRedirect, &s_LogonMethod, &s_MimeMap, &s_PoolIDCTimeout, &s_PutReadSize, &s_Realm, &s_RedirectHeaders, &s_ScriptMaps, &s_SSIExecDisable, &s_UNCAuthenticationPassthrough, &s_UploadReadAheadSize, &s_AppAllowClientDebug, &s_AppAllowDebugging, &s_AppFriendlyName, &s_AppPackageID, &s_AppRoot, &s_AspAllowOutOfProcComponents, &s_AspAllowSessionState, &s_AspBufferingOn, &s_AspCodepage, &s_AspEnableApplicationRestart, &s_AspEnableAspHtmlFallback, &s_AspEnableChunkedEncoding, &s_AspEnableParentPaths, &s_AspEnableTypelibCache, &s_AspErrorsToNTLog, &s_AspExceptionCatchEnable, &s_AspLogErrorRequests, &s_AspProcessorThreadMax, &s_AspQueueConnectionTestTime, &s_AspQueueTimeout, &s_AspRequestQueueMax, &s_AspScriptEngineCacheMax, &s_AspScriptErrorMessage, &s_AspScriptErrorSentToBrowser, &s_AspScriptFileCacheSize, &s_AspScriptLanguage, &s_AspScriptTimeout, &s_AspSessionMax, &s_AspSessionTimeout, &s_AspThreadGateEnabled, &s_AspThreadGateLoadHigh, &s_AspThreadGateLoadLow, &s_AspThreadGateSleepDelay, &s_AspThreadGateSleepMax, &s_AspThreadGateTimeSlice, &s_AspTrackThreadingModel, &s_CacheISAPI, &s_ContentIndexed, &s_DefaultDoc, &s_DirBrowseShowDate, &s_DirBrowseShowExtension, &s_DirBrowseShowLongDate, &s_DirBrowseShowSize, &s_DirBrowseShowTime, &s_EnableDefaultDoc, &s_EnableDirBrowsing, &s_AccessSource, &s_AppOopRecoverLimit, &s_Path, &s_UNCPassword, &s_UNCUserName, // &s_IPSecurity, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebDirectorySettings[] = { &s_AuthFlags, &s_AuthPersistence, &s_AccessFlags, &s_AccessSSLFlags, &s_DirBrowseFlags, &s_AccessExecute, &s_AccessNoRemoteExecute, &s_AccessNoRemoteRead, &s_AccessNoRemoteScript, &s_AccessNoRemoteWrite, &s_AccessRead, &s_AccessScript, &s_AccessSSL, &s_AccessSSL128, &s_AccessSSLMapCert, &s_AccessSSLNegotiateCert, &s_AccessSSLRequireCert, &s_AccessWrite, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_AuthAnonymous, &s_AuthBasic, &s_AuthNTLM, &s_AuthPersistSingleRequest, &s_AuthPersistSingleRequestAlwaysIfProxy, &s_AuthPersistSingleRequestIfProxy, &s_CacheControlCustom, &s_CacheControlMaxAge, &s_CacheControlNoCache, &s_CGITimeout, &s_CpuAppEnabled, &s_CpuCgiEnabled, &s_CreateCGIWithNewConsole, &s_CreateProcessAsUser, &s_DefaultDocFooter, &s_DefaultLogonDomain, &s_DontLog, &s_EnableDocFooter, &s_EnableReverseDns, &s_HttpCustomHeaders, &s_HttpErrors, &s_HttpExpires, &s_HttpPics, &s_HttpRedirect, &s_LogonMethod, &s_MimeMap, &s_PoolIDCTimeout, &s_PutReadSize, &s_Realm, &s_RedirectHeaders, &s_ScriptMaps, &s_SSIExecDisable, &s_UNCAuthenticationPassthrough, &s_UploadReadAheadSize, &s_AppAllowClientDebug, &s_AppAllowDebugging, &s_AppFriendlyName, &s_AppPackageID, &s_AppRoot, &s_AspAllowOutOfProcComponents, &s_AspAllowSessionState, &s_AspBufferingOn, &s_AspCodepage, &s_AspEnableApplicationRestart, &s_AspEnableAspHtmlFallback, &s_AspEnableChunkedEncoding, &s_AspEnableParentPaths, &s_AspEnableTypelibCache, &s_AspErrorsToNTLog, &s_AspExceptionCatchEnable, &s_AspLogErrorRequests, &s_AspProcessorThreadMax, &s_AspQueueConnectionTestTime, &s_AspQueueTimeout, &s_AspRequestQueueMax, &s_AspScriptEngineCacheMax, &s_AspScriptErrorMessage, &s_AspScriptErrorSentToBrowser, &s_AspScriptFileCacheSize, &s_AspScriptLanguage, &s_AspScriptTimeout, &s_AspSessionMax, &s_AspSessionTimeout, &s_AspThreadGateEnabled, &s_AspThreadGateLoadHigh, &s_AspThreadGateLoadLow, &s_AspThreadGateSleepDelay, &s_AspThreadGateSleepMax, &s_AspThreadGateTimeSlice, &s_AspTrackThreadingModel, &s_CacheISAPI, &s_ContentIndexed, &s_DefaultDoc, &s_DirBrowseShowDate, &s_DirBrowseShowExtension, &s_DirBrowseShowLongDate, &s_DirBrowseShowSize, &s_DirBrowseShowTime, &s_EnableDefaultDoc, &s_EnableDirBrowsing, &s_AppOopRecoverLimit, // &s_IPSecurity, NULL }; METABASE_PROPERTY* METABASE_PROPERTY_DATA::s_pmbpWebFileSettings[] = { &s_AuthFlags, &s_AuthPersistence, &s_AccessFlags, &s_AccessSSLFlags, &s_AccessExecute, &s_AccessNoRemoteExecute, &s_AccessNoRemoteRead, &s_AccessNoRemoteScript, &s_AccessNoRemoteWrite, &s_AccessRead, &s_AccessScript, &s_AccessSSL, &s_AccessSSL128, &s_AccessSSLMapCert, &s_AccessSSLNegotiateCert, &s_AccessSSLRequireCert, &s_AccessWrite, &s_AnonymousPasswordSync, &s_AnonymousUserName, &s_AnonymousUserPass, &s_AuthAnonymous, &s_AuthBasic, &s_AuthNTLM, &s_AuthPersistSingleRequest, &s_AuthPersistSingleRequestAlwaysIfProxy, &s_AuthPersistSingleRequestIfProxy, &s_CacheControlCustom, &s_CacheControlMaxAge, &s_CacheControlNoCache, &s_CGITimeout, &s_CpuAppEnabled, &s_CpuCgiEnabled, &s_CreateCGIWithNewConsole, &s_CreateProcessAsUser, &s_DefaultDocFooter, &s_DefaultLogonDomain, &s_DontLog, &s_EnableDocFooter, &s_EnableReverseDns, &s_HttpCustomHeaders, &s_HttpErrors, &s_HttpExpires, &s_HttpPics, &s_HttpRedirect, &s_LogonMethod, &s_MimeMap, &s_PoolIDCTimeout, &s_PutReadSize, &s_Realm, &s_RedirectHeaders, &s_ScriptMaps, &s_SSIExecDisable, &s_UNCAuthenticationPassthrough, &s_UploadReadAheadSize, &s_AccessSource, // &s_IPSecurity, NULL }; // //initialize WMI_METHOD_DATA // WMI_METHOD WMI_METHOD_DATA::s_ServiceCreateNewServer = {L"CreateNewServer", 0}; WMI_METHOD WMI_METHOD_DATA::s_ServerStart = {L"Start", MD_SERVER_COMMAND_START}; WMI_METHOD WMI_METHOD_DATA::s_ServerStop = {L"Stop", MD_SERVER_COMMAND_STOP}; WMI_METHOD WMI_METHOD_DATA::s_ServerContinue = {L"Continue", MD_SERVER_COMMAND_CONTINUE}; WMI_METHOD WMI_METHOD_DATA::s_ServerPause = {L"Pause", MD_SERVER_COMMAND_PAUSE}; WMI_METHOD WMI_METHOD_DATA::s_AppCreate = {L"AppCreate", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppCreate2 = {L"AppCreate2", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppDelete = {L"AppDelete", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppUnLoad = {L"AppUnLoad", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppDisable = {L"AppDisable", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppEnable = {L"AppEnable", 0}; WMI_METHOD WMI_METHOD_DATA::s_AppGetStatus = {L"AppGetStatus", 0}; WMI_METHOD WMI_METHOD_DATA::s_AspAppRestart = {L"AspAppRestart", 0}; WMI_METHOD WMI_METHOD_DATA::s_Backup = {L"Backup", 0}; WMI_METHOD WMI_METHOD_DATA::s_DeleteBackup = {L"DeleteBackup", 0}; WMI_METHOD WMI_METHOD_DATA::s_EnumBackups = {L"EnumBackups", 0}; WMI_METHOD WMI_METHOD_DATA::s_Restore = {L"Restore", 0}; WMI_METHOD WMI_METHOD_DATA::s_CreateMapping = {L"CreateMapping", 0}; WMI_METHOD WMI_METHOD_DATA::s_DeleteMapping = {L"DeleteMapping", 0}; WMI_METHOD WMI_METHOD_DATA::s_GetMapping = {L"GetMapping", 0}; WMI_METHOD WMI_METHOD_DATA::s_SetAcct = {L"SetAcct", 0}; WMI_METHOD WMI_METHOD_DATA::s_SetEnabled = {L"SetEnabled", 0}; WMI_METHOD WMI_METHOD_DATA::s_SetName = {L"SetName", 0}; WMI_METHOD WMI_METHOD_DATA::s_SetPwd = {L"SetPwd", 0}; WMI_METHOD* WMI_METHOD_DATA::s_ServiceMethods[] = { &s_ServiceCreateNewServer, NULL }; WMI_METHOD* WMI_METHOD_DATA::s_ServerMethods[] = { &s_ServerStart, &s_ServerStop, &s_ServerContinue, &s_ServerPause, NULL }; WMI_METHOD* WMI_METHOD_DATA::s_WebAppMethods[] = { &s_AppCreate, &s_AppCreate2, &s_AppDelete, &s_AppUnLoad, &s_AppDisable, &s_AppEnable, &s_AppGetStatus, &s_AspAppRestart, NULL }; WMI_METHOD* WMI_METHOD_DATA::s_ComputerMethods[] = { &s_Backup, &s_DeleteBackup, &s_EnumBackups, &s_Restore, NULL }; WMI_METHOD* WMI_METHOD_DATA::s_CertMapperMethods[] = { &s_CreateMapping, &s_DeleteMapping, &s_GetMapping, &s_SetAcct, &s_SetEnabled, &s_SetName, &s_SetPwd, NULL }; // //initialize WMI_CLASS_DATA // //** Computer WMI_CLASS WMI_CLASS_DATA::s_Computer = {L"IIs_Computer", L"", L"Name", METABASE_PROPERTY_DATA::s_pmbpComputer, IIsComputer, WMI_METHOD_DATA::s_ComputerMethods}; WMI_CLASS WMI_CLASS_DATA::s_ComputerSetting = {L"IIs_ComputerSetting", L"", L"Name", METABASE_PROPERTY_DATA::s_pmbpComputerSettings, IIsComputer, NULL}; //** MimeMap WMI_CLASS WMI_CLASS_DATA::s_MimeMapSetting = {L"IIs_MimeTypeSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpMimeMapSetting, IIsMimeMap, NULL}; //** LogModuleSetting WMI_CLASS WMI_CLASS_DATA::s_LogModuleSetting = {L"IIs_LogModuleSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpLogModuleSetting, IIsLogModule, NULL}; //** CustomLogModuleSetting WMI_CLASS WMI_CLASS_DATA::s_CustomLogModuleSetting = {L"IIs_CustomLogModuleSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpCustomLogModuleSetting, IIsCustomLogModule, NULL}; //** CompressionSchemeSetting WMI_CLASS WMI_CLASS_DATA::s_CompressionSchemeSetting = {L"IIs_CompressionSchemeSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpCompressionSchemeSetting, IIsCompressionScheme, NULL}; //** FtpService WMI_CLASS WMI_CLASS_DATA::s_FtpService = {L"IIs_FtpService", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpService, IIsFtpService, WMI_METHOD_DATA::s_ServiceMethods}; WMI_CLASS WMI_CLASS_DATA::s_FtpServiceSettings = {L"IIs_FtpServiceSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpServiceSettings, IIsFtpService, NULL}; //** FtpInfoSetting WMI_CLASS WMI_CLASS_DATA::s_FtpInfoSetting = {L"IIs_FtpInfoSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpInfoSetting, IIsFtpInfo, NULL}; //** FtpServer WMI_CLASS WMI_CLASS_DATA::s_FtpServer = {L"IIs_FtpServer", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpServer, IIsFtpServer, WMI_METHOD_DATA::s_ServerMethods}; WMI_CLASS WMI_CLASS_DATA::s_FtpServerSettings = {L"IIs_FtpServerSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpServerSettings, IIsFtpServer,NULL}; //** FtpVirtualDir WMI_CLASS WMI_CLASS_DATA::s_FtpVirtualDir = {L"IIs_FtpVirtualDir",L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpVirtualDir, IIsFtpVirtualDir, NULL}; WMI_CLASS WMI_CLASS_DATA::s_FtpVirtualDirSettings = {L"IIs_FtpVirtualDirSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpFtpVirtualDirSettings, IIsFtpVirtualDir, NULL}; //** WebService WMI_CLASS WMI_CLASS_DATA::s_WebService = {L"IIs_WebService", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpWebService, IIsWebService, WMI_METHOD_DATA::s_ServiceMethods}; WMI_CLASS WMI_CLASS_DATA::s_WebServiceSettings = {L"IIs_WebServiceSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpWebServiceSettings, IIsWebService, NULL}; //** WebInfoSetting WMI_CLASS WMI_CLASS_DATA::s_WebInfoSetting = {L"IIs_WebInfoSetting", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpWebInfoSetting, IIsWebInfo, NULL}; //** WebFilter WMI_CLASS WMI_CLASS_DATA::s_WebFilter = {L"IIs_Filter", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpWebFilter, IIsFilter, NULL}; //** WebServer WMI_CLASS WMI_CLASS_DATA::s_WebServer = {L"IIs_WebServer", L"/LM", L"Name", METABASE_PROPERTY_DATA::s_pmbpWebServer, IIsWebServer, WMI_METHOD_DATA::s_ServerMethods}; WMI_CLASS WMI_CLASS_DATA::s_WebServerSettings = {L"IIs_WebServerSetting", L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebServerSettings, IIsWebServer, NULL}; //** Web CertMapper WMI_CLASS WMI_CLASS_DATA::s_WebCertMapper = {L"IIs_CertMapper",L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebCertMapper, IIsCertMapper, WMI_METHOD_DATA::s_CertMapperMethods}; //** Web VirtualDir WMI_CLASS WMI_CLASS_DATA::s_WebVirtualDir = {L"IIs_WebVirtualDir",L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebVirtualDir, IIsWebVirtualDir, WMI_METHOD_DATA::s_WebAppMethods}; WMI_CLASS WMI_CLASS_DATA::s_WebVirtualDirSettings = {L"IIs_WebVirtualDirSetting", L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebVirtualDirSettings, IIsWebVirtualDir, NULL}; //** Web Directory WMI_CLASS WMI_CLASS_DATA::s_WebDirectory = {L"IIs_WebDirectory",L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebDirectory, IIsWebDirectory, WMI_METHOD_DATA::s_WebAppMethods}; WMI_CLASS WMI_CLASS_DATA::s_WebDirectorySettings = {L"IIs_WebDirectorySetting", L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebDirectorySettings, IIsWebDirectory, NULL}; //** Web File WMI_CLASS WMI_CLASS_DATA::s_WebFile = {L"IIs_WebFile",L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebFile, IIsWebFile, NULL}; WMI_CLASS WMI_CLASS_DATA::s_WebFileSettings = {L"IIs_WebFileSetting", L"/LM",L"Name", METABASE_PROPERTY_DATA::s_pmbpWebFileSettings, IIsWebFile, NULL}; //** AdminACL WMI_CLASS WMI_CLASS_DATA::s_AdminACL = {L"IIs_AdminACL", L"/LM",L"Name", NULL, TYPE_AdminACL, NULL}; WMI_CLASS WMI_CLASS_DATA::s_ACE = {L"IIs_ACE", L"/LM",L"Name", NULL, TYPE_AdminACE, NULL}; //** IPSecurity WMI_CLASS WMI_CLASS_DATA::s_IPSecurity = {L"IIs_IPSecuritySetting", L"/LM",L"Name", NULL, TYPE_IPSecurity, NULL}; WMI_CLASS* WMI_CLASS_DATA:: s_WmiClasses[] = { &s_Computer, &s_ComputerSetting, &s_MimeMapSetting, &s_LogModuleSetting, &s_CustomLogModuleSetting, &s_FtpService, &s_FtpServiceSettings, &s_FtpInfoSetting, &s_FtpServer, &s_FtpServerSettings, &s_FtpVirtualDir, &s_FtpVirtualDirSettings, &s_WebService, &s_WebServiceSettings, &s_WebInfoSetting, &s_WebFilter, &s_WebServer, &s_WebServerSettings, &s_WebCertMapper, &s_WebVirtualDir, &s_WebVirtualDirSettings, &s_WebDirectory, &s_WebDirectorySettings, &s_WebFile, &s_WebFileSettings, &s_CompressionSchemeSetting, &s_AdminACL, &s_ACE, &s_IPSecurity, NULL }; // //initialize WMI_ASSOCIATION_DATA // //** Computer **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToMimeMap = { L"IIs_Computer_MimeTypeSetting", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_MimeMapSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToLogModuleSettings = { L"IIs_Computer_LogModuleSetting", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_LogModuleSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToCustomLogModuleSetting = { L"IIs_Computer_CustomLogModuleSetting", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_CustomLogModuleSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToFtpService = { L"IIs_Computer_FtpService", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_FtpService, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToWebService = { L"IIs_Computer_WebService", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_WebService, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_ComputerToComputerSettings = { L"IIs_Computer_ComputerSetting", &WMI_CLASS_DATA::s_Computer, &WMI_CLASS_DATA::s_ComputerSetting, at_ElementSetting, 0}; //** FtpService **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServiceToInfo = { L"IIs_FtpService_FtpInfoSetting", &WMI_CLASS_DATA::s_FtpService, &WMI_CLASS_DATA::s_FtpInfoSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServiceToServer = { L"IIs_FtpService_FtpServer", &WMI_CLASS_DATA::s_FtpService, &WMI_CLASS_DATA::s_FtpServer, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServiceToSettings = { L"IIs_FtpService_FtpServiceSetting", &WMI_CLASS_DATA::s_FtpService, &WMI_CLASS_DATA::s_FtpServiceSettings, at_ElementSetting, 0}; //** FtpServer **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServerToVirtualDir = { L"IIs_FtpServer_FtpVirtualDir", &WMI_CLASS_DATA::s_FtpServer, &WMI_CLASS_DATA::s_FtpVirtualDir, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServerToSettings = { L"IIs_FtpServer_FtpServerSetting", &WMI_CLASS_DATA::s_FtpServer, &WMI_CLASS_DATA::s_FtpServerSettings, at_ElementSetting, 0}; //** Ftp VirtualDir **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpVirtualDirToVirtualDir = { L"IIs_FtpVirtualSubDir", &WMI_CLASS_DATA::s_FtpVirtualDir, &WMI_CLASS_DATA::s_FtpVirtualDir, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpVirtualDirToSettings = { L"IIs_FtpVirtualDir_FtpVirtualDirSetting", &WMI_CLASS_DATA::s_FtpVirtualDir, &WMI_CLASS_DATA::s_FtpVirtualDirSettings, at_ElementSetting, 0}; //** Web Service **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToInfo = { L"IIs_WebService_WebInfoSetting", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_WebInfoSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToFilter = { L"IIs_WebService_Filter", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_WebFilter, at_Component, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToServer = { L"IIs_WebService_WebServer", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_WebServer, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToSettings = { L"IIs_WebService_WebServiceSetting", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_WebServiceSettings, at_ElementSetting, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToCompressionSchemeSetting = { L"IIs_WebService_CompressionSchemeSetting", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_CompressionSchemeSetting, at_ElementSetting, ASSOC_EXTRAORDINARY}; //** WebServer **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToCertMapper = { L"IIs_WebServer_CertMapper", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_WebCertMapper, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToFilter = { L"IIs_WebServer_Filter", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_WebFilter, at_Component, ASSOC_EXTRAORDINARY}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToVirtualDir = { L"IIs_WebServer_WebVirtualDir", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_WebVirtualDir, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToSettings = { L"IIs_WebServer_WebServerSetting", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_WebServerSettings, at_ElementSetting, 0}; //** Web VirtualDir **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToVirtualDir = { L"IIs_WebVirtualSubDir", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_WebVirtualDir, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToDirectory = { L"IIs_WebVirtualDir_WebDirectory", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_WebDirectory, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToFile = { L"IIs_WebVirtualDir_File", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_WebFile, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToSettings = { L"IIs_WebVirtualDir_WebVirtualDirSetting", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_WebVirtualDirSettings, at_ElementSetting, 0}; //** Web Directory **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToDirectory = { L"IIs_WebSubDirectory", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_WebDirectory, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToVirtualDir = { L"IIs_WebDirectory_WebVirtualDir", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_WebVirtualDir, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToFile = { L"IIs_WebDirectory_File", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_WebFile, at_Component, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToSettings = { L"IIs_WebDirectory_WebDirectorySetting", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_WebDirectorySettings, at_ElementSetting, 0}; //** Web File **// WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebFileToSettings = { L"IIs_WebFile_WebFileSetting", &WMI_CLASS_DATA::s_WebFile, &WMI_CLASS_DATA::s_WebFileSettings, at_ElementSetting, 0}; //** AdminACL WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_AdminACLToACE = { L"IIs_AdminACL_ACE", &WMI_CLASS_DATA::s_AdminACL, &WMI_CLASS_DATA::s_ACE, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServiceToAdminACL = { L"IIs_FtpService_AdminACL", &WMI_CLASS_DATA::s_FtpService, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServerToAdminACL = { L"IIs_FtpServer_AdminACL", &WMI_CLASS_DATA::s_FtpServer, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpVirtualDirToAdminACL = { L"IIs_FtpVirtualDir_AdminACL", &WMI_CLASS_DATA::s_FtpVirtualDir, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToAdminACL = { L"IIs_WebService_AdminACL", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToAdminACL = { L"IIs_WebServer_AdminACL", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToAdminACL = { L"IIs_WebVirtualDir_AdminACL", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToAdminACL = { L"IIs_WebDirectory_AdminACL", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebFileToAdminACL = { L"IIs_WebFile_AdminACL", &WMI_CLASS_DATA::s_WebFile, &WMI_CLASS_DATA::s_AdminACL, at_AdminACL, 0}; //** IPSecurity WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServiceToIPSecurity = { L"IIs_FtpService_IPSecuritySetting", &WMI_CLASS_DATA::s_FtpService, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpServerToIPSecurity = { L"IIs_FtpServer_IPSecuritySetting", &WMI_CLASS_DATA::s_FtpServer, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_FtpVirtualDirToIPSecurity = { L"IIs_FtpVirtualDir_IPSecuritySetting", &WMI_CLASS_DATA::s_FtpVirtualDir, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServiceToIPSecurity = { L"IIs_WebService_IPSecuritySetting", &WMI_CLASS_DATA::s_WebService, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebServerToIPSecurity = { L"IIs_WebServer_IPSecuritySetting", &WMI_CLASS_DATA::s_WebServer, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebVirtualDirToIPSecurity = { L"IIs_WebVirtualDir_IPSecuritySetting", &WMI_CLASS_DATA::s_WebVirtualDir, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebDirectoryToIPSecurity = { L"IIs_WebDirectory_IPSecuritySetting", &WMI_CLASS_DATA::s_WebDirectory, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION WMI_ASSOCIATION_DATA::s_WebFileToIPSecurity = { L"IIs_WebFile_IPSecuritySetting", &WMI_CLASS_DATA::s_WebFile, &WMI_CLASS_DATA::s_IPSecurity, at_IPSecurity, 0}; WMI_ASSOCIATION* WMI_ASSOCIATION_DATA:: s_WmiAssociations[] = { &s_ComputerToMimeMap, // Computer &s_ComputerToFtpService, &s_ComputerToWebService, &s_ComputerToComputerSettings, &s_ComputerToLogModuleSettings, &s_ComputerToCustomLogModuleSetting, &s_FtpServiceToInfo, // FtpService &s_FtpServiceToServer, &s_FtpServiceToSettings, &s_FtpServerToVirtualDir, //FtpServer &s_FtpServerToSettings, &s_FtpVirtualDirToVirtualDir, //FtpVirtualDir &s_FtpVirtualDirToSettings, &s_WebServiceToInfo, //WebService &s_WebServiceToFilter, &s_WebServiceToServer, &s_WebServiceToSettings, &s_WebServiceToCompressionSchemeSetting, &s_WebServerToCertMapper, //WebServer &s_WebServerToFilter, &s_WebServerToVirtualDir, &s_WebServerToSettings, &s_WebVirtualDirToVirtualDir, //WebVirtualDir &s_WebVirtualDirToDirectory, &s_WebVirtualDirToFile, &s_WebVirtualDirToSettings, &s_WebDirectoryToDirectory, //WebDirectory &s_WebDirectoryToVirtualDir, &s_WebDirectoryToFile, &s_WebDirectoryToSettings, &s_WebFileToSettings, //WebFile &s_AdminACLToACE, //AdminACL &s_FtpServiceToAdminACL, &s_FtpServerToAdminACL, &s_FtpVirtualDirToAdminACL, &s_WebServiceToAdminACL, &s_WebServerToAdminACL, &s_WebVirtualDirToAdminACL, &s_WebDirectoryToAdminACL, &s_WebFileToAdminACL, &s_FtpServiceToIPSecurity, //IPSecurity &s_FtpServerToIPSecurity, &s_FtpVirtualDirToIPSecurity, &s_WebServiceToIPSecurity, &s_WebServerToIPSecurity, &s_WebVirtualDirToIPSecurity, &s_WebDirectoryToIPSecurity, &s_WebFileToIPSecurity, NULL };
43.270484
167
0.773511
npocmaka
54ef5926fd3330ac54c10fbc7caaa271a59622c6
4,228
cc
C++
chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/web_applications/os_url_handler_system_web_app_info.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/resources/grit/ash_public_unscaled_resources.h" #include "base/feature_list.h" #include "chrome/browser/ash/crosapi/browser_util.h" #include "chrome/browser/ash/web_applications/system_web_app_install_utils.h" #include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h" #include "chrome/common/webui_url_constants.h" #include "chrome/grit/generated_resources.h" #include "chromeos/crosapi/cpp/gurl_os_handler_utils.h" #include "content/public/common/url_constants.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/chromeos/styles/cros_styles.h" namespace { bool g_enable_delegate_for_testing = false; SkColor GetBgColor(bool use_dark_mode) { return cros_styles::ResolveColor( cros_styles::ColorName::kBgColor, use_dark_mode, base::FeatureList::IsEnabled( ash::features::kSemanticColorsDebugOverride)); } } // namespace OsUrlHandlerSystemWebAppDelegate::OsUrlHandlerSystemWebAppDelegate( Profile* profile) : web_app::SystemWebAppDelegate(web_app::SystemAppType::OS_URL_HANDLER, "OsUrlHandler", GURL(chrome::kChromeUIOsUrlAppURL), profile) {} OsUrlHandlerSystemWebAppDelegate::~OsUrlHandlerSystemWebAppDelegate() = default; std::unique_ptr<WebApplicationInfo> OsUrlHandlerSystemWebAppDelegate::GetWebAppInfo() const { auto info = std::make_unique<WebApplicationInfo>(); info->start_url = GURL(chrome::kChromeUIOsUrlAppURL); info->scope = GURL(chrome::kChromeUIOsUrlAppURL); info->title = l10n_util::GetStringUTF16(IDS_OS_URL_HANDLER_APP_NAME); web_app::CreateIconInfoForSystemWebApp( info->start_url, { {"os_url_handler_app_icon_48.png", 48, IDR_OS_URL_HANDLER_APP_ICONS_48_PNG}, {"os_url_handler_app_icon_128.png", 128, IDR_OS_URL_HANDLER_APP_ICONS_128_PNG}, {"os_url_handler_app_icon_192.png", 192, IDR_OS_URL_HANDLER_APP_ICONS_192_PNG}, }, *info); info->theme_color = GetBgColor(/*use_dark_mode=*/false); info->dark_mode_theme_color = GetBgColor(/*use_dark_mode=*/true); info->display_mode = blink::mojom::DisplayMode::kStandalone; info->user_display_mode = blink::mojom::DisplayMode::kStandalone; return info; } bool OsUrlHandlerSystemWebAppDelegate::ShouldCaptureNavigations() const { return true; } bool OsUrlHandlerSystemWebAppDelegate::IsAppEnabled() const { return g_enable_delegate_for_testing || crosapi::browser_util::IsLacrosEnabled(); } bool OsUrlHandlerSystemWebAppDelegate::ShouldShowInLauncher() const { return false; } bool OsUrlHandlerSystemWebAppDelegate::ShouldShowInSearch() const { return false; } bool OsUrlHandlerSystemWebAppDelegate::ShouldReuseExistingWindow() const { return false; } bool OsUrlHandlerSystemWebAppDelegate::IsUrlInSystemAppScope( const GURL& url) const { if (!IsAppEnabled()) return false; GURL target_url = crosapi::gurl_os_handler_utils::SanitizeAshURL(url); if (!target_url.has_scheme() || !target_url.has_host()) return false; if (ChromeWebUIControllerFactory::GetInstance()->CanHandleUrl(target_url)) return true; if (target_url.scheme() != content::kChromeUIScheme) return false; // By the time the web app system gets the link, the os:// scheme will have // been replaced by the chrome:// scheme. As the user cannot enter in ash // chrome:// scheme urls anymore, we should be safely able to assume that they // might have been os:// schemed URLs when being called from Lacros. target_url = crosapi::gurl_os_handler_utils::GetSystemUrlFromChromeUrl(target_url); return ChromeWebUIControllerFactory::GetInstance()->CanHandleUrl(target_url); } void OsUrlHandlerSystemWebAppDelegate::EnableDelegateForTesting(bool enable) { g_enable_delegate_for_testing = enable; }
35.830508
83
0.750473
chromium
54eff18cc3206ea631eff0ef88ca05bfc2195255
982
cpp
C++
src/compiler/CSSATree/cssatree.cpp
JoachimCoenen/ngpl-language
624c5aa98f7c15a9441a7cf31045a1cba3e2bc4b
[ "BSD-3-Clause" ]
null
null
null
src/compiler/CSSATree/cssatree.cpp
JoachimCoenen/ngpl-language
624c5aa98f7c15a9441a7cf31045a1cba3e2bc4b
[ "BSD-3-Clause" ]
null
null
null
src/compiler/CSSATree/cssatree.cpp
JoachimCoenen/ngpl-language
624c5aa98f7c15a9441a7cf31045a1cba3e2bc4b
[ "BSD-3-Clause" ]
null
null
null
#include "cssatree.h" namespace ngpl::CSSA { CSSATree::CSSATree() { } cat::WriterObjectABC& operator +=(cat::WriterObjectABC& s, const TaggedValue& v) { s += "TaggedValue"; auto tuple = std::make_tuple( MEMBER_PAIR(v, id), MEMBER_PAIR(v, generatedBy), MEMBER_PAIR(v, lamportTimestamp), MEMBER_PAIR(v, usageCount), MEMBER_PAIR(v, isAtFinalLocation), MEMBER_PAIR(v, isVirtual) ); formatTupleLike2(s, tuple, {"(", ")"}, cat::_formatFuncKwArg, true); return s; } cat::WriterObjectABC& operator +=(cat::WriterObjectABC& s, const TaggedInstruction& v) { s += "TaggedInstruction"; auto tuple = std::make_tuple( MEMBER_PAIR(v, id), MEMBER_PAIR(v, instr), MEMBER_PAIR(v, operands), //MEMBER_PAIR(v, generatesValues), //MEMBER_PAIR(v, causesSideEffect), MEMBER_PAIR(v, lamportTimestamp) //MEMBER_PAIR(v, recursivelyRequiredValues) ); formatTupleLike2(s, tuple, {"(", ")"}, cat::_formatFuncKwArg, true); return s; } }
23.95122
88
0.677189
JoachimCoenen
54f0320ed4efac113b50a39f9c436865dc1159f7
10,393
cpp
C++
WebLayoutCore/Source/WebCore/html/HTMLAttachmentElement.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
WebLayoutCore/Source/WebCore/html/HTMLAttachmentElement.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
null
null
null
WebLayoutCore/Source/WebCore/html/HTMLAttachmentElement.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2018-07-10T10:53:18.000Z
2018-07-10T10:53:18.000Z
/* * Copyright (C) 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "HTMLAttachmentElement.h" #if ENABLE(ATTACHMENT_ELEMENT) #include "DOMURL.h" #include "Document.h" #include "Editor.h" #include "File.h" #include "FileReaderLoader.h" #include "FileReaderLoaderClient.h" #include "Frame.h" #include "HTMLImageElement.h" #include "HTMLNames.h" #include "HTMLVideoElement.h" #include "MIMETypeRegistry.h" #include "RenderAttachment.h" #include "RenderBlockFlow.h" #include "ShadowRoot.h" #include "SharedBuffer.h" namespace WebCore { using namespace HTMLNames; class AttachmentDataReader : public FileReaderLoaderClient { public: static std::unique_ptr<AttachmentDataReader> create(HTMLAttachmentElement& attachment, Function<void(RefPtr<SharedBuffer>&&)>&& callback) { return std::make_unique<AttachmentDataReader>(attachment, WTFMove(callback)); } AttachmentDataReader(HTMLAttachmentElement& attachment, Function<void(RefPtr<SharedBuffer>&&)>&& callback) : m_attachment(attachment) , m_callback(std::make_unique<Function<void(RefPtr<SharedBuffer>&&)>>(WTFMove(callback))) , m_loader(std::make_unique<FileReaderLoader>(FileReaderLoader::ReadType::ReadAsArrayBuffer, this)) { m_loader->start(&attachment.document(), *attachment.file()); } ~AttachmentDataReader(); private: void didStartLoading() final { } void didReceiveData() final { } void didFinishLoading() final; void didFail(int error) final; void invokeCallbackAndFinishReading(RefPtr<SharedBuffer>&&); HTMLAttachmentElement& m_attachment; std::unique_ptr<Function<void(RefPtr<SharedBuffer>&&)>> m_callback; std::unique_ptr<FileReaderLoader> m_loader; }; HTMLAttachmentElement::HTMLAttachmentElement(const QualifiedName& tagName, Document& document) : HTMLElement(tagName, document) { ASSERT(hasTagName(attachmentTag)); } HTMLAttachmentElement::~HTMLAttachmentElement() = default; Ref<HTMLAttachmentElement> HTMLAttachmentElement::create(const QualifiedName& tagName, Document& document) { return adoptRef(*new HTMLAttachmentElement(tagName, document)); } RenderPtr<RenderElement> HTMLAttachmentElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&) { if (!style.hasAppearance()) { // If this attachment element doesn't have an appearance, defer rendering to child elements. return createRenderer<RenderBlockFlow>(*this, WTFMove(style)); } return createRenderer<RenderAttachment>(*this, WTFMove(style)); } File* HTMLAttachmentElement::file() const { return m_file.get(); } URL HTMLAttachmentElement::blobURL() const { return { { }, attributeWithoutSynchronization(HTMLNames::webkitattachmentbloburlAttr).string() }; } void HTMLAttachmentElement::setFile(RefPtr<File>&& file) { m_file = WTFMove(file); setAttributeWithoutSynchronization(HTMLNames::webkitattachmentbloburlAttr, m_file ? m_file->url() : emptyString()); if (auto* renderAttachment = attachmentRenderer()) renderAttachment->invalidate(); if (auto image = innerImage()) image->setAttributeWithoutSynchronization(srcAttr, emptyString()); if (auto video = innerVideo()) video->setAttributeWithoutSynchronization(srcAttr, emptyString()); populateShadowRootIfNecessary(); } RenderAttachment* HTMLAttachmentElement::attachmentRenderer() const { auto* renderer = this->renderer(); return is<RenderAttachment>(renderer) ? downcast<RenderAttachment>(renderer) : nullptr; } Node::InsertedIntoAncestorResult HTMLAttachmentElement::insertedIntoAncestor(InsertionType type, ContainerNode& ancestor) { auto result = HTMLElement::insertedIntoAncestor(type, ancestor); if (type.connectedToDocument) document().didInsertAttachmentElement(*this); return result; } void HTMLAttachmentElement::removedFromAncestor(RemovalType type, ContainerNode& ancestor) { HTMLElement::removedFromAncestor(type, ancestor); if (type.disconnectedFromDocument) document().didRemoveAttachmentElement(*this); } void HTMLAttachmentElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { if (name == progressAttr || name == subtitleAttr || name == titleAttr || name == typeAttr) { if (auto* renderAttachment = attachmentRenderer()) renderAttachment->invalidate(); } HTMLElement::parseAttribute(name, value); } String HTMLAttachmentElement::uniqueIdentifier() const { return attributeWithoutSynchronization(HTMLNames::webkitattachmentidAttr); } void HTMLAttachmentElement::setUniqueIdentifier(const String& identifier) { setAttributeWithoutSynchronization(HTMLNames::webkitattachmentidAttr, identifier); } String HTMLAttachmentElement::attachmentTitle() const { auto& title = attributeWithoutSynchronization(titleAttr); if (!title.isEmpty()) return title; return m_file ? m_file->name() : String(); } String HTMLAttachmentElement::attachmentType() const { return attributeWithoutSynchronization(typeAttr); } String HTMLAttachmentElement::attachmentPath() const { return attributeWithoutSynchronization(webkitattachmentpathAttr); } void HTMLAttachmentElement::updateDisplayMode(AttachmentDisplayMode mode) { mode = mode == AttachmentDisplayMode::Auto ? defaultDisplayMode() : mode; switch (mode) { case AttachmentDisplayMode::InPlace: populateShadowRootIfNecessary(); setInlineStyleProperty(CSSPropertyWebkitAppearance, CSSValueNone, true); setInlineStyleProperty(CSSPropertyDisplay, CSSValueInlineBlock, true); break; case AttachmentDisplayMode::AsIcon: removeInlineStyleProperty(CSSPropertyWebkitAppearance); removeInlineStyleProperty(CSSPropertyDisplay); break; default: ASSERT_NOT_REACHED(); break; } invalidateStyleAndRenderersForSubtree(); } Ref<HTMLImageElement> HTMLAttachmentElement::ensureInnerImage() { if (auto image = innerImage()) return *image; auto image = HTMLImageElement::create(document()); ensureUserAgentShadowRoot().appendChild(image); return image; } Ref<HTMLVideoElement> HTMLAttachmentElement::ensureInnerVideo() { if (auto video = innerVideo()) return *video; auto video = HTMLVideoElement::create(document()); ensureUserAgentShadowRoot().appendChild(video); return video; } RefPtr<HTMLImageElement> HTMLAttachmentElement::innerImage() const { if (auto root = userAgentShadowRoot()) return childrenOfType<HTMLImageElement>(*root).first(); return nullptr; } RefPtr<HTMLVideoElement> HTMLAttachmentElement::innerVideo() const { if (auto root = userAgentShadowRoot()) return childrenOfType<HTMLVideoElement>(*root).first(); return nullptr; } void HTMLAttachmentElement::populateShadowRootIfNecessary() { auto mimeType = attachmentType(); if (!m_file || mimeType.isEmpty()) return; if (MIMETypeRegistry::isSupportedImageMIMEType(mimeType) || MIMETypeRegistry::isPDFMIMEType(mimeType)) { auto image = ensureInnerImage(); if (image->attributeWithoutSynchronization(srcAttr).isEmpty()) image->setAttributeWithoutSynchronization(srcAttr, DOMURL::createObjectURL(document(), *m_file)); } else if (MIMETypeRegistry::isSupportedMediaMIMEType(mimeType)) { auto video = ensureInnerVideo(); if (video->attributeWithoutSynchronization(srcAttr).isEmpty()) { video->setAttributeWithoutSynchronization(srcAttr, DOMURL::createObjectURL(document(), *m_file)); video->setAttributeWithoutSynchronization(controlsAttr, emptyString()); } } } void HTMLAttachmentElement::requestData(Function<void(RefPtr<SharedBuffer>&&)>&& callback) { if (m_file) m_attachmentReaders.append(AttachmentDataReader::create(*this, WTFMove(callback))); else callback(nullptr); } void HTMLAttachmentElement::destroyReader(AttachmentDataReader& finishedReader) { m_attachmentReaders.removeFirstMatching([&] (const std::unique_ptr<AttachmentDataReader>& reader) -> bool { return reader.get() == &finishedReader; }); } AttachmentDataReader::~AttachmentDataReader() { invokeCallbackAndFinishReading(nullptr); } void AttachmentDataReader::didFinishLoading() { if (auto arrayBuffer = m_loader->arrayBufferResult()) invokeCallbackAndFinishReading(SharedBuffer::create(reinterpret_cast<uint8_t*>(arrayBuffer->data()), arrayBuffer->byteLength())); else invokeCallbackAndFinishReading(nullptr); m_attachment.destroyReader(*this); } void AttachmentDataReader::didFail(int) { invokeCallbackAndFinishReading(nullptr); m_attachment.destroyReader(*this); } void AttachmentDataReader::invokeCallbackAndFinishReading(RefPtr<SharedBuffer>&& data) { auto callback = WTFMove(m_callback); if (!callback) return; m_loader->cancel(); m_loader = nullptr; (*callback)(WTFMove(data)); } } // namespace WebCore #endif // ENABLE(ATTACHMENT_ELEMENT)
33.098726
141
0.743385
gubaojian
54f06f6d1817fce7fb5625cc7c7d5b137c7f4736
1,317
hpp
C++
Trabalho 2/src/headers/generator.hpp
RafaelAmauri/Teoria-de-Grafos
4c5f992b22362379f5dce23b41319abf20cd6c82
[ "MIT" ]
null
null
null
Trabalho 2/src/headers/generator.hpp
RafaelAmauri/Teoria-de-Grafos
4c5f992b22362379f5dce23b41319abf20cd6c82
[ "MIT" ]
null
null
null
Trabalho 2/src/headers/generator.hpp
RafaelAmauri/Teoria-de-Grafos
4c5f992b22362379f5dce23b41319abf20cd6c82
[ "MIT" ]
null
null
null
// Rafael Amauri Diniz Augusto --- 651047 #ifndef GENERATOR_HPP #define GENERATOR_HPP #include <stdlib.h> #include "graph.hpp" void graph_generator(Graph *g, int num_edges, int range) { srand(time(NULL)); int vertex1, vertex2, edge_weight, aux; vertex1 = aux = 0; bool repeated; std::vector<std::map<int, int>> combinations; for(int i = 0; i < num_edges; i++) { do { repeated = false; if(LOGGING_GENERATOR == 1) std::cout << "Resorteando...\n" ; vertex2 = rand()%range; for(auto i : combinations) for(auto j : i) if( (j.first == vertex1 && j.second == vertex2) || (j.first == vertex2 && j.second == vertex1)|| (vertex2 == aux)|| (vertex2 == vertex1)) repeated = true; }while(repeated); aux = vertex1; edge_weight = rand()%range; g->add_edge(vertex1, vertex2, edge_weight); combinations.push_back({{vertex1, vertex2}}); if(LOGGING_GENERATOR == 1) std::cout << "Inserido: " << vertex1 << " - " << vertex2 << " - " << edge_weight << "\n"; vertex1 = vertex2; } } #endif
24.849057
101
0.48899
RafaelAmauri
54f0ef86df8ebf9356f2995d7a7bee04ef3e64e2
1,740
hpp
C++
mesk-installer/Pages/bootloaderPage.hpp
aaly/Mesk-Installer
a3e07318c9bb08d02a7adfdda380eee5c829bab2
[ "BSD-3-Clause" ]
2
2019-01-12T06:20:38.000Z
2019-02-05T06:20:58.000Z
mesk-installer/Pages/bootloaderPage.hpp
aaly/Mesk-Installer
a3e07318c9bb08d02a7adfdda380eee5c829bab2
[ "BSD-3-Clause" ]
null
null
null
mesk-installer/Pages/bootloaderPage.hpp
aaly/Mesk-Installer
a3e07318c9bb08d02a7adfdda380eee5c829bab2
[ "BSD-3-Clause" ]
null
null
null
/****************************************************** * copyright 2011, 2012, 2013 AbdAllah Aly Saad , aaly90[@]gmail.com * Part of Mesklinux Installer * See LICENSE file for more info ******************************************************/ #ifndef BOOTLOADERPAGE_HPP #define BOOTLOADERPAGE_HPP #include <QtWidgets/QWidget> //#include <MPF/pageBase.hpp> #include "ui_bootloaderPage.h" #include <MPF/System/drive.hpp> #include <Pages/diskPage.hpp> #include <MPF/System/chroot.hpp> class bootEntry { public: QString title; QString kernel; QString kernelOptions; QString initramfs; QString options; QString root; QString os; QPair<int, int> rootpartition; QString rootUUID; QString rootDevPath; bool sub; //QVector<bootEntry> subEntries; private: }; class bootloaderPage : public pageBase, private Ui::bootloaderPage { Q_OBJECT public: explicit bootloaderPage(QWidget *parent = 0); int initAll(); ~bootloaderPage(); private: void changeEvent(QEvent* event); chroot croot; QFile bootMenuFile; diskPage* dpage; QList<Drive> drives; QVector<bootEntry> bootMenu; int generateBootMenu(); int installBootLoader(); QString rootPath; QProcess mountRoot; int writeBootMenu(); QString cfgOptions; QString bootPartition; int generateFsTab(); int initMenu(); QString rootdev; private slots: int checkBootloaderPasswordStrength(); int confirmBootloaderPassword(); int removeBootEntry(); int addBootEntry(); int resetBootMenu(); int modifyBootEntry(int, int); int addToBootMenu(); int changeOptions(); public slots: int finishUp(); }; #endif // BOOTLOADERPAGE_HPP
16.571429
67
0.651149
aaly
54f101c539ee0891520d0b6610dbd5206de89e62
2,863
hpp
C++
libcore/include/sirikata/core/transfer/OAuthHttpManager.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
1
2016-05-09T03:34:51.000Z
2016-05-09T03:34:51.000Z
libcore/include/sirikata/core/transfer/OAuthHttpManager.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
libcore/include/sirikata/core/transfer/OAuthHttpManager.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011 Sirikata Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE file. #ifndef _SIRIKATA_LIBCORE_OAUTH_HTTP_MANAGER_HPP_ #define _SIRIKATA_LIBCORE_OAUTH_HTTP_MANAGER_HPP_ #include <sirikata/core/transfer/HttpManager.hpp> #include <liboauthcpp/liboauthcpp.h> namespace Sirikata { namespace Transfer { /** Wrapper around HttpManager which signs requests as an OAuth consumer. Unlike * HttpManager, this is not a Singleton so that you can use this multiple times * to be different consumers to different sites. */ class SIRIKATA_EXPORT OAuthHttpManager { public: OAuthHttpManager(const String& hostname, const String& consumer_key, const String& consumer_secret); OAuthHttpManager(const String& hostname, const String& consumer_key, const String& consumer_secret, const String& token_key, const String& token_secret); void head( Sirikata::Network::Address addr, const String& path, HttpManager::HttpCallback cb, const HttpManager::Headers& headers = HttpManager::Headers(), const HttpManager::QueryParameters& query_params = HttpManager::QueryParameters(), bool allow_redirects = true ); void get( Sirikata::Network::Address addr, const String& path, HttpManager::HttpCallback cb, const HttpManager::Headers& headers = HttpManager::Headers(), const HttpManager::QueryParameters& query_params = HttpManager::QueryParameters(), bool allow_redirects = true ); void post( Sirikata::Network::Address addr, const String& path, const String& content_type, const String& body, HttpManager::HttpCallback cb, const HttpManager::Headers& headers = HttpManager::Headers(), const HttpManager::QueryParameters& query_params = HttpManager::QueryParameters(), bool allow_redirects = true ); void postURLEncoded( Sirikata::Network::Address addr, const String& path, const HttpManager::StringDictionary& body, HttpManager::HttpCallback cb, const HttpManager::Headers& headers = HttpManager::Headers(), const HttpManager::QueryParameters& query_params = HttpManager::QueryParameters(), bool allow_redirects = true ); void postMultipartForm( Sirikata::Network::Address addr, const String& path, const HttpManager::MultipartDataList& data, HttpManager::HttpCallback cb, const HttpManager::Headers& headers = HttpManager::Headers(), const HttpManager::QueryParameters& query_params = HttpManager::QueryParameters(), bool allow_redirects = true ); private: const String mHostname; OAuth::Consumer mConsumer; OAuth::Token mToken; OAuth::Client mClient; }; } // namespace Transfer } // namespace Sirikata #endif //_SIRIKATA_LIBCORE_OAUTH_HTTP_MANAGER_HPP_
41.492754
182
0.735592
pathorn
54f2fafb312cb0b0bdb3e7b1ce3a0f118a73e418
54,481
cc
C++
epid/member/unittests/sign-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
1
2019-04-15T16:27:54.000Z
2019-04-15T16:27:54.000Z
epid/member/unittests/sign-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
null
null
null
epid/member/unittests/sign-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
null
null
null
/*############################################################################ # Copyright 2016-2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################*/ /*! * \file * \brief Sign unit tests. */ #include <vector> #include "epid/common-testhelper/epid_gtest-testhelper.h" #include "gtest/gtest.h" extern "C" { #include "epid/member/api.h" #include "epid/member/src/context.h" #include "epid/verifier/api.h" } #include "epid/common-testhelper/errors-testhelper.h" #include "epid/common-testhelper/prng-testhelper.h" #include "epid/common-testhelper/verifier_wrapper-testhelper.h" #include "epid/member/unittests/member-testhelper.h" namespace { /// Count of elements in array #define COUNT_OF(A) (sizeof(A) / sizeof((A)[0])) ///////////////////////////////////////////////////////////////////////// // Simple error cases TEST_F(EpidMemberTest, SignFailsGivenNullParameters) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; SigRl srl = {{{0}}, {{0}}, {{0}}, {{{{0}, {0}}, {{0}, {0}}}}}; srl.gid = this->kGroupPublicKey.gid; std::vector<uint8_t> sig(EpidGetSigSize(&srl)); THROW_ON_EPIDERR( EpidMemberSetSigRl(member, &srl, sizeof(srl) - sizeof(srl.bk))); EXPECT_EQ(kEpidBadArgErr, EpidSign(nullptr, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig.data(), sig.size())); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), nullptr, sig.size())); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, nullptr, msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig.data(), sig.size())); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, msg.data(), msg.size(), nullptr, bsn.size(), (EpidSignature*)sig.data(), sig.size())); } TEST_F(EpidMemberTest, SignFailsGivenWrongSigLen) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; SigRl srl = {{{0}}, {{0}}, {{0}}, {{{{0}, {0}}, {{0}, {0}}}}}; srl.gid = this->kGroupPublicKey.gid; THROW_ON_EPIDERR( EpidMemberSetSigRl(member, &srl, sizeof(srl) - sizeof(srl.bk))); // signature buffer one byte less than needed std::vector<uint8_t> sig_small(EpidGetSigSize(&srl) - 1); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig_small.data(), sig_small.size())); // signature buffer is one byte - a less than allowed for EpidSignature std::vector<uint8_t> sig_one(1); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig_one.data(), sig_one.size())); } TEST_F(EpidMemberTest, SignFailsGivenUnregisteredBasename) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; auto& bsn1 = this->kBsn1; SigRl srl = {{{0}}, {{0}}, {{0}}, {{{{0}, {0}}, {{0}, {0}}}}}; srl.gid = this->kGroupPublicKey.gid; std::vector<uint8_t> sig(EpidGetSigSize(&srl)); THROW_ON_EPIDERR( EpidMemberSetSigRl(member, &srl, sizeof(srl) - sizeof(srl.bk))); THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); EXPECT_EQ(kEpidBadArgErr, EpidSign(member, msg.data(), msg.size(), bsn1.data(), bsn1.size(), (EpidSignature*)sig.data(), sig.size())); } TEST_F(EpidMemberTest, SignsFailsIfNotProvisioned) { Prng my_prng; MemberCtxObj member(&Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidOutOfSequenceError, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); } ///////////////////////////////////////////////////////////////////////// // Anonymity TEST_F(EpidMemberTest, SignaturesOfSameMessageAreDifferent) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig1(EpidGetSigSize(nullptr)); std::vector<uint8_t> sig2(EpidGetSigSize(nullptr)); // without signature based revocation list EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, (EpidSignature*)sig1.data(), sig1.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, (EpidSignature*)sig2.data(), sig2.size())); EXPECT_TRUE(sig1.size() == sig2.size() && 0 != memcmp(sig1.data(), sig2.data(), sig1.size())); // with signature based revocation list uint8_t sig_rl_data_n2_one[] = { // gid 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // version 0x00, 0x00, 0x00, 0x00, // n2 0x0, 0x00, 0x00, 0x01, // one bk 0x9c, 0xa5, 0xe5, 0xae, 0x5f, 0xae, 0x51, 0x59, 0x33, 0x35, 0x27, 0xd, 0x8, 0xb1, 0xbe, 0x5d, 0x69, 0x50, 0x84, 0xc5, 0xfe, 0xe2, 0x87, 0xea, 0x2e, 0xef, 0xfa, 0xee, 0x67, 0xf2, 0xd8, 0x28, 0x56, 0x43, 0xc6, 0x94, 0x67, 0xa6, 0x72, 0xf6, 0x41, 0x15, 0x4, 0x58, 0x42, 0x16, 0x88, 0x57, 0x9d, 0xc7, 0x71, 0xd1, 0xc, 0x84, 0x13, 0xa, 0x90, 0x23, 0x18, 0x8, 0xad, 0x7d, 0xfe, 0xf5, 0xc8, 0xae, 0xfc, 0x51, 0x40, 0xa7, 0xd1, 0x28, 0xc2, 0x89, 0xb2, 0x6b, 0x4e, 0xb4, 0xc1, 0x55, 0x87, 0x98, 0xbd, 0x72, 0xf9, 0xcf, 0xd, 0x40, 0x15, 0xee, 0x32, 0xc, 0xf3, 0x56, 0xc5, 0xc, 0x61, 0x9d, 0x4f, 0x7a, 0xb5, 0x2b, 0x16, 0xa9, 0xa3, 0x97, 0x38, 0xe2, 0xdd, 0x3a, 0x33, 0xad, 0xf6, 0x7b, 0x68, 0x8b, 0x68, 0xcf, 0xa3, 0xd3, 0x98, 0x37, 0xce, 0xec, 0xd1, 0xa8, 0xc, 0x8b}; SigRl* srl1 = reinterpret_cast<SigRl*>(sig_rl_data_n2_one); size_t srl1_size = sizeof(sig_rl_data_n2_one); std::vector<uint8_t> sig3(EpidGetSigSize(srl1)); std::vector<uint8_t> sig4(EpidGetSigSize(srl1)); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl1, srl1_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, (EpidSignature*)sig3.data(), sig3.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, (EpidSignature*)sig4.data(), sig4.size())); EXPECT_TRUE(sig3.size() == sig4.size() && 0 != memcmp(sig3.data(), sig4.data(), sig3.size())); } TEST_F(EpidMemberTest, SignaturesOfSameMessageWithSameBasenameAreDifferent) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; std::vector<uint8_t> sig1(EpidGetSigSize(nullptr)); std::vector<uint8_t> sig2(EpidGetSigSize(nullptr)); // without signature based revocation list THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig1.data(), sig1.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig2.data(), sig2.size())); EXPECT_TRUE(sig1.size() == sig2.size() && 0 != memcmp(sig1.data(), sig2.data(), sig1.size())); // with signature based revocation list uint8_t sig_rl_data_n2_one[] = { // gid 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // version 0x00, 0x00, 0x00, 0x00, // n2 0x0, 0x00, 0x00, 0x01, // one bk 0x9c, 0xa5, 0xe5, 0xae, 0x5f, 0xae, 0x51, 0x59, 0x33, 0x35, 0x27, 0xd, 0x8, 0xb1, 0xbe, 0x5d, 0x69, 0x50, 0x84, 0xc5, 0xfe, 0xe2, 0x87, 0xea, 0x2e, 0xef, 0xfa, 0xee, 0x67, 0xf2, 0xd8, 0x28, 0x56, 0x43, 0xc6, 0x94, 0x67, 0xa6, 0x72, 0xf6, 0x41, 0x15, 0x4, 0x58, 0x42, 0x16, 0x88, 0x57, 0x9d, 0xc7, 0x71, 0xd1, 0xc, 0x84, 0x13, 0xa, 0x90, 0x23, 0x18, 0x8, 0xad, 0x7d, 0xfe, 0xf5, 0xc8, 0xae, 0xfc, 0x51, 0x40, 0xa7, 0xd1, 0x28, 0xc2, 0x89, 0xb2, 0x6b, 0x4e, 0xb4, 0xc1, 0x55, 0x87, 0x98, 0xbd, 0x72, 0xf9, 0xcf, 0xd, 0x40, 0x15, 0xee, 0x32, 0xc, 0xf3, 0x56, 0xc5, 0xc, 0x61, 0x9d, 0x4f, 0x7a, 0xb5, 0x2b, 0x16, 0xa9, 0xa3, 0x97, 0x38, 0xe2, 0xdd, 0x3a, 0x33, 0xad, 0xf6, 0x7b, 0x68, 0x8b, 0x68, 0xcf, 0xa3, 0xd3, 0x98, 0x37, 0xce, 0xec, 0xd1, 0xa8, 0xc, 0x8b}; SigRl* srl1 = reinterpret_cast<SigRl*>(sig_rl_data_n2_one); size_t srl1_size = sizeof(sig_rl_data_n2_one); std::vector<uint8_t> sig3(EpidGetSigSize(srl1)); std::vector<uint8_t> sig4(EpidGetSigSize(srl1)); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl1, srl1_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig3.data(), sig3.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), (EpidSignature*)sig4.data(), sig4.size())); EXPECT_TRUE(sig3.size() == sig4.size() && 0 != memcmp(sig3.data(), sig4.data(), sig3.size())); } ///////////////////////////////////////////////////////////////////////// // Variable basename TEST_F(EpidMemberTest, SignsMessageUsingRandomBaseNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingRandomBaseWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingBasenameNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingBasenameWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsUsingRandomBaseWithRegisteredBasenamesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsUsingRandomBaseWithRegisteredBasenamesWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsUsingRandomBaseWithoutRegisteredBasenamesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsUsingRandomBaseWithoutRegisteredBasenamesWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } #ifndef TPM_TSS TEST_F(EpidMemberTest, SignsMessageUsingHugeBasenameNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGrpXKey, this->kGrpXMember0PrivKey, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> bsn(1024 * 1024); // exactly 1 MB uint8_t c = 0; for (size_t i = 0; i < bsn.size(); ++i) { bsn[i] = c++; } THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGrpXKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingHugeBasenameWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGrpXKey, this->kGrpXMember0PrivKey, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> bsn(1024 * 1024); // exactly 1 MB uint8_t c = 0; for (size_t i = 0; i < bsn.size(); ++i) { bsn[i] = c++; } THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); SigRl const* srl = reinterpret_cast<SigRl const*>(this->kGrpXSigRl.data()); size_t srl_size = this->kGrpXSigRl.size() * sizeof(this->kGrpXSigRl[0]); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), sig, sig_len)); VerifierCtxObj ctx(this->kGrpXKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); } TEST_F(EpidMemberTest, SignsMsgUsingBsnContainingAllPossibleBytesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kData_0_255; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), bsn.data(), bsn.size(), sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } #endif ///////////////////////////////////////////////////////////////////////// // Variable sigRL TEST_F(EpidMemberTest, SignsMessageGivenNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; size_t sig_len = EpidGetSigSize(nullptr); std::vector<uint8_t> newsig(sig_len); EpidSignature* sig = (EpidSignature*)newsig.data(); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageGivenNoSigRlUsingIKGFData) { GroupPubKey grp_public_key = *reinterpret_cast<const GroupPubKey*>( this->kGroupPublicKeyDataIkgf.data()); PrivKey mbr_private_key = *reinterpret_cast<const PrivKey*>(this->kMemberPrivateKeyDataIkgf.data()); Prng my_prng; auto& msg = this->kMsg0; size_t sig_len = EpidGetSigSize(nullptr); std::vector<uint8_t> newsig(sig_len); // using ikgf keys MemberCtxObj member(grp_public_key, mbr_private_key, &Prng::Generate, &my_prng); EpidSignature* sig = (EpidSignature*)newsig.data(); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(grp_public_key); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageGivenSigRlWithNoEntries) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; uint8_t sig_rl_data_n2_zero[] = { // gid 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // version 0x00, 0x00, 0x00, 0x00, // n2 0x0, 0x00, 0x00, 0x00, // not bk's }; SigRl const* srl = reinterpret_cast<SigRl const*>(sig_rl_data_n2_zero); size_t srl_size = sizeof(sig_rl_data_n2_zero); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageGivenSigRlWithNoEntriesUsingIkgfData) { GroupPubKey grp_public_key = *reinterpret_cast<const GroupPubKey*>( this->kGroupPublicKeyDataIkgf.data()); PrivKey mbr_private_key = *reinterpret_cast<const PrivKey*>(this->kMemberPrivateKeyDataIkgf.data()); Prng my_prng; auto& msg = this->kMsg0; // using ikgf keys MemberCtxObj member_ikgf(grp_public_key, mbr_private_key, &Prng::Generate, &my_prng); uint8_t sig_rl_data_n2_one_gid0[] = { #include "epid/common-testhelper/testdata/ikgf/groupa/sigrl_empty.inc" }; SigRl* srl_ikgf = reinterpret_cast<SigRl*>(sig_rl_data_n2_one_gid0); size_t srl_size = sizeof(sig_rl_data_n2_one_gid0); std::vector<uint8_t> sig_data_ikgf(EpidGetSigSize(srl_ikgf)); EpidSignature* sig_ikgf = reinterpret_cast<EpidSignature*>(sig_data_ikgf.data()); size_t sig_len = sig_data_ikgf.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member_ikgf, srl_ikgf, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member_ikgf, msg.data(), msg.size(), nullptr, 0, sig_ikgf, sig_len)); VerifierCtxObj ctx_ikgf(grp_public_key); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx_ikgf, srl_ikgf, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx_ikgf, sig_ikgf, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageGivenSigRlWithEntries) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; uint8_t sig_rl_data_n2_one[] = { // gid 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // version 0x00, 0x00, 0x00, 0x00, // n2 0x0, 0x00, 0x00, 0x02, // one bk 0x9c, 0xa5, 0xe5, 0xae, 0x5f, 0xae, 0x51, 0x59, 0x33, 0x35, 0x27, 0xd, 0x8, 0xb1, 0xbe, 0x5d, 0x69, 0x50, 0x84, 0xc5, 0xfe, 0xe2, 0x87, 0xea, 0x2e, 0xef, 0xfa, 0xee, 0x67, 0xf2, 0xd8, 0x28, 0x56, 0x43, 0xc6, 0x94, 0x67, 0xa6, 0x72, 0xf6, 0x41, 0x15, 0x4, 0x58, 0x42, 0x16, 0x88, 0x57, 0x9d, 0xc7, 0x71, 0xd1, 0xc, 0x84, 0x13, 0xa, 0x90, 0x23, 0x18, 0x8, 0xad, 0x7d, 0xfe, 0xf5, 0xc8, 0xae, 0xfc, 0x51, 0x40, 0xa7, 0xd1, 0x28, 0xc2, 0x89, 0xb2, 0x6b, 0x4e, 0xb4, 0xc1, 0x55, 0x87, 0x98, 0xbd, 0x72, 0xf9, 0xcf, 0xd, 0x40, 0x15, 0xee, 0x32, 0xc, 0xf3, 0x56, 0xc5, 0xc, 0x61, 0x9d, 0x4f, 0x7a, 0xb5, 0x2b, 0x16, 0xa9, 0xa3, 0x97, 0x38, 0xe2, 0xdd, 0x3a, 0x33, 0xad, 0xf6, 0x7b, 0x68, 0x8b, 0x68, 0xcf, 0xa3, 0xd3, 0x98, 0x37, 0xce, 0xec, 0xd1, 0xa8, 0xc, 0x8b, 0x71, 0x8a, 0xb5, 0x1, 0x7f, 0x7c, 0x92, 0x9a, 0xa2, 0xc9, 0x81, 0x10, 0xfe, 0xbf, 0xc, 0x53, 0xa4, 0x43, 0xaf, 0x31, 0x74, 0x12, 0x25, 0x60, 0x3e, 0xc0, 0x21, 0xe6, 0x63, 0x9a, 0xd2, 0x67, 0x2d, 0xb5, 0xd5, 0x82, 0xc4, 0x49, 0x29, 0x51, 0x42, 0x8f, 0xe0, 0xe, 0xd1, 0x73, 0x27, 0xf5, 0x77, 0x16, 0x4, 0x40, 0x8a, 0x0, 0xe, 0x3a, 0x5d, 0x37, 0x42, 0xd3, 0x8, 0x40, 0xbd, 0x69, 0xf7, 0x5f, 0x74, 0x21, 0x50, 0xf4, 0xce, 0xfe, 0xd9, 0xdd, 0x97, 0x6c, 0xa8, 0xa5, 0x60, 0x6b, 0xf8, 0x1b, 0xba, 0x2, 0xb2, 0xca, 0x5, 0x44, 0x9b, 0xb1, 0x5e, 0x3a, 0xa4, 0x35, 0x7a, 0x51, 0xfa, 0xcf, 0xa4, 0x4, 0xe9, 0xf3, 0xbf, 0x38, 0xd4, 0x24, 0x9, 0x52, 0xf3, 0x58, 0x3d, 0x9d, 0x4b, 0xb3, 0x37, 0x4b, 0xec, 0x87, 0xe1, 0x64, 0x60, 0x3c, 0xb6, 0xf7, 0x7b, 0xff, 0x40, 0x11}; SigRl* srl = reinterpret_cast<SigRl*>(sig_rl_data_n2_one); size_t srl_size = sizeof(sig_rl_data_n2_one); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageGivenSigRlWithEntriesUsingIKGFData) { GroupPubKey grp_public_key = *reinterpret_cast<const GroupPubKey*>( this->kGroupPublicKeyDataIkgf.data()); PrivKey mbr_private_key = *reinterpret_cast<const PrivKey*>(this->kMemberPrivateKeyDataIkgf.data()); Prng my_prng; auto& msg = this->kMsg0; // using ikgf keys MemberCtxObj member_ikgf(grp_public_key, mbr_private_key, &Prng::Generate, &my_prng); uint8_t sig_rl_data_n2_one_gid0[] = { // gid 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // version 0x00, 0x00, 0x00, 0x00, // n2 0x0, 0x00, 0x00, 0x02, // one bk 0x9c, 0xa5, 0xe5, 0xae, 0x5f, 0xae, 0x51, 0x59, 0x33, 0x35, 0x27, 0xd, 0x8, 0xb1, 0xbe, 0x5d, 0x69, 0x50, 0x84, 0xc5, 0xfe, 0xe2, 0x87, 0xea, 0x2e, 0xef, 0xfa, 0xee, 0x67, 0xf2, 0xd8, 0x28, 0x56, 0x43, 0xc6, 0x94, 0x67, 0xa6, 0x72, 0xf6, 0x41, 0x15, 0x4, 0x58, 0x42, 0x16, 0x88, 0x57, 0x9d, 0xc7, 0x71, 0xd1, 0xc, 0x84, 0x13, 0xa, 0x90, 0x23, 0x18, 0x8, 0xad, 0x7d, 0xfe, 0xf5, 0xc8, 0xae, 0xfc, 0x51, 0x40, 0xa7, 0xd1, 0x28, 0xc2, 0x89, 0xb2, 0x6b, 0x4e, 0xb4, 0xc1, 0x55, 0x87, 0x98, 0xbd, 0x72, 0xf9, 0xcf, 0xd, 0x40, 0x15, 0xee, 0x32, 0xc, 0xf3, 0x56, 0xc5, 0xc, 0x61, 0x9d, 0x4f, 0x7a, 0xb5, 0x2b, 0x16, 0xa9, 0xa3, 0x97, 0x38, 0xe2, 0xdd, 0x3a, 0x33, 0xad, 0xf6, 0x7b, 0x68, 0x8b, 0x68, 0xcf, 0xa3, 0xd3, 0x98, 0x37, 0xce, 0xec, 0xd1, 0xa8, 0xc, 0x8b, 0x71, 0x8a, 0xb5, 0x1, 0x7f, 0x7c, 0x92, 0x9a, 0xa2, 0xc9, 0x81, 0x10, 0xfe, 0xbf, 0xc, 0x53, 0xa4, 0x43, 0xaf, 0x31, 0x74, 0x12, 0x25, 0x60, 0x3e, 0xc0, 0x21, 0xe6, 0x63, 0x9a, 0xd2, 0x67, 0x2d, 0xb5, 0xd5, 0x82, 0xc4, 0x49, 0x29, 0x51, 0x42, 0x8f, 0xe0, 0xe, 0xd1, 0x73, 0x27, 0xf5, 0x77, 0x16, 0x4, 0x40, 0x8a, 0x0, 0xe, 0x3a, 0x5d, 0x37, 0x42, 0xd3, 0x8, 0x40, 0xbd, 0x69, 0xf7, 0x5f, 0x74, 0x21, 0x50, 0xf4, 0xce, 0xfe, 0xd9, 0xdd, 0x97, 0x6c, 0xa8, 0xa5, 0x60, 0x6b, 0xf8, 0x1b, 0xba, 0x2, 0xb2, 0xca, 0x5, 0x44, 0x9b, 0xb1, 0x5e, 0x3a, 0xa4, 0x35, 0x7a, 0x51, 0xfa, 0xcf, 0xa4, 0x4, 0xe9, 0xf3, 0xbf, 0x38, 0xd4, 0x24, 0x9, 0x52, 0xf3, 0x58, 0x3d, 0x9d, 0x4b, 0xb3, 0x37, 0x4b, 0xec, 0x87, 0xe1, 0x64, 0x60, 0x3c, 0xb6, 0xf7, 0x7b, 0xff, 0x40, 0x11}; SigRl* srl_ikgf = reinterpret_cast<SigRl*>(sig_rl_data_n2_one_gid0); size_t srl_size = sizeof(sig_rl_data_n2_one_gid0); std::vector<uint8_t> sig_data_ikgf(EpidGetSigSize(srl_ikgf)); EpidSignature* sig_ikgf = reinterpret_cast<EpidSignature*>(sig_data_ikgf.data()); size_t sig_len = sig_data_ikgf.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member_ikgf, srl_ikgf, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member_ikgf, msg.data(), msg.size(), nullptr, 0, sig_ikgf, sig_len)); VerifierCtxObj ctx_ikgf(grp_public_key); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx_ikgf, srl_ikgf, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx_ikgf, sig_ikgf, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignMessageReportsIfMemberRevoked) { // note: a complete sig + nr proof should still be returned!! auto& pub_key = this->kGrpXKey; auto& priv_key = this->kGrpXMember0PrivKey; auto& msg = this->kMsg0; Prng my_prng; MemberCtxObj member(pub_key, priv_key, &Prng::Generate, &my_prng); const std::vector<uint8_t> kGrpXSigRlMember0Sha512Rndbase0Msg0MiddleEntry = { #include "epid/common-testhelper/testdata/grp_x/sigrl_member0_sig_sha512_rndbase_msg0_revoked_middle_entry.inc" }; auto srl = reinterpret_cast<SigRl const*>( kGrpXSigRlMember0Sha512Rndbase0Msg0MiddleEntry.data()); size_t srl_size = kGrpXSigRlMember0Sha512Rndbase0Msg0MiddleEntry.size(); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(pub_key); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignMessageReportsIfMemberRevokedUsingIKGFData) { // note: a complete sig + nr proof should still be returned!! GroupPubKey grp_public_key = *reinterpret_cast<const GroupPubKey*>( this->kGroupPublicKeyDataIkgf.data()); const PrivKey member_private_key_revoked_by_sig = { #include "epid/common-testhelper/testdata/ikgf/groupa/sigrevokedmember0/mprivkey.inc" }; Prng my_prng; MemberCtxObj member(grp_public_key, member_private_key_revoked_by_sig, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; const std::vector<uint8_t> sig_Rl = { #include "epid/common-testhelper/testdata/ikgf/groupa/sigrl.inc" }; auto srl = reinterpret_cast<SigRl const*>(sig_Rl.data()); size_t srl_size = sig_Rl.size(); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(grp_public_key); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } ///////////////////////////////////////////////////////////////////////// // Revoked member by sigRL for TPM case TEST_F(EpidMemberTest, PROTECTED_SignMessageByCedentialReportsIfMemberRevoked_EPS0) { // note: a complete sig + nr proof should still be returned!! auto& pub_key = this->kEps0GroupPublicKey; auto credential = *(MembershipCredential const*)&this->kEps0MemberPrivateKey; const std::vector<uint8_t> msg = {'t', 'e', 's', 't', '2'}; Prng my_prng; MemberCtxObj member(pub_key, credential, &Prng::Generate, &my_prng); const std::vector<uint8_t> kEps0SigRlMember0Sha256Rndbase0Msg0FirstEntry = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x39, 0x97, 0x09, 0x11, 0x30, 0xb0, 0x2a, 0x29, 0xa7, 0x9b, 0xf1, 0xef, 0xe9, 0xe5, 0xc7, 0x03, 0x17, 0xe6, 0x4f, 0x6f, 0x49, 0x4d, 0xeb, 0x0f, 0xfd, 0x1c, 0x3f, 0xce, 0xcc, 0xc8, 0x40, 0x6b, 0x23, 0xd3, 0xec, 0x78, 0x78, 0x15, 0x4a, 0x34, 0x0f, 0xd1, 0xd3, 0xfa, 0xd2, 0xb2, 0x5a, 0xc9, 0xec, 0xa2, 0x41, 0xe1, 0x46, 0x6d, 0xed, 0xb3, 0x4a, 0xa6, 0xdf, 0xb6, 0xc2, 0x11, 0x49, 0x0d, 0x8b, 0xc4, 0xdc, 0xe0, 0x3f, 0x86, 0x59, 0xb6, 0x47, 0x0e, 0x72, 0xd9, 0x04, 0x91, 0x06, 0x8d, 0xe7, 0xb0, 0x4e, 0x40, 0x4a, 0x72, 0xe2, 0x99, 0xcc, 0xf2, 0x93, 0x1f, 0xcb, 0x32, 0x2e, 0xa3, 0x62, 0xf5, 0x35, 0x51, 0x8b, 0x8e, 0xc8, 0xf4, 0x1e, 0xbe, 0xc9, 0xf4, 0xa9, 0xc4, 0x63, 0xd3, 0x86, 0x5d, 0xf6, 0x44, 0x36, 0x5c, 0x44, 0x11, 0xb4, 0xa3, 0x85, 0xd5, 0x9e, 0xaf, 0x56, 0x83}; auto srl = reinterpret_cast<SigRl const*>( kEps0SigRlMember0Sha256Rndbase0Msg0FirstEntry.data()); size_t srl_size = kEps0SigRlMember0Sha256Rndbase0Msg0FirstEntry.size(); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); VerifierCtxObj ctx(pub_key); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigRevokedInSigRl, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } ///////////////////////////////////////////////////////////////////////// // Variable hash alg TEST_F(EpidMemberTest, SignsMessageUsingSha256HashAlg) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, kSha256, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha256)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingSha384HashAlg) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, kSha384, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha384)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingSha512HashAlg) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, kSha512, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha512)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageUsingSha512256HashAlg) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, kSha512_256, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha512_256)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } ///////////////////////////////////////////////////////////////////////// // Variable hash alg for TPM data TEST_F(EpidMemberTest, PROTECTED_SignsMessageByCredentialUsingSha256HashAlg_EPS0) { Prng my_prng; MemberCtxObj member( this->kEps0GroupPublicKey, *(MembershipCredential const*)&this->kEps0MemberPrivateKey, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kEps0GroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha256)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, DISABLED_PROTECTED_SignsMessageByCredentialUsingSha384HashAlg_EPS0) { Prng my_prng; MemberCtxObj member( this->kEps0GroupPublicKey, *(MembershipCredential const*)&this->kEps0MemberPrivateKey, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetHashAlg(member, kSha384)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kEps0GroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha384)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, DISABLED_PROTECTED_SignsMessageByCredentialUsingSha512HashAlg_EPS0) { Prng my_prng; MemberCtxObj member( this->kEps0GroupPublicKey, *(MembershipCredential const*)&this->kEps0MemberPrivateKey, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetHashAlg(member, kSha512)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify signature VerifierCtxObj ctx(this->kEps0GroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetHashAlg(ctx, kSha512)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } ///////////////////////////////////////////////////////////////////////// // Variable precomputed signatures TEST_F(EpidMemberTest, SignConsumesPrecomputedSignaturesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); THROW_ON_EPIDERR(EpidAddPreSigs(member, 3)); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); EXPECT_EQ((size_t)2, EpidGetNumPreSigs(member)); } TEST_F(EpidMemberTest, SignConsumesPrecomputedSignaturesWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); THROW_ON_EPIDERR(EpidAddPreSigs(member, 3)); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); EXPECT_EQ((size_t)2, EpidGetNumPreSigs(member)); } TEST_F(EpidMemberTest, SignsMessageWithPrecomputedSignaturesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); THROW_ON_EPIDERR(EpidAddPreSigs(member, 1)); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageWithPrecomputedSignaturesWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); THROW_ON_EPIDERR(EpidAddPreSigs(member, 1)); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageWithoutPrecomputedSignaturesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); // test sign without precomputed signatures EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } TEST_F(EpidMemberTest, SignsMessageWithoutPrecomputedSignaturesWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); // test sign without precomputed signatures EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } ///////////////////////////////////////////////////////////////////////// // Variable messages TEST_F(EpidMemberTest, SignsEmptyMessageNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; auto& bsn = this->kBsn0; std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidRegisterBasename(member, bsn.data(), bsn.size())); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), 0, bsn.data(), bsn.size(), sig, sig_len)); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetBasename(ctx, bsn.data(), bsn.size())); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), 0)); } TEST_F(EpidMemberTest, SignsEmptyMessageWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); auto& msg = this->kMsg0; SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), 0, nullptr, 0, sig, sig_len)); // verify basic signature VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), 0)); } TEST_F(EpidMemberTest, SignsShortMessageNoSigRl) { // check: 1, 13, 128, 256, 512, 1021, 1024 bytes // 13 and 1021 are primes Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); VerifierCtxObj ctx(this->kGroupPublicKey); size_t lengths[] = {1, 13, 128, 256, 512, 1021, 1024}; // have desired lengths to loop over std::vector<uint8_t> msg( lengths[COUNT_OF(lengths) - 1]); // allocate message for max size for (size_t n = 0; n < msg.size(); n++) { msg[n] = (uint8_t)n; } for (auto length : lengths) { EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), length, nullptr, 0, sig, sig_len)) << "EpidSign for message_len: " << length << " failed"; EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), length)) << "EpidVerify for message_len: " << length << " failed"; } } TEST_F(EpidMemberTest, SignsShortMessageWithSigRl) { // check: 1, 13, 128, 256, 512, 1021, 1024 bytes // 13 and 1021 are primes Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); size_t message_len = 0; VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); size_t lengths[] = {1, 13, 128, 256, 512, 1021, 1024}; // have desired lengths to loop over std::vector<uint8_t> msg( lengths[COUNT_OF(lengths) - 1]); // allocate message for max size for (size_t n = 0; n < msg.size(); n++) { msg.at(n) = (uint8_t)n; } THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); for (auto length : lengths) { EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), length, nullptr, 0, sig, sig_len)) << "EpidSign for message_len: " << message_len << " failed"; EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), length)) << "EpidVerify for message_len: " << message_len << " failed"; } } TEST_F(EpidMemberTest, SignsLongMessageNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); VerifierCtxObj ctx(this->kGroupPublicKey); std::vector<uint8_t> msg(1000000); // allocate message for max size for (size_t n = 0; n < msg.size(); n++) { msg.at(n) = (uint8_t)n; } EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)) << "EpidSign for message_len: " << 1000000 << " failed"; EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())) << "EpidVerify for message_len: " << 1000000 << " failed"; } TEST_F(EpidMemberTest, SignsLongMessageWithSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); SigRl const* srl = reinterpret_cast<SigRl const*>(this->kSigRl5EntryData.data()); size_t srl_size = this->kSigRl5EntryData.size() * sizeof(uint8_t); std::vector<uint8_t> sig_data(EpidGetSigSize(srl)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); VerifierCtxObj ctx(this->kGroupPublicKey); THROW_ON_EPIDERR(EpidVerifierSetSigRl(ctx, srl, srl_size)); std::vector<uint8_t> msg(1000000); // allocate message for max size for (size_t n = 0; n < msg.size(); n++) { msg.at(n) = (uint8_t)n; } THROW_ON_EPIDERR(EpidMemberSetSigRl(member, srl, srl_size)); EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)) << "EpidSign for message_len: " << 1000000 << " failed"; EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())) << "EpidVerify for message_len: " << 1000000 << " failed"; } TEST_F(EpidMemberTest, SignsMsgContainingAllPossibleBytesNoSigRl) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); std::vector<uint8_t> sig_data(EpidGetSigSize(nullptr)); EpidSignature* sig = reinterpret_cast<EpidSignature*>(sig_data.data()); size_t sig_len = sig_data.size() * sizeof(uint8_t); VerifierCtxObj ctx(this->kGroupPublicKey); std::vector<uint8_t> msg = this->kData_0_255; EXPECT_EQ(kEpidNoErr, EpidSign(member, msg.data(), msg.size(), nullptr, 0, sig, sig_len)); EXPECT_EQ(kEpidSigValid, EpidVerify(ctx, sig, sig_len, msg.data(), msg.size())); } } // namespace
46.925926
111
0.673703
TinkerBoard-Android
54f3d12579cb8e2a9b2145b2a85f0a84efd66f75
27,871
cpp
C++
libs2eplugins/src/s2e/Plugins/Checkers/MemoryBugChecker.cpp
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
7
2020-04-27T03:53:16.000Z
2021-12-31T02:04:48.000Z
libs2eplugins/src/s2e/Plugins/Checkers/MemoryBugChecker.cpp
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
null
null
null
libs2eplugins/src/s2e/Plugins/Checkers/MemoryBugChecker.cpp
trusslab/mousse
eb6ac492b15e2ca416a3b23bd4c4d115ae83b606
[ "MIT" ]
1
2020-07-15T05:19:28.000Z
2020-07-15T05:19:28.000Z
/// Copyright (C) 2010-2015, Dependable Systems Laboratory, EPFL /// Copyright (C) 2020, TrussLab@University of California, Irvine. /// Authors: Hsin-Wei Hung<hsinweih@uci.edu> /// All rights reserved. /// /// Licensed under the Cyberhaven Research License Agreement. /// #include "MemoryBugChecker.h" #include <s2e/S2E.h> #include <s2e/ConfigFile.h> #include <s2e/Utils.h> #include <s2e/S2EExecutor.h> #include <s2e/Plugins/OSMonitors/ModuleDescriptor.h> #include <cpu/se_libcpu.h> #include <cpu/tb.h> #include <cpu/exec.h> #include <klee/Solver.h> #include <klee/util/ExprTemplates.h> #include <klee/Internal/ADT/ImmutableMap.h> #include "klee/util/ExprPPrinter.h" #include <sys/types.h> #include <unistd.h> #include <fstream> #include <iostream> #include <sstream> extern llvm::cl::opt<bool> ConcolicMode; namespace s2e { namespace plugins { S2E_DEFINE_PLUGIN(MemoryBugChecker, "MemoryBugChecker plugin", "MemoryBugChecker", "ExecutionTracer"); namespace { struct MemoryRange { uint64_t start; uint64_t size; }; //Used to track OS resources that are accessed //through a handle struct ResourceHandle { uint64_t allocPC; std::string type; uint64_t handle; }; //XXX: Should also add per-module permissions struct MemoryRegion { MemoryRange range; uint64_t perms; uint64_t allocPC; std::string type; uint64_t id; bool permanent; }; struct StoreAttribute { bool stack; //true: stack; false: heap bool local; //true: only access within stack frame, false: only access memory beyond current stack frame uint64_t framePC; // if the write is to stack and not local }; struct MemoryRangeLT { bool operator()(const MemoryRange& a, const MemoryRange& b) const { return a.start + a.size <= b.start; } }; typedef klee::ImmutableMap<MemoryRange, const MemoryRegion*, MemoryRangeLT> MemoryMap; typedef std::map<uint64_t /*pc of the str*/, StoreAttribute> StoreMap; } // namespace inline bool is_aligned(uint64_t addr) { return !(addr % TARGET_PAGE_SIZE); } uint64_t align(uint64_t addr, bool floor) { uint64_t add = floor? 0: is_aligned(addr)? 0: 1; return (addr/TARGET_PAGE_SIZE + add) * TARGET_PAGE_SIZE; } class MemoryBugCheckerState: public PluginState { public: uint64_t m_brkAddress; uint64_t m_brkPageAddress; MemoryBugChecker* m_plugin; MemoryMap m_memoryMap; StoreMap m_storeMap; public: MemoryBugCheckerState() {} ~MemoryBugCheckerState() {} MemoryBugCheckerState *clone() const { return new MemoryBugCheckerState(*this); } static PluginState *factory(Plugin* p, S2EExecutionState* s) { MemoryBugCheckerState *ret = new MemoryBugCheckerState(); ret->m_plugin = static_cast<MemoryBugChecker *>(p); return ret; } uint64_t &getBRKAddress() { return m_brkAddress; } uint64_t &getBRKPageAddress() { return m_brkPageAddress; } void setBRKAddress(uint64_t addr) { m_brkAddress = addr; m_brkPageAddress = align(addr, false); } MemoryMap &getMemoryMap() { return m_memoryMap; } void setMemoryMap(const MemoryMap& memoryMap) { m_memoryMap = memoryMap; } StoreMap &getStoreMap() { return m_storeMap; } void setStoreMap(const StoreMap& storeMap) { m_storeMap = storeMap; } }; void MemoryBugChecker::initialize() { ConfigFile *cfg = s2e()->getConfig(); m_debugLevel = cfg->getInt(getConfigKey() + ".debugLevel", 0); m_checkBugs = cfg->getBool(getConfigKey() + ".checkMemoryBugs", true); m_checkNullPtrDerefBug = cfg->getBool(getConfigKey() + ".checkNullPtrDereferenceBug", false); m_checkRetPtrOverrideBug = cfg->getBool(getConfigKey() + ".checkReturnPtrOverrideBug", false); m_checkOOBAccessBug = cfg->getBool(getConfigKey() + ".checkOOBAccessBug", false); m_terminateOnBugs = cfg->getBool(getConfigKey() + ".terminateOnBugs", true); m_traceMemoryAccesses = cfg->getBool(getConfigKey() + ".traceMemoryAccesses", false); m_stackMonitor = s2e()->getPlugin<StackMonitor>(); m_pm = s2e()->getPlugin<ProcessMonitor>(); assert(m_pm); s2e()->getCorePlugin()->onBeforeSymbolicDataMemoryAccess.connect( sigc::mem_fun(*this, &MemoryBugChecker::onBeforeSymbolicDataMemoryAccess)); s2e()->getCorePlugin()->onConcreteDataMemoryAccess.connect( sigc::mem_fun(*this, &MemoryBugChecker::onConcreteDataMemoryAccess)); s2e()->getCorePlugin()->onAlwaysConcreteMemoryAccess.connect( sigc::mem_fun(*this, &MemoryBugChecker::onAlwaysConcreteMemoryAccess)); } void MemoryBugChecker::printImageInfo(S2EExecutionState *state, ImageInfo *info) { getDebugStream(state) << "\n" << "[Binary]\n" << "load_bias: " << hexval(info->load_bias) << " load_addr: " << hexval(info->load_addr) << "\n" << "start_code: " << hexval(info->start_code) << " end_code: " << hexval(info->end_code) << "\n" << "start_data: " << hexval(info->start_data) << " end_data: " << hexval(info->end_data) << "\n" << "start_brk: " << hexval(info->start_brk) << " brk: " << hexval(info->brk) << "\n" << "start_mmap: " << hexval(info->start_mmap) << " mmap: " << hexval(info->mmap) << "\n" << "rss: " << hexval(info->rss) << "\n" << "start_stack: " << hexval(info->start_stack) << " stack_limit: " << hexval(info->stack_limit) << "\n" << "entry: " << hexval(info->entry) << "\n" << "code_offset: " << hexval(info->code_offset) << "\n" << "data_offset: " << hexval(info->data_offset) << "\n" << "saved_auxv: " << hexval(info->saved_auxv) << " auxv_len: " << hexval(info->auxv_len) << "\n" << "arg_start: " << hexval(info->arg_start) << " arg_end: " << hexval(info->arg_end) << "\n" << "elf_flags: " << hexval(info->elf_flags) << "\n\n"; if (info->interp_info) { ImageInfo* interp_info = info->interp_info; getDebugStream(state) << "\n" << "[ELF interpreter]\n" << "load_bias: " << hexval(interp_info->load_bias) << " load_addr: " << hexval(interp_info->load_addr) << "\n" << "start_code: " << hexval(interp_info->start_code) << " end_code: " << hexval(interp_info->end_code) << "\n" << "start_data: " << hexval(interp_info->start_data) << " end_data: " << hexval(interp_info->end_data) << "\n" << "start_brk: " << hexval(interp_info->start_brk) << " brk: " << hexval(interp_info->brk) << "\n" << "start_mmap: " << hexval(interp_info->start_mmap) << " mmap: " << hexval(interp_info->mmap) << "\n" << "rss: " << hexval(interp_info->rss) << "\n" << "start_stack: " << hexval(interp_info->start_stack) << " stack_limit: " << hexval(interp_info->stack_limit) << "\n" << "entry: " << hexval(interp_info->entry) << "\n" << "code_offset: " << hexval(interp_info->code_offset) << "\n" << "data_offset: " << hexval(interp_info->data_offset) << "\n" << "saved_auxv: " << hexval(interp_info->saved_auxv) << " auxv_len: " << hexval(interp_info->auxv_len) << "\n" << "arg_start: " << hexval(interp_info->arg_start) << " arg_end: " << hexval(interp_info->arg_end) << "\n" << "elf_flags: " << hexval(interp_info->elf_flags) << "\n\n"; } } void MemoryBugChecker::emitOnBugDetected(S2EExecutionState *state, uint32_t bug, uint64_t pc) { if (pc == 0) pc = state->regs()->getPc(); std::string file = m_pm->getFileName(pc); uint32_t offset = m_pm->getOffsetWithinFile(file, pc); uint32_t insn; if (!state->mem()->read<uint32_t>(pc, &insn, VirtualAddress, false)) { getWarningsStream(state) << "cannot get instruction at " << hexval(pc); insn = 0xffffffff; } onBugDetected.emit(state, bug, offset, insn, file, m_bugInputs); } void MemoryBugChecker::printConcreteInputs(llvm::raw_ostream &os, const ConcreteInputs &inputs) { std::stringstream ss; for (auto& it : inputs) { const VarValuePair &vp = it; ss << std::setw(20) << vp.first << " = {"; for (unsigned i = 0; i < vp.second.size(); ++i) { if (i != 0) ss << ", "; ss << std::setw(2) << std::setfill('0') << "0x" << std::hex << (unsigned) vp.second[i] << std::dec; } ss << "}" << std::setfill(' ') << "; "; if (vp.second.size() == sizeof(int32_t)) { int32_t valueAsInt = vp.second[0] | ((int32_t) vp.second[1] << 8) | ((int32_t) vp.second[2] << 16) | ((int32_t) vp.second[3] << 24); ss << "(int32_t) " << valueAsInt << ", "; } if (vp.second.size() == sizeof(int64_t)) { int64_t valueAsInt = vp.second[0] | ((int64_t) vp.second[1] << 8) | ((int64_t) vp.second[2] << 16) | ((int64_t) vp.second[3] << 24) | ((int64_t) vp.second[4] << 32) | ((int64_t) vp.second[5] << 40) | ((int64_t) vp.second[6] << 48) | ((int64_t) vp.second[7] << 56); ss << "(int64_t) " << valueAsInt << ", "; } ss << "(string) \""; for (unsigned i = 0; i < vp.second.size(); ++i) { ss << (char) (std::isprint(vp.second[i]) ? vp.second[i] : '.'); } ss << "\"\n"; } os << "concrete inputs:\n" << ss.str(); } // Check if the experssion could have multiple feasible value under current constriants bool MemoryBugChecker::checkRange(S2EExecutionState *state, klee::ref<klee::Expr> expr) { std::pair<klee::ref<klee::Expr>, klee::ref<klee::Expr>> range; klee::Query query(state->constraints, expr); range = s2e()->getExecutor()->getSolver(*state)->getRange(query); uint64_t min = dyn_cast<klee::ConstantExpr>(range.first)->getZExtValue(); uint64_t max = dyn_cast<klee::ConstantExpr>(range.second)->getZExtValue(); getWarningsStream(state) << "checkRange min = " << hexval(min) << " max = " << hexval(max) << "fd = " << state->regs()->read<uint32_t>(CPU_OFFSET(regs[0])) <<"\n"; return (min != max); } bool MemoryBugChecker::assume(S2EExecutionState *state, klee::ref<klee::Expr> expr) { getDebugStream(state) << "Thread = " << hexval((unsigned long)pthread_self()) << " assume: " << expr << "\n"; klee::ref<klee::Expr> zero = klee::ConstantExpr::create(0, expr.get()->getWidth()); klee::ref<klee::Expr> boolexpr = klee::NeExpr::create(expr, zero); // check if expr may be true under current path constraints bool isValid = true; bool truth; klee::Solver *solver = s2e()->getExecutor()->getSolver(*state); klee::Query query(state->constraints, boolexpr); bool res = solver->mustBeTrue(query.negateExpr(), truth); if (!res || truth) { isValid = false; } if (!isValid) { std::stringstream ss; ss << "MemoryBugChecker: specified constraint cannot be satisfied " << expr; } else { std::vector<std::vector<unsigned char>> values; std::vector<const klee::Array *> objects; for (auto it : state->symbolics) { objects.push_back(it.second); } klee::ConstraintManager tmpConstraints = state->constraints; tmpConstraints.addConstraint(expr); // ConcreteInputs inputs; m_bugInputs.clear(); isValid = solver->getInitialValues( klee::Query(tmpConstraints, klee::ConstantExpr::alloc(0, klee::Expr::Bool)), objects, values); assert(isValid && "should be solvable"); for (unsigned i = 0; i != state->symbolics.size(); ++i) { // inputs.push_back( m_bugInputs.push_back( std::make_pair(state->symbolics[i].first->name, values[i])); } printConcreteInputs(getWarningsStream(state), m_bugInputs); } return isValid; } bool MemoryBugChecker::checkNullPtrDeref(S2EExecutionState *state, klee::ref<klee::Expr> addr) { klee::ref<klee::Expr> nullValue = E_CONST(0, state->getPointerWidth()); klee::ref<klee::Expr> nullAddressRead = klee::EqExpr::create(nullValue, addr); return assume(state, nullAddressRead); } bool MemoryBugChecker::checkAddressRange(S2EExecutionState *state, klee::ref<klee::Expr> addr, uint64_t lower, uint64_t upper) { klee::ref<klee::Expr> lowerValue = E_CONST(lower, state->getPointerWidth()); klee::ref<klee::Expr> upperValue = E_CONST(upper, state->getPointerWidth()); klee::ref<klee::Expr> rangeConstraint = klee::AndExpr::create(klee::UgeExpr::create(addr, lowerValue), klee::UleExpr::create(addr, upperValue)); bool ret = assume(state, rangeConstraint); getDebugStream(state) << "check if addr: " << addr << " can fall in the range(" << hexval(lower) << "," << hexval(upper) << "):" << ret << "\n"; return ret; } bool MemoryBugChecker::checkRetPtrOverride(S2EExecutionState *state, klee::ref<klee::Expr> addr) { bool isSeedState = false; bool hasBug = false; // if (m_seedSearcher) { // isSeedState = m_seedSearcher->isSeedState(state); // } /* * For every EIP stored on the stack, fork a state that will overwrite it. */ StackMonitor::CallStack cs; if (!m_stackMonitor->getCallStack(state, 1, pthread_self(), cs)) { getWarningsStream(state) << "Failed to get call stack\n"; return false; } std::vector<klee::ref<klee::Expr>> retAddrLocations; for (unsigned i = 1; i < cs.size(); i++) { // always skip first dummy frame retAddrLocations.push_back(E_CONST(cs[i].FrameTop, state->getPointerWidth())); } bool forkState = false; if (forkState) { std::vector<klee::ExecutionState *> states = s2e()->getExecutor()->forkValues(state, isSeedState, addr, retAddrLocations); assert(states.size() == retAddrLocations.size()); for (unsigned i = 0; i < states.size(); i++) { S2EExecutionState *valuableState = static_cast<S2EExecutionState *>(states[i]); /* if (valuableState) { // We've forked a state where symbolic address will be concretized to one exact value. // Put the state into separate CUPA group to distinguish it from other states that were // produced by fork and concretise at the same PC. m_keyValueStore->setProperty(valuableState, "group", CUPA_GROUP_SYMBOLIC_ADDRESS); } */ std::ostringstream os; os << "Stack frame " << i << " retAddr @ " << retAddrLocations[i]; if (valuableState) { os << " overriden in state " << valuableState->getID(); getWarningsStream(state) << os.str() << "\n"; hasBug = true; } else { os << " can not be overriden"; getDebugStream(state) << os.str() << "\n"; } } } else { for (unsigned i = 0; i < retAddrLocations.size(); i++) { std::ostringstream os; os << "Stack frame " << i << " retAddr @ " << retAddrLocations[i]; klee::ref<klee::Expr> retAddrLocationWrite = klee::EqExpr::create(retAddrLocations.at(i), addr); if (assume(state, retAddrLocationWrite)) { os << " could be overridden"; getWarningsStream(state) << os.str() << "\n"; hasBug = true; } else { } } } return hasBug; } /* bool MemoryBugChecker::checkSymbolicUnallocatedHeapAccess(S2EExecutionState *state, klee::ref<klee::Expr> addr) { m_pm->updateProcessAddressMap("[anon:libc_malloc]", 0xffffffff); bool notAllocated = true; if (isAddressWithinFile(addr, "[anon:libc_malloc]")) { for (auto region : m_libcMallocRegions) { if (addr >= region.first && addr + size < region.second) { notAllocated = false; break; } } } if (notAllocated) { err << "MemoryBugChecker::checkMemoryAccess: " << "BUG: memory range at " << hexval(addr) << " of size " << hexval(size) << " can not be accessed by instruction " << getPrettyCodeLocation(state) << ": using not allocated region in heap" << '\n'; emitOnBugDetected(state, BUG_C_LIBC_UNALLOCHEAP); } return notAllocated; }*/ bool MemoryBugChecker::checkSymbolicMemoryAccess(S2EExecutionState *state, klee::ref<klee::Expr> start, klee::ref<klee::Expr> value, bool isWrite, llvm::raw_ostream &err) { DECLARE_PLUGINSTATE(MemoryBugCheckerState, state); if (!m_checkBugs) return true; bool hasBug = false; if (checkRange(state, start)) { emitOnBugDetected(state, BUG_S_MEMACCESS); getWarningsStream(state) << "Symbolic memory access\n" << " Instruction: " << getPrettyCodeLocation(state) << "\n" << " Address: " << start << "\n"; m_stackMonitor->printCallStack(state); } if (m_checkNullPtrDerefBug) { hasBug = checkNullPtrDeref(state, start); if (hasBug) { err << "BUG: potential null pointer dereference\n" << " Instruction: " << getPrettyCodeLocation(state) << "\n" << " Address: " << start << "\n"; emitOnBugDetected(state, BUG_S_R_NULLPTR); } } if (isWrite) { if (m_checkRetPtrOverrideBug) { hasBug = checkRetPtrOverride(state, start); if (hasBug) { err << "BUG: potential return pointer override\n" << " Instruction: " << getPrettyCodeLocation(state) << "\n" << " Address: "<< start << "\n"; emitOnBugDetected(state, BUG_S_W_RETPTR); } } if (m_checkOOBAccessBug) { StackMonitor::CallStack cs; if (m_stackMonitor->getCallStack(state, 1, pthread_self(), cs)) { ImageInfo* info = &m_binaryInfo; if (checkAddressRange(state, start, cs.back().FrameTop, info->start_stack) && checkAddressRange(state, start, info->start_code, plgState->getBRKAddress())) { err << "BUG: suspicious memory access (could access to both heap and stack)\n" << " Instruction: " << getPrettyCodeLocation(state) << "\n" << " Address: "<< start << "\n"; hasBug = true; emitOnBugDetected(state, BUG_S_W_STACKANDHEAP); } } } if (m_checkOOBAccessBug) { ImageInfo* info = &m_binaryInfo; if (checkAddressRange(state, start, info->start_code, info->end_code)) { err << "BUG: potential write to code section\n" << " Instruction: " << getPrettyCodeLocation(state) << "\n" << " Address: "<< start << "\n"; hasBug = true; emitOnBugDetected(state, BUG_S_W_CODE); } } } return !hasBug; } void MemoryBugChecker::onBeforeSymbolicDataMemoryAccess(S2EExecutionState* state, klee::ref<klee::Expr> virtualAddress, klee::ref<klee::Expr> value, bool isWrite) { std::string errstr; llvm::raw_string_ostream err(errstr); bool result = checkSymbolicMemoryAccess(state, virtualAddress, value, isWrite, err); if (!result) { if (m_terminateOnBugs) { s2e()->getExecutor()->terminateStateEarly(*state, err.str()); } else { s2e()->getWarningsStream(state) << err.str(); m_stackMonitor->printCallStack(state); } } } bool MemoryBugChecker::checkConcreteOOBAccess(S2EExecutionState *state, uint64_t addr, int size, bool isWrite, llvm::raw_ostream &err) { // DECLARE_PLUGINSTATE(MemoryBugCheckerState, state); // StoreMap &storeMap = plgState->getStoreMap(); if (!m_checkRetPtrOverrideBug) return false; bool hasError = false; if (isWrite) { StackMonitor::CallStack cs; if (!m_stackMonitor->getCallStack(state, 1, pthread_self(), cs)) { getWarningsStream(state) << "Failed to get call stack\n"; return false; } bool stack = (addr <= m_binaryInfo.start_stack && addr > m_binaryInfo.stack_limit); uint64_t framePc = 0; uint64_t pc = state->regs()->getPc(); int wordSize = state->getPointerWidth() / 8; //getDebugStream(state) <<'\n'; if (stack) { for (unsigned i = 1; i < cs.size(); i++) { // always skip first dummy frame //getDebugStream(state) << " waddr: "<< hexval(addr) // << " frameTop: " << hexval(cs[i].FrameTop) << '\n'; if ((addr < cs[i].FrameTop && addr >= cs[i].FrameTop + wordSize) || (addr + wordSize < cs[i].FrameTop && addr + wordSize >= cs[i].FrameTop + wordSize)) { err << "MemoryBugChecker::checkMemoryAccess: " << "BUG: memory range at " << hexval(addr) << " of size " << hexval(size) << " can not be accessed by instruction " << getPrettyCodeLocation(state) << ": the return pointer at " << hexval(cs[i].FrameTop) << " should not be overriden" << "\n"; hasError = true; emitOnBugDetected(state, BUG_C_W_RETPTR, pc); break; } if (addr >= cs[i].FrameTop) { framePc = cs[i].FramePc; } } } // //Check the access pattern // StoreAttribute *attr = new StoreAttribute(); // attr->stack = stack; // attr->local = (framePc == cs.back().FramePc); // attr->framePC = framePc; // // auto it = storeMap.find(pc); // if (it != storeMap.end()) { // storeMap.insert(std::pair<uint64_t, StoreAttribute>(pc, *attr)); // } else { // if (it->second.stack != attr->stack || // (attr->stack == true && it->second.local != attr->local)) { // err << "MemoryBugChecker::checkMemoryAccess: " // << "BUG: memory range at " << hexval(addr) << " of size " << hexval(size) // << " accessed by instruction " << getPrettyCodeLocation(state) // << " : Access pattern mismatch. This could be an out-of-bound access. " << "\n"; // hasError = true; // emitOnBugDetected(state, BUG_C_W_STACKANDHEAP, pc); // } // } } return hasError; } /* bool MemoryBugChecker::checkUnallocatedHeapAccess(S2EExecutionState *state, uint64_t addr, int size, llvm::raw_ostream &err) { if (m_pm->isAddressUnknown(addr)) m_pm->updateProcessAddressMap("[anon:libc_malloc]", addr + size); bool notAllocated = true; if (m_pm->isAddressWithinFile(addr, "[anon:libc_malloc]")) { for (auto region : m_libcMallocRegions) { if (addr >= region.first && addr + size < region.second) { notAllocated = false; break; } } } if (notAllocated) { err << "MemoryBugChecker::checkMemoryAccess: " << "BUG: memory range at " << hexval(addr) << " of size " << hexval(size) << " can not be accessed by instruction " << getPrettyCodeLocation(state) << ": using not allocated region in heap" << '\n'; emitOnBugDetected(state, BUG_C_LIBC_UNALLOCHEAP); } return notAllocated; }*/ bool MemoryBugChecker::checkMemoryAccess(S2EExecutionState *state, uint64_t start, uint64_t size, uint8_t perms, llvm::raw_ostream &err) { if (!m_checkBugs) return true; bool hasError = false; //FIXME: should move the checking for concrete null pointer dereference to a handler //connected to a signal emitted before concrete memory access. Otherwise, null //pointer dereference will trigger qemu bad ram pointer error before the checking. if (m_checkNullPtrDerefBug && (start == 0)) { err << "MemoryBugChecker::checkMemoryAccess: " << "BUG: memory range at " << hexval(start) << " of size " << hexval(size) << " can not be accessed by instruction " << getPrettyCodeLocation(state) << ": reading memory @ 0x0, could be null pointer dereference" << '\n'; hasError = true; } hasError |= checkConcreteOOBAccess(state, start, size, perms & WRITE, err); // hasError |= checkUnallocatedHeapAccess(state, start, size, err); return !hasError; } void MemoryBugChecker::onAlwaysConcreteMemoryAccess(S2EExecutionState *state, klee::ref<klee::Expr> value, bool isWrite) { if (isWrite) getWarningsStream(state) << "write pc\n"; else getWarningsStream(state) << "read pc\n"; } void MemoryBugChecker::onConcreteDataMemoryAccess(S2EExecutionState *state, uint64_t virtualAddress, uint64_t value, uint8_t size, unsigned flags) { bool isWrite = flags & MEM_TRACE_FLAG_WRITE; onPreCheck.emit(state, virtualAddress, size, isWrite); std::string errstr; llvm::raw_string_ostream err(errstr); bool result = checkMemoryAccess(state, virtualAddress, size, isWrite ? WRITE : READ, err); if (!result) { onPostCheck.emit(state, virtualAddress, size, isWrite, &result); if (result) { return; } if (m_terminateOnBugs) s2e()->getExecutor()->terminateStateEarly(*state, err.str()); else s2e()->getWarningsStream(state) << err.str(); } } std::string MemoryBugChecker::getPrettyCodeLocation(S2EExecutionState *state) { std::stringstream ss; uint64_t pc = state->regs()->getPc(); uint32_t insn; std::string binary = m_pm->getFileName(pc); if (!state->mem()->read<uint32_t>(pc, &insn, VirtualAddress, false)) { getWarningsStream(state) << "cannot get instruction at " << hexval(pc); } ss << hexval(insn) << " @" << hexval(pc) << " " << binary; return ss.str(); } } // namespace plugins } // namespace s2e
38.495856
167
0.559757
trusslab
54f5801d9388ffab36e8d18a91e7f7804e4b564e
463
cpp
C++
leetcode/problems/easy/504-base-7.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/504-base-7.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/504-base-7.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Base 7 https://leetcode.com/problems/base-7/ Given an integer num, return a string of its base 7 representation. Example 1: Input: num = 100 Output: "202" Example 2: Input: num = -7 Output: "-10" Constraints: -107 <= num <= 107 */ class Solution { public: string convertToBase7(int n) { if (n < 0) return "-" + convertToBase7(-n); if (n < 7) return to_string(n); return convertToBase7(n / 7) + to_string(n % 7); } };
14.935484
67
0.609071
wingkwong
54f642de2d6c37b21f4bbf4a19b278b1e07e7524
3,999
cpp
C++
emf_core_bindings/src/emf_event.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
null
null
null
emf_core_bindings/src/emf_event.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
null
null
null
emf_core_bindings/src/emf_event.cpp
GabeRealB/emf
a233edaed7ed99948b0a935e6378bac131fdf4c2
[ "Apache-2.0", "MIT" ]
1
2021-01-10T15:00:08.000Z
2021-01-10T15:00:08.000Z
#include <emf_core/emf_event.h> #include <emf_core_bindings/emf_core_bindings.h> using namespace EMF::Core::C; namespace EMF::Core::Bindings::C { extern "C" { emf_event_handle_t EMF_CALL_C emf_event_create( const emf_event_name_t* EMF_NOT_NULL event_name, emf_event_handler_fn_t EMF_MAYBE_NULL event_handler) EMF_NOEXCEPT { EMF_ASSERT_ERROR(event_name != nullptr, "emf_event_create()") EMF_ASSERT_ERROR(emf_event_name_exists(event_name) == emf_bool_false, "emf_event_create()") return emf_binding_interface->event_create_fn(event_name, event_handler); } EMF_NODISCARD emf_event_handle_t EMF_CALL_C emf_event_create_private( emf_event_handler_fn_t EMF_MAYBE_NULL event_handler) EMF_NOEXCEPT { return emf_binding_interface->event_create_private_fn(event_handler); } void EMF_CALL_C emf_event_destroy(emf_event_handle_t event_handle) EMF_NOEXCEPT { EMF_ASSERT_ERROR(emf_event_handle_exists(event_handle) == emf_bool_true, "emf_event_destroy()") emf_binding_interface->event_destroy_fn(event_handle); } void EMF_CALL_C emf_event_publish(emf_event_handle_t event_handle, const emf_event_name_t* EMF_NOT_NULL event_name) EMF_NOEXCEPT { EMF_ASSERT_ERROR(event_name != nullptr, "emf_event_publish()") EMF_ASSERT_ERROR(emf_event_name_exists(event_name) == emf_bool_false, "emf_event_publish()") emf_binding_interface->event_publish_fn(event_handle, event_name); } EMF_NODISCARD size_t EMF_CALL_C emf_event_get_num_public_events() EMF_NOEXCEPT { return emf_binding_interface->event_get_num_public_events_fn(); } size_t EMF_CALL_C emf_event_get_public_events(emf_event_name_span_t* EMF_NOT_NULL buffer) EMF_NOEXCEPT { EMF_ASSERT_ERROR(buffer != nullptr, "emf_event_get_public_events()") EMF_ASSERT_ERROR(buffer->length >= emf_event_get_num_public_events(), "emf_event_get_public_events()") EMF_ASSERT_ERROR(buffer->data != nullptr, "emf_event_get_public_events()") return emf_binding_interface->event_get_public_events_fn(buffer); } EMF_NODISCARD emf_event_handle_t EMF_CALL_C emf_event_get_event_handle( const emf_event_name_t* EMF_NOT_NULL event_name) EMF_NOEXCEPT { EMF_ASSERT_ERROR(event_name != nullptr, "emf_event_get_event_handle()") EMF_ASSERT_ERROR(emf_event_name_exists(event_name) == emf_bool_true, "emf_event_get_event_handle()") return emf_binding_interface->event_get_event_handle_fn(event_name); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_event_handle_exists(emf_event_handle_t event_handle) EMF_NOEXCEPT { return emf_binding_interface->event_handle_exists_fn(event_handle); } EMF_NODISCARD emf_bool_t EMF_CALL_C emf_event_name_exists(const emf_event_name_t* EMF_NOT_NULL event_name) EMF_NOEXCEPT { EMF_ASSERT_ERROR(event_name != nullptr, "emf_event_name_exists()") return emf_binding_interface->event_name_exists_fn(event_name); } void EMF_CALL_C emf_event_subscribe_handler( emf_event_handle_t event_handle, emf_event_handler_fn_t EMF_NOT_NULL event_handler) EMF_NOEXCEPT { EMF_ASSERT_ERROR(emf_event_handle_exists(event_handle) == emf_bool_true, "emf_event_subscribe_handler()") EMF_ASSERT_ERROR(event_handler != nullptr, "emf_event_subscribe_handler()") emf_binding_interface->event_subscribe_handler_fn(event_handle, event_handler); } void EMF_CALL_C emf_event_unsubscribe_handler( emf_event_handle_t event_handle, emf_event_handler_fn_t EMF_NOT_NULL event_handler) EMF_NOEXCEPT { EMF_ASSERT_ERROR(emf_event_handle_exists(event_handle) == emf_bool_true, "emf_event_unsubscribe_handler()") EMF_ASSERT_ERROR(event_handler != nullptr, "emf_event_unsubscribe_handler()") emf_binding_interface->event_unsubscribe_handler_fn(event_handle, event_handler); } void EMF_CALL_C emf_event_signal(emf_event_handle_t event_handle, emf_event_data_t EMF_MAYBE_NULL event_data) EMF_NOEXCEPT { EMF_ASSERT_ERROR(emf_event_handle_exists(event_handle) == emf_bool_true, "emf_event_signal()") emf_binding_interface->event_signal_fn(event_handle, event_data); } } }
43
128
0.829457
GabeRealB
54f8453c90ce9688988ec717ad5a17241d7ee8d8
180
cpp
C++
Landlords/Player.cpp
jie65535/Landlords
cb0cbae732af868c34fb66e01a7159dfc90992ee
[ "MIT" ]
null
null
null
Landlords/Player.cpp
jie65535/Landlords
cb0cbae732af868c34fb66e01a7159dfc90992ee
[ "MIT" ]
null
null
null
Landlords/Player.cpp
jie65535/Landlords
cb0cbae732af868c34fb66e01a7159dfc90992ee
[ "MIT" ]
1
2019-05-19T15:12:30.000Z
2019-05-19T15:12:30.000Z
#include "stdafx.h" #include "Player.h" Player::Player(playerID_t id): m_id(id), m_name(), m_integral(0), m_currRoom(0), isReady(false) { } Player::~Player() { }
12.857143
66
0.611111
jie65535
54f8fdaf7e1d511fb369cc5bce93040fbad5917e
3,493
cpp
C++
kernel/syscallhandler.cpp
Twometer/nekosys
cbcdaddaf8087cde1c375dbc19c576475965f5b4
[ "Apache-2.0" ]
1
2021-08-28T19:50:32.000Z
2021-08-28T19:50:32.000Z
kernel/syscallhandler.cpp
Twometer/nekosys
cbcdaddaf8087cde1c375dbc19c576475965f5b4
[ "Apache-2.0" ]
null
null
null
kernel/syscallhandler.cpp
Twometer/nekosys
cbcdaddaf8087cde1c375dbc19c576475965f5b4
[ "Apache-2.0" ]
null
null
null
#include <kernel/syscallhandler.h> #include <kernel/syscalls.h> #include <kernel/memory/stack.h> #include <kernel/tasks/thread.h> #include <kernel/kdebug.h> #include <kernel/video/tty.h> #include <errno.h> using namespace Memory; namespace Kernel { DEFINE_SINGLETON(SyscallHandler) SyscallHandler::SyscallHandler() { syscalls = new nk::Vector<syscall_t>(); } void SyscallHandler::Register() { AddSyscall(SYS_TEXIT, sys$$texit); AddSyscall(SYS_PRINT, sys$$print); AddSyscall(SYS_EXIT, sys$$exit); AddSyscall(SYS_PUTCHAR, sys$$putchar); AddSyscall(SYS_FOPEN, sys$$fopen); AddSyscall(SYS_FREAD, sys$$fread); AddSyscall(SYS_FWRITE, sys$$fwrite); AddSyscall(SYS_FCLOSE, sys$$fclose); AddSyscall(SYS_PAGEALLOC, sys$$pagealloc); AddSyscall(SYS_SLEEP, sys$$sleep); AddSyscall(SYS_SPAWNP, sys$$spawnp); AddSyscall(SYS_WAITP, sys$$waitp); AddSyscall(SYS_READLN, sys$$readln); AddSyscall(SYS_FBACQUIRE, sys$$fb_acquire); AddSyscall(SYS_FBFLUSH, sys$$fb_flush); AddSyscall(SYS_FBRELEASE, sys$$fb_release); AddSyscall(SYS_CHDIR, sys$$chdir); AddSyscall(SYS_GETCWD, sys$$getcwd); AddSyscall(SYS_GETENV, sys$$getenv); AddSyscall(SYS_READDIR, sys$$readdir); AddSyscall(SYS_SHBUFCREATE, sys$$shbuf_create); AddSyscall(SYS_SHBUFMAP, sys$$shbuf_map); AddSyscall(SYS_SHBUFUNMAP, sys$$shbuf_unmap); AddSyscall(SYS_PIPEOPEN, sys$$pipe_open); AddSyscall(SYS_PIPECLOSE, sys$$pipe_close); AddSyscall(SYS_PIPESEND, sys$$pipe_send); AddSyscall(SYS_PIPERECV, sys$$pipe_recv); AddSyscall(SYS_THCREATE, sys$$thread_create); AddSyscall(SYS_THJOIN, sys$$thread_join); AddSyscall(SYS_MOUSEPOLL, sys$$mouse_poll); Interrupts::AddHandler(0x80, this); } void SyscallHandler::HandleInterrupt(unsigned int, RegisterStates *regs) { // When the interrupt is called, ESP is saved to the regs state. // At that point however, it is already the kernel's ESP0. The // user-mode stack pointer was pushed to the stack by the CPU. // The value at ESP+12 therefore gets us the address of where // the user thread's stack is located. There, the syscall params // are stored. auto user_stack_ptr = *(uint32_t *)(regs->esp + 12); // For easy access to the struct, we create ourselves a "virtual" // stack Stack stack((void *)user_stack_ptr); stack.Pop(); // The return pointer - we don't need that uint32_t syscall_num = stack.Pop(); // Syscall number void *param_ptr = (void *)stack.Pop(); // Pointer to the param struct uint32_t *retval = (uint32_t *)stack.GetStackPtr(); // Stack now points at the retval ptr auto syscallHandler = syscalls->At(syscall_num); if (syscallHandler == nullptr) { *retval = -ENOSYS; kdbg("warn: Thread %d attempted invalid syscall %x\n", Thread::Current()->GetId(), syscall_num); return; } else { *retval = syscallHandler(param_ptr); } } void SyscallHandler::AddSyscall(uint32_t number, syscall_t call) { syscalls->Reserve(number + 1); syscalls->At(number) = call; } } // namespace Kernel
37.55914
108
0.626396
Twometer
54fe6917cba19e2966b310eb77007a25e7d3dbf1
22,871
cc
C++
GRPC/grpc.pb.cc
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
150
2015-01-14T15:06:38.000Z
2018-08-28T09:34:17.000Z
GRPC/grpc.pb.cc
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
28
2015-05-11T02:45:39.000Z
2018-08-24T11:43:17.000Z
GRPC/grpc.pb.cc
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
91
2015-05-04T09:52:41.000Z
2018-08-18T13:02:15.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: grpc.proto #include "grpc.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG constexpr EchoRequest::EchoRequest( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : message_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , name_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct EchoRequestDefaultTypeInternal { constexpr EchoRequestDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~EchoRequestDefaultTypeInternal() {} union { EchoRequest _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT EchoRequestDefaultTypeInternal _EchoRequest_default_instance_; constexpr EchoResponse::EchoResponse( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : message_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string){} struct EchoResponseDefaultTypeInternal { constexpr EchoResponseDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~EchoResponseDefaultTypeInternal() {} union { EchoResponse _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT EchoResponseDefaultTypeInternal _EchoResponse_default_instance_; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_grpc_2eproto[2]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_grpc_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_grpc_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_grpc_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::EchoRequest, _has_bits_), PROTOBUF_FIELD_OFFSET(::EchoRequest, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EchoRequest, message_), PROTOBUF_FIELD_OFFSET(::EchoRequest, name_), 0, 1, PROTOBUF_FIELD_OFFSET(::EchoResponse, _has_bits_), PROTOBUF_FIELD_OFFSET(::EchoResponse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::EchoResponse, message_), 0, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 7, sizeof(::EchoRequest)}, { 9, 15, sizeof(::EchoResponse)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::_EchoRequest_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::_EchoResponse_default_instance_), }; const char descriptor_table_protodef_grpc_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\ngrpc.proto\",\n\013EchoRequest\022\017\n\007message\030\001" " \001(\t\022\014\n\004name\030\002 \001(\t\"\037\n\014EchoResponse\022\017\n\007me" "ssage\030\001 \001(\t2.\n\007Example\022#\n\004Echo\022\014.EchoReq" "uest\032\r.EchoResponse" ; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_grpc_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_grpc_2eproto = { false, false, 139, descriptor_table_protodef_grpc_2eproto, "grpc.proto", &descriptor_table_grpc_2eproto_once, nullptr, 0, 2, schemas, file_default_instances, TableStruct_grpc_2eproto::offsets, file_level_metadata_grpc_2eproto, file_level_enum_descriptors_grpc_2eproto, file_level_service_descriptors_grpc_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_grpc_2eproto_getter() { return &descriptor_table_grpc_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_grpc_2eproto(&descriptor_table_grpc_2eproto); // =================================================================== class EchoRequest::_Internal { public: using HasBits = decltype(std::declval<EchoRequest>()._has_bits_); static void set_has_message(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; EchoRequest::EchoRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:EchoRequest) } EchoRequest::EchoRequest(const EchoRequest& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); message_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_message()) { message_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_message(), GetArenaForAllocation()); } name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:EchoRequest) } inline void EchoRequest::SharedCtor() { message_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } EchoRequest::~EchoRequest() { // @@protoc_insertion_point(destructor:EchoRequest) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void EchoRequest::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); message_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void EchoRequest::ArenaDtor(void* object) { EchoRequest* _this = reinterpret_cast< EchoRequest* >(object); (void)_this; } void EchoRequest::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EchoRequest::SetCachedSize(int size) const { _cached_size_.Set(size); } void EchoRequest::Clear() { // @@protoc_insertion_point(message_clear_start:EchoRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { message_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { name_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* EchoRequest::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional string message = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_message(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EchoRequest.message"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; // optional string name = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EchoRequest.name"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* EchoRequest::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EchoRequest) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string message = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_message().data(), static_cast<int>(this->_internal_message().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EchoRequest.message"); target = stream->WriteStringMaybeAliased( 1, this->_internal_message(), target); } // optional string name = 2; if (cached_has_bits & 0x00000002u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_name().data(), static_cast<int>(this->_internal_name().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EchoRequest.name"); target = stream->WriteStringMaybeAliased( 2, this->_internal_name(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EchoRequest) return target; } size_t EchoRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EchoRequest) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string message = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_message()); } // optional string name = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EchoRequest::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, EchoRequest::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EchoRequest::GetClassData() const { return &_class_data_; } void EchoRequest::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from) { static_cast<EchoRequest *>(to)->MergeFrom( static_cast<const EchoRequest &>(from)); } void EchoRequest::MergeFrom(const EchoRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EchoRequest) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_message(from._internal_message()); } if (cached_has_bits & 0x00000002u) { _internal_set_name(from._internal_name()); } } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void EchoRequest::CopyFrom(const EchoRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EchoRequest) if (&from == this) return; Clear(); MergeFrom(from); } bool EchoRequest::IsInitialized() const { return true; } void EchoRequest::InternalSwap(EchoRequest* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &message_, GetArenaForAllocation(), &other->message_, other->GetArenaForAllocation() ); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &name_, GetArenaForAllocation(), &other->name_, other->GetArenaForAllocation() ); } ::PROTOBUF_NAMESPACE_ID::Metadata EchoRequest::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_grpc_2eproto_getter, &descriptor_table_grpc_2eproto_once, file_level_metadata_grpc_2eproto[0]); } // =================================================================== class EchoResponse::_Internal { public: using HasBits = decltype(std::declval<EchoResponse>()._has_bits_); static void set_has_message(HasBits* has_bits) { (*has_bits)[0] |= 1u; } }; EchoResponse::EchoResponse(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned) : ::PROTOBUF_NAMESPACE_ID::Message(arena, is_message_owned) { SharedCtor(); if (!is_message_owned) { RegisterArenaDtor(arena); } // @@protoc_insertion_point(arena_constructor:EchoResponse) } EchoResponse::EchoResponse(const EchoResponse& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); message_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_message()) { message_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_message(), GetArenaForAllocation()); } // @@protoc_insertion_point(copy_constructor:EchoResponse) } inline void EchoResponse::SharedCtor() { message_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } EchoResponse::~EchoResponse() { // @@protoc_insertion_point(destructor:EchoResponse) if (GetArenaForAllocation() != nullptr) return; SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } inline void EchoResponse::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); message_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void EchoResponse::ArenaDtor(void* object) { EchoResponse* _this = reinterpret_cast< EchoResponse* >(object); (void)_this; } void EchoResponse::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void EchoResponse::SetCachedSize(int size) const { _cached_size_.Set(size); } void EchoResponse::Clear() { // @@protoc_insertion_point(message_clear_start:EchoResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { message_.ClearNonDefaultToEmpty(); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* EchoResponse::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional string message = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_message(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); #ifndef NDEBUG ::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "EchoResponse.message"); #endif // !NDEBUG CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* EchoResponse::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:EchoResponse) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string message = 1; if (cached_has_bits & 0x00000001u) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::VerifyUTF8StringNamedField( this->_internal_message().data(), static_cast<int>(this->_internal_message().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SERIALIZE, "EchoResponse.message"); target = stream->WriteStringMaybeAliased( 1, this->_internal_message(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:EchoResponse) return target; } size_t EchoResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:EchoResponse) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional string message = 1; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_message()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } const ::PROTOBUF_NAMESPACE_ID::Message::ClassData EchoResponse::_class_data_ = { ::PROTOBUF_NAMESPACE_ID::Message::CopyWithSizeCheck, EchoResponse::MergeImpl }; const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*EchoResponse::GetClassData() const { return &_class_data_; } void EchoResponse::MergeImpl(::PROTOBUF_NAMESPACE_ID::Message*to, const ::PROTOBUF_NAMESPACE_ID::Message&from) { static_cast<EchoResponse *>(to)->MergeFrom( static_cast<const EchoResponse &>(from)); } void EchoResponse::MergeFrom(const EchoResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:EchoResponse) GOOGLE_DCHECK_NE(&from, this); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from._internal_has_message()) { _internal_set_message(from._internal_message()); } _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); } void EchoResponse::CopyFrom(const EchoResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:EchoResponse) if (&from == this) return; Clear(); MergeFrom(from); } bool EchoResponse::IsInitialized() const { return true; } void EchoResponse::InternalSwap(EchoResponse* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::InternalSwap( &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), &message_, GetArenaForAllocation(), &other->message_, other->GetArenaForAllocation() ); } ::PROTOBUF_NAMESPACE_ID::Metadata EchoResponse::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_grpc_2eproto_getter, &descriptor_table_grpc_2eproto_once, file_level_metadata_grpc_2eproto[1]); } // @@protoc_insertion_point(namespace_scope) PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::EchoRequest* Arena::CreateMaybeMessage< ::EchoRequest >(Arena* arena) { return Arena::CreateMessageInternal< ::EchoRequest >(arena); } template<> PROTOBUF_NOINLINE ::EchoResponse* Arena::CreateMaybeMessage< ::EchoResponse >(Arena* arena) { return Arena::CreateMessageInternal< ::EchoResponse >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
38.374161
162
0.738883
SoftlySpoken
0700bb15828544b0a9ec4b43b7fd8d5b47ca6769
4,061
cc
C++
mojo/public/cpp/bindings/tests/array_unittest.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
mojo/public/cpp/bindings/tests/array_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
mojo/public/cpp/bindings/tests/array_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/bindings/array.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/tests/array_common_test.h" #include "mojo/public/cpp/bindings/tests/container_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace mojo { namespace test { namespace { using ArrayTest = testing::Test; ARRAY_COMMON_TEST(Array, NullAndEmpty) ARRAY_COMMON_TEST(Array, Basic) ARRAY_COMMON_TEST(Array, Bool) ARRAY_COMMON_TEST(Array, Handle) ARRAY_COMMON_TEST(Array, HandlesAreClosed) ARRAY_COMMON_TEST(Array, Clone) ARRAY_COMMON_TEST(Array, Serialization_ArrayOfPOD) ARRAY_COMMON_TEST(Array, Serialization_EmptyArrayOfPOD) ARRAY_COMMON_TEST(Array, Serialization_ArrayOfArrayOfPOD) ARRAY_COMMON_TEST(Array, Serialization_ArrayOfBool) ARRAY_COMMON_TEST(Array, Serialization_ArrayOfString) ARRAY_COMMON_TEST(Array, Resize_Copyable) ARRAY_COMMON_TEST(Array, Resize_MoveOnly) TEST_F(ArrayTest, PushBack_Copyable) { ASSERT_EQ(0u, CopyableType::num_instances()); Array<CopyableType> array(2); array = nullptr; std::vector<CopyableType*> value_ptrs; size_t capacity = array.storage().capacity(); for (size_t i = 0; i < capacity; i++) { CopyableType value; value_ptrs.push_back(value.ptr()); array.push_back(value); ASSERT_EQ(i + 1, array.size()); ASSERT_EQ(i + 1, value_ptrs.size()); EXPECT_EQ(array.size() + 1, CopyableType::num_instances()); EXPECT_TRUE(array[i].copied()); EXPECT_EQ(value_ptrs[i], array[i].ptr()); array[i].ResetCopied(); EXPECT_TRUE(array); } { CopyableType value; value_ptrs.push_back(value.ptr()); array.push_back(value); EXPECT_EQ(array.size() + 1, CopyableType::num_instances()); } ASSERT_EQ(capacity + 1, array.size()); EXPECT_EQ(array.size(), CopyableType::num_instances()); for (size_t i = 0; i < array.size(); i++) { EXPECT_TRUE(array[i].copied()); EXPECT_EQ(value_ptrs[i], array[i].ptr()); } array = nullptr; EXPECT_EQ(0u, CopyableType::num_instances()); } TEST_F(ArrayTest, PushBack_MoveOnly) { ASSERT_EQ(0u, MoveOnlyType::num_instances()); Array<MoveOnlyType> array(2); array = nullptr; std::vector<MoveOnlyType*> value_ptrs; size_t capacity = array.storage().capacity(); for (size_t i = 0; i < capacity; i++) { MoveOnlyType value; value_ptrs.push_back(value.ptr()); array.push_back(std::move(value)); ASSERT_EQ(i + 1, array.size()); ASSERT_EQ(i + 1, value_ptrs.size()); EXPECT_EQ(array.size() + 1, MoveOnlyType::num_instances()); EXPECT_TRUE(array[i].moved()); EXPECT_EQ(value_ptrs[i], array[i].ptr()); array[i].ResetMoved(); EXPECT_TRUE(array); } { MoveOnlyType value; value_ptrs.push_back(value.ptr()); array.push_back(std::move(value)); EXPECT_EQ(array.size() + 1, MoveOnlyType::num_instances()); } ASSERT_EQ(capacity + 1, array.size()); EXPECT_EQ(array.size(), MoveOnlyType::num_instances()); for (size_t i = 0; i < array.size(); i++) { EXPECT_TRUE(array[i].moved()); EXPECT_EQ(value_ptrs[i], array[i].ptr()); } array = nullptr; EXPECT_EQ(0u, MoveOnlyType::num_instances()); } TEST_F(ArrayTest, MoveFromAndToSTLVector_Copyable) { std::vector<CopyableType> vec1(1); Array<CopyableType> arr(std::move(vec1)); ASSERT_EQ(1u, arr.size()); ASSERT_FALSE(arr[0].copied()); std::vector<CopyableType> vec2(arr.PassStorage()); ASSERT_EQ(1u, vec2.size()); ASSERT_FALSE(vec2[0].copied()); ASSERT_EQ(0u, arr.size()); ASSERT_TRUE(arr.is_null()); } TEST_F(ArrayTest, MoveFromAndToSTLVector_MoveOnly) { std::vector<MoveOnlyType> vec1(1); Array<MoveOnlyType> arr(std::move(vec1)); ASSERT_EQ(1u, arr.size()); std::vector<MoveOnlyType> vec2(arr.PassStorage()); ASSERT_EQ(1u, vec2.size()); ASSERT_EQ(0u, arr.size()); ASSERT_TRUE(arr.is_null()); } } // namespace } // namespace test } // namespace mojo
30.765152
73
0.709677
xzhan96
07016fe79275e12cad833d95c6c5912e76247d7f
5,105
cpp
C++
sandbox/SeqIg_sandbox/apps/SeqIg/SeqIg.cpp
jwillis0720/seqan
36b300b8c4c42bbfc03edd3220fa299961d517be
[ "BSD-3-Clause" ]
1
2015-01-15T16:04:56.000Z
2015-01-15T16:04:56.000Z
sandbox/SeqIg_sandbox/apps/SeqIg/SeqIg.cpp
jwillis0720/seqan
36b300b8c4c42bbfc03edd3220fa299961d517be
[ "BSD-3-Clause" ]
null
null
null
sandbox/SeqIg_sandbox/apps/SeqIg/SeqIg.cpp
jwillis0720/seqan
36b300b8c4c42bbfc03edd3220fa299961d517be
[ "BSD-3-Clause" ]
null
null
null
// ========================================================================== // SeqIg // ========================================================================== // Copyright (c) 2006-2013, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Your Name <your.email@example.net> // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/arg_parse.h> #include "DatabaseIO.h" #include "SeqIg.h" #include "StructDefs.h" void setUpArgumentParser(seqan::ArgumentParser & parser) { setAppName(parser, "SeqIg"); setShortDescription(parser, "SeqIg - Immunoglobulin Germline Gene Assignment"); setCategory(parser, "Database Locations"); setDate(parser, "December 2014"); //Database Options addOption(parser, seqan::ArgParseOption("d","database_path", "The database path", seqan::ArgParseArgument::STRING)); addOption(parser, seqan::ArgParseOption("r","receptor", "The receptor type", seqan::ArgParseArgument::STRING)); addOption(parser, seqan::ArgParseOption("c","chain", "The chain type", seqan::ArgParseArgument::STRING)); addOption(parser, seqan::ArgParseOption("s","species", "The species type", seqan::ArgParseArgument::STRING)); //Set Database Default Values setDefaultValue(parser, "database_path","/Users/jordanwillis/Git_repos/pyig/data_dir"); setDefaultValue(parser, "receptor","Ig"); setDefaultValue(parser, "chain","heavy"); setDefaultValue(parser, "species","human"); } seqan::ArgumentParser::ParseResult extractOptions(seqan::ArgumentParser const & parser, SeqIgOptions & options) { bool stop = false; //getOptionvalue sets structure in place getOptionValue(options.database_path, parser, "database_path"); getOptionValue(options.receptor,parser, "receptor"); getOptionValue(options.chain, parser, "chain"); getOptionValue(options.species, parser, "species"); return (stop) ? seqan::ArgumentParser::PARSE_ERROR : seqan::ArgumentParser::PARSE_OK; } void setDatabaseFastas(SeqIgOptions const &options, DatabasePaths &dbpaths){ std::string top_leve_dir = options.database_path + "/" + options.receptor + "/" +options.chain + "/" + options.species + "/" + options.species; dbpaths.Vgene_db = top_leve_dir + "_gl_V.fasta"; dbpaths.Dgene_db = top_leve_dir + "_gl_D.fasta"; dbpaths.Jgene_db = top_leve_dir + "_gl_J.fasta"; }; int main(int argc, char const ** argv) { // Parse the command line. seqan::ArgumentParser parser; //structs SeqIgOptions options; DatabasePaths dbpaths; setUpArgumentParser(parser); seqan::ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; res = extractOptions(parser, options); if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; setDatabaseFastas(options, dbpaths); bool rtd = parseDatabase(dbpaths); if(!rtd){ std::cerr << "Fatal Error: Problem with database " << options.database_path << "\n"; return 1; } return 0; }
44.391304
148
0.638002
jwillis0720
0701c19396d73fb85d535bbc66f42e8da46a8c49
2,033
cpp
C++
Source/Qurses/Windows/WinQCgetsc.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/Qurses/Windows/WinQCgetsc.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/Qurses/Windows/WinQCgetsc.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
// Public Domain Curses #include "Qurses/Windows/pdcwin.h" #include "WinQL/Application/Console/WinQLConsoleScreenBuffer.h" #include "WinQL/Application/WinQLApplication.h" RCSID("$Id: pdcgetsc.c,v 1.36 2008/07/14 04:24:52 wmcbrine Exp $") //------------------------------------------------------------------------------ // get the cursor size/shape int PDC_get_cursor_mode( void ) { __QCS_FCONTEXT( "PDC_get_cursor_mode" ); nsWin32::ConsoleCursorInfo cci; if( !nsWin32::CConsole::TheWin32Console()->ScreenBuffer()->GetCursorInfo( cci ) ) { return ERR; } return cci.dwSize; } //------------------------------------------------------------------------------ // return number of screen rows int PDC_get_rows( void ) { __QCS_FCONTEXT( "PDC_get_rows" ); nsWin32::ConsoleScreenBufferInfoEx scr; memset( &scr, 0, sizeof( nsWin32::ConsoleScreenBufferInfoEx ) ); scr.cbSize = sizeof( nsWin32::ConsoleScreenBufferInfoEx ); nsWin32::CConsole::TheWin32Console()->ScreenBuffer()->GetInfoEx( scr ); return scr.srWindow.Bottom - scr.srWindow.Top + 1; } //------------------------------------------------------------------------------ // return number of buffer rows int PDC_get_buffer_rows( void ) { __QCS_FCONTEXT( "PDC_get_buffer_rows" ); nsWin32::ConsoleScreenBufferInfoEx scr; memset( &scr, 0, sizeof( nsWin32::ConsoleScreenBufferInfoEx ) ); scr.cbSize = sizeof( nsWin32::ConsoleScreenBufferInfoEx ); nsWin32::CConsole::TheWin32Console()->ScreenBuffer()->GetInfoEx( scr ); return scr.dwSize.Y; } //------------------------------------------------------------------------------ // return width of screen/viewport int PDC_get_columns( void ) { __QCS_FCONTEXT( "PDC_get_colomns" ); nsWin32::ConsoleScreenBufferInfoEx scr; memset( &scr, 0, sizeof( nsWin32::ConsoleScreenBufferInfoEx ) ); scr.cbSize = sizeof( nsWin32::ConsoleScreenBufferInfoEx ); nsWin32::CConsole::TheWin32Console()->ScreenBuffer()->GetInfoEx( scr ); return scr.srWindow.Right - scr.srWindow.Left + 1; }
31.765625
85
0.614855
mfaithfull
07042b5ff176afe9602386c4bb725084db362100
1,720
cpp
C++
ewk/unittest/utc_blink_ewk_custom_handlers_data_url_get_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
9
2015-04-09T20:22:08.000Z
2021-03-17T08:34:56.000Z
ewk/unittest/utc_blink_ewk_custom_handlers_data_url_get_func.cpp
Jabawack/chromium-efl
6d3a3accc8afba0aa0eff6461eb5c83138172e6e
[ "BSD-3-Clause" ]
2
2015-02-04T13:41:12.000Z
2015-05-25T14:00:40.000Z
ewk/unittest/utc_blink_ewk_custom_handlers_data_url_get_func.cpp
isabella232/chromium-efl
db2d09aba6498fb09bbea1f8440d071c4b0fde78
[ "BSD-3-Clause" ]
14
2015-02-12T16:20:47.000Z
2022-01-20T10:36:26.000Z
// Copyright 2014 Samsung Electronics. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "utc_blink_ewk_base.h" class utc_blink_ewk_custom_handlers_data_url_get: public utc_blink_ewk_base { protected: void PostSetUp() { evas_object_smart_callback_add(GetEwkWebView(),"protocolhandler,registration,requested", (void(*)(void*, Evas_Object*, void*))custom_handler, this); } void PreTearDown() { evas_object_smart_callback_del(GetEwkWebView(),"protocolhandler,registration,requested", (void(*)(void*, Evas_Object*, void*))custom_handler); } void LoadFinished(Evas_Object* webview) { utc_message("[loadFinished] :: "); EventLoopStop(Failure); } static void custom_handler(utc_blink_ewk_custom_handlers_data_url_get* owner, Evas_Object* /*webview*/, Ewk_Custom_Handlers_Data* custom_handler_data) { utc_message("[custom handler] :: \n"); ASSERT_TRUE(NULL != owner); ASSERT_TRUE(NULL != custom_handler_data); ASSERT_STREQ("http://codebits.glennjones.net/registerprotocol/register.html?%s", ewk_custom_handlers_data_url_get(custom_handler_data)); owner->EventLoopStop(Success); } }; /** * @brief Checking if base_url is returned properly. */ TEST_F(utc_blink_ewk_custom_handlers_data_url_get, POS_TEST) { ASSERT_EQ(EINA_TRUE, ewk_view_url_set(GetEwkWebView(), "http://codebits.glennjones.net/registerprotocol/register.html")); ASSERT_EQ(Success, EventLoopStart()); } /** * @brief Checking if NULL is returned when custom_handler_data is NULL. */ TEST_F(utc_blink_ewk_custom_handlers_data_url_get, NEG_TEST) { ASSERT_EQ(NULL, ewk_custom_handlers_data_url_get(NULL)); }
33.076923
152
0.764535
Jabawack
07043bd8b9db17683fd695131cccbf06e343a650
41,075
cpp
C++
src/gfx/conetracing_utils.cpp
scanberg/viamd
2e5330fad35f7c2116e15b4a538d5c4a5a18ca59
[ "MIT" ]
11
2018-06-04T14:51:32.000Z
2021-12-21T13:35:08.000Z
src/gfx/conetracing_utils.cpp
scanberg/viamd
2e5330fad35f7c2116e15b4a538d5c4a5a18ca59
[ "MIT" ]
19
2019-03-03T14:42:03.000Z
2022-03-01T19:09:49.000Z
src/gfx/conetracing_utils.cpp
scanberg/viamd
2e5330fad35f7c2116e15b4a538d5c4a5a18ca59
[ "MIT" ]
1
2020-06-08T15:56:57.000Z
2020-06-08T15:56:57.000Z
#include "conetracing_utils.h" #include <core/md_allocator.h> #include <core/md_log.h> #include <core/md_vec_math.h> #include <core/md_sync.h> #include "gfx/gl_utils.h" #include "gfx/immediate_draw_utils.h" #include "color_utils.h" #include "task_system.h" #include <atomic> namespace cone_trace { static GLuint vao = 0; static GLuint vbo = 0; static const char* v_shader_fs_quad_src = R"( #version 150 core out vec2 uv; void main() { uint idx = uint(gl_VertexID) % 3U; gl_Position = vec4_t( (float( idx &1U)) * 4.0 - 1.0, (float((idx>>1U)&1U)) * 4.0 - 1.0, 0, 1.0); uv = gl_Position.xy * 0.5 + 0.5; } )"; namespace voxelize { static struct { GLuint program = 0; GLuint vao = 0; struct { GLint volume_dim = -1; GLint volume_min = -1; GLint voxel_ext = -1; GLint tex_volume = -1; } uniform_location; } gl; static const char* v_shader_src = R"( #version 430 core uniform ivec3_t u_volume_dim; uniform vec3_t u_volume_min; uniform vec3_t u_voxel_ext; layout(binding=0, rgba8) uniform image3D u_tex_volume; in vec4_t sphere; in vec4_t color; ivec3_t compute_voxel_coord(vec3_t coord) { return clamp(ivec3_t((coord - u_volume_min) / u_voxel_ext), ivec3_t(0), u_volume_dim - 1); } void main() { if (color.a == 0.0) discard; ivec3_t coord = ivec3_t((sphere.xyz - u_volume_min) / u_voxel_ext); vec3_t pos = sphere.xyz; float r2 = sphere.w * sphere.w; ivec3_t min_cc = compute_voxel_coord(sphere.xyz - vec3_t(sphere.w)); ivec3_t max_cc = compute_voxel_coord(sphere.xyz + vec3_t(sphere.w)); ivec3_t cc; for (cc.z = min_cc.z; cc.z <= max_cc.z; cc.z++) { for (cc.y = min_cc.y; cc.y <= max_cc.y; cc.y++) { for (cc.x = min_cc.x; cc.x <= max_cc.x; cc.x++) { vec3_t min_voxel = u_volume_min + vec3_t(cc) * u_voxel_ext; vec3_t max_voxel = min_voxel + u_voxel_ext; vec3_t clamped_pos = clamp(pos, min_voxel, max_voxel); vec3_t d = clamped_pos - pos; if (dot(d, d) < r2) { imageStore(u_tex_volume, cc, color); } } } } } )"; static void initialize(int version_major, int version_minor) { if (!gl.program) { if (version_major >= 4 && version_minor >= 3) { constexpr int BUFFER_SIZE = 1024; char buffer[BUFFER_SIZE]; GLuint v_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(v_shader, 1, &v_shader_src, 0); glCompileShader(v_shader); if (gl::get_shader_compile_error(buffer, BUFFER_SIZE, v_shader)) { md_printf(MD_LOG_TYPE_ERROR, "Compiling sphere binning vertex shader:\n%s\n", buffer); } gl.program = glCreateProgram(); glAttachShader(gl.program, v_shader); glLinkProgram(gl.program); if (gl::get_program_link_error(buffer, BUFFER_SIZE, gl.program)) { md_printf(MD_LOG_TYPE_ERROR, "Linking sphere binning program:\n%s\n", buffer); } glDetachShader(gl.program, v_shader); glDeleteShader(v_shader); gl.uniform_location.volume_dim = glGetUniformLocation(gl.program, "u_volume_dim"); gl.uniform_location.volume_min = glGetUniformLocation(gl.program, "u_volume_min"); gl.uniform_location.voxel_ext = glGetUniformLocation(gl.program, "u_voxel_ext"); gl.uniform_location.tex_volume = glGetUniformLocation(gl.program, "u_tex_volume"); } else { md_print(MD_LOG_TYPE_INFO, "Sphere binning shader requires OpenGL 4.3"); } } if (!gl.vao) glGenVertexArrays(1, &gl.vao); } static void shutdown() { if (gl.program) { glDeleteProgram(gl.program); gl.program = 0; } if (gl.vao) { glDeleteVertexArrays(1, &gl.vao); gl.vao = 0; } } } // namespace voxelize namespace cone_trace { static struct { GLuint program = 0; struct { GLint depth_tex = -1; GLint normal_tex = -1; GLint color_alpha_tex = -1; GLint f0_smoothness_tex = -1; GLint voxel_tex = -1; GLint voxel_grid_min = -1; GLint voxel_grid_size = -1; GLint voxel_dimensions = -1; GLint voxel_extent = -1; GLint indirect_diffuse_scale = -1; GLint indirect_specular_scale = -1; GLint ambient_occlusion_scale = -1; GLint cone_angle = -1; GLint inv_view_mat = -1; GLint inv_view_proj_mat = -1; GLint world_space_camera = -1; } uniform_location; } gl; // Modified version of // https://github.com/Cigg/Voxel-Cone-Tracing static const char* f_shader_src = R"( #version 330 core in vec2 uv; out vec4_t frag_color; // Textures uniform sampler2D u_depth_texture; uniform sampler2D u_normal_texture; uniform sampler2D u_color_alpha_texture; uniform sampler2D u_f0_smoothness_texture; // Voxel stuff uniform sampler3D u_voxel_texture; uniform vec3_t u_voxel_grid_world_size; uniform vec3_t u_voxel_grid_world_min; uniform ivec3_t u_voxel_dimensions; uniform float u_voxel_extent; // Scaling factors uniform float u_indirect_diffuse_scale = 1.f; uniform float u_indirect_specular_scale = 1.f; uniform float u_ambient_occlusion_scale = 1.f; uniform float u_cone_angle = 0.08; // View parameters uniform mat4_t u_inv_view_mat; uniform mat4_t u_inv_view_proj_mat; uniform vec3_t u_world_space_camera; const float MAX_DIST = 1000.0; const float ALPHA_THRESH = 0.95; // 6 60 degree cone const int NUM_CONES = 6; const vec3_t cone_directions[6] = vec3[] ( vec3_t(0, 1, 0), vec3_t(0, 0.5, 0.866025), vec3_t(0.823639, 0.5, 0.267617), vec3_t(0.509037, 0.5, -0.700629), vec3_t(-0.509037, 0.5, -0.700629), vec3_t(-0.823639, 0.5, 0.267617) ); const float cone_weights[6] = float[](0.25, 0.15, 0.15, 0.15, 0.15, 0.15); // // 5 90 degree cones // const int NUM_CONES = 5; // vec3_t coneDirections[5] = vec3[] // ( vec3_t(0, 1, 0), // vec3_t(0, 0.707, 0.707), // vec3_t(0, 0.707, -0.707), // vec3_t(0.707, 0.707, 0), // vec3_t(-0.707, 0.707, 0) // ); // float coneWeights[5] = float[](0.28, 0.18, 0.18, 0.18, 0.18); vec4_t sample_voxels(vec3_t world_position, float lod) { vec3_t tc = (world_position - u_voxel_grid_world_min) / (u_voxel_grid_world_size); //vec3_t d = tc - vec3_t(0.5); //if (dot(d,d) > 1) return vec4_t(0,0,0,1); //tc = tc + vec3_t(0.5) / vec3_t(u_voxel_dimensions); return textureLod(u_voxel_texture, tc, lod); } // Third argument to say how long between steps? vec4_t cone_trace(vec3_t world_position, vec3_t world_normal, vec3_t direction, float tan_half_angle, out float occlusion) { // lod level 0 mipmap is full size, level 1 is half that size and so on float lod = 0.0; vec4_t rgba = vec4_t(0); occlusion = 0.0; float dist = u_voxel_extent; // Start one voxel away to avoid self occlusion vec3_t start_pos = world_position + world_normal * u_voxel_extent; // Plus move away slightly in the normal direction to avoid // self occlusion in flat surfaces while(dist < MAX_DIST && rgba.a < ALPHA_THRESH) { // smallest sample diameter possible is the voxel size float diameter = max(u_voxel_extent, 2.0 * tan_half_angle * dist); float lod_level = log2(diameter / u_voxel_extent); vec4_t voxel_color = sample_voxels(start_pos + dist * direction, lod_level); //if (voxel_color.a < 0) break; // front-to-back compositing float a = (1.0 - rgba.a); rgba += a * voxel_color; occlusion += (a * voxel_color.a) / (1.0 + 0.03 * diameter); //dist += diameter * 0.5; // smoother dist += diameter; // faster but misses more voxels } return rgba; } vec4_t indirect_light(in vec3_t world_position, in vec3_t world_normal, in mat3 tangent_to_world, out float occlusion_out) { vec4_t color = vec4_t(0); occlusion_out = 0.0; for(int i = 0; i < NUM_CONES; i++) { float occlusion = 0.0; // 60 degree cones -> tan(30) = 0.577 // 90 degree cones -> tan(45) = 1.0 color += cone_weights[i] * cone_trace(world_position, world_normal, tangent_to_world * cone_directions[i], 0.577, occlusion); occlusion_out += cone_weights[i] * occlusion; } occlusion_out = 1.0 - occlusion_out; return color; } mat3 compute_ON_basis(in vec3_t v1) { vec3_t v0; vec3_t v2; float d0 = dot(vec3_t(1,0,0), v1); float d1 = dot(vec3_t(0,0,1), v1); if (d0 < d1) { v0 = normalize(vec3_t(1,0,0) - v1 * d0); } else { v0 = normalize(vec3_t(0,0,1) - v1 * d1); } v2 = cross(v0, v1); return mat3(v0, v1, v2); } vec4_t depth_to_world_coord(vec2 tex_coord, float depth) { vec4_t clip_coord = vec4_t(vec3_t(tex_coord, depth) * 2.0 - 1.0, 1.0); vec4_t world_coord = u_inv_view_proj_mat * clip_coord; return world_coord / world_coord.w; } // https://aras-p.info/texts/CompactNormalStorage.html vec3_t decode_normal(vec2 enc) { vec2 fenc = enc*4-2; float f = dot(fenc,fenc); float g = sqrt(1-f/4.0); vec3_t n; n.xy = fenc*g; n.z = 1-f/2.0; return n; } vec3_t fresnel(vec3_t f0, float H_dot_V) { //const float n1 = 1.0; //const float n2 = 1.5; //const float R0 = pow((n1-n2)/(n1+n2), 2); return f0 + (1.0 - f0) * pow(1.0 - H_dot_V, 5.0); } vec3_t shade(vec3_t albedo, float alpha, vec3_t f0, float smoothness, vec3_t P, vec3_t V, vec3_t N) { const float PI_QUARTER = 3.14159265 * 0.25; const vec3_t env_radiance = vec3_t(0.5); const vec3_t dir_radiance = vec3_t(0.5); const vec3_t L = normalize(vec3_t(1)); const float spec_exp = 10.0; mat3 tangent_to_world = compute_ON_basis(N); float N_dot_V = max(0.0, -dot(N, V)); vec3_t R = -V + 2.0 * dot(N, V) * N; vec3_t H = normalize(L + V); float H_dot_V = max(0.0, dot(H, V)); float N_dot_H = max(0.0, dot(N, H)); float N_dot_L = max(0.0, dot(N, L)); vec3_t fresnel_direct = fresnel(f0, H_dot_V); vec3_t fresnel_indirect = fresnel(f0, N_dot_V); float tan_half_angle = tan(mix(PI_QUARTER, 0.0, smoothness)); float diffuse_occlusion; vec3_t direct_diffuse = env_radiance + N_dot_L * dir_radiance; vec3_t indirect_diffuse = indirect_light(P, N, tangent_to_world, diffuse_occlusion).rgb; float transmissive_occlusion; vec3_t transmissive = vec3_t(0); //alpha = 0.1; //if (alpha < 1.0) { // transmissive = cone_trace(P, N, -V, tan_half_angle, transmissive_occlusion).rgb; // transmissive *= 1.0 - alpha * albedo; // direct_diffuse *= alpha; // indirect_diffuse *= alpha; //} float specular_occlusion; vec3_t direct_specular = dir_radiance * pow(N_dot_H, spec_exp); vec3_t indirect_specular = cone_trace(P, N, R, tan_half_angle, specular_occlusion).rgb; vec3_t result = vec3_t(0); result += albedo * (direct_diffuse + u_indirect_diffuse_scale * indirect_diffuse) * pow(diffuse_occlusion, u_ambient_occlusion_scale * 0.5); result += direct_specular * fresnel_direct + u_indirect_specular_scale * indirect_specular * fresnel_indirect; result += transmissive; return result; } void main() { float depth = texture(u_depth_texture, uv).r; if (depth == 1.0) discard; vec2 encoded_normal = texture(u_normal_texture, uv).rg; vec4_t albedo_alpha = texture(u_color_alpha_texture, uv); vec4_t f0_smoothness = texture(u_f0_smoothness_texture, uv); vec3_t albedo = albedo_alpha.rgb; float alpha = albedo_alpha.a; vec3_t f0 = f0_smoothness.rgb; float smoothness = f0_smoothness.a; vec3_t world_position = depth_to_world_coord(uv, depth).xyz; vec3_t world_normal = mat3(u_inv_view_mat) * decode_normal(encoded_normal); vec3_t world_eye = u_world_space_camera; vec3_t P = world_position; vec3_t V = normalize(world_eye - world_position); vec3_t N = world_normal; frag_color = vec4_t(shade(albedo, alpha, f0, smoothness, P, V, N), 1); } )"; static void initialize() { constexpr int BUFFER_SIZE = 1024; char buffer[BUFFER_SIZE]; GLuint v_shader = glCreateShader(GL_VERTEX_SHADER); GLuint f_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(v_shader, 1, &v_shader_fs_quad_src, 0); glShaderSource(f_shader, 1, &f_shader_src, 0); glCompileShader(v_shader); if (gl::get_shader_compile_error(buffer, BUFFER_SIZE, v_shader)) { md_printf(MD_LOG_TYPE_ERROR,"Compiling cone_tracing vertex shader:\n%s\n", buffer); } glCompileShader(f_shader); if (gl::get_shader_compile_error(buffer, BUFFER_SIZE, f_shader)) { md_printf(MD_LOG_TYPE_ERROR,"Compiling cone_tracing fragment shader:\n%s\n", buffer); } gl.program = glCreateProgram(); glAttachShader(gl.program, v_shader); glAttachShader(gl.program, f_shader); glLinkProgram(gl.program); if (gl::get_program_link_error(buffer, BUFFER_SIZE, gl.program)) { md_printf(MD_LOG_TYPE_ERROR,"Linking cone_tracing program:\n%s\n", buffer); } glDetachShader(gl.program, v_shader); glDetachShader(gl.program, f_shader); glDeleteShader(v_shader); glDeleteShader(f_shader); gl.uniform_location.depth_tex = glGetUniformLocation(gl.program, "u_depth_texture"); gl.uniform_location.normal_tex = glGetUniformLocation(gl.program, "u_normal_texture"); gl.uniform_location.color_alpha_tex = glGetUniformLocation(gl.program, "u_color_alpha_texture"); gl.uniform_location.f0_smoothness_tex = glGetUniformLocation(gl.program, "u_f0_smoothness_texture"); gl.uniform_location.voxel_tex = glGetUniformLocation(gl.program, "u_voxel_texture"); gl.uniform_location.voxel_grid_min = glGetUniformLocation(gl.program, "u_voxel_grid_world_min"); gl.uniform_location.voxel_grid_size = glGetUniformLocation(gl.program, "u_voxel_grid_world_size"); gl.uniform_location.voxel_dimensions = glGetUniformLocation(gl.program, "u_voxel_dimensions"); gl.uniform_location.voxel_extent = glGetUniformLocation(gl.program, "u_voxel_extent"); gl.uniform_location.indirect_diffuse_scale = glGetUniformLocation(gl.program, "u_indirect_diffuse_scale"); gl.uniform_location.indirect_specular_scale = glGetUniformLocation(gl.program, "u_indirect_specular_scale"); gl.uniform_location.ambient_occlusion_scale = glGetUniformLocation(gl.program, "u_ambient_occlusion_scale"); gl.uniform_location.cone_angle = glGetUniformLocation(gl.program, "u_cone_angle"); gl.uniform_location.inv_view_mat = glGetUniformLocation(gl.program, "u_inv_view_mat"); gl.uniform_location.inv_view_proj_mat = glGetUniformLocation(gl.program, "u_inv_view_proj_mat"); gl.uniform_location.world_space_camera = glGetUniformLocation(gl.program, "u_world_space_camera"); } static void shutdown() { if (gl.program) { glDeleteProgram(gl.program); gl.program = 0; } } } // namespace cone_trace namespace directional_occlusion { static GLuint program = 0; void initialize() { if (!program) { program = glCreateProgram(); } GLuint v_shader = gl::compile_shader_from_source(v_shader_fs_quad_src, GL_VERTEX_SHADER); GLuint f_shader = gl::compile_shader_from_file(VIAMD_SHADER_DIR "/cone_tracing/directional_occlusion.frag", GL_FRAGMENT_SHADER); const GLuint shaders[] = {v_shader, f_shader}; gl::attach_link_detach(program, shaders, ARRAY_SIZE(shaders)); } void shutdown() { if (program) glDeleteProgram(program); } } // namespace directional_occlusion void initialize(int version_major, int version_minor) { if (!vao) glGenVertexArrays(1, &vao); if (!vbo) glGenBuffers(1, &vbo); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, 12, nullptr, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0); glBindVertexArray(0); cone_trace::initialize(); voxelize::initialize(version_major, version_minor); directional_occlusion::initialize(); } void shutdown() { cone_trace::shutdown(); voxelize::shutdown(); directional_occlusion::shutdown(); } void init_rgba_volume(GPUVolume* vol, int res_x, int res_y, int res_z, vec3_t min_box, vec3_t max_box) { ASSERT(vol); if (!vol->texture_id) glGenTextures(1, &vol->texture_id); vol->min_box = min_box; vol->max_box = max_box; vol->voxel_ext = (max_box - min_box) / vec3_t{(float)res_x, (float)res_y, (float)res_z}; if (res_x != vol->res_x || res_y != vol->res_y || res_z != vol->res_z) { vol->res_x = res_x; vol->res_y = res_y; vol->res_z = res_z; glBindTexture(GL_TEXTURE_3D, vol->texture_id); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); // glTexStorage3D(GL_TEXTURE_3D, 4, GL_RGBA8, res.x, res.y, res.z); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, res_x, res_y, res_z, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindTexture(GL_TEXTURE_3D, 0); } } uint32_t floor_power_of_two(uint32_t v) { uint32_t r = 0; while (v >>= 1) { r++; } return 1 << r; } uint32_t ceil_power_of_two(uint32_t x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } void init_occlusion_volume(GPUVolume* vol, vec3_t min_box, vec3_t max_box, float voxel_ext_target) { ASSERT(vol); if (min_box == max_box) { return; } const float voxel_ext = voxel_ext_target; const vec3_t ext = (max_box - min_box); const float max_ext = MAX(ext.x, MAX(ext.y, ext.z)); int32_t dim = (int32_t)CLAMP(ceil_power_of_two((uint32_t)(max_ext / voxel_ext_target)), 1, 256); int res[3] = {dim, dim, dim}; for (int i = 0; i < 3; i++) { float half_ext = max_ext * 0.5f; while (ext[i] < half_ext && dim > 1) { res[i] /= 2; half_ext *= 0.5f; } } const vec3_t center = (min_box + max_box) * 0.5f; const vec3_t half_ext = vec3_t{(float)res[0], (float)res[1], (float)res[2]} * voxel_ext * 0.5f; min_box = center - half_ext; max_box = center + half_ext; vol->min_box = min_box; vol->max_box = max_box; vol->voxel_ext = vec3_t{voxel_ext, voxel_ext, voxel_ext}; if (res[0] != vol->res_x || res[1] != vol->res_y || res[2] != vol->res_z) { // @NOTE: Compute log2 (integer version) to find the amount of mipmaps required int mips = 1; { int max_dim = MAX(res[0], MAX(res[1], res[2])); while (max_dim >>= 1) ++mips; } if (vol->texture_id) glDeleteTextures(1, &vol->texture_id); glGenTextures(1, &vol->texture_id); glBindTexture(GL_TEXTURE_3D, vol->texture_id); glTexStorage3D(GL_TEXTURE_3D, mips, GL_R8, res[0], res[1], res[2]); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, mips - 1); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); glBindTexture(GL_TEXTURE_3D, 0); vol->res_x = res[0]; vol->res_y = res[1]; vol->res_z = res[2]; } } void free_volume(GPUVolume* vol) { if (vol->texture_id) { glDeleteTextures(1, &vol->texture_id); vol->texture_id = 0; } } struct ivec3_t { int x, y, z; }; inline ivec3_t compute_voxel_coord(const GPUVolume& data, const vec3_t& coord) { ivec3_t c; c.x = CLAMP((int)((coord.x - data.min_box.x) / data.voxel_ext.x), 0, data.res_x - 1); c.y = CLAMP((int)((coord.y - data.min_box.y) / data.voxel_ext.y), 0, data.res_y - 1); c.z = CLAMP((int)((coord.z - data.min_box.z) / data.voxel_ext.z), 0, data.res_z - 1); return c; } inline int compute_voxel_idx(const ivec3_t& res, const ivec3_t& coord) { return coord.z * res.x * res.y + coord.y * res.x + coord.x; } inline int compute_voxel_idx(const GPUVolume& data, const vec3_t& coord) { return compute_voxel_idx({data.res_x, data.res_y, data.res_z}, compute_voxel_coord(data, coord)); } inline uint32_t accumulate_voxel_color(uint32_t current_color, uint32_t new_color, float counter) { vec4_t c = convert_color(current_color); vec4_t n = convert_color(new_color); c = (counter * c + n) / (counter + 1.f); return convert_color(c); } void voxelize_spheres_cpu(const GPUVolume& vol, const float* x, const float* y, const float* z, const float* r, const uint32_t* colors, int64_t count) { const int32_t voxel_count = vol.res_x * vol.res_y * vol.res_z; if (voxel_count == 0) { md_print(MD_LOG_TYPE_ERROR, "Volume resolution is zero on one or more axes."); return; } uint32_t* voxel_data = (uint32_t*)md_alloc(default_allocator, voxel_count * sizeof(uint32_t)); float* voxel_counter = (float*)md_alloc(default_allocator, voxel_count * sizeof(float)); defer { md_free(default_allocator, voxel_counter, voxel_count * sizeof(float)); md_free(default_allocator, voxel_data, voxel_count * sizeof(uint32_t)); }; ivec3_t vol_res = {vol.res_x, vol.res_y, vol.res_z}; for (int64_t i = 0; i < count; i++) { vec3_t pos = {x[i], y[i], z[i]}; float radius = r[i]; uint32_t color = colors[i]; const float r2 = radius * radius; ivec3_t min_cc = compute_voxel_coord(vol, pos - radius); ivec3_t max_cc = compute_voxel_coord(vol, pos + radius); ivec3_t cc; for (cc.z = min_cc.z; cc.z <= max_cc.z; cc.z++) { for (cc.y = min_cc.y; cc.y <= max_cc.y; cc.y++) { for (cc.x = min_cc.x; cc.x <= max_cc.x; cc.x++) { vec3_t min_voxel = vol.min_box + vec3_t{(float)cc.x, (float)cc.y, (float)cc.z} * vol.voxel_ext; vec3_t max_voxel = min_voxel + vol.voxel_ext; vec3_t clamped_pos = vec3_clamp(pos, min_voxel, max_voxel); vec3_t d = clamped_pos - pos; if (vec3_dot(d, d) < r2) { int voxel_idx = compute_voxel_idx(vol_res, cc); voxel_data[voxel_idx] = accumulate_voxel_color(voxel_data[voxel_idx], color, voxel_counter[voxel_idx] + 1); voxel_counter[voxel_idx] += 1; } } } } } // Apply crude lambert illumination model for (int32_t i = 0; i < voxel_count; ++i) { vec4_t c = convert_color(voxel_data[i]); voxel_data[i] = convert_color(vec4_from_vec3(vec3_from_vec4(c) / 3.1415926535f, c.w)); } glBindTexture(GL_TEXTURE_3D, vol.texture_id); glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, 0, vol.res_x, vol.res_y, vol.res_z, GL_RGBA, GL_UNSIGNED_BYTE, voxel_data); glGenerateMipmap(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, 0); } void voxelize_spheres_gpu(const GPUVolume& vol, GLuint position_radius_buffer, GLuint color_buffer, int32_t num_spheres) { if (!voxelize::gl.program) { md_print(MD_LOG_TYPE_ERROR, "sphere_binning program is not compiled"); return; } glClearTexImage(vol.texture_id, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glBindVertexArray(voxelize::gl.vao); glBindBuffer(GL_ARRAY_BUFFER, position_radius_buffer); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(vec4_t), nullptr); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, color_buffer); glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(uint32_t), nullptr); glEnableVertexAttribArray(1); glUseProgram(voxelize::gl.program); glUniform3i(voxelize::gl.uniform_location.volume_dim, vol.res_x, vol.res_y, vol.res_z); glUniform3fv(voxelize::gl.uniform_location.volume_min, 1, &vol.min_box[0]); glUniform3fv(voxelize::gl.uniform_location.voxel_ext, 1, &vol.voxel_ext[0]); glUniform1i(voxelize::gl.uniform_location.tex_volume, 0); glBindTexture(GL_TEXTURE_3D, vol.texture_id); glBindImageTexture(0, vol.texture_id, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8); glColorMask(0, 0, 0, 0); glDepthMask(0); glEnable(GL_RASTERIZER_DISCARD); glDrawArrays(GL_POINTS, 0, num_spheres); // glMemoryBarrier(GL_ALL_BARRIER_BITS); // glGenerateMipmap(GL_TEXTURE_3D); glDisable(GL_RASTERIZER_DISCARD); glDepthMask(1); glColorMask(1, 1, 1, 1); glUseProgram(0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } /* enum IlluminationDirection { POSITIVE_X, NEGATIVE_X, POSITIVE_Y, NEGATIVE_Y, POSITIVE_Z, NEGATIVE_Z }; void illuminate_voxels_directional_constant(Array<vec3> light_voxels, Array<const uint32> rgba_voxels, const ivec3& voxel_dim, IlluminationDirection direction, const vec3& intensity) { const auto dim = cone_trace::volume.dim; const bool positive = direction % 2 == 0; ivec3_t step = {1, 1, 1}; ivec3_t beg_idx = {0, 0, 0}; ivec3_t end_idx = dim; switch (direction) { case POSITIVE_X: case NEGATIVE_X: { if (positive) { beg_idx.x = 1; } else { step.x = -1; beg_idx.x = dim.x - 2; end_idx.x = -1; } for (int32 z = beg_idx.z; z != end_idx.z; z += step.z) { for (int32 y = beg_idx.y; y != end_idx.y; y += step.y) { light_voxels[z * dim.y * dim.x + y * dim.x + (beg_idx.x - step.x)] += intensity; } } for (int32 x = beg_idx.x; x != end_idx.x; x += step.x) { for (int32 z = beg_idx.z; z != end_idx.z; z += step.z) { for (int32 y = beg_idx.y; y != end_idx.y; y += step.y) { const int32 src_vol_idx = z * dim.y * dim.x + y * dim.x + (x - step.x); const int32 dst_vol_idx = z * dim.y * dim.x + y * dim.x + x; const vec4_t voxel_rgba = math::convert_color(rgba_voxels[src_vol_idx]); light_voxels[dst_vol_idx] += (1.f - voxel_rgba.a) * light_voxels[src_vol_idx]; } } } } break; case POSITIVE_Y: case NEGATIVE_Y: { if (positive) { beg_idx.y = 1; } else { step.y = -1; beg_idx.y = dim.y - 2; end_idx.y = -1; } for (int32 z = beg_idx.z; z != end_idx.z; z += step.z) { for (int32 x = beg_idx.x; x != end_idx.x; x += step.x) { light_voxels[z * dim.y * dim.x + (beg_idx.y - step.y) * dim.x + x] += intensity; } } for (int32 y = beg_idx.y; y != end_idx.y; y += step.y) { for (int32 z = beg_idx.z; z != end_idx.z; z += step.z) { for (int32 x = beg_idx.x; x != end_idx.x; x += step.x) { const int32 src_vol_idx = z * dim.y * dim.x + (y - step.y) * dim.x + x; const int32 dst_vol_idx = z * dim.y * dim.x + y * dim.x + x; const vec4_t voxel_rgba = math::convert_color(rgba_voxels[src_vol_idx]); light_voxels[dst_vol_idx] += (1.f - voxel_rgba.a) * light_voxels[src_vol_idx]; } } } } break; case POSITIVE_Z: case NEGATIVE_Z: { if (positive) { beg_idx.z = 1; } else { step.z = -1; beg_idx.z = dim.z - 2; end_idx.z = -1; } for (int32 y = beg_idx.y; y != end_idx.y; y += step.y) { for (int32 x = beg_idx.x; x != end_idx.x; x += step.x) { light_voxels[(beg_idx.z - step.z) * dim.y * dim.x + y * dim.x + x] += intensity; } } for (int32 z = beg_idx.z; z != end_idx.z; z += step.z) { for (int32 y = beg_idx.y; y != end_idx.y; y += step.y) { for (int32 x = beg_idx.x; x != end_idx.x; x += step.x) { const int32 src_vol_idx = (z - step.z) * dim.y * dim.x + y * dim.x + x; const int32 dst_vol_idx = z * dim.y * dim.x + y * dim.x + x; const vec4_t voxel_rgba = math::convert_color(rgba_voxels[src_vol_idx]); light_voxels[dst_vol_idx] += (1.f - voxel_rgba.a) * light_voxels[src_vol_idx]; } } } } break; } } void illuminate_voxels_omnidirectional_constant(const vec3& intensity) { auto dim = cone_trace::volume.dim; DynamicArray<vec3> light_vol(cone_trace::volume.voxel_data.size(), vec3_t(0)); illuminate_voxels_directional_constant(light_vol, cone_trace::volume.voxel_data, dim, POSITIVE_X, intensity); illuminate_voxels_directional_constant(light_vol, cone_trace::volume.voxel_data, dim, NEGATIVE_X, intensity); for (int32 i = 0; i < light_vol.count; i++) { vec4_t voxel_rgba = math::convert_color(cone_trace::volume.voxel_data[i]); voxel_rgba *= vec4_t(light_vol[i], 1.f); cone_trace::volume.voxel_data[i] = math::convert_color(voxel_rgba); } // illuminate_voxels_directional_constant(NEGATIVE_X, intensity); // illuminate_voxels_directional_constant(POSITIVE_Y, intensity); // illuminate_voxels_directional_constant(NEGATIVE_Y, intensity); // illuminate_voxels_directional_constant(POSITIVE_Z, intensity); // illuminate_voxels_directional_constant(NEGATIVE_Z, intensity); // X-direction sweep plane DynamicArray<vec4_t> plane_slice_zy[2] = { { cone_trace::volume.dim.y * cone_trace::volume.dim.z, vec4_t(intensity, 0) }, { cone_trace::volume.dim.y * cone_trace::volume.dim.z, vec4_t(intensity, 0) } }; int curr_plane = 0; int prev_plane = 1; const auto dim = cone_trace::volume.dim; Array<uint32> voxels = cone_trace::volume.voxel_data; for (int32 x = 1; x < dim.x; x++) { for (int32 z = 0; z < dim.z; z++) { for (int32 y = 0; y < dim.y; y++) { const int32 plane_idx = z * dim.y + y; const int32 src_vol_idx = z * dim.y * dim.x + y * dim.x + (x - 1); const int32 dst_vol_idx = z * dim.y * dim.x + y * dim.x + x; const vec4_t voxel_rgba = math::convert_color(voxels[src_vol_idx]); const vec4_t& src_light_voxel = plane_slice_zy[prev_plane][plane_idx]; vec4_t& dst_light_voxel = plane_slice_zy[curr_plane][plane_idx]; dst_light_voxel = (1.f - voxel_rgba.a) * src_light_voxel; vec4_t dst_rgba = math::convert_color(voxels[dst_vol_idx]); dst_rgba = vec4_t(vec3_t(dst_rgba) * vec3_t(dst_light_voxel), dst_rgba.a); voxels[dst_vol_idx] = math::convert_color(dst_rgba); prev_plane = (prev_plane + 1) % 2; curr_plane = (curr_plane + 1) % 2; } } } } void draw_voxelized_scene(const GPUVolume& vol, const mat4_t& view_mat, const mat4_t& proj_mat) { immediate::set_model_view_matrix(view_mat); immediate::set_proj_matrix(proj_mat); immediate::set_material(immediate::MATERIAL_ROUGH_BLACK); for (int32 z = 0; z < vol.res_z; z++) { for (int32 y = 0; y < vol.res_y; y++) { for (int32 x = 0; x < vol.res_x; x++) { int32 i = compute_voxel_idx(volume.dim, ivec3_t(x, y, z)); if (cone_trace::volume.voxel_data[i] > 0) { vec3_t min_box = cone_trace::volume.min_box + vec3_t(x, y, z) * cone_trace::volume.voxel_ext; vec3_t max_box = min_box + cone_trace::volume.voxel_ext; immediate::draw_aabb_lines(min_box, max_box); } } } } immediate::flush(); } */ void compute_occupancy_volume(const GPUVolume& vol, const float* x, const float* y, const float* z, const float* rad, int64_t count) { const int32_t voxel_count = vol.res_x * vol.res_y * vol.res_z; if (voxel_count == 0) { md_print(MD_LOG_TYPE_ERROR, "Volume resolution is zero on one or more axes"); return; } const float inv_voxel_volume = 1.0f / (vol.voxel_ext.x * vol.voxel_ext.y * vol.voxel_ext.z); std::atomic_uint32_t* voxel_data = (std::atomic_uint32_t*)md_alloc(default_allocator, voxel_count * sizeof(std::atomic_uint32_t)); defer { md_free(default_allocator, voxel_data, voxel_count * sizeof(std::atomic_uint32_t)); }; #if 0 task_system::ID id = task_system::pool_enqueue( "Computing occupancy", (uint32_t)count, [voxel_data, x, y, z, r, &vol, inv_voxel_volume](task_system::TaskSetRange range) { // We assume atom radius <<< voxel extent and just increment the bin constexpr float sphere_vol_scl = (4.0f / 3.0f) * 3.1415926535f; for (uint32_t i = range.beg; i < range.end; i++) { const int idx = compute_voxel_idx(vol, {x[i], y[i], z[i]}); const float rad = r[i]; const float sphere_vol = sphere_vol_scl * rad * rad * rad; const uint32_t occ = (uint32_t)(sphere_vol * inv_voxel_volume * 0xFFFFFFFFU); atomic_fetch_add(&voxel_data[idx], occ); } }); task_system::wait_for_task(id); #else constexpr float sphere_vol_scl = (4.0f / 3.0f) * 3.1415926535f; for (int32_t i = 0; i < count; i++) { const vec3_t pos = {x[i], y[i], z[i]}; const int idx = compute_voxel_idx(vol, pos); const float r = rad[i]; const float sphere_vol = sphere_vol_scl * r * r * r; const float fract = sphere_vol * inv_voxel_volume; const uint32_t occ = uint32_t(fract * 0xFFFFFFFFU); voxel_data[idx] += occ; } #endif glBindTexture(GL_TEXTURE_3D, vol.texture_id); glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, 0, vol.res_x, vol.res_y, vol.res_z, GL_RED, GL_UNSIGNED_INT, voxel_data); glGenerateMipmap(GL_TEXTURE_3D); glBindTexture(GL_TEXTURE_3D, 0); } void render_directional_occlusion(GLuint depth_tex, GLuint normal_tex, const GPUVolume& vol, const mat4_t& view_mat, const mat4_t& proj_mat, float occlusion_scale, float step_scale) { const mat4_t inv_view_proj_mat = mat4_inverse(proj_mat * view_mat); const mat4_t inv_view_mat = mat4_inverse(view_mat); const vec3_t world_space_camera = mat4_mul_vec3(inv_view_mat, {0,0,0}, 1); const vec3_t voxel_grid_min = vol.min_box; const vec3_t voxel_grid_ext = vol.max_box - vol.min_box; float voxel_ext = MAX(MAX(vol.voxel_ext.x, vol.voxel_ext.y), vol.voxel_ext.z); GLuint program = directional_occlusion::program; glUseProgram(program); glUniform1i(glGetUniformLocation(program, "u_depth_texture"), 0); glUniform1i(glGetUniformLocation(program, "u_normal_texture"), 1); glUniform1i(glGetUniformLocation(program, "u_voxel_texture"), 2); glUniform3fv(glGetUniformLocation(program, "u_voxel_grid_world_min"), 1, &voxel_grid_min[0]); glUniform3fv(glGetUniformLocation(program, "u_voxel_grid_world_size"), 1, &voxel_grid_ext[0]); glUniform3i(glGetUniformLocation(program, "u_voxel_dimensions"), vol.res_x, vol.res_y, vol.res_z); glUniform1f(glGetUniformLocation(program, "u_voxel_extent"), voxel_ext); glUniform1f(glGetUniformLocation(program, "u_occlusion_scale"), occlusion_scale); glUniform1f(glGetUniformLocation(program, "u_step_scale"), step_scale); glUniformMatrix4fv(glGetUniformLocation(program, "u_inv_view_mat"), 1, GL_FALSE, &inv_view_mat[0][0]); glUniformMatrix4fv(glGetUniformLocation(program, "u_inv_view_proj_mat"), 1, GL_FALSE, &inv_view_proj_mat[0][0]); glUniform3fv(glGetUniformLocation(program, "u_world_space_camera"), 1, &world_space_camera[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depth_tex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normal_tex); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_3D, vol.texture_id); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_ZERO, GL_SRC_COLOR); glColorMask(1, 1, 1, 0); glDepthMask(GL_FALSE); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glDisable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); glColorMask(1, 1, 1, 1); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_3D, 0); } void cone_trace_scene(GLuint depth_tex, GLuint normal_tex, GLuint color_alpha_tex, GLuint f0_smoothness_tex, const GPUVolume& vol, const mat4_t& view_mat, const mat4_t& proj_mat, float indirect_diffuse_scale, float indirect_specular_scale, float ambient_occlusion_scale) { mat4_t inv_view_proj_mat = mat4_inverse(proj_mat * view_mat); mat4_t inv_view_mat = mat4_inverse(view_mat); vec3_t world_space_camera = mat4_mul_vec3(inv_view_mat, {0, 0, 0}, 1); // printf("cam: %.2f %.2f %.2f\n", world_space_camera.x, world_space_camera.y, world_space_camera.z); vec3_t voxel_grid_min = vol.min_box; vec3_t voxel_grid_ext = vol.max_box - vol.min_box; float voxel_ext = MAX(MAX(vol.voxel_ext.x, vol.voxel_ext.y), vol.voxel_ext.z); // const float cone_angle = 0.07; // 0.2 = 22.6 degrees, 0.1 = 11.4 degrees, 0.07 = 8 degrees angle glUseProgram(cone_trace::gl.program); glUniform1i(cone_trace::gl.uniform_location.depth_tex, 0); glUniform1i(cone_trace::gl.uniform_location.normal_tex, 1); glUniform1i(cone_trace::gl.uniform_location.color_alpha_tex, 2); glUniform1i(cone_trace::gl.uniform_location.f0_smoothness_tex, 3); glUniform1i(cone_trace::gl.uniform_location.voxel_tex, 4); glUniform3fv(cone_trace::gl.uniform_location.voxel_grid_min, 1, &voxel_grid_min[0]); glUniform3fv(cone_trace::gl.uniform_location.voxel_grid_size, 1, &voxel_grid_ext[0]); glUniform3i(cone_trace::gl.uniform_location.voxel_dimensions, vol.res_x, vol.res_y, vol.res_z); glUniform1f(cone_trace::gl.uniform_location.voxel_extent, voxel_ext); glUniform1f(cone_trace::gl.uniform_location.indirect_diffuse_scale, indirect_diffuse_scale); glUniform1f(cone_trace::gl.uniform_location.indirect_specular_scale, indirect_specular_scale); glUniform1f(cone_trace::gl.uniform_location.ambient_occlusion_scale, ambient_occlusion_scale); glUniformMatrix4fv(cone_trace::gl.uniform_location.inv_view_mat, 1, GL_FALSE, &inv_view_mat[0][0]); glUniformMatrix4fv(cone_trace::gl.uniform_location.inv_view_proj_mat, 1, GL_FALSE, &inv_view_proj_mat[0][0]); glUniform3fv(cone_trace::gl.uniform_location.world_space_camera, 1, &world_space_camera[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, depth_tex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normal_tex); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, color_alpha_tex); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, f0_smoothness_tex); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_3D, vol.texture_id); glDisable(GL_DEPTH_TEST); // glEnable(GL_BLEND); // glBlendFunc(GL_ONE, GL_ONE); // glColorMask(1, 1, 1, 0); glDepthMask(GL_FALSE); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); // glDisable(GL_BLEND); // glBlendFunc(GL_ONE, GL_ZERO); // glColorMask(1, 1, 1, 1); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); } } // namespace cone_trace
38.859981
152
0.642045
scanberg
0705ded8c58594566fd83efaab62fd5ad440f7fa
734
cpp
C++
src/DonePullBackTransition.cpp
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
3
2020-12-19T01:00:33.000Z
2021-12-01T01:13:21.000Z
src/DonePullBackTransition.cpp
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
null
null
null
src/DonePullBackTransition.cpp
songchaow/starcrat2-ai
ac6fbdb0e3d7839a76addea4e6aa50a4545841f3
[ "MIT" ]
2
2021-02-22T18:50:38.000Z
2022-03-21T17:37:24.000Z
#pragma once #include "DonePullBackTransition.h" #include "Util.h" DonePullBackTransition::DonePullBackTransition(const sc2::Unit * unit, sc2::Point2D position, FocusFireFSMState* nextState) { m_unit = unit; m_nextState = nextState; m_position = position; } bool DonePullBackTransition::isValid(const sc2::Unit * target, const std::vector<const sc2::Unit*> * units, std::unordered_map<sc2::Tag, float> *, CCBot*) { bool done(false); done = m_position == m_unit->pos; if (Util::Dist(m_position, m_unit->pos) < 1.5f) return true; else return false; } FocusFireFSMState* DonePullBackTransition::getNextState() { return m_nextState; } void DonePullBackTransition::onTransition() { }
23.677419
154
0.70436
songchaow
070bc5340d136098d418f419daa2889b4798258f
1,557
cpp
C++
src/IceRay/main/interface/python/core/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/main/interface/python/core/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/main/interface/python/core/camera/sphere/horizontal.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include <boost/python.hpp> #include "../../../def_submodule.hpp" #include "./camera.hpp" void expose_IceRay_camera_sphere_horizontal() { using namespace GS_DDMRM::S_IceRay::S_main::S_interface::S_python; //MAKE_SUBMODULE( IceRay ); MAKE_SUBMODULE( core ); MAKE_SUBMODULE( camera ); typedef GS_DDMRM::S_IceRay::S_camera::S_sphere::GC_horizontal GTs_sphereHorizontal; typedef GTs_scalar const& (GTs_sphereHorizontal::*Tf_getScalar)(void) const; typedef bool (GTs_sphereHorizontal::*Tf_setScalar )(GTs_scalar const&); Tf_getScalar I_getPhi = &GTs_sphereHorizontal::F_phi; Tf_setScalar I_setPhi = &GTs_sphereHorizontal::F_phi; Tf_getScalar I_getTheta = &GTs_sphereHorizontal::F_theta; Tf_setScalar I_setTheta = &GTs_sphereHorizontal::F_theta; // TODO Tf_getScalar I_getRadius = &GTs_sphereHorizontal::F_theta; // TODO Tf_setScalar I_setRadius = &GTs_sphereHorizontal::F_theta; boost::python::class_<GTs_sphereHorizontal, boost::python::bases<GTs__pure> >("CameraSpherePolarHorizontal" ) .def( boost::python::init<>() ) .def( "phi", I_getPhi , boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "phi", I_setPhi ) .def( "theta", I_getTheta , boost::python::return_value_policy<boost::python::copy_const_reference>() ) .def( "theta", I_setTheta ) //TODO .def( "radius", I_getRadius , boost::python::return_value_policy<boost::python::copy_const_reference>() ) //TODO .def( "radius", I_setRadius ) ; }
37.97561
118
0.71034
dmilos
070deed25ac1f79f3c817fa7d40653f414f79cd1
79,397
cc
C++
src/CoordinatorServerList.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
1
2016-01-18T12:41:28.000Z
2016-01-18T12:41:28.000Z
src/CoordinatorServerList.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
src/CoordinatorServerList.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
/* Copyright (c) 2011-2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <list> #include "Common.h" #include "ClientException.h" #include "CoordinatorServerList.h" #include "Cycles.h" #include "LogCabinHelper.h" #include "MasterRecoveryManager.h" #include "ServerTracker.h" #include "ShortMacros.h" #include "TransportManager.h" #include "Context.h" namespace RAMCloud { /** * Constructor for CoordinatorServerList. * * \param context * Overall information about the RAMCloud server. The constructor * will modify \c context so that its \c serverList and * \c coordinatorServerList members refer to this object. */ CoordinatorServerList::CoordinatorServerList(Context* context) : AbstractServerList(context) , serverList() , numberOfMasters(0) , numberOfBackups(0) , stopUpdater(true) , lastScan() , update() , updates() , hasUpdatesOrStop() , listUpToDate() , updaterThread() , minConfirmedVersion(0) , numUpdatingServers(0) , nextReplicationId(1) , logIdAppendServerAlive(NO_ID) , logIdServerListVersion(NO_ID) , logIdServerUpUpdate(NO_ID) , logIdServerReplicationUpUpdate(NO_ID) { context->coordinatorServerList = this; startUpdater(); } /** * Destructor for CoordinatorServerList. */ CoordinatorServerList::~CoordinatorServerList() { haltUpdater(); } ////////////////////////////////////////////////////////////////////// // CoordinatorServerList Public Methods ////////////////////////////////////////////////////////////////////// /** * Get the number of backups in the list; does not include servers in * crashed status. */ uint32_t CoordinatorServerList::backupCount() const { Lock _(mutex); return numberOfBackups; } /** * Implements enlisting a server onto the CoordinatorServerList and * propagating updates to the cluster. * * \param replacesId * Server id of the server that the enlisting server is replacing. * A null value means that the enlisting server is not replacing another * server. * \param serviceMask * Services supported by the enlisting server. * \param readSpeed * Read speed of the enlisting server. * \param serviceLocator * Service Locator of the enlisting server. * * \return * Server id assigned to the enlisting server. */ ServerId CoordinatorServerList::enlistServer( ServerId replacesId, ServiceMask serviceMask, const uint32_t readSpeed, const char* serviceLocator) { Lock lock(mutex); // The order of the updates in serverListUpdate is important: the remove // must be ordered before the add to ensure that as members apply the // update they will see the removal of the old server id before the // addition of the new, replacing server id. if (iget(replacesId)) { LOG(NOTICE, "%s is enlisting claiming to replace server id " "%s, which is still in the server list, taking its word " "for it and assuming the old server has failed", serviceLocator, replacesId.toString().c_str()); ServerNeedsRecovery(*this, lock, replacesId).execute(); ServerCrashed(*this, lock, replacesId, version + 1).execute(); } // Indicate that the next server enlistment would have to send out "UP" // updates to the cluster. // However: // I can skip this step if such a log entry is pointed to by the csl's // logIdServerUpUpdate. // Because: // This log entry is is not specific to a particular server that is // enlisting, rather just meant for the "next" server enlisting. // If it were meant for a particular server, it would be pointed to // by the server entry's logIdServerUpUpdate, not csl's logIdServerUpUpdate. // This situation an arise if the coordinator was in the middle of // an enlistServer() operation (it had completed ServerUpUpdate::execute(), // but not EnlistServer::complete()) when it last crashed. // Reusing such an entry also helps prevent dangling ServerUpUpdate // log entries. if (logIdServerUpUpdate == NO_ID) { ServerUpUpdate(*this, lock).execute(); } // Enlist the server. ServerId newServerId = EnlistServer(*this, lock, ServerId(), serviceMask, readSpeed, serviceLocator, version + 1).execute(); if (replacesId.isValid()) { LOG(NOTICE, "Newly enlisted server %s replaces server %s", newServerId.toString().c_str(), replacesId.toString().c_str()); } return newServerId; } /** * Get the number of masters in the list; does not include servers in * crashed status. */ uint32_t CoordinatorServerList::masterCount() const { Lock _(mutex); return numberOfMasters; } /** * Returns a copy of the details associated with the given ServerId. * * Note: This function explictly acquires a lock, and is hence to be used * only by functions external to CoordinatorServerList to prevent deadlocks. * If a function in CoordinatorServerList class (that has already acquired * a lock) wants to use this functionality, it should directly call * #getEntry function. * * \param serverId * ServerId to look up in the list. * \throw * Exception is thrown if the given ServerId is not in this list. */ CoordinatorServerList::Entry CoordinatorServerList::operator[](ServerId serverId) const { Lock _(mutex); Entry* entry = getEntry(serverId); if (!entry) { throw ServerListException(HERE, format("Invalid ServerId (%s)", serverId.toString().c_str())); } return *entry; } /** * Returns a copy of the details associated with the given position * in the server list. * * Note: This function explictly acquires a lock, and is hence to be used * only by functions external to CoordinatorServerList to prevent deadlocks. * If a function in CoordinatorServerList class (that has already acquired * a lock) wants to use this functionality, it should directly call * #getEntry function. * * \param index * Position of entry in the server list to return a copy of. * \throw * Exception is thrown if the position in the list is unoccupied. */ CoordinatorServerList::Entry CoordinatorServerList::operator[](size_t index) const { Lock _(mutex); Entry* entry = getEntry(index); if (!entry) { throw ServerListException(HERE, format("Index beyond array length (%zd) or entry" "doesn't exist", index)); } return *entry; } /** * Mark a server as REMOVE, typically when it is no longer part of * the system and we don't care about it anymore (it crashed and has * been properly recovered). * * When the update sent to and acknowledged by the rest of the cluster * is being pruned, the server list entry for this server will be removed. * * This method may actually append two entries to \a update (see below). * * The result of this operation will be added in the class's update Protobuffer * intended for the cluster. To send out the update, call pushUpdate() * which will also increment the version number. Calls to remove() * and crashed() must proceed call to add() to ensure ordering guarantees * about notifications related to servers which re-enlist. * * The addition will be pushed to all registered trackers and those with * callbacks will be notified. * * \param serverId * The ServerId of the server to remove from the CoordinatorServerList. * It must be in the list (either UP or CRASHED). */ void CoordinatorServerList::recoveryCompleted(ServerId serverId) { Lock lock(mutex); ServerRemoveUpdate(*this, lock, serverId, version + 1).execute(); } /** * Serialize this list (or part of it, depending on which services the * caller wants) to a protocol buffer. Not all state is included, but * enough to be useful for disseminating cluster membership information * to other servers. * * \param[out] protoBuf * Reference to the ProtoBuf to fill. * \param services * If a server has *any* service included in \a services it will be * included in the serialization; otherwise, it is skipped. */ void CoordinatorServerList::serialize(ProtoBuf::ServerList& protoBuf, ServiceMask services) const { Lock lock(mutex); serialize(lock, protoBuf, services); } /** * This method is invoked when a server is determined to have crashed. * It marks the server as crashed, propagates that information * (through server trackers and the cluster updater) and invokes recovery. * It returns before the recovery has completed. * Once recovery has finished, the server will be removed from the server list. * * \param serverId * ServerId of the server that is suspected to be down. */ void CoordinatorServerList::serverCrashed(ServerId serverId) { Lock lock(mutex); // Indicate that the crashed server needs to be recovered. // However: // I can skip this step if such a log entry already exists. // This situation can arise if the coordinator was in the middle of // a crashedServer() operation (it had completed // ServerNeedsRecovery::execute(), but not ServerCrashed::complete()) // or had completed serverCrashed() not completed the recovery for // the crashed server when it last crashed. // Reusing this log entry also helps prevent having multiple // ServerNeedsRecovery log entries for crashed servers. Entry* entry = getEntry(serverId); if (entry && entry->logIdServerNeedsRecovery == NO_ID) { ServerNeedsRecovery(*this, lock, serverId).execute(); } // Remove the crashed server from the cluster. ServerCrashed(*this, lock, serverId, version + 1).execute(); } /** * Reset extra metadata for \a serverId that will be needed to safely recover * the master's log. * * \param serverId * ServerId of the server whose master recovery info will be set. * \param recoveryInfo * Information the coordinator will need to safely recover the master * at \a serverId. The information is opaque to the coordinator other * than its master recovery routines, but, basically, this is used to * prevent inconsistent open replicas from being used during recovery. * \return * Whether the operation succeeded or not (i.e. if the serverId exists). */ bool CoordinatorServerList::setMasterRecoveryInfo( ServerId serverId, const ProtoBuf::MasterRecoveryInfo& recoveryInfo) { Lock lock(mutex); Entry* entry = getEntry(serverId); if (entry) { entry->masterRecoveryInfo = recoveryInfo; ServerUpdate(*this, lock, serverId, recoveryInfo, entry->logIdServerUpdate).execute(); return true; } else { return false; } } ////////////////////////////////////////////////////////////////////// // CoordinatorServerList Recovery Methods ////////////////////////////////////////////////////////////////////// /** * Complete a ServerCrashed during coordinator recovery. * * \param state * The ProtoBuf that encapsulates the state of the ServerCrashed * operation to be recovered. * \param logIdServerCrashed * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerCrashed( ProtoBuf::ServerCrashInfo* state, EntryId logIdServerCrashed) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerCrashed()"); ServerCrashed(*this, lock, ServerId(state->server_id()), state->update_version()).complete(logIdServerCrashed); } void CoordinatorServerList::recoverServerListVersion( ProtoBuf::ServerListVersion* state, EntryId logIdServerListVersion) { Lock lock(mutex); uint64_t version = state->version(); PersistServerListVersion(*this, lock, version).complete( logIdServerListVersion); // When coordinator recovers, all the server list entries created // corresponding to all the servers, will have a verified version and // update version of 0. (Since it It will be too expensive to log the // most up-to-date value of verified version for each entry during // normal operation and then recover that later.) // This would result in the entire server list being sent out to all // the servers. This is not expected behavior (and the servers will // shoot themselves in the head). // Hence: // Set these versions for every server entry in server list to be the // ServerListVersion number that was last logged to LogCabin // (since which was the minimum verified update number). // This way, some servers might still get some updates they had already // received, but the number will hopefully be low, and they will at least // never receive the entire server list again. for (size_t index = 0; index < isize(); index++) { Entry* entry = getEntry(index); if (entry != NULL) { entry->verifiedVersion = version; entry->updateVersion = version; } } } /** * During coordinator recovery, record in server list that for this server * (that had crashed), we need to start the master crash recovery. * * \param state * The ProtoBuf that encapsulates the state of the ServerNeedsRecovery * operation to be recovered. * \param logIdServerNeedsRecovery * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerNeedsRecovery( ProtoBuf::ServerCrashInfo* state, EntryId logIdServerNeedsRecovery) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerNeedsRecovery()"); ServerNeedsRecovery(*this, lock, ServerId(state->server_id())).complete( logIdServerNeedsRecovery); } /** * During coordinator recovery, propagate REMOVE updates for a crashed server * whose recovery had already completed. * * \param state * The ProtoBuf that encapsulates the state of the ServerRemoveUpdate * operation to be recovered. * \param logIdServerRemoveUpdate * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerRemoveUpdate( ProtoBuf::ServerCrashInfo* state, EntryId logIdServerRemoveUpdate) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerRemoveUpdate()"); ServerRemoveUpdate(*this, lock, ServerId(state->server_id()), state->update_version()).complete( logIdServerRemoveUpdate); } /** * During Coordinator recovery, enlist a server that was either being enlisted * at the time of crash, or had already successfully enlisted. * * \param state * The ProtoBuf that encapsulates the information about the server to be * enlisted. * \param logIdServerUp * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerUp( ProtoBuf::ServerInformation* state, EntryId logIdServerUp) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerUp()"); EnlistServer(*this, lock, ServerId(state->server_id()), ServiceMask::deserialize(state->service_mask()), state->read_speed(), state->service_locator().c_str(), state->update_version()).complete(logIdServerUp); } /** * During Coordinator recovery, recover the entry that indicates that the * next server enlistment will have to send out "UP" updates. * * \param state * The ProtoBuf that indicates that the server enlistment will have to * send out "UP" updates. * \param logIdServerUpUpdate * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerUpUpdate( ProtoBuf::EntryType* state, EntryId logIdServerUpUpdate) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerUpUpdate()"); ServerUpUpdate(*this, lock).complete(logIdServerUpUpdate); } /** * During Coordinator recovery, recover the entry that indicates that the * replication id update will have to send out updates to the entire cluster. * * \param state * The ProtoBuf that indicates that the coordinator will need to send * out replication id updates. * \param logIdServerReplicationUpUpdate * The entry id of the LogCabin entry corresponding to the state. */ void CoordinatorServerList::recoverServerReplicationUpUpdate( ProtoBuf::EntryType* state, EntryId logIdServerReplicationUpUpdate) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerReplicationUpUpdate()"); ServerReplicationUpUpdate(*this, lock).complete( logIdServerReplicationUpUpdate); } /** * During Coordinator recovery, set update-able fields for the server. * * \param state * The ProtoBuf that has the updates for the server. * \param logIdServerUpdate * The entry id of the LogCabin entry corresponding to serverUpdate. */ void CoordinatorServerList::recoverServerUpdate( ProtoBuf::ServerUpdate* state, EntryId logIdServerUpdate) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerUpdate()"); // If there are other update-able fields in the future, read them in from // ServerUpdate and update them all. ServerUpdate(*this, lock, ServerId(state->server_id()), state->master_recovery_info()).complete(logIdServerUpdate); } /** * During Coordinator recovery, set update-able fields for the server. * * \param state * The ProtoBuf that has the updates for the server. * \param logIdServerReplicationUpdate * The entry id of the LogCabin entry corresponding to * serverReplicationUpdate. */ void CoordinatorServerList::recoverServerReplicationUpdate( ProtoBuf::ServerReplicationUpdate* state, EntryId logIdServerReplicationUpdate) { Lock lock(mutex); LOG(DEBUG, "CoordinatorServerList::recoverServerReplicationUpdate()"); // If there are other update-able fields in the future, read them in from // ServerReplicationUpdate and update them all. ServerReplicationUpdate(*this, lock, ServerId(state->server_id()), state->master_recovery_info(), state->replication_id(), version + 1).complete(logIdServerReplicationUpdate); } ////////////////////////////////////////////////////////////////////// // CoordinatorServerList Private Methods ////////////////////////////////////////////////////////////////////// /** * Do everything needed to execute the EnlistServer operation. * Do any processing required before logging the state * in LogCabin, log the state in LogCabin, then call #complete(). */ ServerId CoordinatorServerList::EnlistServer::execute() { newServerId = csl.generateUniqueId(lock); ProtoBuf::ServerInformation stateServerUp; stateServerUp.set_entry_type("ServerUp"); stateServerUp.set_server_id(newServerId.getId()); stateServerUp.set_service_mask(serviceMask.serialize()); stateServerUp.set_read_speed(readSpeed); stateServerUp.set_service_locator(string(serviceLocator)); stateServerUp.set_update_version(updateVersion); EntryId logIdServerUp = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, stateServerUp); LOG(DEBUG, "LogCabin: ServerUp entryId: %lu", logIdServerUp); return complete(logIdServerUp); } /** * Complete the EnlistServer operation after its state has been * logged in LogCabin. * This is called internally by #execute() in case of normal operation * (which is in turn called by #enlistServer()), and * directly for coordinator recovery (by #recoverEnlistServer()). * * \param logIdServerUp * The entry id of the LogCabin entry that has initial information * for this server. */ ServerId CoordinatorServerList::EnlistServer::complete( EntryId logIdServerUp) { if (csl.logIdServerUpUpdate == NO_ID) { // Server had already been successfully enlisted (presumably before a // coordinator crash) -- hence its "UP" updates had been sent out to the // cluster and acknowledged. Just add the entry to the coordinator // server list, and do not send updates to the cluster. csl.add(lock, newServerId, serviceLocator, serviceMask, readSpeed, false); } else { csl.add(lock, newServerId, serviceLocator, serviceMask, readSpeed); csl.version = updateVersion; csl.pushUpdate(lock, updateVersion); } Entry* entry = csl.getEntry(newServerId); entry->logIdServerUp = logIdServerUp; // No-op if csl.logIdServerUpUpdate is already NO_ID. entry->logIdServerUpUpdate = csl.logIdServerUpUpdate; csl.logIdServerUpUpdate = NO_ID; LOG(NOTICE, "Enlisting server at %s (server id %s) supporting " "services: %s", serviceLocator, newServerId.toString().c_str(), entry->services.toString().c_str()); if (entry->isBackup()) { LOG(DEBUG, "Backup at id %s has %u MB/s read", newServerId.toString().c_str(), readSpeed); csl.createReplicationGroup(lock); } return newServerId; } void CoordinatorServerList::PersistServerListVersion::execute() { ProtoBuf::ServerListVersion state; state.set_entry_type("ServerListVersion"); state.set_version(version); vector<EntryId> invalidates; if (csl.logIdServerListVersion != NO_ID) invalidates.push_back(csl.logIdServerListVersion); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state, invalidates); LOG(DEBUG, "LogCabin: ServerListVersion entryId: %lu", entryId); complete(entryId); } void CoordinatorServerList::PersistServerListVersion::complete( EntryId logIdServerListVersion) { csl.version = version; csl.logIdServerListVersion = logIdServerListVersion; } /** * Do everything needed to remove a server from the cluster. * Do any processing required before logging the state * in LogCabin, log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerCrashed::execute() { if (!csl.getEntry(serverId)) { throw ServerListException(HERE, format("Invalid ServerId (%s)", serverId.toString().c_str())); } ProtoBuf::ServerCrashInfo state; state.set_entry_type("ServerCrashed"); state.set_server_id(serverId.getId()); state.set_update_version(updateVersion); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state); LOG(DEBUG, "LogCabin: ServerCrashed entryId: %lu", entryId); complete(entryId); } /** * Complete the operation to remove a server from the cluster * after its state has been logged in LogCabin. * This is called internally by #execute() in case of normal operation, and * directly for coordinator recovery (by #recoverServerCrashed()). * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerCrashed::complete(EntryId entryId) { csl.crashed(lock, serverId); csl.version = updateVersion; csl.pushUpdate(lock, updateVersion); // If this machine has a backup and master on the same server it is best // to remove the dead backup before initiating recovery. Otherwise, other // servers may try to backup onto a dead machine which will cause delays. Entry* entry = csl.getEntry(serverId); entry->logIdServerCrashed = entryId; if (entry->needsRecovery) { if (!entry->services.has(WireFormat::MASTER_SERVICE)) { // If the server being replaced did not have a master then there // will be no recovery. That means it needs to transition to // removed status now (usually recoveries remove servers from the // list when they complete). CoordinatorServerList::ServerRemoveUpdate( csl, lock, serverId, ++csl.version).execute(); } csl.context->recoveryManager->startMasterRecovery(*entry); } else { // Don't start recovery when the coordinator is replaying a serverDown // log entry for a server that had already been recovered. } csl.removeReplicationGroup(lock, entry->replicationId); csl.createReplicationGroup(lock); } /** * Indicate that a crashed server needs to be recovered. * Log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerNeedsRecovery::execute() { if (!csl.getEntry(serverId)) { throw ServerListException(HERE, format("Invalid ServerId (%s)", serverId.toString().c_str())); } ProtoBuf::ServerCrashInfo state; state.set_entry_type("ServerNeedsRecovery"); state.set_server_id(serverId.getId()); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state); LOG(DEBUG, "LogCabin: ServerNeedsRecovery entryId: %lu", entryId); complete(entryId); } /** * Complete the operation to indicate that a crashed server needs to be * recovered after its state has been logged in LogCabin. * This is called internally by #execute() in case of normal operation, and * directly for coordinator recovery (by #recoverServerNeedsRecovery()). * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerNeedsRecovery::complete(EntryId entryId) { Entry* entry = csl.getEntry(serverId); if (!entry) { LOG(WARNING, "Server being updated doesn't exist: %s", serverId.toString().c_str()); csl.context->logCabinHelper->invalidate( *csl.context->expectedEntryId, vector<EntryId>(entryId)); return; } entry->needsRecovery = true; entry->logIdServerNeedsRecovery = entryId; } /** * Indicate that a crashed server needs to be recovered. * Log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerRemoveUpdate::execute() { Entry* entry = csl.getEntry(serverId); if (!entry) { throw ServerListException(HERE, format("Invalid ServerId (%s)", serverId.toString().c_str())); } ProtoBuf::ServerCrashInfo state; state.set_entry_type("ServerRemoveUpdate"); state.set_server_id(serverId.getId()); state.set_update_version(updateVersion); vector<EntryId> invalidates; if (entry->logIdServerNeedsRecovery) invalidates.push_back(entry->logIdServerNeedsRecovery); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state, invalidates); LOG(DEBUG, "LogCabin: ServerRemoveUpdate entryId: %lu", entryId); complete(entryId); } /** * Complete the operation to indicate that a crashed server needs to be * recovered after its state has been logged in LogCabin. * This is called internally by #execute() in case of normal operation, and * directly for coordinator recovery (by #recoverServerRemoveUpdate()). * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerRemoveUpdate::complete(EntryId entryId) { Entry* entry = csl.getEntry(serverId); if (!entry) { LOG(WARNING, "Server being updated doesn't exist: %s", serverId.toString().c_str()); csl.context->logCabinHelper->invalidate( *csl.context->expectedEntryId, vector<EntryId>(entryId)); return; } entry->logIdServerRemoveUpdate = entryId; // This is a no-op if server was already marked as CRASHED. csl.crashed(lock, serverId); // Setting state gets the serialized update message's state field correct. entry->status = ServerStatus::REMOVE; LOG(NOTICE, "Removing %s from cluster/coordinator server list", serverId.toString().c_str()); ProtoBuf::ServerList_Entry& protoBufEntry(*(csl.update).add_server()); entry->serialize(protoBufEntry); foreach (ServerTrackerInterface* tracker, csl.trackers) tracker->enqueueChange(*entry, ServerChangeEvent::SERVER_REMOVED); foreach (ServerTrackerInterface* tracker, csl.trackers) tracker->fireCallback(); csl.version = updateVersion; csl.pushUpdate(lock, updateVersion); } /** * Do everything needed to set update-able fields corresponding to a server. * Do any processing required before logging the state to LogCabin, * log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerUpdate::execute() { ProtoBuf::ServerUpdate serverUpdate; serverUpdate.set_entry_type("ServerUpdate"); serverUpdate.set_server_id(serverId.getId()); (*serverUpdate.mutable_master_recovery_info()) = recoveryInfo; vector<EntryId> invalidates; if (oldServerUpdateEntryId != NO_ID) invalidates.push_back(oldServerUpdateEntryId); EntryId newEntryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, serverUpdate, invalidates); LOG(DEBUG, "LogCabin: ServerUpdate entryId: %lu", newEntryId); complete(newEntryId); } /** * Complete the operation to set update-able fields corresponding to a server * after its state has been logged to LogCabin. * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerUpdate::complete(EntryId entryId) { Entry* entry = csl.getEntry(serverId); if (entry) { entry->masterRecoveryInfo = recoveryInfo; entry->logIdServerUpdate = entryId; } else { LOG(WARNING, "Server being updated doesn't exist: %s", serverId.toString().c_str()); csl.context->logCabinHelper->invalidate( *csl.context->expectedEntryId, vector<EntryId>(entryId)); } } /** * Do everything needed to set update-able fields corresponding to a server. * Do any processing required before logging the state to LogCabin, * log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerReplicationUpdate::execute() { ProtoBuf::ServerReplicationUpdate serverReplicationUpdate; serverReplicationUpdate.set_entry_type("ServerReplicationUpdate"); serverReplicationUpdate.set_replication_id(replicationId); serverReplicationUpdate.set_server_id(serverId.getId()); (*serverReplicationUpdate.mutable_master_recovery_info()) = recoveryInfo; vector<EntryId> invalidates; if (oldServerReplicationUpdateEntryId != NO_ID) invalidates.push_back(oldServerReplicationUpdateEntryId); EntryId newEntryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, serverReplicationUpdate, invalidates); LOG(DEBUG, "LogCabin: ServerReplicationUpdate entryId: %lu", newEntryId); complete(newEntryId); } /** * Complete the operation to set update-able fields corresponding to a server * after its state has been logged to LogCabin. * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerReplicationUpdate::complete(EntryId entryId) { Entry* entry = csl.getEntry(serverId); if (entry) { entry->masterRecoveryInfo = recoveryInfo; entry->logIdServerReplicationUpdate = entryId; entry->replicationId = replicationId; entry->logIdServerReplicationUpUpdate = csl.logIdServerReplicationUpUpdate; // We check to see if the replication update field is set in // Log Cabin. If it is, we can be sure that the replication id // update hasn't been sent out to the masters. if (csl.logIdServerReplicationUpUpdate != NO_ID) { ProtoBuf::ServerList_Entry& protoBufEntry( *(csl.update).add_server()); entry->serialize(protoBufEntry); csl.version = updateVersion; csl.pushUpdate(lock, updateVersion); csl.logIdServerReplicationUpUpdate = NO_ID; } } else { LOG(WARNING, "Server being updated doesn't exist: %s", serverId.toString().c_str()); csl.context->logCabinHelper->invalidate( *csl.context->expectedEntryId, vector<EntryId>(entryId)); } } /** * Indicate that a the next server to be enlisted has to send out "UP" updates * to the cluster. * Log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerUpUpdate::execute() { ProtoBuf::EntryType state; state.set_entry_type("ServerUpUpdate"); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state); LOG(DEBUG, "LogCabin: ServerUpUpdate entryId: %lu", entryId); complete(entryId); } /** * Complete the operation to indicate that the next server to be enlisted * has to send out "UP" updates to the cluster. * This is called internally by #execute() in case of normal operation, and * directly for coordinator recovery (by #recoverServerUpUpdate()). * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerUpUpdate::complete(EntryId entryId) { csl.logIdServerUpUpdate = entryId; } ServerDetails* CoordinatorServerList::iget(ServerId id) { return getEntry(id); } ServerDetails* CoordinatorServerList::iget(uint32_t index) { return (serverList[index].entry) ? serverList[index].entry.get() : NULL; } /** * Indicate that all servers have already received a replication Id update. * Log the state in LogCabin, then call #complete(). */ void CoordinatorServerList::ServerReplicationUpUpdate::execute() { ProtoBuf::EntryType state; state.set_entry_type("ServerReplicationUpUpdate"); EntryId entryId = csl.context->logCabinHelper->appendProtoBuf( *csl.context->expectedEntryId, state); LOG(DEBUG, "LogCabin: ServerReplicationUpUpdate entryId: %lu", entryId); complete(entryId); } /** * Complete the operation to indicate that all the servers have already * received a replication Id update. * This is called internally by #execute(). * * \param entryId * The entry id of the LogCabin entry corresponding to the state * of the operation to be completed. */ void CoordinatorServerList::ServerReplicationUpUpdate::complete(EntryId entryId) { csl.logIdServerReplicationUpUpdate = entryId; } /** * Return the number of valid indexes in this list w/o lock. Valid does not mean * that they're occupied, only that they are within the bounds of the array. */ size_t CoordinatorServerList::isize() const { return serverList.size(); } /** * Returns the entry corresponding to a ServerId with bounds checks. * Assumes caller already has CoordinatorServerList lock. * * \param id * ServerId corresponding to the entry you want to get. * \return * The Entry, null if id is invalid. */ CoordinatorServerList::Entry* CoordinatorServerList::getEntry(ServerId id) const { uint32_t index = id.indexNumber(); if ((index < serverList.size()) && serverList[index].entry) { Entry* e = const_cast<Entry*>(serverList[index].entry.get()); if (e->serverId == id) return e; } return NULL; } /** * Obtain a pointer to the entry associated with the given position * in the server list with bounds check. Assumes caller already has * CoordinatorServerList lock. * * \param index * Position of entry in the server list to return a copy of. * \return * The Entry, null if index doesn't have an entry or is out of bounds */ CoordinatorServerList::Entry* CoordinatorServerList::getEntry(size_t index) const { if ((index < serverList.size()) && serverList[index].entry) { Entry* e = const_cast<Entry*>(serverList[index].entry.get()); return e; } return NULL; } /** * Add a new server to the CoordinatorServerList with a given ServerId. * * The result of this operation will be added in the class's update Protobuffer * intended for the cluster. To send out the update, call pushUpdate() * which will also increment the version number. Calls to remove() * and crashed() must precede call to add() to ensure ordering guarantees * about notifications related to servers which re-enlist. * * The addition will be pushed to all registered trackers and those with * callbacks will be notified. * * It doesn't acquire locks and does not send out updates * since it is used internally. * * \param lock * Explicity needs CoordinatorServerList lock. * \param serverId * The serverId to be assigned to the new server. * \param serviceLocator * The ServiceLocator string of the server to add. * \param serviceMask * Which services this server supports. * \param readSpeed * Speed of the storage on the enlisting server if it includes a backup * service. Argument is ignored otherwise. * \param enqueueUpdate * Whether the update (to be sent to the cluster) about the enlisting * server should be enqueued. This is false during coordinator recovery * while replaying an AliveServer entry since it only needs local * (coordinator) change, and the rest of the cluster had already * acknowledged the update. */ void CoordinatorServerList::add(Lock& lock, ServerId serverId, string serviceLocator, ServiceMask serviceMask, uint32_t readSpeed, bool enqueueUpdate) { uint32_t index = serverId.indexNumber(); // When add is not preceded by generateUniqueId(), // for example, during coordinator recovery while adding a server that // had already enlisted before the previous coordinator leader crashed, // the serverList might not have space allocated for this index number. // So we need to resize it explicitly. if (index >= serverList.size()) serverList.resize(index + 1); auto& pair = serverList[index]; pair.nextGenerationNumber = serverId.generationNumber(); pair.nextGenerationNumber++; pair.entry.construct(serverId, serviceLocator, serviceMask); if (serviceMask.has(WireFormat::MASTER_SERVICE)) { numberOfMasters++; } if (serviceMask.has(WireFormat::BACKUP_SERVICE)) { numberOfBackups++; pair.entry->expectedReadMBytesPerSec = readSpeed; } if (enqueueUpdate) { ProtoBuf::ServerList_Entry& protoBufEntry(*update.add_server()); pair.entry->serialize(protoBufEntry); foreach (ServerTrackerInterface* tracker, trackers) tracker->enqueueChange(*pair.entry, ServerChangeEvent::SERVER_ADDED); foreach (ServerTrackerInterface* tracker, trackers) tracker->fireCallback(); } } /** * Mark a server as crashed in the list (when it has crashed and is * being recovered and resources [replicas] for its recovery must be * retained). * * This is a no-op if the server is already marked as crashed; * the effect is undefined if the server's status is REMOVE. * * The result of this operation will be added in the class's update Protobuffer * intended for the cluster. To send out the update, call pushUpdate() * which will also increment the version number. Calls to remove() * and crashed() must proceed call to add() to ensure ordering guarantees * about notifications related to servers which re-enlist. * * It doesn't acquire locks and does not send out updates * since it is used internally. * * The addition will be pushed to all registered trackers and those with * callbacks will be notified. * * \param lock * Explicity needs CoordinatorServerList lock. * \param serverId * The ServerId of the server to remove from the CoordinatorServerList. * It must not have been removed already (see remove()). */ void CoordinatorServerList::crashed(const Lock& lock, ServerId serverId) { Entry* entry = getEntry(serverId); if (!entry) { throw ServerListException(HERE, format("Invalid ServerId (%s)", serverId.toString().c_str())); } if (entry->status == ServerStatus::CRASHED) return; assert(entry->status != ServerStatus::REMOVE); if (entry->isMaster()) numberOfMasters--; if (entry->isBackup()) numberOfBackups--; entry->status = ServerStatus::CRASHED; ProtoBuf::ServerList_Entry& protoBufEntry(*update.add_server()); entry->serialize(protoBufEntry); foreach (ServerTrackerInterface* tracker, trackers) tracker->enqueueChange(*entry, ServerChangeEvent::SERVER_CRASHED); foreach (ServerTrackerInterface* tracker, trackers) tracker->fireCallback(); } /** * Return the first free index in the server list. If the list is * completely full, resize it and return the next free one. * * Note that index 0 is reserved. This method must never return it. */ uint32_t CoordinatorServerList::firstFreeIndex() { // Naive, but probably fast enough for a good long while. size_t index; for (index = 1; index < serverList.size(); index++) { if (!serverList[index].entry) break; } if (index >= serverList.size()) serverList.resize(index + 1); assert(index != 0); return downCast<uint32_t>(index); } /** * Generate a new, unique ServerId that may later be assigned to a server * using add(). * * \param lock * Explicity needs CoordinatorServerList lock. * \return * The unique ServerId generated. */ ServerId CoordinatorServerList::generateUniqueId(Lock& lock) { uint32_t index = firstFreeIndex(); auto& pair = serverList[index]; ServerId id(index, pair.nextGenerationNumber); pair.nextGenerationNumber++; pair.entry.construct(id, "", ServiceMask()); return id; } /** * Serialize the entire list to a Protocol Buffer form. Only used internally in * CoordinatorServerList; requires a lock on #mutex is held for duration of call. * * \param lock * Unused, but required to statically check that the caller is aware that * a lock must be held on #mutex for this call to be safe. * \param[out] protoBuf * Reference to the ProtoBuf to fill. */ void CoordinatorServerList::serialize(const Lock& lock, ProtoBuf::ServerList& protoBuf) const { serialize(lock, protoBuf, {WireFormat::MASTER_SERVICE, WireFormat::BACKUP_SERVICE}); } /** * Serialize this list (or part of it, depending on which services the * caller wants) to a protocol buffer. Not all state is included, but * enough to be useful for disseminating cluster membership information * to other servers. Only used internally in CoordinatorServerList; requires * a lock on #mutex is held for duration of call. * * All entries are serialize to the protocol buffer in the order they appear * in the server list. The order has some important implications. See * ServerList::applyServerList() for details. * * \param lock * Unused, but required to statically check that the caller is aware that * a lock must be held on #mutex for this call to be safe. * \param[out] protoBuf * Reference to the ProtoBuf to fill. * \param services * If a server has *any* service included in \a services it will be * included in the serialization; otherwise, it is skipped. */ void CoordinatorServerList::serialize(const Lock& lock, ProtoBuf::ServerList& protoBuf, ServiceMask services) const { for (size_t i = 0; i < serverList.size(); i++) { if (!serverList[i].entry) continue; const Entry& entry = *serverList[i].entry; if ((entry.services.has(WireFormat::MASTER_SERVICE) && services.has(WireFormat::MASTER_SERVICE)) || (entry.services.has(WireFormat::BACKUP_SERVICE) && services.has(WireFormat::BACKUP_SERVICE))) { ProtoBuf::ServerList_Entry& protoBufEntry(*protoBuf.add_server()); entry.serialize(protoBufEntry); } } protoBuf.set_version_number(version); protoBuf.set_type(ProtoBuf::ServerList_Type_FULL_LIST); } /** * Assign a new replicationId to a backup, and inform the backup which nodes * are in its replication group. * * \param lock * Explicity needs CoordinatorServerList lock. * \param replicationId * New replication group Id that is assigned to backup. * \param replicationGroupIds * Includes the ServerId's of all the members of the replication group. * * \return * False if one of the servers is dead, true if all of them are alive. */ bool CoordinatorServerList::assignReplicationGroup( Lock& lock, uint64_t replicationId, const vector<ServerId>& replicationGroupIds) { foreach (ServerId backupId, replicationGroupIds) { Entry* e = getEntry(backupId); if (!e) { return false; } if (e->status == ServerStatus::UP) { ServerReplicationUpUpdate(*this, lock).execute(); ServerReplicationUpdate(*this, lock, e->serverId, e->masterRecoveryInfo, replicationId, version + 1).execute(); } } return true; } /** * Try to create a new replication group. Look for groups of backups that * are not assigned a replication group and are up. * If there are not enough available candidates for a new group, the function * returns without sending out any Rpcs. If there are enough group members * to form a new group, but one of the servers is down, hintServerCrashed will * reset the replication group of that server. * * \param lock * Explicity needs CoordinatorServerList lock. */ void CoordinatorServerList::createReplicationGroup(Lock& lock) { // Create a list of all servers who do not belong to a replication group // and are up. Note that this is a performance optimization and is not // required for correctness. vector<ServerId> freeBackups; for (size_t i = 0; i < isize(); i++) { if (serverList[i].entry && serverList[i].entry->isBackup() && serverList[i].entry->replicationId == 0) { freeBackups.push_back(serverList[i].entry->serverId); } } // TODO(cidon): The coordinator currently has no knowledge of the // replication factor, so we manually set the replication group size to 3. // We should make this parameter configurable. const uint32_t numReplicas = 3; vector<ServerId> group; while (freeBackups.size() >= numReplicas) { group.clear(); for (uint32_t i = 0; i < numReplicas; i++) { const ServerId& backupId = freeBackups.back(); group.push_back(backupId); freeBackups.pop_back(); } assignReplicationGroup(lock, nextReplicationId, group); nextReplicationId++; } } /** * Reset the replicationId for all backups with groupId. * * \param lock * Explicity needs CoordinatorServerList lock. * \param groupId * Replication group that needs to be reset. */ void CoordinatorServerList::removeReplicationGroup(Lock& lock, uint64_t groupId) { // Cannot remove groupId 0, since it is the default groupId. if (groupId == 0) { return; } vector<ServerId> group; for (size_t i = 0; i < isize(); i++) { if (serverList[i].entry && serverList[i].entry->isBackup() && serverList[i].entry->replicationId == groupId) { group.push_back(serverList[i].entry->serverId); } if (group.size() != 0) { assignReplicationGroup(lock, 0, group); } } } /** * Increments the server list version and notifies the async updater to * propagate the buffered Protobuf::ServerList update. The buffered update * will be Clear()ed and empty updates are silently ignored. * * \param lock * Explicity needs CoordinatorServerList lock. * \param updateVersion * Server list version number to be assigned to the update being pushed. */ void CoordinatorServerList::pushUpdate(const Lock& lock, uint64_t updateVersion) { ProtoBuf::ServerList full; // If there are no updates, don't generate a send. if (update.server_size() == 0) return; // prepare incremental server list update.set_version_number(updateVersion); update.set_type(ProtoBuf::ServerList_Type_UPDATE); // prepare full server list serialize(lock, full); updates.emplace_back(update, full); // Link the previous tail with the new tail in the deque. if (updates.size() > 1) (updates.end()-2)->next = &(updates.back()); hasUpdatesOrStop.notify_one(); update.Clear(); } /** * Stops the background updater. It cancel()'s all pending update rpcs * and leaves the cluster potentially out-of-date. To force a * synchronization point before halting, call sync() first. * * This will block until the updater thread stops. */ void CoordinatorServerList::haltUpdater() { // Signal stop Lock lock(mutex); stopUpdater = true; hasUpdatesOrStop.notify_one(); lock.unlock(); // Wait for Thread stop if (updaterThread && updaterThread->joinable()) { updaterThread->join(); updaterThread.destroy(); } } /** * Starts the background updater that keeps the cluster's * server lists up-to-date. */ void CoordinatorServerList::startUpdater() { Lock _(mutex); // Start thread if not started if (!updaterThread) { lastScan.reset(); stopUpdater = false; updaterThread.construct(&CoordinatorServerList::updateLoop, this); } // Tell it to start work regardless hasUpdatesOrStop.notify_one(); } /** * Checks if the cluster is up-to-date. * * \param lock * explicity needs CoordinatorServerList lock * \return * true if entire list is up-to-date */ bool CoordinatorServerList::isClusterUpToDate(const Lock& lock) { return (serverList.size() == 0) || (numUpdatingServers == 0 && minConfirmedVersion == version); } /** * Causes a deletion of server list updates that are no longer needed * by the coordinator serverlist. This will delete all updates older than * the CoordinatorServerList's current minConfirmedVersion. * * This is safe to invoke whenever, but is typically done so after a * new minConfirmedVersion is set. * * \param lock * explicity needs CoordinatorServerList lock */ void CoordinatorServerList::pruneUpdates(const Lock& lock) { if (minConfirmedVersion == UNINITIALIZED_VERSION) return; if (minConfirmedVersion > version) { LOG(ERROR, "Inconsistent state detected! CoordinatorServerList's " "minConfirmedVersion %lu is larger than it's current " "version %lu. This should NEVER happen!", minConfirmedVersion, version); // Reset minVersion in the hopes of it being a transient bug. minConfirmedVersion = 0; return; } if (minConfirmedVersion == version) { PersistServerListVersion(*this, lock, version).execute(); } while (!updates.empty() && updates.front().version <= minConfirmedVersion) { ProtoBuf::ServerList currentUpdate = updates.front().incremental; assert(currentUpdate.type() == ProtoBuf::ServerList::Type::ServerList_Type_UPDATE); for (int i = 0; i < currentUpdate.server().size(); i++) { ProtoBuf::ServerList::Entry currentEntry = currentUpdate.server(i); ServerStatus updateStatus = ServerStatus(currentEntry.status()); if (updateStatus == ServerStatus::UP) { // An enlistServer operation has successfully completed. if (context->logCabinHelper) { ServerId serverId = ServerId(currentEntry.server_id()); Entry* entry = getEntry(serverId); assert(entry != NULL); // We are relying on the fact that enlistServer has to be // sent out before the replication id update is sent out by // the coordinator, and therefore the order of // acknowledgement has to be in the same order. // Otherwise, the coordinator will invalidate the wrong // updates. bool isUpUpdate = true; if (entry->logIdServerUpUpdate != NO_ID) { vector<EntryId> invalidates {entry->logIdServerUpUpdate}; context->logCabinHelper->invalidate( *context->expectedEntryId, invalidates); } else { isUpUpdate = false; vector<EntryId> invalidates {entry->logIdServerReplicationUpUpdate}; context->logCabinHelper->invalidate( *context->expectedEntryId, invalidates); } if (isUpUpdate) { entry->logIdServerUpUpdate = NO_ID; } else { entry->logIdServerReplicationUpUpdate = NO_ID; } } } else if (updateStatus == ServerStatus::CRASHED) { // A serverCrashed operation has completed. The server that // crashed may be still recovering. // So we're not invalidating its LogCabin entries just yet. } else if (updateStatus == ServerStatus::REMOVE) { // This marks the final completion of serverCrashed() operation. // i.e., If the crashed server was a master, then its recovery // (sparked by a serverCrashed operation) has completed. // If it was not a master, then the serverCrashed operation // (which will not spark any recoveries) has completed. ServerId serverId = ServerId(currentEntry.server_id()); Tub<Entry>& entry = serverList[serverId.indexNumber()].entry; if (context->logCabinHelper) { assert(entry); vector<EntryId> invalidates { entry->logIdServerUp, entry->logIdServerCrashed, entry->logIdServerRemoveUpdate}; if (entry->logIdServerUpdate != NO_ID) invalidates.push_back(entry->logIdServerUpdate); context->logCabinHelper->invalidate( *context->expectedEntryId, invalidates); } entry.destroy(); } } updates.pop_front(); } if (updates.empty()) // Empty list = no updates to send listUpToDate.notify_all(); } /** * Blocks until all of the cluster is up-to-date. */ void CoordinatorServerList::sync() { startUpdater(); Lock lock(mutex); while (!isClusterUpToDate(lock)) { listUpToDate.wait(lock); } } /** * Main loop that checks for outdated servers and sends out update rpcs. * This is the top-level method of a dedicated thread separate from the * main coordinator's. * * Once invoked, this loop can be exited by calling haltUpdater() in another * thread. * * The Updater Loop manages starting, stopping, and following up on ServerList * Update RPCs asynchronous to the main thread with minimal locking of * Coordinator Server List, CSL. The intention of this mechanism is to * ensure that the critical sections of the CSL are not delayed while * waiting for RPCs to finish. * * Since Coordinator Server List houses all the information about updatable * servers, this mechanism requires at least two entry points (conceptual) * into the server list, a) a way to get info about outdated servers and b) * a way to signal update success/failure. The former is achieved via * getWork() and the latter is achieved by workSucceeded()/workFailed(). * For polling efficiency, there is an additional call, waitForWork(), that * will sleep until more servers get out of date. These are the only calls * that require locks on the Coordinator Server List that UpdateLoop uses. * Other than that, the updateLoop operates asynchronously from the CSL. * */ void CoordinatorServerList::updateLoop() { UpdaterWorkUnit wu; uint64_t max_rpcs = 8; std::deque<Tub<UpdateServerListRpc>> rpcs_backing; std::list<Tub<UpdateServerListRpc>*> rpcs; std::list<Tub<UpdateServerListRpc>*>::iterator it; /** * The Updater Loop manages a number of outgoing RPCs. The maximum number * of concurrent RPCs is determined dynamically in the hopes of finding a * sweet spot where the time to iterate through the list of outgoing RPCs * is roughly equivalent to the time of one RPC finishing. The heuristic * for doing this is simply only allowing one new RPC to be started with * each pass through the internal list of outgoing RPCs and allowing an * unlimited number to finish. The intuition for doing this is based on * the observation that checking whether an RPC is finished and finishing * it takes ~10-20ns whereas starting a new RPC takes much longer. Thus, * by limiting the number of RPCs started per iteration, we would allow * for rapid polling of unfinished RPCs and a rapid ramp up to the steady * state where roughly one RPC finishes per iteration. This is preferable * over trying start multiple new RPCs per iteration. * * The Updater keeps track of the outgoing RPCs internally in a * List<Tub<UpdateServerListRPC*>> that is organized as such: * * **************************************************.... * * Active RPCS * Inactive RPCs * Unused RPCs .... * ************************************************** * /\ max_rpcs * * Active RPCs are ones that have started but not finished. They are * compacted to the left so that scans through the list would look at * the active RPCs first. Inactive RPCs are ones that have not been * started and are allocated, unoccupied Tubs. Unused RPCs conceptually * represent RPCs that are unallocated and are outside the max_rpcs range. * * The division between Active RPCs and Inactive RPCs is defined as the * index where the first, leftmost unoccupied Tub resides. The division * between inactive and unused RPCs is the physical size of the list * which monotonically increases as the updater determines that more * RPCs need to be started. * * In normal operation, the Updater will start scanning through the list * left to right. Conceptually, the actions it takes would depend on * which region of the list it's in. In the active RPCs range, it will * check for finished RPCs. If it encounters one, it will clean up the * RPC and place its Tub at the back of the list to compact the active * range. Once in the inactive range, it will start up one new RPC and * continue on. * * At this point, the iteration will either still be in the inactive * range or it would have reached the max_rpcs marker (unused range). * If it's in the unused range, it will allocate more Tubs. Otherwise, * it will determine if the thread should sleep or not. The thread will * sleep when the active range is empty. */ try { while (!stopUpdater) { // Phase 0: Alloc more RPCs to fill max_rpcs. for (size_t i = rpcs.size(); i < max_rpcs && !stopUpdater; i++) { rpcs_backing.emplace_back(); rpcs.push_back(&rpcs_backing.back()); } // Phase 1: Scan through and compact active rpcs to the front. it = rpcs.begin(); while ( it != rpcs.end() && !stopUpdater ) { UpdateServerListRpc* rpc = (*it)->get(); // Reached end of active rpcs, enter phase 2. if (!rpc) break; // Skip not-finished rpcs if (!rpc->isReady()) { it++; continue; } // Finished rpc found bool success = false; try { rpc->wait(); success = true; } catch (const ServerNotUpException& e) {} if (success) workSuccess(rpc->id); else workFailed(rpc->id); (*it)->destroy(); // Compaction swap rpcs.push_back(*it); it = rpcs.erase(it); } // Phase 2: Start up to 1 new rpc if ( it != rpcs.end() && !stopUpdater ) { if (getWork(&wu)) { auto* initial_list = (wu.sendFullList) ? &(wu.firstUpdate->full) : &(wu.firstUpdate->incremental); (*it)->construct(context, wu.targetServer, initial_list); // Batch up multiple requests const ServerListUpdatePair* updatePtr = wu.firstUpdate; while (updatePtr->version < wu.updateVersionTail) { updatePtr = updatePtr->next; (**it)->appendServerList(&(updatePtr->incremental)); } (**it)->send(); it++; } } // Phase 3: Expand and/or stop if (it == rpcs.end()) { max_rpcs += 8; } else if (it == rpcs.begin()) { waitForWork(); } } // wend; stopUpdater = true for (size_t i = 0; i < rpcs_backing.size(); i++) { if (rpcs_backing[i]) { workFailed(rpcs_backing[i]->id); rpcs_backing[i]->cancel(); rpcs_backing[i].destroy(); } } } catch (const std::exception& e) { LOG(ERROR, "Fatal error in CoordinatorServerList: %s", e.what()); throw; } catch (...) { LOG(ERROR, "Unknown fatal error in CoordinatorServerList."); throw; } } /** * Invoked by the updater thread to wait (sleep) until there are * more updates. This will block until there is more updating work * to be done and will notify those waiting for the server list to * be up to date (if any). */ void CoordinatorServerList::waitForWork() { Lock lock(mutex); while (minConfirmedVersion == version && !stopUpdater) { listUpToDate.notify_all(); hasUpdatesOrStop.wait(lock); } } /** * Attempts to find servers that require updates that don't already * have outstanding update rpcs. * * This call MUST be followed by a workSuccuss or workFailed call * with the serverId contained within the WorkUnit at some point in * the future to ensure that internal metadata is reset for the work * unit so that the server can receive future updates. * * There is a contract that comes with call. All updates that come after- * and the update that starts on- the iterator in the WorkUnit is * GUARANTEED to be NOT deleted as long as a workSuccess or workFailed * is not invoked with the corresponding serverId in the WorkUnit. There * are no guarantees for updates that come before the iterator's starting * position, so don't iterate backwards. See documentation on UpdaterWorkUnit * for more info. * * \param wu * Work Unit that can be filled out by this method * * \return * true if an updatable server (work) was found * */ bool CoordinatorServerList::getWork(UpdaterWorkUnit* wu) { Lock lock(mutex); // Heuristic to prevent duplicate scans when no new work has shown up. if (serverList.size() == 0 || (numUpdatingServers > 0 && lastScan.noWorkFoundForEpoch == version)) return false; /** * Searches through the server list for servers that are eligible * for updates and are currently not updating. The former is defined as * the server having MEMBERSHIP_SERVICE, is UP, and has a verfiedVersion * not equal to the current version. The latter is defined as a server * having verfiedVersion == updateVersion. * * The search starts at lastScan.searchIndex, which is a marker for * where the last invocation of getWork() stopped before returning. * The search ends when either the entire server list has been scanned * (when we reach lastScan.searchIndex again) or when an outdated server * eligible for updates has been found. In the latter case, the function * will package the update details into a WorkUnit and mark the index it * left off on in lastScan.searchIndex. * * Updates get packed into WorkUnits as one would expect; servers that * haven't heard from the Coordinator get one full list and those that * have get a batch of incremental updates. One peculiarity is the version * of the full list. If the work unit was created during the first scan * through the server list, the lowest version is used. Otherwise, the * latest server list is used. * * The reason for this is because when the updater thread stops or the * coordinator crashes, update rpcs may be prematurely canceled. Some * servers may have actually gotten a full list and applied it but could * not respond in time. Thus, to prevent sending servers a newer full * server list they can't process, we send the oldest server list on the * first scan through the server list and then later patch it up to date * with a batch of incremental updates. This is called 'slow start.' * * While scanning, the loop will also keep track of the minimum * verifiedVersion in the server list and will propagate this * value to minConfirmedVersion. This is done to track whether * the server list is up to date and which old updates, which * are guaranteed to never be used again, can be pruned. The * propagation occurs only when the minVersion in the scan is * interesting, i.e. not MAX64 and not UNINITIALIZED_VERSION. * The former means that there are no updatable servers and the * latter means there are updatable servers with uninitialized * server lists. Neither contribute to the knowledge of what * the minimum server list version in the cluster is and what * can be pruned. */ size_t i = lastScan.searchIndex; uint64_t numUpdatableServers = 0; do { Entry* server = serverList[i].entry.get(); // Does server exist and is it updatable? if (server && server->status == ServerStatus::UP && server->services.has(WireFormat::MEMBERSHIP_SERVICE)) { // Record Stats numUpdatableServers++; if (server->verifiedVersion < lastScan.minVersion) { lastScan.minVersion = server->verifiedVersion; } // update required if (server->updateVersion != version && server->updateVersion == server->verifiedVersion) { // New server, send full server list if (server->verifiedVersion == UNINITIALIZED_VERSION) { wu->sendFullList = true; // 'slow start' if (lastScan.completeScansSinceStart == 0) { wu->firstUpdate = &(updates.front()); } else { wu->firstUpdate = &(updates.back()); } } else { // Incremental update(s). wu->sendFullList = false; uint64_t firstVersion = server->verifiedVersion + 1; size_t offset = firstVersion - updates.front().version; wu->firstUpdate = &*(updates.begin()+=offset); } wu->targetServer = server->serverId; wu->updateVersionTail = std::min(version, wu->firstUpdate->version + MAX_UPDATES_PER_RPC-1); numUpdatingServers++; lastScan.searchIndex = i; server->updateVersion = wu->updateVersionTail; return true; } } i = (i+1)%serverList.size(); // update statistics if (i == 0) { // Record min version only if it's interesting if ( lastScan.minVersion != UNINITIALIZED_VERSION && lastScan.minVersion != MAX64) minConfirmedVersion = lastScan.minVersion; lastScan.completeScansSinceStart++; lastScan.minVersion = MAX64; pruneUpdates(lock); } // While we haven't reached a full scan through the list yet. } while (i != lastScan.searchIndex); // If no one is updating, then it's safe to prune ALL updates. if (numUpdatableServers == 0) { minConfirmedVersion = version; pruneUpdates(lock); } lastScan.noWorkFoundForEpoch = version; return false; } /** * Signals the success of updater to complete a work unit. This * will update internal metadata to allow the server described by * the work unit to be updatable again. * * Note that this should only be invoked AT MOST ONCE for each WorkUnit. * * \param id * The serverId originally contained in the work unit * that just succeeded. */ void CoordinatorServerList::workSuccess(ServerId id) { Lock lock(mutex); // Error checking for next 3 blocks if (numUpdatingServers > 0) { numUpdatingServers--; } else { LOG(ERROR, "Bookeeping issue detected; server's count of " "numUpdatingServers just went negative. Not total failure " "but will cause the updater thread to spin even w/o work. " "Cause is mismatch # of getWork() and workSuccess/Failed()"); } Entry* server = getEntry(id); if (server == NULL) { // Typically not an error, but this is UNUSUAL in normal cases. LOG(DEBUG, "Server %s responded to a server list update but " "is no longer in the server list...", id.toString().c_str()); return; } if (server->verifiedVersion == server->updateVersion) { LOG(ERROR, "Invoked for server %s even though either no update " "was sent out or it has already been invoked. Possible " "race/bookeeping issue.", server->serverId.toString().c_str()); } else { // Meat of actual functionality LOG(DEBUG, "ServerList Update Success: %s update (%ld => %ld)", server->serverId.toString().c_str(), server->verifiedVersion, server->updateVersion); server->verifiedVersion = server->updateVersion; } // If update didn't update all the way or it's the last server updating, // hint for a full scan to update minConfirmedVersion. if (server->verifiedVersion < version) lastScan.noWorkFoundForEpoch = 0; } /** * Signals the failure of the updater to execute a work unit. Causes * an internal rollback on metadata so that the server involved will * be retried later. * * \param id * The serverId contained within the work unit that the updater * had failed to send out. */ void CoordinatorServerList::workFailed(ServerId id) { Lock lock(mutex); if (numUpdatingServers > 0) { numUpdatingServers--; } else { LOG(ERROR, "Bookeeping issue detected; server's count of " "numUpdatingServers just went negative. Not total failure " "but will cause the updater thread to spin even w/o work. " "Cause is mismatch # of getWork() and workSuccess/Failed()"); } Entry* server = getEntry(id); if (server) { server->updateVersion = server->verifiedVersion; LOG(DEBUG, "ServerList Update Failed : %s update (%ld => %ld)", server->serverId.toString().c_str(), server->verifiedVersion, server->updateVersion); } lastScan.noWorkFoundForEpoch = 0; } ////////////////////////////////////////////////////////////////////// // CoordinatorServerList::UpdateServerListRpc Methods ////////////////////////////////////////////////////////////////////// /** * Constructor for UpdateServerListRpc that creates but does not send() * a server list update rpc. It initially accepts one protobuf to ensure * that the rpc would never be sent empty and provides a convenient way to * send only a single full list. * * After invoking the constructor, it is up to the caller to invoke * as many appendServerList() calls as necessary to batch up multiple * updates and follow it up with a send(). * * \param context * Overall information about this RAMCloud server. * \param serverId * Identifies the server to which this update should be sent. * \param list * The complete server list representing all cluster membership. */ CoordinatorServerList::UpdateServerListRpc::UpdateServerListRpc( Context* context, ServerId serverId, const ProtoBuf::ServerList* list) : ServerIdRpcWrapper(context, serverId, sizeof(WireFormat::UpdateServerList::Response)) { allocHeader<WireFormat::UpdateServerList>(serverId); auto* part = new(&request, APPEND) WireFormat::UpdateServerList::Request::Part(); part->serverListLength = serializeToRequest(&request, list); } /** * Appends a server list update ProtoBuf to the request rpc. This is used * to batch up multiple server list updates into one rpc for the server and * can be invoked multiple times on the same rpc. * * It is the caller's responsibility invoke send() on the rpc when enough * updates have been appended and to ensure that this append is invoked only * when the RPC has not been started yet. * * \param list * ProtoBuf::ServerList to append to the new RPC * \return * true if append succeeded, false if it didn't fit in the current rpc * and has been removed. In the later case, it's time to call send(). */ bool CoordinatorServerList::UpdateServerListRpc::appendServerList( const ProtoBuf::ServerList* list) { assert(this->getState() == NOT_STARTED); uint32_t sizeBefore = request.getTotalLength(); auto* part = new(&request, APPEND) WireFormat::UpdateServerList::Request::Part(); part->serverListLength = serializeToRequest(&request, list); uint32_t sizeAfter = request.getTotalLength(); if (sizeAfter > Transport::MAX_RPC_LEN) { request.truncateEnd(sizeAfter - sizeBefore); return false; } return true; } ////////////////////////////////////////////////////////////////////// // CoordinatorServerList::Entry Methods ////////////////////////////////////////////////////////////////////// /** * Construct a new Entry, which contains no valid information. */ CoordinatorServerList::Entry::Entry() : ServerDetails() , masterRecoveryInfo() , needsRecovery(false) , verifiedVersion(UNINITIALIZED_VERSION) , updateVersion(UNINITIALIZED_VERSION) , logIdServerCrashed(NO_ID) , logIdServerNeedsRecovery(NO_ID) , logIdServerRemoveUpdate(NO_ID) , logIdServerUp(NO_ID) , logIdServerUpdate(NO_ID) , logIdServerUpUpdate(NO_ID) , logIdServerReplicationUpdate(NO_ID) , logIdServerReplicationUpUpdate(NO_ID) { } /** * Construct a new Entry, which contains the data a coordinator * needs to maintain about an enlisted server. * * \param serverId * The ServerId of the server this entry describes. * * \param serviceLocator * The ServiceLocator string that can be used to address this * entry's server. * * \param services * Which services this server supports. */ CoordinatorServerList::Entry::Entry(ServerId serverId, const string& serviceLocator, ServiceMask services) : ServerDetails(serverId, serviceLocator, services, 0, ServerStatus::UP) , masterRecoveryInfo() , needsRecovery(false) , verifiedVersion(UNINITIALIZED_VERSION) , updateVersion(UNINITIALIZED_VERSION) , logIdServerCrashed(NO_ID) , logIdServerNeedsRecovery(NO_ID) , logIdServerRemoveUpdate(NO_ID) , logIdServerUp(NO_ID) , logIdServerUpdate(NO_ID) , logIdServerUpUpdate(NO_ID) , logIdServerReplicationUpdate(NO_ID) , logIdServerReplicationUpUpdate(NO_ID) { } /** * Serialize this entry into the given ProtoBuf. */ void CoordinatorServerList::Entry::serialize(ProtoBuf::ServerList_Entry& dest) const { dest.set_services(services.serialize()); dest.set_server_id(serverId.getId()); dest.set_service_locator(serviceLocator); dest.set_status(uint32_t(status)); if (isBackup()) dest.set_expected_read_mbytes_per_sec(expectedReadMBytesPerSec); else dest.set_expected_read_mbytes_per_sec(0); // Tests expect the field. dest.set_replication_id(replicationId); } } // namespace RAMCloud
35.381907
81
0.658199
taschik
070e227492af93823042ca32da4c98d057bebc36
1,155
cpp
C++
d639.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
d639.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
d639.cpp
puyuliao/ZJ-d879
bead48e0a500f21bc78f745992f137706d15abf8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <stdint.h> #define IOS {cin.tie(0); ios_base::sync_with_stdio(false);} using namespace std; #define MOD 10007 int in[3][1] = {1,1,1}; int a[3][3] = { {1,1,1}, {1,0,0}, {0,1,0} }; int ans[3][3]; void smul(int cmd,int n){ int c[n][n]; memset(c,0,sizeof(c)); if(cmd==1){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ c[i][j] += a[i][k]*ans[k][j]; c[i][j] %= MOD; } } } memcpy(ans,c,n*n<<2); } else{ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ for(int k=0;k<n;k++){ c[i][j] += a[i][k]*a[k][j]; c[i][j] %= MOD; } } } memcpy(a,c,n*n<<2); } } int main() { int n; cin >> n; if(n<4) cout << 1; else{ for(int i=0;i<3;i++) ans[i][i]=1; int b = n-3; for(;b;b>>=1){ if(b&1){ smul(1,3); } smul(2,3); } int tmp[3][1]; memset(tmp,0,sizeof(tmp)); for(int i=0;i<3;i++){ for(int j=0;j<1;j++){ for(int k=0;k<3;k++){ tmp[i][j] += ans[i][k]*in[k][j]; tmp[i][j] %= MOD; } } } cout << tmp[0][0]; } return 0; }
15.608108
60
0.415584
puyuliao
071654015793756e32bc9eb08a7b895030ceeca0
1,780
cpp
C++
day07/main.cpp
LMesaric/AoC-2021
134f52c69675fd4f1b8d04aad9debcf82e604911
[ "MIT" ]
5
2021-12-01T22:34:33.000Z
2021-12-25T11:34:13.000Z
day07/main.cpp
LMesaric/AoC-2021
134f52c69675fd4f1b8d04aad9debcf82e604911
[ "MIT" ]
null
null
null
day07/main.cpp
LMesaric/AoC-2021
134f52c69675fd4f1b8d04aad9debcf82e604911
[ "MIT" ]
null
null
null
#include <algorithm> #include <cassert> #include <iostream> #include <numeric> #include <sstream> #include <vector> std::vector<int32_t> parseInput() { std::string line; std::getline(std::cin, line); std::stringstream ss(line); std::vector<int32_t> positions; for (int32_t i; ss >> i;) { positions.push_back(i); if (ss.peek() != ',') break; ss.ignore(); } return positions; } int32_t findMedian(std::vector<int32_t> &values) { std::sort(values.begin(), values.end()); return values[values.size() / 2]; } int32_t sumDistancesLinear(std::vector<int32_t> &values, int32_t p) { int32_t sum = 0; for (const auto v: values) sum += abs(p - v); return sum; } int64_t sumDistancesQuadratic(std::vector<int32_t> &values, int32_t p) { int64_t sum = 0; for (const auto v: values) { const auto dist = abs(p - v); sum += dist * (dist + 1); } return sum / 2; } int32_t calculateFirstTask(std::vector<int32_t> &positions) { const auto median = findMedian(positions); return sumDistancesLinear(positions, median); } int64_t calculateSecondTask(std::vector<int32_t> &positions) { const double sum = std::accumulate(positions.begin(), positions.end(), 0); const double avg = sum / positions.size(); return std::min( sumDistancesQuadratic(positions, floor(avg)), sumDistancesQuadratic(positions, ceil(avg)) ); } int main() { auto positions = parseInput(); auto resultOne = calculateFirstTask(positions); assert(resultOne == 355150); std::cout << resultOne << std::endl; auto resultTwo = calculateSecondTask(positions); assert(resultTwo == 98368490); std::cout << resultTwo << std::endl; }
25.428571
78
0.632022
LMesaric
0717e18e0d1418347b37c6001e9ec780e45ab8c6
594
cxx
C++
Code/Graph/testGraph.cxx
konny0311/algorithms-nutshell-2ed
760b0b8a296fb6be923c89406f61e773a48c59db
[ "MIT" ]
522
2016-02-21T18:44:23.000Z
2022-03-31T09:29:04.000Z
Code/Graph/testGraph.cxx
linfachen/algorithms-nutshell-2ed
17bd6e9cf9917727501f9eeadbfb2100f94eede0
[ "MIT" ]
3
2020-04-09T01:52:52.000Z
2022-01-13T08:18:55.000Z
Code/Graph/testGraph.cxx
linfachen/algorithms-nutshell-2ed
17bd6e9cf9917727501f9eeadbfb2100f94eede0
[ "MIT" ]
216
2015-10-16T16:50:10.000Z
2022-02-10T00:57:20.000Z
/** * @file Graph/testGraph.cxx Sample (and Simple!) graph tests. * @brief * Just a few test cases. Not too much here, really. * * @author George Heineman * @date 6/15/08 */ #include <iostream> #include <assert.h> #include "Graph.h" /** Launch the tests. */ int main () { Graph g (3,false); g.addEdge (0, 1); g.addEdge (0, 2); g.addEdge (1, 2); assert (g.isEdge (0,1)); g.removeEdge (1,0); assert (!g.isEdge (0,1)); g.addEdge (0, 1); g.addEdge (0, 1); assert (g.isEdge (0,1)); g.removeEdge (0,1); assert (!g.isEdge (0,1)); cout << "Passed Test\n"; }
18
64
0.577441
konny0311
0718c00818e0f711b465c54464e451619c0c61d2
30,427
cpp
C++
src/zimg/graph/filtergraph.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
src/zimg/graph/filtergraph.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
src/zimg/graph/filtergraph.cpp
dubhater/zimg
59ca0556789656a439f32b4cdfc8e26db32b8252
[ "WTFPL" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdint> #include <vector> #include "common/align.h" #include "common/alloc.h" #include "common/except.h" #include "common/make_unique.h" #include "common/pixel.h" #include "common/zassert.h" #include "basic_filter.h" #include "filtergraph.h" #include "image_filter.h" namespace zimg { namespace graph { namespace { class ColorExtendFilter : public CopyFilter { bool m_rgb; public: ColorExtendFilter(const image_attributes &attr, bool rgb) : CopyFilter{ attr.width, attr.height, attr.type }, m_rgb{ rgb } { } filter_flags get_flags() const override { filter_flags flags = CopyFilter::get_flags(); flags.in_place = false; flags.color = true; return flags; } void process(void *, const ImageBuffer<const void> src[], const ImageBuffer<void> dst[], void *, unsigned i, unsigned left, unsigned right) const override { CopyFilter::process(nullptr, src, dst + 0, nullptr, i, left, right); if (m_rgb) { CopyFilter::process(nullptr, src, dst + 1, nullptr, i, left, right); CopyFilter::process(nullptr, src, dst + 2, nullptr, i, left, right); } } }; class ChromaInitializeFilter : public ImageFilterBase { image_attributes m_attr; unsigned m_subsample_w; unsigned m_subsample_h; union { uint8_t b; uint16_t w; float f; } m_value; template <class T> void fill(T *ptr, const T &val, unsigned left, unsigned right) const { std::fill(ptr + left, ptr + right, val); } public: ChromaInitializeFilter(image_attributes attr, unsigned subsample_w, unsigned subsample_h, unsigned depth) : m_attr{ attr.width >> subsample_w, attr.height >> subsample_h, attr.type }, m_subsample_w{ subsample_w }, m_subsample_h{ subsample_h }, m_value{} { if (attr.type == PixelType::BYTE) m_value.b = static_cast<uint8_t>(1U << (depth - 1)); else if (attr.type == PixelType::WORD) m_value.w = static_cast<uint8_t>(1U << (depth - 1)); else if (attr.type == PixelType::HALF) m_value.w = 0; else if (attr.type == PixelType::FLOAT) m_value.f = 0.0f; } filter_flags get_flags() const override { filter_flags flags{}; flags.same_row = true; flags.in_place = true; return flags; } image_attributes get_image_attributes() const override { return m_attr; } pair_unsigned get_required_row_range(unsigned i) const { return{ i << m_subsample_h, (i + 1) << m_subsample_h }; } pair_unsigned get_required_col_range(unsigned left, unsigned right) const { return{ left << m_subsample_w, right << m_subsample_w }; } void process(void *, const ImageBuffer<const void> src[], const ImageBuffer<void> dst[], void *, unsigned i, unsigned left, unsigned right) const override { void *dst_p = (*dst)[i]; if (m_attr.type == PixelType::BYTE) fill(static_cast<uint8_t *>(dst_p), m_value.b, left, right); else if (m_attr.type == PixelType::WORD || m_attr.type == PixelType::HALF) fill(static_cast<uint16_t *>(dst_p), m_value.w, left, right); else if (m_attr.type == PixelType::FLOAT) fill(static_cast<float *>(dst_p), m_value.f, left, right); } }; class SimulationState { std::vector<unsigned> m_cache_pos; public: explicit SimulationState(unsigned size) : m_cache_pos(size) { } unsigned &pos(unsigned id) { return m_cache_pos[id]; } }; class ExecutionState { LinearAllocator m_alloc; const ImageBuffer<const void> *m_src_buf; const ImageBuffer<void> *m_dst_buf; FilterGraph::callback m_unpack_cb; FilterGraph::callback m_pack_cb; void **m_context_table; void *m_base; public: ExecutionState(unsigned id_counter, const ImageBuffer<const void> src_buf[], const ImageBuffer<void> dst_buf[], void *pool, FilterGraph::callback unpack_cb, FilterGraph::callback pack_cb) : m_alloc{ pool }, m_src_buf{ src_buf }, m_dst_buf{ dst_buf }, m_unpack_cb{ unpack_cb }, m_pack_cb{ pack_cb }, m_context_table{}, m_base{ pool } { m_context_table = m_alloc.allocate_n<void *>(id_counter); std::fill_n(m_context_table, id_counter, nullptr); } void *alloc_context(unsigned id, size_t size) { _zassert(!m_context_table[id], "context already allocated"); m_context_table[id] = m_alloc.allocate(size); return m_context_table[id]; } void *get_context(unsigned id) const { return m_context_table[id]; } const ImageBuffer<const void> *get_input_buffer() const { return m_src_buf; } const ImageBuffer<void> *get_output_buffer() const { return m_dst_buf; } void *get_tmp() const { return static_cast<char *>(m_base) + m_alloc.count(); } FilterGraph::callback get_unpack_cb() const { return m_unpack_cb; } FilterGraph::callback get_pack_cb() const { return m_pack_cb; } static size_t context_table_size(unsigned id_counter) { return ceil_n(sizeof(void *) * id_counter, ALIGNMENT); } }; class GraphNode { protected: struct node_context { static const uint64_t GUARD_PATTERN = 0xDEADBEEFDEADBEEFULL; const uint64_t guard_pattern = GUARD_PATTERN; unsigned cache_pos; unsigned source_left; unsigned source_right; void assert_guard_pattern() const { _zassert(guard_pattern == GUARD_PATTERN, "buffer overflow detected"); } }; private: unsigned m_id; unsigned m_ref_count; unsigned m_cache_lines; protected: GraphNode(unsigned id) : m_id{ id }, m_ref_count{}, m_cache_lines{} { } unsigned get_id() const { return m_id; } unsigned get_real_cache_lines() const { return get_cache_lines() == BUFFER_MAX ? get_image_attributes(false).height : get_cache_lines(); } ptrdiff_t get_cache_stride() const { auto attr = get_image_attributes(false); return ceil_n(attr.width * pixel_size(attr.type), ALIGNMENT); } void set_cache_lines(unsigned n) { if (n > m_cache_lines) { if (n >= get_image_attributes().height) m_cache_lines = BUFFER_MAX; else m_cache_lines = select_zimg_buffer_mask(n) + 1; } } void init_context_base(node_context *ctx) const { ctx->cache_pos = 0; ctx->source_left = 0; ctx->source_right = 0; } void reset_context_base(node_context *ctx) const { auto attr = get_image_attributes(false); ctx->cache_pos = 0; ctx->source_left = attr.width; ctx->source_right = 0; } public: virtual ~GraphNode() = default; unsigned add_ref() { return ++m_ref_count; } unsigned get_ref() const { return m_ref_count; } unsigned get_cache_lines() const { return m_cache_lines; } virtual ImageFilter::image_attributes get_image_attributes(bool uv = false) const = 0; virtual bool entire_row() const = 0; virtual void simulate(SimulationState *sim, unsigned first, unsigned last, bool uv = false) = 0; virtual size_t get_context_size() const = 0; virtual size_t get_tmp_size(unsigned left, unsigned right) const = 0; virtual void init_context(ExecutionState *state) const = 0; virtual void reset_context(ExecutionState *state) const = 0; virtual void set_tile_region(ExecutionState *state, unsigned left, unsigned right, bool uv) const = 0; virtual const ImageBuffer<const void> *generate_line(ExecutionState *state, const ImageBuffer<void> *external, unsigned i, bool uv) const = 0; }; class SourceNode final : public GraphNode { ImageFilter::image_attributes m_attr; unsigned m_subsample_w; unsigned m_subsample_h; bool m_color; public: SourceNode(unsigned id, unsigned width, unsigned height, PixelType type, unsigned subsample_w, unsigned subsample_h, bool color) : GraphNode(id), m_attr{ width, height, type }, m_subsample_w{ subsample_w }, m_subsample_h{ subsample_h }, m_color{ color } { } ImageFilter::image_attributes get_image_attributes(bool uv) const override { auto attr = m_attr; if (uv) { attr.width >>= m_subsample_w; attr.height >>= m_subsample_h; } return attr; } bool entire_row() const override { return false; } void simulate(SimulationState *sim, unsigned first, unsigned last, bool uv) override { unsigned step = 1 << m_subsample_h; unsigned pos = sim->pos(get_id()); first <<= uv ? m_subsample_h : 0; last <<= uv ? m_subsample_h : 0; if (pos < last) pos = floor_n(last - 1, step) + step; sim->pos(get_id()) = pos; set_cache_lines(pos - first); } size_t get_context_size() const override { return ceil_n(sizeof(node_context), zimg::ALIGNMENT); } size_t get_tmp_size(unsigned left, unsigned right) const override { return 0; } void init_context(ExecutionState *state) const override { size_t context_size = get_context_size(); LinearAllocator alloc{ state->alloc_context(get_id(), get_context_size()) }; node_context *context = new (alloc.allocate_n<node_context>(1)) node_context{}; init_context_base(context); _zassert(alloc.count() <= context_size, "buffer overflow detected"); _zassert_d(alloc.count() == context_size, "allocation mismatch"); } void reset_context(ExecutionState *state) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); reset_context_base(context); } void set_tile_region(ExecutionState *state, unsigned left, unsigned right, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); if (uv) { left <<= m_subsample_w; right <<= m_subsample_w; } context->source_left = std::min(context->source_left, left); context->source_right = std::max(context->source_right, right); } const ImageBuffer<const void> *generate_line(ExecutionState *state, const ImageBuffer<void> *external, unsigned i, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); unsigned step = 1 << m_subsample_h; unsigned line = uv ? i * step : i; unsigned pos = context->cache_pos; if (line >= pos) { if (state->get_unpack_cb()) { for (; pos <= line; pos += step) { state->get_unpack_cb()(pos, context->source_left, context->source_right); } } else { pos = floor_n(line, step) + step; } context->cache_pos = pos; } return static_buffer_cast<const void>(state->get_input_buffer()); } }; class FilterNode final : public GraphNode { struct node_context : public GraphNode::node_context { void *filter_ctx; ImageBuffer<void> cache_buf[3]; }; std::unique_ptr<ImageFilter> m_filter; ImageFilter::filter_flags m_flags; GraphNode *m_parent; GraphNode *m_parent_uv; unsigned m_step; unsigned get_num_planes() const { return m_flags.color ? 3U : 1U; } public: FilterNode(unsigned id, std::unique_ptr<ImageFilter> &&filter, GraphNode *parent, GraphNode *parent_uv) : GraphNode(id), m_flags(filter->get_flags()), m_parent{ parent }, m_parent_uv{ parent_uv }, m_step{ filter->get_simultaneous_lines() } { m_filter = std::move(filter); } ImageFilter::image_attributes get_image_attributes(bool) const override { return m_filter->get_image_attributes(); } bool entire_row() const override { return m_flags.entire_row || m_parent->entire_row() || (m_parent_uv && m_parent_uv->entire_row()); } void simulate(SimulationState *sim, unsigned first, unsigned last, bool) override { unsigned pos = sim->pos(get_id()); for (; pos < last; pos += m_step) { auto range = m_filter->get_required_row_range(pos); m_parent->simulate(sim, range.first, range.second, false); if (m_parent_uv) m_parent_uv->simulate(sim, range.first, range.second, true); } sim->pos(get_id()) = pos; set_cache_lines(pos - first); } size_t get_context_size() const override { FakeAllocator alloc; alloc.allocate_n<node_context>(1); unsigned num_planes = get_num_planes(); unsigned cache_lines = get_real_cache_lines(); ptrdiff_t stride = get_cache_stride(); alloc.allocate((size_t)num_planes * cache_lines * stride); alloc.allocate(m_filter->get_context_size()); return alloc.count(); } size_t get_tmp_size(unsigned left, unsigned right) const override { size_t tmp_size = 0; auto range = m_filter->get_required_col_range(left, right); tmp_size = std::max(tmp_size, m_filter->get_tmp_size(left, right)); tmp_size = std::max(tmp_size, m_parent->get_tmp_size(range.first, range.second)); if (m_parent_uv) tmp_size = std::max(tmp_size, m_parent_uv->get_tmp_size(range.first, range.second)); return tmp_size; } void init_context(ExecutionState *state) const override { size_t context_size = get_context_size(); LinearAllocator alloc{ state->alloc_context(get_id(), context_size) }; node_context *context = new (alloc.allocate_n<node_context>(1)) node_context{}; init_context_base(context); ptrdiff_t stride = get_cache_stride(); unsigned cache_lines = get_real_cache_lines(); unsigned mask = select_zimg_buffer_mask(get_cache_lines()); context->filter_ctx = alloc.allocate(m_filter->get_context_size()); for (unsigned p = 0; p < get_num_planes(); ++p) { context->cache_buf[p] = ImageBuffer<void>{ alloc.allocate((size_t)cache_lines * stride), stride, mask }; } _zassert(alloc.count() <= context_size, "buffer overflow detected"); _zassert_d(alloc.count() == context_size, "allocation mismatch"); } void reset_context(ExecutionState *state) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); reset_context_base(context); m_filter->init_context(context->filter_ctx); } void set_tile_region(ExecutionState *state, unsigned left, unsigned right, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); auto range = m_filter->get_required_col_range(left, right); m_parent->set_tile_region(state, range.first, range.second, false); if (m_parent_uv) m_parent_uv->set_tile_region(state, range.first, range.second, true); context->source_left = std::min(context->source_left, left); context->source_right = std::max(context->source_right, right); } const ImageBuffer<const void> *generate_line(ExecutionState *state, const ImageBuffer<void> *external, unsigned i, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); const ImageBuffer<void> *output_buffer = external ? external : context->cache_buf; unsigned pos = context->cache_pos; for (; pos <= i; pos += m_step) { const ImageBuffer<const void> *input_buffer = nullptr; const ImageBuffer<const void> *input_buffer_uv = nullptr; auto range = m_filter->get_required_row_range(pos); _zassert_d(range.first < range.second, "bad row range"); for (unsigned ii = range.first; ii < range.second; ++ii) { input_buffer = m_parent->generate_line(state, nullptr, ii, false); if (m_parent_uv) input_buffer_uv = m_parent_uv->generate_line(state, nullptr, ii, true); } if (m_parent_uv) { ImageBuffer<const void> input_buffer_yuv[3] = { input_buffer[0], input_buffer_uv[1], input_buffer_uv[2] }; m_filter->process(context->filter_ctx, input_buffer_yuv, output_buffer, state->get_tmp(), pos, context->source_left, context->source_right); } else { m_filter->process(context->filter_ctx, input_buffer, output_buffer, state->get_tmp(), pos, context->source_left, context->source_right); } } context->cache_pos = pos; return static_buffer_cast<const void>(output_buffer); } }; class FilterNodeUV final : public GraphNode { struct node_context : public GraphNode::node_context { void *filter_ctx_u; void *filter_ctx_v; ImageBuffer<void> cache_buf[3]; }; std::unique_ptr<ImageFilter> m_filter; ImageFilter::filter_flags m_flags; GraphNode *m_parent; unsigned m_step; unsigned get_num_planes() const { return 2; } public: FilterNodeUV(unsigned id, std::unique_ptr<ImageFilter> &&filter, GraphNode *parent) : GraphNode(id), m_flags(filter->get_flags()), m_parent{ parent }, m_step{ filter->get_simultaneous_lines() } { m_filter = std::move(filter); } ImageFilter::image_attributes get_image_attributes(bool) const override { return m_filter->get_image_attributes(); } bool entire_row() const override { return m_flags.entire_row || m_parent->entire_row(); } void simulate(SimulationState *sim, unsigned first, unsigned last, bool) override { unsigned pos = sim->pos(get_id()); for (; pos < last; pos += m_step) { auto range = m_filter->get_required_row_range(pos); m_parent->simulate(sim, range.first, range.second, true); } sim->pos(get_id()) = pos; set_cache_lines(pos - first); } size_t get_context_size() const override { FakeAllocator alloc; alloc.allocate_n<node_context>(1); unsigned num_planes = get_num_planes(); unsigned cache_lines = get_real_cache_lines(); ptrdiff_t stride = get_cache_stride(); alloc.allocate((size_t)num_planes * cache_lines * stride); alloc.allocate(m_filter->get_context_size()); alloc.allocate(m_filter->get_context_size()); return alloc.count(); } size_t get_tmp_size(unsigned left, unsigned right) const override { size_t tmp_size = 0; auto range = m_filter->get_required_col_range(left, right); tmp_size = std::max(tmp_size, m_filter->get_tmp_size(left, right)); tmp_size = std::max(tmp_size, m_parent->get_tmp_size(range.first, range.second)); return tmp_size; } void init_context(ExecutionState *state) const override { size_t context_size = get_context_size(); LinearAllocator alloc{ state->alloc_context(get_id(), context_size) }; node_context *context = new (alloc.allocate_n<node_context>(1)) node_context{}; init_context_base(context); ptrdiff_t stride = get_cache_stride(); unsigned cache_lines = get_real_cache_lines(); unsigned mask = select_zimg_buffer_mask(get_cache_lines()); context->filter_ctx_u = alloc.allocate(m_filter->get_context_size()); context->filter_ctx_v = alloc.allocate(m_filter->get_context_size()); context->cache_buf[1] = ImageBuffer<void>{ alloc.allocate((size_t)cache_lines * stride), stride, mask }; context->cache_buf[2] = ImageBuffer<void>{ alloc.allocate((size_t)cache_lines * stride), stride, mask }; _zassert(alloc.count() <= context_size, "buffer overflow detected"); _zassert_d(alloc.count() == context_size, "allocation mismatch"); } void reset_context(ExecutionState *state) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); reset_context_base(context); m_filter->init_context(context->filter_ctx_u); m_filter->init_context(context->filter_ctx_v); } void set_tile_region(ExecutionState *state, unsigned left, unsigned right, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); auto range = m_filter->get_required_col_range(left, right); m_parent->set_tile_region(state, range.first, range.second, true); context->source_left = std::min(context->source_left, left); context->source_right = std::max(context->source_right, right); } const ImageBuffer<const void> *generate_line(ExecutionState *state, const ImageBuffer<void> *external, unsigned i, bool uv) const override { node_context *context = static_cast<node_context *>(state->get_context(get_id())); context->assert_guard_pattern(); const ImageBuffer<void> *output_buffer = external ? external : context->cache_buf; unsigned pos = context->cache_pos; for (; pos <= i; pos += m_step) { const ImageBuffer<const void> *input_buffer = nullptr; auto range = m_filter->get_required_row_range(pos); _zassert_d(range.first < range.second, "bad row range"); for (unsigned ii = range.first; ii < range.second; ++ii) { input_buffer = m_parent->generate_line(state, nullptr, ii, true); } m_filter->process(context->filter_ctx_u, input_buffer + 1, output_buffer + 1, state->get_tmp(), pos, context->source_left, context->source_right); m_filter->process(context->filter_ctx_v, input_buffer + 2, output_buffer + 2, state->get_tmp(), pos, context->source_left, context->source_right); } context->cache_pos = pos; return static_buffer_cast<const void>(output_buffer); } }; } // namespace class FilterGraph::impl { static const unsigned HORIZONTAL_STEP = 512; static const unsigned TILE_MIN = 64; std::vector<std::unique_ptr<GraphNode>> m_node_set; GraphNode *m_head; GraphNode *m_node; GraphNode *m_node_uv; unsigned m_id_counter; unsigned m_subsample_w; unsigned m_subsample_h; bool m_is_complete; unsigned get_horizontal_step() const { auto head_attr = m_head->get_image_attributes(); auto tail_attr = m_node->get_image_attributes(); bool entire_row = m_node->entire_row() || (m_node_uv && m_node_uv->entire_row()); if (!entire_row) { double scale = std::max((double)tail_attr.width / head_attr.width, 1.0); unsigned step = floor_n((unsigned)std::lrint(HORIZONTAL_STEP * scale), ALIGNMENT); return std::min(step, tail_attr.width); } else { return tail_attr.width; } } void check_incomplete() const { if (m_is_complete) throw error::InternalError{ "cannot modify completed graph" }; } void check_complete() const { if (!m_is_complete) throw error::InternalError{ "cannot query properties on incomplete graph" }; } public: impl(unsigned width, unsigned height, PixelType type, unsigned subsample_w, unsigned subsample_h, bool color) : m_head{}, m_node{}, m_node_uv{}, m_id_counter{}, m_subsample_w{}, m_subsample_h{}, m_is_complete{} { if (!color && (subsample_w || subsample_h)) throw error::InternalError{ "greyscale images can not be subsampled" }; if (subsample_w > 2 || subsample_h > 2) throw error::UnsupportedSubsampling{ "subsampling factor must not exceed 4" }; m_node_set.emplace_back( ztd::make_unique<SourceNode>(m_id_counter++, width, height, type, subsample_w, subsample_h, color)); m_head = m_node_set.back().get(); m_node = m_head; if (color) m_node_uv = m_head; } void attach_filter(std::unique_ptr<ImageFilter> &&filter) { check_incomplete(); ImageFilter::filter_flags flags = filter->get_flags(); GraphNode *parent = m_node; GraphNode *parent_uv = nullptr; if (flags.color) { auto attr = m_node->get_image_attributes(); auto attr_uv = m_node->get_image_attributes(); if (!m_node_uv) throw error::InternalError{ "cannot use color filter in greyscale graph" }; if (attr.width != attr_uv.width || attr.height != attr_uv.height || attr.type != attr_uv.type) throw error::InternalError{ "cannot use color filter with mismatching Y and UV format" }; parent_uv = m_node_uv; } m_node_set.reserve(m_node_set.size() + 1); m_node_set.emplace_back( ztd::make_unique<FilterNode>(m_id_counter++, std::move(filter), parent, parent_uv)); m_node = m_node_set.back().get(); parent->add_ref(); if (parent_uv) parent_uv->add_ref(); if (flags.color) m_node_uv = m_node; } void attach_filter_uv(std::unique_ptr<ImageFilter> &&filter) { check_incomplete(); if (filter->get_flags().color) throw error::InternalError{ "cannot use color filter as UV filter" }; GraphNode *parent = m_node_uv; m_node_set.reserve(m_node_set.size() + 1); m_node_set.emplace_back( ztd::make_unique<FilterNodeUV>(m_id_counter++, std::move(filter), parent)); m_node_uv = m_node_set.back().get(); parent->add_ref(); } void color_to_grey() { check_incomplete(); if (!m_node_uv) throw error::InternalError{ "cannot remove chroma from greyscale image" }; ImageFilter::image_attributes attr = m_node->get_image_attributes(); GraphNode *parent = m_node; m_node_set.reserve(m_node_set.size() + 1); m_node_set.emplace_back( ztd::make_unique<FilterNode>(m_id_counter++, ztd::make_unique<CopyFilter>(attr.width, attr.height, attr.type), parent, nullptr)); m_node = m_node_set.back().get(); m_node_uv = nullptr; parent->add_ref(); } void grey_to_color(bool yuv, unsigned subsample_w, unsigned subsample_h, unsigned depth) { check_incomplete(); if (m_node_uv) throw error::InternalError{ "cannot add chroma to color image" }; ImageFilter::image_attributes attr = m_node->get_image_attributes(); GraphNode *parent = m_node; m_node_set.emplace_back( ztd::make_unique<FilterNode>(m_id_counter++, ztd::make_unique<ColorExtendFilter>(attr, !yuv), parent, nullptr)); m_node = m_node_set.back().get(); m_node_uv = m_node; parent->add_ref(); if (yuv) attach_filter_uv(ztd::make_unique<ChromaInitializeFilter>(attr, subsample_w, subsample_h, depth)); } void complete() { check_incomplete(); auto node_attr = m_node->get_image_attributes(false); auto node_attr_uv = m_node_uv ? m_node_uv->get_image_attributes(true) : node_attr; unsigned subsample_w = 0; unsigned subsample_h = 0; for (unsigned ss = 0; ss < 3; ++ss) { if (node_attr.width == node_attr_uv.width << ss) subsample_w = ss; if (node_attr.height == node_attr_uv.height << ss) subsample_h = ss; } if (node_attr.width != node_attr_uv.width << subsample_w) throw error::InternalError{ "unsupported horizontal subsampling" }; if (node_attr.height != node_attr_uv.height << subsample_h) throw error::InternalError{ "unsupported vertical subsampling" }; if (node_attr.type != node_attr_uv.type) throw error::InternalError{ "UV pixel type can not differ" }; if (m_node == m_head || m_node->get_ref()) attach_filter(ztd::make_unique<CopyFilter>(node_attr.width, node_attr.height, node_attr.type)); if (m_node_uv && (m_node_uv == m_head || m_node_uv->get_ref())) attach_filter_uv(ztd::make_unique<CopyFilter>(node_attr_uv.width, node_attr_uv.height, node_attr_uv.type)); SimulationState sim{ m_id_counter }; for (unsigned i = 0; i < node_attr.height; i += (1 << subsample_h)) { m_node->simulate(&sim, i, i + (1 << subsample_h)); if (m_node_uv) m_node_uv->simulate(&sim, i >> subsample_h, (i >> subsample_h) + 1, true); } m_subsample_w = subsample_w; m_subsample_h = subsample_h; m_is_complete = true; } size_t get_tmp_size() const { check_complete(); auto attr = m_node->get_image_attributes(); unsigned step = get_horizontal_step(); FakeAllocator alloc; size_t tmp_size = 0; alloc.allocate(ExecutionState::context_table_size(m_id_counter)); for (const auto &node : m_node_set) { alloc.allocate(node->get_context_size()); } for (unsigned j = 0; j < attr.width; j += step) { unsigned j_end = std::min(j + step, attr.width); if (attr.width - j_end < TILE_MIN) { j_end = attr.width; step = attr.width - j; } tmp_size = std::max(tmp_size, m_node->get_tmp_size(j, j_end)); if (m_node_uv) tmp_size = std::max(tmp_size, m_node_uv->get_tmp_size(j >> m_subsample_w, j_end >> m_subsample_w)); } alloc.allocate(tmp_size); return alloc.count(); } unsigned get_input_buffering() const { check_complete(); return m_head->get_cache_lines(); } unsigned get_output_buffering() const { check_complete(); unsigned lines = m_node->get_cache_lines(); if (m_node_uv) { unsigned lines_uv = m_node_uv->get_cache_lines(); lines_uv = (lines_uv == BUFFER_MAX) ? lines_uv : lines_uv << m_subsample_h; lines = std::max(lines, lines_uv); } return lines; } void process(const ImageBuffer<const void> src[], const ImageBuffer<void> dst[], void *tmp, callback unpack_cb, callback pack_cb) const { check_complete(); ExecutionState state{ m_id_counter, src, dst, tmp, unpack_cb, pack_cb }; auto attr = m_node->get_image_attributes(); unsigned h_step = get_horizontal_step(); unsigned v_step = 1 << m_subsample_h; for (const auto &node : m_node_set) { node->init_context(&state); } for (unsigned j = 0; j < attr.width; j += h_step) { unsigned j_end = std::min(j + h_step, attr.width); if (attr.width - j_end < TILE_MIN) { j_end = attr.width; h_step = attr.width - j; } for (const auto &node : m_node_set) { node->reset_context(&state); } m_node->set_tile_region(&state, j, j_end, false); if (m_node_uv) m_node_uv->set_tile_region(&state, j >> m_subsample_w, j_end >> m_subsample_w, true); for (unsigned i = 0; i < attr.height; i += v_step) { for (unsigned ii = i; ii < i + v_step; ++ii) { m_node->generate_line(&state, state.get_output_buffer(), ii, false); } if (m_node_uv) m_node_uv->generate_line(&state, state.get_output_buffer(), i / v_step, true); if (state.get_pack_cb()) state.get_pack_cb()(i, j, j_end); } } } }; FilterGraph::callback::callback(std::nullptr_t) : m_func{}, m_user{} { } FilterGraph::callback::callback(func_type func, void *user) : m_func{ func }, m_user{ user } { } FilterGraph::callback::operator bool() const { return m_func != nullptr; } void FilterGraph::callback::operator()(unsigned i, unsigned left, unsigned right) const { if (m_func(m_user, i, left, right)) throw error::UserCallbackFailed{ "user callback failed" }; } FilterGraph::FilterGraph(unsigned width, unsigned height, PixelType type, unsigned subsample_w, unsigned subsample_h, bool color) : m_impl{ ztd::make_unique<impl>(width, height, type, subsample_w, subsample_h, color) } { } FilterGraph::FilterGraph(FilterGraph &&other) = default; FilterGraph::~FilterGraph() = default; FilterGraph &FilterGraph::operator=(FilterGraph &&other) = default; void FilterGraph::attach_filter(std::unique_ptr<ImageFilter> &&filter) { m_impl->attach_filter(std::move(filter)); } void FilterGraph::attach_filter_uv(std::unique_ptr<ImageFilter> &&filter) { m_impl->attach_filter_uv(std::move(filter)); } void FilterGraph::color_to_grey() { m_impl->color_to_grey(); } void FilterGraph::grey_to_color(bool yuv, unsigned subsample_w, unsigned subsample_h, unsigned depth) { m_impl->grey_to_color(yuv, subsample_w, subsample_h, depth); } void FilterGraph::complete() { m_impl->complete(); } size_t FilterGraph::get_tmp_size() const { return m_impl->get_tmp_size(); } unsigned FilterGraph::get_input_buffering() const { return m_impl->get_input_buffering(); } unsigned FilterGraph::get_output_buffering() const { return m_impl->get_output_buffering(); } void FilterGraph::process(const ImageBuffer<const void> *src, const ImageBuffer<void> *dst, void *tmp, callback unpack_cb, callback pack_cb) const { m_impl->process(src, dst, tmp, unpack_cb, pack_cb); } } // namespace graph } // namespace zimg
27.166964
155
0.717685
dubhater
071acf7b15d940c30e26b7e142a93f1d516e8f91
2,272
hpp
C++
android-28/android/widget/NumberPicker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/widget/NumberPicker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/widget/NumberPicker.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./LinearLayout.hpp" class JArray; namespace android::content { class Context; } namespace android::graphics { class Canvas; } namespace android::view { class KeyEvent; } namespace android::view { class MotionEvent; } namespace android::view::accessibility { class AccessibilityNodeProvider; } namespace android::widget { class NumberPicker : public android::widget::LinearLayout { public: // Fields // QJniObject forward template<typename ...Ts> explicit NumberPicker(const char *className, const char *sig, Ts...agv) : android::widget::LinearLayout(className, sig, std::forward<Ts>(agv)...) {} NumberPicker(QJniObject obj); // Constructors NumberPicker(android::content::Context arg0); NumberPicker(android::content::Context arg0, JObject arg1); NumberPicker(android::content::Context arg0, JObject arg1, jint arg2); NumberPicker(android::content::Context arg0, JObject arg1, jint arg2, jint arg3); // Methods void computeScroll() const; jboolean dispatchKeyEvent(android::view::KeyEvent arg0) const; jboolean dispatchTouchEvent(android::view::MotionEvent arg0) const; jboolean dispatchTrackballEvent(android::view::MotionEvent arg0) const; android::view::accessibility::AccessibilityNodeProvider getAccessibilityNodeProvider() const; JArray getDisplayedValues() const; jint getMaxValue() const; jint getMinValue() const; jint getSolidColor() const; jint getValue() const; jboolean getWrapSelectorWheel() const; void jumpDrawablesToCurrentState() const; jboolean onInterceptTouchEvent(android::view::MotionEvent arg0) const; jboolean onTouchEvent(android::view::MotionEvent arg0) const; jboolean performClick() const; jboolean performLongClick() const; void scrollBy(jint arg0, jint arg1) const; void setDisplayedValues(JArray arg0) const; void setEnabled(jboolean arg0) const; void setFormatter(JObject arg0) const; void setMaxValue(jint arg0) const; void setMinValue(jint arg0) const; void setOnLongPressUpdateInterval(jlong arg0) const; void setOnScrollListener(JObject arg0) const; void setOnValueChangedListener(JObject arg0) const; void setValue(jint arg0) const; void setWrapSelectorWheel(jboolean arg0) const; }; } // namespace android::widget
30.293333
175
0.766285
YJBeetle
071ca975acd4d8f19bb9c6e09446bbd8b9f07cc6
3,285
hh
C++
packages/Alea/mc_solvers/ForwardMcKernel.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/Alea/mc_solvers/ForwardMcKernel.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/Alea/mc_solvers/ForwardMcKernel.hh
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file Alea/mc_solvers/ForwardMcKernel.hh * \author Steven Hamilton * \brief Perform adjoint MC histories to solve linear system. */ //---------------------------------------------------------------------------// #ifndef Alea_mc_solvers_ForwardMcKernel_hh #define Alea_mc_solvers_ForwardMcKernel_hh #include "MC_Data.hh" #include "AleaSolver.hh" #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "Teuchos_ArrayView.hpp" #include "Kokkos_Parallel.hpp" #include "AleaTypedefs.hh" namespace alea { //---------------------------------------------------------------------------// /*! * \class ForwardMcKernel * \brief Perform Monte Carlo random walks on linear system. * * This class performs random walks using the forward Monte Carlo algorithm. * The interface of this function conforms to the Kokkos "parallel_reduce" * functor API to enable automated shared memory parallelism over MC histories. */ //---------------------------------------------------------------------------// class ForwardMcKernel { public: // Required typedefs for Kokkos functor API //! Type of device where kernel will be executed typedef Kokkos::TeamPolicy<DEVICE> policy_type; typedef policy_type::member_type member_type; ForwardMcKernel(const Teuchos::ArrayView<const Teuchos::ArrayView<const SCALAR> > P, const Teuchos::ArrayView<const Teuchos::ArrayView<const SCALAR> > W, const Teuchos::ArrayView<const Teuchos::ArrayView<const LO> > inds, const Teuchos::ArrayView<const SCALAR> coeffs, const LO local_length, const Teuchos::ArrayView<const SCALAR> x, const Teuchos::ArrayView<SCALAR> y, const int histories_per_state, bool print); // Kokkos "parallel_for" API functions //! \brief Compute kernel KOKKOS_INLINE_FUNCTION void operator()(member_type member) const; private: inline void getNewRow(const GO state, Teuchos::ArrayView<const SCALAR> &p_vals, Teuchos::ArrayView<const SCALAR> &w_vals, Teuchos::ArrayView<const LO> &inds) const; inline GO getNewState(const Teuchos::ArrayView<const SCALAR> cdf, const int thread ) const; const LO d_local_length; // Warning, these are non reference-counted views // The underlying reference-counted objects from which they were // created must stay alive for the entire life of this object const Teuchos::ArrayView<const Teuchos::ArrayView<const SCALAR> > d_P; const Teuchos::ArrayView<const Teuchos::ArrayView<const SCALAR> > d_W; const Teuchos::ArrayView<const Teuchos::ArrayView<const LO> > d_inds; const Teuchos::ArrayView<const SCALAR> d_coeffs; const Teuchos::ArrayView<const SCALAR> d_x; const Teuchos::ArrayView<SCALAR> d_y; //const ThreadedRNG d_rng; const int d_histories_per_state; const bool d_print; const int d_max_history_length; }; } // namespace alea #include "ForwardMcKernel.i.hh" #endif // Alea_mc_solvers_ForwardMcKernel_hh
33.865979
88
0.620091
GCZhang
071d364afaa90c88adc4731ad4709eb2f3b9a775
9,643
cpp
C++
SinkTheFleet/SinkTheFleet/CPlayer.cpp
MJBrune/RandomProjects
c24d8aa78aa9d5a6df8ae186a92a82165a96c50c
[ "WTFPL" ]
null
null
null
SinkTheFleet/SinkTheFleet/CPlayer.cpp
MJBrune/RandomProjects
c24d8aa78aa9d5a6df8ae186a92a82165a96c50c
[ "WTFPL" ]
null
null
null
SinkTheFleet/SinkTheFleet/CPlayer.cpp
MJBrune/RandomProjects
c24d8aa78aa9d5a6df8ae186a92a82165a96c50c
[ "WTFPL" ]
null
null
null
#include "CPlayer.h" using namespace JP_CSHIPINFO; CPlayer::CPlayer(unsigned short whichPlayer, char gridSize) :m_whichPlayer(whichPlayer), m_gridSize(gridSize) { for (short i = 0; i < 2; i++) m_gameGrid[i] = NULL; allocateMemory(); for (short j = 0; j < 6; j++)//SHIP_SIZE_ARRAYSIZE { m_ships[j].setName((MB_CSHIP::Ship)j); m_ships[j].setPiecesLeft(MB_CSHIP::shipSize[j + 1]); } m_piecesLeft = 17; //TOTALPIECES } CPlayer::~CPlayer() { deleteMemory(); } CPlayer::CPlayer(const CPlayer & player) : m_whichPlayer(player.m_whichPlayer), m_gridSize(player.m_gridSize) { for (short i = 0; i < 2; i++) m_gameGrid[i] = NULL; allocateMemory(); for (short j = 0; j < 6; j++)//6 = SHIP_SIZE_ARRAYSIZE { m_ships[j] = player.m_ships[j]; } m_piecesLeft = player.m_piecesLeft; } void CPlayer::allocateMemory() { short numberOfRows = LARGEROWS; short numberOfCols = LARGECOLS; try { m_gameGrid[0] = new MB_CSHIP::CShip*[numberOfRows]; m_gameGrid[1] = new MB_CSHIP::CShip*[numberOfRows]; for(short j = 0; j < numberOfRows; ++j) { m_gameGrid[0][j] = new MB_CSHIP::CShip[numberOfCols]; m_gameGrid[1][j] = new MB_CSHIP::CShip[numberOfCols]; for(short k = 0; k < numberOfCols; ++k) { m_gameGrid[0][j][k] = MB_CSHIP::CShip(MB_CSHIP::NOSHIP); m_gameGrid[1][j][k] = MB_CSHIP::CShip(MB_CSHIP::NOSHIP); } // end for k } // end for j } catch(exception e) { deleteMemory(); cerr << "exception: " << e.what() << endl; cout << "shutting down" << endl; cin.ignore(BUFFER_SIZE, '\n'); exit(EXIT_FAILURE); } } void CPlayer::deleteMemory() { short numberOfRows = LARGEROWS; for (short j = 0; j < numberOfRows; j++) { if (this[m_whichPlayer].m_gameGrid[0][j] != NULL) delete[] this[m_whichPlayer].m_gameGrid[0][j]; } if (this[m_whichPlayer].m_gameGrid[0] != NULL) delete[] this[m_whichPlayer].m_gameGrid[0]; } bool CPlayer::isValidLocation(short whichShip) { short numberOfRows = (toupper(m_gridSize)=='L') ? LARGEROWS : SMALLROWS; short numberOfCols = (toupper(m_gridSize)=='L') ? LARGECOLS : SMALLCOLS; if(m_ships[whichShip].getOrientaion() == MB_CDIRECTION::HORIZONTAL && m_ships[whichShip].getBowLocation().getCol() + MB_CSHIP::shipSize[whichShip] <= numberOfCols) { for(short i = 0; i < MB_CSHIP::shipSize[whichShip]; i++) if(m_gameGrid[0][m_ships[whichShip].getBowLocation().getRow()] [m_ships[whichShip].getBowLocation().getCol() + i] != MB_CSHIP::NOSHIP) { return false; } } else if(m_ships[whichShip].getOrientaion() == MB_CDIRECTION::VERTICAL && m_ships[whichShip].getBowLocation().getRow() + MB_CSHIP::shipSize[whichShip] <= numberOfRows) { for(short i = 0; i < MB_CSHIP::shipSize[whichShip]; i++) if(m_gameGrid[0] [m_ships[whichShip].getBowLocation().getRow() + i] [m_ships[whichShip].getBowLocation().getCol()] != MB_CSHIP::NOSHIP) { return false; } } else { return false; } return true; } void CPlayer::printGrid(std::ostream& sout, short whichGrid) { short numberOfRows = (toupper(m_gridSize)=='L') ? LARGEROWS : SMALLROWS; short numberOfCols = (toupper(m_gridSize)=='L') ? LARGECOLS : SMALLCOLS; sout << ' '; for (short j = 1; j <= numberOfCols; ++j) sout << setw(3) << j; sout << endl; sout << HORIZ << CROSS << HORIZ << HORIZ << CROSS; for (short l = 0; l < numberOfCols - 1; l++) sout << HORIZ << HORIZ << CROSS; sout << endl; for (short i = 0; i < numberOfRows; i++) { sout << static_cast<char>(i + 65) << VERT; for (short h = 0; h < numberOfCols; h++) { m_gameGrid[whichGrid][i][h].print(sout); } sout << endl; sout << HORIZ << CROSS << HORIZ << HORIZ; for (short j = 0; j < numberOfCols - 1; j++) sout << CROSS << HORIZ << HORIZ; sout << CROSS; sout << endl; } } bool CPlayer::getGrid(std::string filename) { char ship; std::ifstream ifs; short shipCount[MB_CSHIP::SHIP_SIZE_ARRAYSIZE] = {0}; char cell = ' '; char fsize = 'S'; char line[256]; char choice = 'N'; short numberOfRows = (toupper(m_gridSize)=='L') ? LARGEROWS : SMALLROWS; short numberOfCols = (toupper(m_gridSize)=='L') ? LARGECOLS : SMALLCOLS; int totalCells = numberOfRows * numberOfCols; ifs.open(filename); if (!ifs) { cout << "could not open file " << filename << endl << "press <enter> to continue" << endl; cin.ignore(256, '\n');//256 = BUFFER_SIZE return false; } fsize = ifs.get(); if (fsize != m_gridSize) { cout << "saved grid is not the correct size " << filename << endl << " press <enter> to continue" << endl; cin.get(); return false; } ifs.ignore(256, '\n');//magic number ifs.getline(line, 256);//magic number for (int rows = 0; rows != numberOfRows; rows++) { ifs.getline(line, 256); for (int cols = 0; cols != numberOfCols; cols++) { ship = ifs.get(); while (ship != ' ') ship = ifs.get(); ship = ifs.get(); switch (ship) { case 'M': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::MINESWEEPER; break; case 'S': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::SUB; break; case 'F': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::FRIGATE; break; case 'B': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::BATTLESHIP; break; case 'C': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::CARRIER; break; case ' ': this[m_whichPlayer].m_gameGrid[0][rows][cols] = MB_CSHIP::NOSHIP; break; default: cout << "The file has become corrupt. Sorry" << endl << " press <enter> to continue" << endl; return false; } } } system("cls"); printGrid(cout, m_whichPlayer); cin.ignore(256, '\n');//BUFFER_SIZE choice = safeChoice("is this the grid you wanted?", 'Y', 'N'); if (choice == 'Y') return true; else { system("cls"); return false; } } void CPlayer::saveGrid() { short numberOfRows = (toupper(m_gridSize)=='L') ? LARGEROWS : SMALLROWS; short numberOfCols = (toupper(m_gridSize)=='L') ? LARGECOLS : SMALLCOLS; std::ofstream file; std::string filename; std::cout << "NOTE: .shp will be appended to the filename" << std::endl; std::cout << "What should this grid be saved as? "; std::cin >> filename; file.open(filename + ".shp"); if (file) { file << m_gridSize << endl; printGrid(file, m_whichPlayer); file.close(); std::cout << "Grid has been saved as " << filename + ".shp" << std::endl; std::cin.get(); } else { std::cout << "could not open file " << filename + ".shp" << std::endl; std::cout << "Press <enter> to continue" << endl; std::cin.ignore(256, '\n');//BUFFER_SIZE } std::cin.ignore(256, '\n');//BUFFER_SIZE } void CPlayer::setShips(short whichplayer) { char input = 'V'; char save = 'N'; MB_CCELL::CCell location(0,0); MB_CSHIP::Ship name = MB_CSHIP::NOSHIP; m_whichPlayer = whichplayer; for(short j = 1; j < MB_CSHIP::SHIP_SIZE_ARRAYSIZE; j++) { system("cls"); printGrid(cout, 0); //outSStream.str(""); cout << "Player " << m_whichPlayer + 1 << " Enter "; m_ships[j].getName().printName(cout); cout << " orientation"; input = safeChoice("", 'V', 'H'); m_ships[j].setOrientaion((input == 'V') ? MB_CDIRECTION::VERTICAL : MB_CDIRECTION::HORIZONTAL); cout << "Player " << m_whichPlayer + 1 << " Enter " << m_ships[j].getName() << " bow coordinates <row letter><col #>\n"; location.inputCoordinates(cin, m_gridSize); m_ships[j].setBowLocation(location); // if ok if(!isValidLocation(j)) { cout << "invalid location. Press <enter>" ; cin.get(); j--; // try again continue; } if(m_ships[j].getOrientaion() == MB_CDIRECTION::VERTICAL) { for(int i = 0; i < MB_CSHIP::shipSize[j]; i++) { m_gameGrid[0][location.getRow() + i][location.getCol()] = (MB_CSHIP::Ship)j; } } else { for(int i = 0; i < MB_CSHIP::shipSize[j]; i++) { m_gameGrid[0][location.getRow()][location.getCol() + i] = (MB_CSHIP::Ship)j; } } system("cls"); printGrid(cout, 0); } // end for j save = safeChoice("\nSave starting grid?", 'Y', 'N'); if(save == 'Y') saveGrid(); system("cls"); } void CPlayer::randGrid() { char input = 'V'; char save = 'N'; MB_CCELL::CCell location(0,0); MB_CSHIP::Ship name = MB_CSHIP::NOSHIP; for(short j = 1; j < MB_CSHIP::SHIP_SIZE_ARRAYSIZE; j++) { system("cls"); printGrid(cout, 0); cout << "Player " << m_whichPlayer + 1 << " Enter "; m_ships[j].getName().printName(cout); cout << " orientation"; m_ships[j].setOrientaion((rand() % 2 == 0) ? MB_CDIRECTION::VERTICAL : MB_CDIRECTION::HORIZONTAL); cout << "Player " << m_whichPlayer + 1 << " Enter " << m_ships[j].getName() << " bow coordinates <row letter><col #>\n"; location.randomCell(m_gridSize); m_ships[j].setBowLocation(location); // if ok if(!isValidLocation(j)) { j--; // try again continue; } if(m_ships[j].getOrientaion() == MB_CDIRECTION::VERTICAL) { for(int i = 0; i < MB_CSHIP::shipSize[j]; i++) { m_gameGrid[0][location.getRow() + i][location.getCol()] = (MB_CSHIP::Ship)j; } } else { for(int i = 0; i < MB_CSHIP::shipSize[j]; i++) { m_gameGrid[0][location.getRow()][location.getCol() + i] = (MB_CSHIP::Ship)j; } } system("cls"); printGrid(cout, 0); } // end for j save = safeChoice("\nSave starting grid?", 'Y', 'N'); if(save == 'Y') saveGrid(); system("cls"); } CShipInfo CPlayer::operator[](short index) const { if (index >= 6)//SHIP_SIZE_ARRAYSIZE throw range_error("index out of range"); return m_ships[index]; }
24.1075
100
0.619724
MJBrune
0722657e681c7753b6516b601577f01c8f95483c
696
cpp
C++
tests/core/test_random_queue.cpp
tatsy/lime
385695486443808141668e98e65a5f545fd80b10
[ "MIT" ]
49
2015-01-30T08:08:25.000Z
2021-11-13T05:31:11.000Z
tests/core/test_random_queue.cpp
tatsy/lime
385695486443808141668e98e65a5f545fd80b10
[ "MIT" ]
10
2016-09-26T10:23:29.000Z
2021-05-24T06:10:05.000Z
tests/core/test_random_queue.cpp
tatsy/lime
385695486443808141668e98e65a5f545fd80b10
[ "MIT" ]
16
2015-10-10T16:10:17.000Z
2021-10-30T13:53:10.000Z
#include "gtest/gtest.h" #include "lime.hpp" using lime::random_queue; static const int nTest = 1 << 20; class RandomQueueTest : public ::testing::Test { protected: virtual void setUp() { } random_queue<int> que; }; TEST_F(RandomQueueTest, InEmpty) { EXPECT_TRUE(que.empty()); } TEST_F(RandomQueueTest, EnqueueDequeueWorks) { for (int i = 0; i < nTest; i++) { EXPECT_EQ(que.size(), i); que.push(i); } EXPECT_FALSE(que.empty()); for (int i = 0; i < nTest; i++) { EXPECT_EQ(que.size(), nTest - i); que.pop(); } EXPECT_TRUE(que.empty()); } TEST_F(RandomQueueTest, InvalidOperation) { ASSERT_DEATH(que.pop(), ""); }
19.333333
48
0.602011
tatsy
072745020649226af6dd2f0f5e63cc5cd212aab1
1,420
cpp
C++
src/queries/model/not.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/queries/model/not.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/queries/model/not.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
#include "not.hpp" #include "../../queries/builders/ast.hpp" using namespace std; using namespace indexes; namespace queries::model { void NotModel::execute(queries::builders::AST *ast) { if (exprList.size() != 1) { Log::error(ast->getQueryStatus(),"SQL query NOT should have 1 children. "+ast->getSaveqQuery()); return; } auto a = exprList.at(0)->getWorkingSet(); if (a == nullptr) { Log::error(ast->getQueryStatus(),"SQL subexpression NOT failed "+ast->getSaveqQuery()); return; } allocWorkingSet(exprList.at(0)->getWorkingSetSize()); for (int chunk=0; chunk < workingSetSize*8/CHUNK_SIZE; chunk ++) { shared_ptr<IndexChunk> c = exprList.at(0)->getIndexManager(0)->getChunkForRead(chunk); uint32_t l = 128*(c->getBase()->getNbDocuments()/1024); uint64_t p = chunk*CHUNK_SIZE/64; fastNot(workingSet+p,exprList.at(0)->getWorkingSet()+p, l); for (uint32_t i=l*8; i < c->getBase()->getNbDocuments(); i++) { uint32_t k = i >> 6; uint32_t x = i&63; uint64_t b = (exprList.at(0)->getWorkingSet()[p+k] >> x) &1; b = b == 0 ? 1 : 0; workingSet[p+k] |= b << x; } fastAnd(workingSet+p,workingSet+p,c->getBase()->getDeletedInfo(),CHUNK_SIZE/8); } exprList.at(0)->freeWorkingSet(); nbResults = fastCount(workingSet,workingSetSize); } }
34.634146
104
0.602113
enerc
072876a54d00a63c68199a0d2f66973e7ab4d171
1,524
hpp
C++
cpp/include/cg3/common/material.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/material.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
cpp/include/cg3/common/material.hpp
tychota/cg3-path-tracer
548519121cacb01a4be835c0bece21238b56f92b
[ "Beerware" ]
null
null
null
#pragma once #include "cg3/common/tiny_vec.hpp" #include "cg3/common/intersection_info.hpp" #include "cg3/common/light_source.hpp" class Material { public: Material(); void set_diffuse( tiny_vec<float,3>& col ) ; void set_diffuse( float r, float g, float b); tiny_vec<float,3>& get_diffuse(); const tiny_vec<float,3>& get_diffuse() const; void set_specular( tiny_vec<float,3>& col ) ; void set_specular( float r, float g, float b ); tiny_vec<float,3> & get_specular() ; tiny_vec<float,3> const& get_specular() const; void set_shininess( float ); float get_shininess() const; void set_reflectivity( float ); float get_reflectivity() const ; void set_refractivity( float ) ; float get_refractivity() const ; void set_index_of_refraction( float ); float get_index_of_refraction() const; virtual tiny_vec< real_type, 3 > brdf( direction< 3 > const& in, direction< 3 > const& out, intersection_info const& ) const; protected: virtual tiny_vec< real_type, 3 > diffuse_brdf( direction< 3 > const& in, direction< 3 > const& out, intersection_info const& ) const = 0; virtual tiny_vec< real_type, 3 > specular_brdf( direction< 3 > const& in, direction< 3 > const& out, intersection_info const& ) const = 0; tiny_vec<float,3> diffuse; tiny_vec<float,3> specular; float shininess; float reflection; float refraction; float refrac_index; };
26.736842
143
0.65748
tychota
072a4bc92f78df02e0967b942cb33b9ba3b7d900
4,683
cpp
C++
src/demuxer.cpp
OpenGene/defq
1cbe6cfc04705dcd010a734b4c51f02ab8a5ce7e
[ "MIT" ]
27
2017-12-06T06:53:40.000Z
2021-08-19T02:11:45.000Z
src/demuxer.cpp
OpenGene/defq
1cbe6cfc04705dcd010a734b4c51f02ab8a5ce7e
[ "MIT" ]
4
2017-12-28T02:41:31.000Z
2021-08-21T12:07:37.000Z
src/demuxer.cpp
OpenGene/defq
1cbe6cfc04705dcd010a734b4c51f02ab8a5ce7e
[ "MIT" ]
8
2017-12-06T09:41:40.000Z
2021-03-19T19:22:07.000Z
#include "demuxer.h" #include "util.h" #include <memory.h> Demuxer::Demuxer(Options* opt){ mOptions = opt; mBuf = NULL; init(); } Demuxer::~Demuxer() { if(mBuf) { delete mBuf; mBuf = NULL; } } void Demuxer::init() { if(mOptions == NULL) return; mUseIndex1 = false; mUseIndex2 = false; mHasN = false; mLongestIndex = 0; bool sameLength = true; for(int i=0; i<mOptions->samples.size(); i++) { Sample s = mOptions->samples[i]; if(!s.index1.empty()) mUseIndex1 = true; if(!s.index2.empty()) mUseIndex2 = true; if(contains(s.index1, 'N') || contains(s.index2, 'N')) mHasN = true; if(s.index1.empty() && s.index2.empty()) { error_exit("bad format sample sheet. You should specify either index1 or index2 for each record"); } if(s.index1.length() > mLongestIndex) mLongestIndex = s.index1.length(); if(s.index2.length() > mLongestIndex) mLongestIndex = s.index2.length(); if(i>0) { if(mOptions->samples[i].index1.length() != mOptions->samples[i-1].index1.length()) sameLength = false; if(mOptions->samples[i].index2.length() != mOptions->samples[i-1].index2.length()) sameLength = false; } cout << "file (" << s.file << ") = " << s.index1 << "," << s.index2 << endl; } mFastMode = true; if(mUseIndex1 && mUseIndex2) { mFastMode = false; error_exit("bad format sample sheet. You can use either index1 or index2, but cannot use both."); } if(mHasN) { mFastMode = false; error_exit("bad format sample sheet. N base is not supported."); } if(!sameLength) mFastMode = false; if(mLongestIndex > 14) mFastMode = false; mBuf = NULL; if(mFastMode) { mBufLen = 0x01 << (mLongestIndex*2); mBuf = new int[mBufLen]; // initialize to Undetermined memset(mBuf, -1, sizeof(int)*mBufLen); for(int i=0; i<mOptions->samples.size(); i++) { Sample s = mOptions->samples[i]; int kmer = 0; if(mUseIndex1) kmer = kmer2int(s.index1); else kmer = kmer2int(s.index2); if(kmer <0) error_exit("index can only have A/T/C/G bases"); mBuf[kmer] = i; } } else { mShortestIndex = mLongestIndex; for(int i=0; i<mOptions->samples.size(); i++) { Sample s = mOptions->samples[i]; string index; if(mUseIndex1) index = s.index1; else index = s.index2; if(index.length() < mShortestIndex) mShortestIndex = index.length(); mIndexSample[index] = i; } } } int Demuxer::demux(Read* r) { string index; if(mUseIndex1) index = r->firstIndex(); else if(mUseIndex2) index = r->lastIndex(); if(mFastMode) { // return the Undetermined one if(index.length() < mLongestIndex) return -1; else if(index.length() > mLongestIndex) index = index.substr(0, mLongestIndex); int kmer = kmer2int(index); if(kmer<0) return -1; return mBuf[kmer]; } else { // match longer first for(int l = std::min(mLongestIndex, (int)index.length()); l>= mShortestIndex; l--) { if(l == index.length()) { if(mIndexSample.count(index) >0 ) { return mIndexSample[index]; } } else { string indexPart = index.substr(0, l); if(mIndexSample.count(indexPart) >0 ) { return mIndexSample[indexPart]; } } } return -1; } } int Demuxer::kmer2int(string& str) { int kmer = 0; const char* data = str.c_str(); for(int k=0; k<str.length(); k++) { int val = base2val(data[k]); if(val < 0) { return -1; } kmer = (kmer<<2) | val; } return kmer; } int Demuxer::base2val(char base) { switch(base){ case 'A': return 0; case 'T': return 1; case 'C': return 2; case 'G': return 3; default: return -1; } } bool Demuxer::test(){ Demuxer d(NULL); string s1("AGTCAGAA"); string s2("ATTCAGAA"); cout << d.kmer2int(s1) << endl; cout << d.kmer2int(s2) << endl; return true; }
26.162011
110
0.500747
OpenGene
072e60f746552c111c7bc04bf4cb3d53b3ca989a
5,018
cpp
C++
test/test_mrt.cpp
balsini/FREDSim
720dc30d4c2f8a51a05ec74584aef352f029c19f
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-05-24T15:20:53.000Z
2020-05-24T15:20:53.000Z
test/test_mrt.cpp
balsini/rtlib2.0
720dc30d4c2f8a51a05ec74584aef352f029c19f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
test/test_mrt.cpp
balsini/rtlib2.0
720dc30d4c2f8a51a05ec74584aef352f029c19f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "catch.hpp" #include <metasim.hpp> #include <rttask.hpp> #include <mrtkernel.hpp> #include <edfsched.hpp> #include <cbserver.hpp> using namespace MetaSim; using namespace RTSim; TEST_CASE("multicore") { EDFScheduler sched; MRTKernel kern(&sched, 2); PeriodicTask t1(10, 10, 0, "task 1"); t1.insertCode("fixed(4);"); t1.setAbort(false); PeriodicTask t2(15, 15, 0, "task 2"); t2.insertCode("fixed(5);"); t2.setAbort(false); PeriodicTask t3(25, 25, 0, "task 3"); t3.insertCode("fixed(4);"); t3.setAbort(false); kern.addTask(t1); kern.addTask(t2); kern.addTask(t3); SIMUL.initSingleRun(); SIMUL.run_to(4); REQUIRE(t1.getExecTime() == 4); REQUIRE(t2.getExecTime() == 4); REQUIRE(t3.getExecTime() == 0); SIMUL.run_to(5); REQUIRE(t1.getExecTime() == 4); REQUIRE(t3.getExecTime() == 1); REQUIRE(t2.getExecTime() == 5); SIMUL.run_to(8); REQUIRE(t1.getExecTime() == 4); REQUIRE(t3.getExecTime() == 4); REQUIRE(t2.getExecTime() == 5); SIMUL.endSingleRun(); } TEST_CASE("multicore with cbs") { EDFScheduler sched; MRTKernel kern(&sched, 2); PeriodicTask t1(10, 10, 0, "task 1"); t1.insertCode("fixed(4);"); t1.setAbort(false); PeriodicTask t2(15, 15, 0, "task 2"); t2.insertCode("fixed(5);"); t2.setAbort(false); PeriodicTask t3(25, 25, 0, "task 3"); t3.insertCode("fixed(4);"); t3.setAbort(false); CBServer serv1(4, 10, 10, true, "server1", "FIFOSched"); CBServer serv2(5, 15, 15, true, "server2", "FIFOSched"); CBServer serv3(2, 12, 12, true, "server3", "FIFOSched"); serv1.addTask(t1); serv2.addTask(t2); serv3.addTask(t3); kern.addTask(serv1); kern.addTask(serv2); kern.addTask(serv3); SIMUL.initSingleRun(); SIMUL.run_to(1); REQUIRE(t1.getExecTime() == 1); REQUIRE(t2.getExecTime() == 0); REQUIRE(t3.getExecTime() == 1); REQUIRE(serv1.get_remaining_budget() == 3); REQUIRE(serv1.getDeadline() == 10); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 15); REQUIRE(serv3.get_remaining_budget() == 1); REQUIRE(serv3.getDeadline() == 12); SIMUL.run_to(2); REQUIRE(t1.getExecTime() == 2); REQUIRE(t2.getExecTime() == 0); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 2); REQUIRE(serv1.getDeadline() == 10); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 15); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(4); REQUIRE(t1.getExecTime() == 4); REQUIRE(t2.getExecTime() == 2); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 4); REQUIRE(serv1.getDeadline() == 20); REQUIRE(serv2.get_remaining_budget() == 3); REQUIRE(serv2.getDeadline() == 15); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(5); REQUIRE(t1.getExecTime() == 4); REQUIRE(t2.getExecTime() == 3); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 4); REQUIRE(serv1.getDeadline() == 20); REQUIRE(serv2.get_remaining_budget() == 2); REQUIRE(serv2.getDeadline() == 15); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(7); REQUIRE(t1.getExecTime() == 4); REQUIRE(t2.getExecTime() == 5); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 4); REQUIRE(serv1.getDeadline() == 20); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 30); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(10); REQUIRE(t1.getExecTime() == 0); REQUIRE(t2.getExecTime() == 5); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 4); REQUIRE(serv1.getDeadline() == 20); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 30); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(12); REQUIRE(t1.getExecTime() == 2); REQUIRE(t2.getExecTime() == 5); REQUIRE(t3.getExecTime() == 2); REQUIRE(serv1.get_remaining_budget() == 2); REQUIRE(serv1.getDeadline() == 20); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 30); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 24); SIMUL.run_to(14); REQUIRE(t1.getExecTime() == 4); REQUIRE(t2.getExecTime() == 5); REQUIRE(t3.getExecTime() == 4); REQUIRE(serv1.get_remaining_budget() == 4); REQUIRE(serv1.getDeadline() == 30); REQUIRE(serv2.get_remaining_budget() == 5); REQUIRE(serv2.getDeadline() == 30); REQUIRE(serv3.get_remaining_budget() == 2); REQUIRE(serv3.getDeadline() == 36); SIMUL.endSingleRun(); }
29.174419
61
0.624352
balsini
073004cd565b9f199516972e25a6a3aba0258f63
2,800
cpp
C++
src/speedex/LiquidityPoolSetFrame.cpp
sandymule/stellar-core
d5f0abf8d78770aec1f6d0b8f3718f4dc0462a13
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
4
2021-11-05T07:18:21.000Z
2021-12-13T01:16:25.000Z
src/speedex/LiquidityPoolSetFrame.cpp
sandymule/stellar-core
d5f0abf8d78770aec1f6d0b8f3718f4dc0462a13
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2021-12-09T04:33:19.000Z
2021-12-09T04:33:19.000Z
src/speedex/LiquidityPoolSetFrame.cpp
sandymule/stellar-core
d5f0abf8d78770aec1f6d0b8f3718f4dc0462a13
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
1
2021-12-08T23:16:19.000Z
2021-12-08T23:16:19.000Z
#include "speedex/LiquidityPoolSetFrame.h" #include "ledger/LedgerTxn.h" #include "speedex/DemandUtils.h" #include "speedex/sim_utils.h" #include <utility> #include "util/types.h" namespace stellar { LiquidityPoolSetFrame::LiquidityPoolSetFrame(std::vector<Asset> const& assets, AbstractLedgerTxn& ltx) { for (auto const& sellAsset : assets) { for (auto const& buyAsset : assets) { if (sellAsset < buyAsset) { AssetPair pair1 { .selling = sellAsset, .buying = buyAsset }; AssetPair pair2 { .selling = buyAsset, .buying = sellAsset }; mBaseFrames.emplace_back(std::make_unique<LiquidityPoolFrameBaseLtx>(ltx, pair1)); mLiquidityPools.emplace(std::piecewise_construct, std::forward_as_tuple(pair1), std::forward_as_tuple(*mBaseFrames.back(), pair1)); mLiquidityPools.emplace(std::piecewise_construct, std::forward_as_tuple(pair2), std::forward_as_tuple(*mBaseFrames.back(), pair2)); } } } } LiquidityPoolSetFrame::LiquidityPoolSetFrame(SpeedexSimConfig const& sim) { for (auto const& ammconfig : sim.ammConfigs) { AssetPair p = AssetPair{ .selling = makeSimAsset(ammconfig.assetA), .buying = makeSimAsset(ammconfig.assetB) }; if (p.buying < p.selling) { p = p.reverse(); } mBaseFrames.emplace_back(std::make_unique<LiquidityPoolFrameBaseSim>(ammconfig)); mLiquidityPools.emplace(std::piecewise_construct, std::forward_as_tuple(p), std::forward_as_tuple(*mBaseFrames.back(), p)); p = p.reverse(); mLiquidityPools.emplace(std::piecewise_construct, std::forward_as_tuple(p), std::forward_as_tuple(*mBaseFrames.back(), p)); } } void LiquidityPoolSetFrame::demandQuery(std::map<Asset, uint64_t> const& prices, SupplyDemand& supplyDemand) const { for (auto const& [tradingPair, lpFrame] : mLiquidityPools) { int128_t sellAmountTimesPrice = lpFrame.amountOfferedForSaleTimesSellPrice(prices.at(tradingPair.selling), prices.at(tradingPair.buying)); //std::printf("lp sell %s buy %s: %lf %ld\n", // assetToString(tradingPair.selling).c_str(), // assetToString(tradingPair.buying).c_str(), // (double) sellAmountTimesPrice, // (int64_t) sellAmountTimesPrice); supplyDemand.addSupplyDemand(tradingPair, sellAmountTimesPrice); } } LiquidityPoolSetFrame::int128_t LiquidityPoolSetFrame::demandQueryOneAssetPair(AssetPair const& tradingPair, std::map<Asset, uint64_t> const& prices) const { auto iter = mLiquidityPools.find(tradingPair); if (iter == mLiquidityPools.end()) { return 0; } return iter->second.amountOfferedForSaleTimesSellPrice(prices.at(tradingPair.selling), prices.at(tradingPair.buying)); } LiquidityPoolFrame& LiquidityPoolSetFrame::getFrame(AssetPair const& tradingPair) { return mLiquidityPools.at(tradingPair); } } /* stellar */
27.184466
140
0.735714
sandymule
0730fb13c4c0c48914c88c97430ecfff43d01c53
657
cpp
C++
src/cpp/2016-12-3/Code9-240-SearchA2DMatrix2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
src/cpp/2016-12-3/Code9-240-SearchA2DMatrix2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
1
2018-10-24T05:48:27.000Z
2018-10-24T05:52:14.000Z
src/cpp/2016-12-3/Code9-240-SearchA2DMatrix2.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
/* Description: Write an efficient algorithm that searches for a value in an m*n matrix, this matrix has the following properties: * integers in each row are sorted in ascending from left to right; * integers in each column are sorted in ascending from top to bottom. */ // O(M+N) class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int m = matrix.size(); if (m == 0) return false; int n = matrix[0].size(); int i = 0 , j = n - 1; while (i < m && j >= 0) { if (matrix[i][j] == target) return true; else if (matrix[i][j] > target) j--; else ++i; } return false; } }
24.333333
73
0.613394
spurscoder
0732a25a1d8aa2ecb1706820e779cf60b1e30811
116,763
cpp
C++
ToolKit/SyntaxEdit/XTPSyntaxEditLexParser.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
2
2018-03-30T06:40:08.000Z
2022-02-23T12:40:13.000Z
ToolKit/SyntaxEdit/XTPSyntaxEditLexParser.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
null
null
null
ToolKit/SyntaxEdit/XTPSyntaxEditLexParser.cpp
11Zero/DemoBCG
8f41d5243899cf1c82990ca9863fb1cb9f76491c
[ "MIT" ]
1
2020-08-11T05:48:02.000Z
2020-08-11T05:48:02.000Z
// XTPSyntaxEditLexParser.cpp : implementation file // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME SYNTAX EDIT LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" // common includes #include "Common/XTPNotifyConnection.h" #include "Common/XTPSmartPtrInternalT.h" // syntax editor includes #include "XTPSyntaxEditDefines.h" #include "XTPSyntaxEditStruct.h" #include "XTPSyntaxEditLexPtrs.h" #include "XTPSyntaxEditLexClassSubObjT.h" #include "XTPSyntaxEditTextIterator.h" #include "XTPSyntaxEditSectionManager.h" #include "XTPSyntaxEditLexCfgFileReader.h" #include "XTPSyntaxEditLexClassSubObjDef.h" #include "XTPSyntaxEditLexClass.h" #include "XTPSyntaxEditLexParser.h" #include "XTPSyntaxEditLexColorFileReader.h" #include "XTPSyntaxEditBufferManager.h" #include "XTPSyntaxEditCtrl.h" #include <afxmt.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef _DEBUG // #define DBG_TRACE_LOAD_CLASS_SCH // Trace text blocks start,end when parser running; // #define DBG_TRACE_PARSE_START_STOP TRACE // Trace text blocks start,end when parser running; // #define DBG_TRACE_PARSE_RUN_BLOCKS TRACE // Trace updating schema mechanism when parser running; // #define DBG_TRACE_PARSE_RUN_UPDATE TRACE // #define DBG_TRACE_PARSE_RUN_RESULTS // #define DBG_TRACE_PARSE_TIME // #define DBG_TRACE_PARSE_TIME_DLG // #define DBG_TRACE_DRAW_BLOCKS #endif #ifndef DBG_TRACE_PARSE_RUN_BLOCKS #define DBG_TRACE_PARSE_RUN_BLOCKS #endif #ifndef DBG_TRACE_PARSE_RUN_UPDATE #define DBG_TRACE_PARSE_RUN_UPDATE #endif #ifndef DBG_TRACE_PARSE_START_STOP #define DBG_TRACE_PARSE_START_STOP #endif //////////////////////////////////////////////////////////////////////////// #ifdef _DEBUG #define DBG_TRACE_TIME_BEGIN(nID) DWORD dbg_TT_##nID##_dwTime_0 = ::GetTickCount(); #define DBG_TRACE_TIME_END(nID, strComment) { DWORD dwTime1 = ::GetTickCount(); \ TRACE(_T("%s (%.3f sec) \n"), strComment, labs(dwTime1-dbg_TT_##nID##_dwTime_0)/1000.0); } class C_DBG_Time { CString m_strComment; DWORD m_dwTime0; public: C_DBG_Time(LPCTSTR lpcszComment) { m_dwTime0 = ::GetTickCount(); m_strComment = lpcszComment; }; ~C_DBG_Time() { DWORD dwTime1 = ::GetTickCount(); TRACE(_T("%s (%.3f sec) \n"), (LPCTSTR)m_strComment, labs(dwTime1-m_dwTime0)/1000.0); }; }; //#define DBG_TRACE_TIME(nID, strComment) C_DBG_Time dbg_TT_##nID(strComment); #endif #ifndef DBG_TRACE_TIME #define DBG_TRACE_TIME(nID, strComment) #endif //////////////////////////////////////////////////////////////////////////// using namespace XTPSyntaxEditLexAnalyser; namespace XTPSyntaxEditLexAnalyser { extern CXTPSyntaxEditLexAutomatMemMan* XTPGetLexAutomatMemMan(); extern void ConcatenateLVArrays(CXTPSyntaxEditLexVariantPtrArray* pArDest, CXTPSyntaxEditLexVariantPtrArray* pAr2, int nMaxCount = INT_MAX); extern BOOL SortTagsInLexVarArray(CXTPSyntaxEditLexVariantPtrArray& rarTags, BOOL bAscending, BOOL bNoCase); int FindStrCount(const CStringArray& rarData, LPCTSTR pcszStr, BOOL bCase = FALSE) { int nStrCount = 0; int nCount = (int)rarData.GetSize(); for (int i = 0; i < nCount; i++) { const CString& strI = rarData[i]; if (bCase) { if (strI.Compare(pcszStr) == 0) { nStrCount++; } } else { if (strI.CompareNoCase(pcszStr) == 0) { nStrCount++; } } } return nStrCount; } int FindStr(const CStringArray& rarData, LPCTSTR pcszStr, BOOL bCase = FALSE) { int nCount = (int)rarData.GetSize(); for (int i = 0; i < nCount; i++) { const CString& strI = rarData[i]; if (bCase) { if (strI.Compare(pcszStr) == 0) { return i; } } else { if (strI.CompareNoCase(pcszStr) == 0) { return i; } } } return -1; } int Find_noCase(CStringArray& rarData, LPCTSTR strData) { return FindStr(rarData, strData, FALSE); } void AddIfNeed_noCase(CStringArray& rarData, LPCTSTR strNew) { int nFIdx = Find_noCase(rarData, strNew); if (nFIdx < 0) { rarData.Add(strNew); } } void ConcatenateArrays_noCase(CStringArray& rarDest, CStringArray& rarSrc) { int nCount = (int)rarSrc.GetSize(); for (int i = 0; i < nCount; i++) { CString strI = rarSrc[i]; AddIfNeed_noCase(rarDest, strI); } } BOOL IsEventSet(HANDLE hEvent) { DWORD dwRes = ::WaitForSingleObject(hEvent, 0); return dwRes == WAIT_OBJECT_0; } BOOL IsMutexLocked(CMutex* pMu) { if (!pMu) { ASSERT(FALSE); return FALSE; } BOOL bEntered = pMu->Lock(0); if (bEntered) { pMu->Unlock(); } return !bEntered; } CString DBG_TraceIZone(const XTP_EDIT_LINECOL* pLCStart, const XTP_EDIT_LINECOL* pLCEnd) { CString sDBGpos, sTmp; if (pLCStart && !pLCEnd && pLCStart->GetXLC() == XTP_EDIT_XLC(1, 0) ) { sDBGpos = _T("All:(1,0 - NULL)"); } else if (pLCStart || pLCEnd) { sDBGpos = _T("Part:("); sTmp = _T("NULL"); if (pLCStart) { sTmp.Format(_T("%d,%d"), pLCStart->nLine, pLCStart->nCol); } sDBGpos += sTmp + _T(" - "); sTmp = _T("NULL"); if (pLCEnd) { sTmp.Format(_T("%d,%d"), pLCEnd->nLine, pLCEnd->nCol); } sDBGpos += sTmp; sDBGpos += _T(")"); } else { sDBGpos = _T("Rest(NULL - NULL)"); } return sDBGpos; } CString DBG_TraceTB_StartEndCls(CXTPSyntaxEditLexTextBlock* pTB) { if (!pTB) { return _T("?<NULL> (? - ?) - ?"); } CString str; str.Format(_T("(%d,%d - %d,%d) - %s"), pTB->m_PosStartLC.nLine, pTB->m_PosStartLC.nCol, pTB->m_PosEndLC.nLine, pTB->m_PosEndLC.nCol, pTB->m_ptrLexClass ? (LPCTSTR)pTB->m_ptrLexClass->GetClassName() : _T("???<NULL>") ); return str; } } //BEGIN_IMPLEMENT_XTPSINK(CXTPSyntaxEditLexParser, m_SinkMT) // ON_XTP_NOTIFICATION(xtpEditOnParserStarted, OnParseEvent_NotificationHandler) // ON_XTP_NOTIFICATION(xtpEditOnTextBlockParsed, OnParseEvent_NotificationHandler) // ON_XTP_NOTIFICATION(xtpEditOnParserEnded, OnParseEvent_NotificationHandler) //END_IMPLEMENT_XTPSINK //////////////////////////////////////////////////////////////////////////// // CXTPSyntaxEditLexTextSchema void CXTPSyntaxEditTextRegion::Clear() { m_posStart.Clear(); m_posEnd.Clear(); } void CXTPSyntaxEditTextRegion::Set(const XTP_EDIT_LINECOL* pLCStart, const XTP_EDIT_LINECOL* pLCEnd) { m_posStart.nLine = INT_MAX; m_posStart.nCol = 0; m_posEnd.Clear(); if (pLCStart) { m_posStart = *pLCStart; } if (pLCEnd) { m_posEnd = *pLCEnd; } } CXTPSyntaxEditLexTokensDef::~CXTPSyntaxEditLexTokensDef() { } CXTPSyntaxEditLexTokensDef::CXTPSyntaxEditLexTokensDef(const CXTPSyntaxEditLexTokensDef& rSrc) { m_arTokens.Copy(rSrc.m_arTokens); m_arStartSeps.Copy(rSrc.m_arStartSeps); m_arEndSeps.Copy(rSrc.m_arEndSeps); } const CXTPSyntaxEditLexTokensDef& CXTPSyntaxEditLexTokensDef::operator=(const CXTPSyntaxEditLexTokensDef& rSrc) { m_arTokens.RemoveAll(); m_arStartSeps.RemoveAll(); m_arEndSeps.RemoveAll(); m_arTokens.Append(rSrc.m_arTokens); m_arStartSeps.Append(rSrc.m_arStartSeps); m_arEndSeps.Append(rSrc.m_arEndSeps); return *this; } CXTPSyntaxEditLexTextSchema::CXTPSyntaxEditLexTextSchema(LPCTSTR pcszSchName): m_evBreakParsing(FALSE, TRUE) { //m_CloserManager.SetParentObject(this); m_pClassSchema = new CXTPSyntaxEditLexClassSchema(); m_pConnectMT = new CXTPNotifyConnectionMT(); m_nNoEndedClassesCount = 0; m_curInvalidZone.Clear(); m_mapLastParsedBlocks.InitHashTable(101); m_nSeekNext_TagWaitChars = 0; m_strSchName = pcszSchName; m_bSendProgressEvents = FALSE; } CXTPSyntaxEditLexTextSchema::~CXTPSyntaxEditLexTextSchema() { Close(); CMDTARGET_RELEASE(m_pClassSchema); CMDTARGET_RELEASE(m_pConnectMT); } CString CXTPSyntaxEditLexTextSchema::GetSchName() const { return m_strSchName; } //CXTPSyntaxEditLexTextSchemaCloserManPtr CXTPSyntaxEditLexTextSchema::GetCloserManager() //{ // CSingleLock singleLockCls(GetClassSchLoker(), TRUE); // CSingleLock singleLock(GetDataLoker(), TRUE); // // ASSERT(m_CloserManager.m_ptrParentObj || m_CloserManager.m_dwRef == 0); // ASSERT(this == (CXTPSyntaxEditLexTextSchema*)m_CloserManager.m_ptrParentObj || !m_CloserManager.m_ptrParentObj); // // m_CloserManager.SetParentObject(this); // // CXTPSyntaxEditLexTextSchemaCloserManPtr ptrRes(&m_CloserManager, TRUE); // return ptrRes; //} CXTPNotifyConnection* CXTPSyntaxEditLexTextSchema::GetConnection() { return m_pConnectMT; } CXTPSyntaxEditLexClassSchema* CXTPSyntaxEditLexTextSchema::GetClassSchema() { return m_pClassSchema; } CXTPSyntaxEditLexTextSchema* CXTPSyntaxEditLexTextSchema::Clone() { CXTPSyntaxEditLexTextSchema* ptrNewSch = new CXTPSyntaxEditLexTextSchema(m_strSchName); if (!ptrNewSch) { return NULL; } CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); if (!m_pClassSchema->Copy(ptrNewSch->m_pClassSchema)) { ptrNewSch->InternalRelease(); return NULL; } return ptrNewSch; } void CXTPSyntaxEditLexTextSchema::Close() { CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); RemoveAll(); m_pClassSchema->Close(); } void CXTPSyntaxEditLexTextSchema::RemoveAll() { CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); Close(m_ptrFirstBlock); m_ptrFirstBlock = NULL; m_mapLastParsedBlocks.RemoveAll(); m_ptrLastParsedBlock = NULL; } void CXTPSyntaxEditLexTextSchema::Close(CXTPSyntaxEditLexTextBlock* pFirst) { CXTPSyntaxEditLexTextBlockPtr ptrChTB(pFirst, TRUE); while (ptrChTB) { CXTPSyntaxEditLexTextBlockPtr ptrChTBnext = ptrChTB->m_ptrNext; ptrChTB->Close(); ptrChTB = ptrChTBnext; } } BOOL CXTPSyntaxEditLexTextSchema::IsBlockStartStillHere(CTextIter* pTxtIter, CXTPSyntaxEditLexTextBlock* pTB) { if (!pTxtIter || !pTB || !pTB->m_ptrLexClass) { ASSERT(FALSE); return FALSE; } if (!pTxtIter->SeekPos(pTB->m_PosStartLC, m_evBreakParsing)) { return FALSE; } CXTPSyntaxEditLexTextBlockPtr ptrTBtmp; int nPres = pTB->m_ptrLexClass->RunParse(pTxtIter, this, ptrTBtmp); BOOL bStarted = (nPres & xtpEditLPR_StartFound) != 0; return bStarted; } // DEBUG //////////////////////////////////////////////////////////////// #ifdef DBG_TRACE_PARSE_RUN_RESULTS #define DBG_TRACE_PARSE_RUN_RESULTS_PROC(bFull) TraceTxtBlocks(bFull); #else #define DBG_TRACE_PARSE_RUN_RESULTS_PROC(bFull) #endif // END DEBUG //////////////////////////////////////////////////////////// void CXTPSyntaxEditLexTextSchema::TraceTxtBlocks(BOOL bFull) { TRACE(_T("\n*** DBG_TRACE_PARSE_RUN_RESULTS *** --( %s )---------\n"), bFull ? _T("FULL") : _T("updated part") ); CXTPSyntaxEditLexTextBlockPtr ptrTB = bFull ? m_ptrFirstBlock : m_ptrNewChainTB1; for (int i = 0; ptrTB && (bFull || ptrTB->m_ptrPrev != m_ptrNewChainTB2); i++) { TRACE(_T("(%05d) startPos=(%d,%d) endPos=(%d,%d), [%s]\n"), i, ptrTB->m_PosStartLC.nLine, ptrTB->m_PosStartLC.nCol, ptrTB->m_PosEndLC.nLine, ptrTB->m_PosEndLC.nCol, (LPCTSTR)ptrTB->m_ptrLexClass->m_strClassName); ptrTB = ptrTB->m_ptrNext; } } int CXTPSyntaxEditLexTextSchema::RunParseUpdate(BOOL bShort, CTextIter* pTxtIter, const XTP_EDIT_LINECOL* pLCStart, const XTP_EDIT_LINECOL* pLCEnd, BOOL bSendProgressEvents) { CSingleLock singleLock(GetDataLoker(), TRUE); m_mapLastParsedBlocks.RemoveAll(); singleLock.Unlock(); if (bSendProgressEvents) { m_pConnectMT->PostEvent(xtpEditOnParserStarted, 0, 0, xtpNotifyGuarantyPost | xtpNotifyDirectCallForOneThread); } int nParseRes = Run_ParseUpdate0(bShort, pTxtIter, pLCStart, pLCEnd, bSendProgressEvents); if (bSendProgressEvents) { m_pConnectMT->PostEvent(xtpEditOnParserEnded, nParseRes, 0, xtpNotifyGuarantyPost|xtpNotifyDirectCallForOneThread); } return nParseRes; } int CXTPSyntaxEditLexTextSchema::Run_ParseUpdate0(BOOL bShort, CTextIter* pTxtIter, const XTP_EDIT_LINECOL* pLCStart, const XTP_EDIT_LINECOL* pLCEnd, BOOL bSendProgressEvents) { if (!pTxtIter) { ASSERT(FALSE); return xtpEditLPR_Error; } CSingleLock singleLockCls(GetClassSchLoker(), TRUE); //------------------------- m_curInvalidZone.Set(pLCStart, pLCEnd); m_ptrNewChainTB1 = NULL; m_ptrNewChainTB2 = NULL; m_ptrOldChainTBFirst = NULL; m_nNoEndedClassesCount = 0; m_bSendProgressEvents = bSendProgressEvents; int nParseRes = 0; //** (1) ** ------------------------- CXTPSyntaxEditLexTextBlockPtr ptrStartTB = FindNearestTextBlock(m_curInvalidZone.m_posStart); if (ptrStartTB) { nParseRes = Run_ClassesUpdate1(pTxtIter, ptrStartTB, FALSE); if (nParseRes != -1) { if (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked|xtpEditLPR_RunFinished)) { DBG_TRACE_PARSE_RUN_RESULTS_PROC(TRUE); DBG_TRACE_PARSE_RUN_RESULTS_PROC(FALSE); if (m_ptrNewChainTB1) { BOOL bByBreak = (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked)) != 0; FinishNewChain(bByBreak, pTxtIter->IsEOF()); } return nParseRes; } } } if (!pLCStart || *pLCStart == XTP_EDIT_LINECOL::Pos1 || nParseRes == -1 || !ptrStartTB ) { nParseRes = 0; m_ptrOldChainTBFirst = m_ptrFirstBlock ? m_ptrFirstBlock->m_ptrNext : NULL; //** (2) ** ------------------------- CXTPSyntaxEditLexClassPtrArray* ptrArClasses = m_pClassSchema->GetClasses(bShort); int nCCount = ptrArClasses ? (int)ptrArClasses->GetSize() : 0; CXTPSyntaxEditLexClassPtr ptrTopClass = nCCount ? ptrArClasses->GetAt(0) : NULL; BOOL bRunEOF = TRUE; while (nCCount && (!pTxtIter->IsEOF() || bRunEOF) ) { bRunEOF = !pTxtIter->IsEOF(); nParseRes = Run_ClassesUpdate2(pTxtIter, ptrArClasses, m_ptrFirstBlock); if (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked|xtpEditLPR_RunFinished)) { DBG_TRACE_PARSE_RUN_RESULTS_PROC(TRUE); DBG_TRACE_PARSE_RUN_RESULTS_PROC(FALSE); if (m_ptrNewChainTB1) { BOOL bByBreak = (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked)) != 0; FinishNewChain(bByBreak, pTxtIter->IsEOF()); } return nParseRes; } //** ------------------------------------------------------------- if (!pTxtIter->IsEOF() && nCCount && !(nParseRes & xtpEditLPR_Iterated)) { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } SeekNextEx(pTxtIter, ptrTopClass); } } } DBG_TRACE_PARSE_RUN_RESULTS_PROC(TRUE); DBG_TRACE_PARSE_RUN_RESULTS_PROC(FALSE); if (m_ptrNewChainTB1) { BOOL bByBreak = (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked)) != 0; FinishNewChain(bByBreak, pTxtIter->IsEOF()); } return xtpEditLPR_RunFinished; } int CXTPSyntaxEditLexTextSchema::Run_ClassesUpdate1(CTextIter* pTxtIter, CXTPSyntaxEditLexTextBlockPtr ptrStartTB, BOOL bStarted) { if (!pTxtIter || !ptrStartTB || !ptrStartTB->m_ptrLexClass) { return xtpEditLPR_Error; } BOOL bIterated = FALSE; int nPres = 0; BOOL bRunEOF = TRUE; BOOL bEnded = FALSE; BOOL bStarted1 = bStarted; if (!bStarted) { CXTPSyntaxEditLexTextBlockPtr ptrTB = ptrStartTB; XTP_EDIT_LINECOL posStart = ptrStartTB->m_PosStartLC; bStarted1 = IsBlockStartStillHere(pTxtIter, ptrTB); while (!bStarted1 && ptrTB->m_ptrPrev) { ptrTB = ptrTB->m_ptrPrev; posStart = ptrTB->m_PosStartLC; bStarted1 = IsBlockStartStillHere(pTxtIter, ptrTB); if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } } if (!bStarted1) { return -1; // Full reparse } if (m_curInvalidZone.m_posEnd.IsValidData() && ptrTB->m_PosEndLC > m_curInvalidZone.m_posEnd) { if (ptrTB->m_ptrParent || !ptrTB->m_ptrNext) { m_curInvalidZone.m_posEnd = ptrTB->m_PosEndLC; } else { // level: file ASSERT(ptrTB->m_ptrNext); if (ptrTB->m_ptrNext->m_PosEndLC > m_curInvalidZone.m_posEnd) { m_curInvalidZone.m_posEnd = ptrTB->m_ptrNext->m_PosEndLC; } } } m_curInvalidZone.m_posStart = posStart; DBG_TRACE_PARSE_RUN_BLOCKS(_T("\nREPARSE will start from pos =(%d,%d), Run class [%s] {%d}-noEndedStack \n"), posStart.nLine, posStart.nCol, ptrTB->m_ptrParent ? (ptrTB->m_ptrParent->m_ptrLexClass ? ptrTB->m_ptrParent->m_ptrLexClass->m_strClassName : _T("?<NULL> (parent)") ) :( ptrTB->m_ptrLexClass ? ptrTB->m_ptrLexClass->m_strClassName : _T("?<NULL>") ) , m_nNoEndedClassesCount ); CString sDBGzone = DBG_TraceIZone(&m_curInvalidZone.m_posStart, &m_curInvalidZone.m_posEnd); DBG_TRACE_PARSE_RUN_UPDATE(_T("- Parser change invalid Zone [ %s ] \n"), sDBGzone); // Seek iterator to begin of the block if (!pTxtIter->SeekPos(posStart, m_evBreakParsing)) { return xtpEditLPR_Error; } if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } ASSERT(!m_ptrNewChainTB1); m_ptrNewChainTB1 = ptrTB; if (ptrTB->m_ptrPrev) { m_ptrNewChainTB1 = ptrTB->m_ptrPrev; } m_ptrOldChainTBFirst = m_ptrNewChainTB1->m_ptrNext; DBG_TRACE_PARSE_RUN_UPDATE(_T(" NewChainTB1: %s \n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB1)); DBG_TRACE_PARSE_RUN_UPDATE(_T(" OldChainTBFirst: %s \n"), DBG_TraceTB_StartEndCls(m_ptrOldChainTBFirst)); ptrStartTB = ptrTB; } CXTPSyntaxEditLexClassPtr ptrRunClass = ptrStartTB->m_ptrLexClass; //** 1 **// Run existing block with children until block end while (bStarted && !bEnded && (bRunEOF || !pTxtIter->IsEOF()) ) { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } bRunEOF = !pTxtIter->IsEOF(); BOOL bSkipIterate = FALSE; nPres = ptrRunClass->RunParse(pTxtIter, this, ptrStartTB); if (nPres & (xtpEditLPR_Error|/*xtpEditLPR_RunBreaked|*/xtpEditLPR_RunFinished)) { return nPres; } //--------------------------------------------------------------------------- if (nPres & xtpEditLPR_Iterated) { bSkipIterate = TRUE; bIterated = TRUE; } //--------------------------------------------------------------------------- bEnded = (nPres & xtpEditLPR_EndFound) != 0; if (bEnded) { CSingleLock singleLock(GetDataLoker(), TRUE); m_nNoEndedClassesCount--; int nECount = ptrStartTB->EndChildren(this); m_nNoEndedClassesCount -= nECount; //*** VALIDATION (when reparsing) if (m_ptrNewChainTB2 && m_ptrNewChainTB2->m_ptrNext) { while (m_ptrNewChainTB2->m_ptrNext && m_ptrNewChainTB2->m_ptrNext->m_PosStartLC < ptrStartTB->m_PosEndLC) { m_ptrNewChainTB2->m_ptrNext = m_ptrNewChainTB2->m_ptrNext->m_ptrNext; } } DBG_TRACE_PARSE_RUN_BLOCKS(_T("(%08x) ENDED startPos=(%d,%d) endPos=(%d,%d), [%s] {%d}-noEndedStack \n"), (CXTPSyntaxEditLexTextBlock*)ptrStartTB, ptrStartTB->m_PosStartLC.nLine, ptrStartTB->m_PosStartLC.nCol, ptrStartTB->m_PosEndLC.nLine, ptrStartTB->m_PosEndLC.nCol, ptrStartTB->m_ptrLexClass->m_strClassName, m_nNoEndedClassesCount); SendEvent_OnTextBlockParsed(ptrStartTB); } //--------------------------------------------------------------------------- if (!bEnded && !bSkipIterate) { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } SeekNextEx(pTxtIter, ptrRunClass); } } //** end run existing **// if (bStarted && !bEnded && pTxtIter->IsEOF()) { CXTPSyntaxEditLexTextBlock* pTB2end = ptrStartTB; for (; pTB2end; pTB2end = pTB2end->m_ptrParent) { pTB2end->m_PosEndLC = pTxtIter->GetPosLC(); } return xtpEditLPR_RunFinished; } if (bStarted && bEnded || pTxtIter->IsEOF()) { return xtpEditLPR_RunFinished; } //=========================================================================== CXTPSyntaxEditLexTextBlockPtr ptrTBrun = ptrStartTB; if (ptrStartTB->m_ptrParent) { ptrTBrun = ptrStartTB->m_ptrParent; bEnded = FALSE; if (ptrTBrun->m_PosEndLC >= m_curInvalidZone.m_posStart && ptrTBrun->m_PosEndLC <= m_curInvalidZone.m_posEnd) { m_nNoEndedClassesCount++; } } if (!bEnded && !pTxtIter->IsEOF()) { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } nPres = Run_ClassesUpdate1(pTxtIter, ptrTBrun, bStarted1); if (nPres & (xtpEditLPR_Error|xtpEditLPR_RunBreaked|xtpEditLPR_RunFinished)) { return nPres; } //--------------------------------- if (nPres & xtpEditLPR_Iterated) { bIterated = TRUE; } } //--------------------------------------------------------------------------- return (bIterated ? xtpEditLPR_Iterated : 0) | (pTxtIter->IsEOF() ? xtpEditLPR_RunFinished : 0); } int CXTPSyntaxEditLexTextSchema::Run_ClassesUpdate2(CTextIter* pTxtIter, CXTPSyntaxEditLexClassPtrArray* pArClasses, CXTPSyntaxEditLexTextBlockPtr ptrParentTB, CXTPSyntaxEditLexOnScreenParseCnt* pOnScreenRunCnt) { int nCCount = (int)pArClasses->GetSize(); BOOL bIterated = FALSE; int nReturn = 0; for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexClass* pClass = pArClasses->GetAt(i, FALSE); ASSERT(pClass); if (!pClass) continue; CXTPSyntaxEditLexTextBlockPtr ptrTB = NULL; int nPres = 0; BOOL bStarted = FALSE; BOOL bEnded = FALSE; BOOL bRunEOF = FALSE; do { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } bRunEOF = !pTxtIter->IsEOF(); BOOL bSkipIterate = FALSE; nPres = pClass->RunParse(pTxtIter, this, ptrTB, pOnScreenRunCnt); if (nPres & (xtpEditLPR_Error|/*xtpEditLPR_RunBreaked|*/xtpEditLPR_RunFinished)) { return nPres; } //--------------------------------------------------------------------------- if ((nPres & xtpEditLPR_StartFound) && ptrTB && !ptrTB->m_ptrPrev) { bStarted = TRUE; CSingleLock singleLock(GetDataLoker(), TRUE); ptrTB->m_ptrParent = ptrParentTB; if (ptrTB->m_ptrParent) { ptrTB->m_ptrParent->m_ptrLastChild = ptrTB; } if (!pOnScreenRunCnt) { //*** VALIDATION (when reparsing) if (m_ptrNewChainTB2 && m_ptrNewChainTB2->m_ptrNext) { while (m_ptrNewChainTB2->m_ptrNext && m_ptrNewChainTB2->m_ptrNext->m_PosStartLC < ptrTB->m_PosStartLC) { m_ptrNewChainTB2->m_ptrNext = m_ptrNewChainTB2->m_ptrNext->m_ptrNext; } if (m_ptrNewChainTB2->m_ptrNext && m_curInvalidZone.m_posEnd.IsValidData() ) { DBG_TRACE_PARSE_RUN_UPDATE(_T("\n <VALIDATE> TB current: %s \n"), DBG_TraceTB_StartEndCls(ptrTB)); DBG_TRACE_PARSE_RUN_UPDATE(_T(" <VALIDATE> TB next OLD: %s [NoEndedStack=%d]\n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB2->m_ptrNext), m_nNoEndedClassesCount); if (m_ptrNewChainTB2->m_ptrNext->m_PosStartLC == ptrTB->m_PosStartLC && ptrTB->IsEqualLexClasses(m_ptrNewChainTB2->m_ptrNext) && m_curInvalidZone.m_posEnd.IsValidData() && m_ptrNewChainTB2->m_ptrNext->m_PosStartLC > m_curInvalidZone.m_posEnd) { // BREAK. if (m_nNoEndedClassesCount <= 0) { FinishNewChain(FALSE, pTxtIter->IsEOF()); return xtpEditLPR_RunFinished; } } } } //*** m_nNoEndedClassesCount++; //************************** if (!m_ptrNewChainTB1) { // Full reparse m_ptrNewChainTB1 = ptrTB; m_ptrNewChainTB2 = NULL; //ASSERT(m_ptrFirstBlock == NULL); m_ptrFirstBlock = ptrTB; DBG_TRACE_PARSE_RUN_UPDATE(_T(" NewChainTB1 (&FirstBlock): %s \n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB1)); } else if (!m_ptrNewChainTB2) { m_ptrNewChainTB2 = m_ptrNewChainTB1; } if (nPres&xtpEditLPR_TBpop1) { if (m_ptrNewChainTB2) { if (m_ptrNewChainTB2->m_ptrPrev) { m_ptrNewChainTB2->m_ptrPrev->m_ptrNext = ptrTB; } ptrTB->m_ptrPrev = m_ptrNewChainTB2->m_ptrPrev; ptrTB->m_ptrNext = m_ptrNewChainTB2; m_ptrNewChainTB2->m_ptrPrev = ptrTB; m_ptrNewChainTB2->m_ptrParent = ptrTB; } else { m_ptrNewChainTB2 = ptrTB; //SetPrevBlock(ptrTB); } } else { if (m_ptrNewChainTB2) { ptrTB->m_ptrNext = m_ptrNewChainTB2->m_ptrNext; ptrTB->m_ptrPrev = m_ptrNewChainTB2; //GetPrevBlock(); // m_ptrNewChainTB2->m_ptrNext = ptrTB; } m_ptrNewChainTB2 = ptrTB; //SetPrevBlock(ptrTB); } //************************** } else { if (nPres&xtpEditLPR_TBpop1) { if (pOnScreenRunCnt->m_ptrTBLast) { if (pOnScreenRunCnt->m_ptrTBLast->m_ptrPrev) { pOnScreenRunCnt->m_ptrTBLast->m_ptrPrev->m_ptrNext = ptrTB; } ptrTB->m_ptrPrev = pOnScreenRunCnt->m_ptrTBLast->m_ptrPrev; ptrTB->m_ptrNext = pOnScreenRunCnt->m_ptrTBLast; pOnScreenRunCnt->m_ptrTBLast->m_ptrPrev = ptrTB; pOnScreenRunCnt->m_ptrTBLast->m_ptrParent = ptrTB; } else { pOnScreenRunCnt->m_ptrTBLast = ptrTB; } } else { ptrTB->m_ptrPrev = pOnScreenRunCnt->m_ptrTBLast; if (pOnScreenRunCnt->m_ptrTBLast) { pOnScreenRunCnt->m_ptrTBLast->m_ptrNext = ptrTB; } pOnScreenRunCnt->m_ptrTBLast = ptrTB; } } // DEBUG //////////////////////////////////////////////////////////////// DBG_TRACE_PARSE_RUN_BLOCKS(_T("(%08x) START startPos=(%d,%d), ______________ [%s] {%d}-noEndedStack \n"), (CXTPSyntaxEditLexTextBlock*)ptrTB, ptrTB->m_PosStartLC.nLine, ptrTB->m_PosStartLC.nCol, ptrTB->m_ptrLexClass->m_strClassName, m_nNoEndedClassesCount); // END DEBUG //////////////////////////////////////////////////////////// } //--------------------------------------------------------------------------- if (nPres & xtpEditLPR_Iterated) { bSkipIterate = TRUE; bIterated = TRUE; } //--------------------------------------------------------------------------- bEnded = (nPres & xtpEditLPR_EndFound) != 0; if (bEnded) { CSingleLock singleLock(GetDataLoker(), TRUE); m_nNoEndedClassesCount--; int nECount = ptrTB->EndChildren(pOnScreenRunCnt ? NULL : this); m_nNoEndedClassesCount -= nECount; // DEBUG //////////////////////////////////////////////////////////////// DBG_TRACE_PARSE_RUN_BLOCKS(_T("(%08x) ENDED startPos=(%d,%d) endPos=(%d,%d), [%s] {%d}-noEndedStack \n"), (CXTPSyntaxEditLexTextBlock*)ptrTB, ptrTB->m_PosStartLC.nLine, ptrTB->m_PosStartLC.nCol, ptrTB->m_PosEndLC.nLine, ptrTB->m_PosEndLC.nCol, ptrTB->m_ptrLexClass->m_strClassName, m_nNoEndedClassesCount); // END DEBUG //////////////////////////////////////////////////////////// if (!pOnScreenRunCnt) { SendEvent_OnTextBlockParsed(ptrTB); } } if (nPres & xtpEditLPR_RunBreaked) { return nPres; } //--------------------------------------------------------------------------- if (bStarted && !bEnded && !bSkipIterate) { if (IsEventSet(m_evBreakParsing)) { return xtpEditLPR_RunBreaked; } SeekNextEx(pTxtIter, pClass, pOnScreenRunCnt); bIterated = TRUE; } //--------------------------------------------------------------------------- if (pOnScreenRunCnt) { XTP_EDIT_LINECOL lcTextPos = pTxtIter->GetPosLC(); if (lcTextPos.nLine > pOnScreenRunCnt->m_nRowEnd) { return xtpEditLPR_RunFinished; } } } while (bStarted && !bEnded && (bRunEOF || !pTxtIter->IsEOF()) ); if (bEnded && pClass->IsRestartRunLoop()) { nReturn |= xtpEditLPR_RunRestart; break; } } return nReturn | (bIterated ? xtpEditLPR_Iterated : 0); } UINT CXTPSyntaxEditLexTextSchema::SendEvent_OnTextBlockParsed(CXTPSyntaxEditLexTextBlock* pTB) { CSingleLock singleLock(GetDataLoker(), TRUE); if (!m_bSendProgressEvents) { return 0; } CXTPSyntaxEditLexTextBlockPtr ptrTB(pTB, TRUE); WPARAM dwTBid = (WPARAM)pTB; m_mapLastParsedBlocks[dwTBid] = ptrTB; m_ptrLastParsedBlock.SetPtr(pTB, TRUE); BOOL bIsSubscribers = m_pConnectMT->PostEvent(xtpEditOnTextBlockParsed, dwTBid, 0, xtpNotifyDirectCallForOneThread); if (bIsSubscribers) { // WARNING: Why? EventsWnd must call GetLastParsedBlock() // to withdraw objects from the map! //ASSERT(m_mapLastParsedBlocks.GetCount() < 10*1000); static BOOL s_bAssert = FALSE; if (!s_bAssert && m_mapLastParsedBlocks.GetCount() > 10*1000) { s_bAssert = TRUE; ASSERT(FALSE); } } else { m_mapLastParsedBlocks.RemoveAll(); } return 0; } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::GetLastParsedBlock(WPARAM dwID) { CSingleLock singleLock(GetDataLoker(), TRUE); if (dwID) { CXTPSyntaxEditLexTextBlockPtr ptrTB; if (m_mapLastParsedBlocks.Lookup(dwID, ptrTB)) { m_mapLastParsedBlocks.RemoveKey(dwID); return ptrTB.Detach(); } } else { return m_ptrLastParsedBlock.GetInterface(TRUE); } // ASSERT(FALSE); return NULL; } void CXTPSyntaxEditLexTextSchema::FinishNewChain(BOOL bByBreak, BOOL bEOF) { CSingleLock singleLock(GetDataLoker(), TRUE); CXTPSyntaxEditLexTextBlockPtr ptrTBOldLast = NULL; DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> NewChainTB1: %s \n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB1)); if (m_ptrNewChainTB2) { DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> NewChainTB2-raw: %s \n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB2)); if (bByBreak && !bEOF) { // roll back no-ended blocks while ( !m_ptrNewChainTB2->m_PosEndLC.IsValidData() && m_ptrNewChainTB2->m_ptrPrev && m_ptrNewChainTB2 != m_ptrNewChainTB1) { CXTPSyntaxEditLexTextBlockPtr ptrTBclose = m_ptrNewChainTB2; m_ptrNewChainTB2 = m_ptrNewChainTB2->m_ptrPrev; m_ptrNewChainTB2->m_ptrNext = ptrTBclose->m_ptrNext; DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> CLOSE TB-RollBacked: %s \n"), DBG_TraceTB_StartEndCls(ptrTBclose)); ptrTBclose->Close(); } DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> NewChainTB2-RollBacked: %s \n"), DBG_TraceTB_StartEndCls(m_ptrNewChainTB2)); } // end no-ended blocks EndBlocksByParent(m_ptrNewChainTB1, m_ptrNewChainTB2); if (m_ptrNewChainTB2 == m_ptrNewChainTB1) { UpdateLastSchBlock(m_ptrNewChainTB2); m_ptrOldChainTBFirst = NULL; return; } // synchronize new and old chains while (m_ptrNewChainTB2->m_ptrNext && (m_ptrNewChainTB2->m_ptrNext->m_PosStartLC < m_ptrNewChainTB2->m_PosStartLC || m_ptrNewChainTB2->m_ptrNext->m_PosStartLC == m_ptrNewChainTB2->m_PosStartLC && m_ptrNewChainTB2->m_ptrNext->IsEqualLexClasses(m_ptrNewChainTB2) ) ) { m_ptrNewChainTB2->m_ptrNext = m_ptrNewChainTB2->m_ptrNext->m_ptrNext; } if (m_ptrNewChainTB2->m_ptrNext) { m_ptrNewChainTB2->m_ptrNext->m_ptrPrev = m_ptrNewChainTB2; m_curInvalidZone.m_posEnd = m_ptrNewChainTB2->m_ptrNext->m_PosStartLC; } else { m_curInvalidZone.m_posEnd = m_ptrNewChainTB2->m_PosStartLC; } if (!bEOF) { ptrTBOldLast = m_ptrNewChainTB2->m_ptrNext; } } else if (bByBreak) { if (m_ptrNewChainTB2) { UpdateLastSchBlock(m_ptrNewChainTB2); } m_ptrOldChainTBFirst = NULL; m_ptrNewChainTB1 = NULL; m_ptrNewChainTB2 = NULL; m_nNoEndedClassesCount = 0; return; } else { // No new blocks found after chain branch. // (All rest blocks where deleted) if (m_ptrNewChainTB1) { m_ptrNewChainTB1->m_ptrNext = NULL; UpdateLastSchBlock(m_ptrNewChainTB1, TRUE); } else if (m_ptrFirstBlock) { m_ptrFirstBlock->m_ptrNext = NULL; UpdateLastSchBlock(m_ptrFirstBlock, TRUE); } } DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> OldChainTBFirst: %s \n"), DBG_TraceTB_StartEndCls(m_ptrOldChainTBFirst)); DBG_TRACE_PARSE_RUN_UPDATE(_T(" <F> TBOldLast: %s \n"), DBG_TraceTB_StartEndCls(ptrTBOldLast)); CXTPSyntaxEditLexTextBlockPtr ptrTBOld = m_ptrOldChainTBFirst; while (ptrTBOld && ptrTBOld != ptrTBOldLast) { CXTPSyntaxEditLexTextBlockPtr ptrTBclose = ptrTBOld; ptrTBOld = ptrTBOld->m_ptrNext; ptrTBclose->Close(); } if (m_ptrNewChainTB2 && m_ptrNewChainTB2->m_ptrNext && m_ptrNewChainTB2->m_ptrNext->IsLookLikeClosed()) { m_ptrNewChainTB2->m_ptrNext = NULL; UpdateLastSchBlock(m_ptrNewChainTB2, TRUE); } //=================================== if (m_ptrNewChainTB2 && m_ptrNewChainTB1) { UpdateNewChainParentsChildren(); } //=================================== if (m_ptrNewChainTB2) { // && m_ptrNewChainTB2->m_ptrNext == NULL) UpdateLastSchBlock(m_ptrNewChainTB2); } //----------------------------------- m_ptrOldChainTBFirst = NULL; m_ptrNewChainTB1 = NULL; m_ptrNewChainTB2 = NULL; m_nNoEndedClassesCount = 0; } void CXTPSyntaxEditLexTextSchema::UpdateNewChainParentsChildren() { CSingleLock singleLock(GetDataLoker(), TRUE); if (!m_ptrNewChainTB2 || !m_ptrNewChainTB1) { return; } if (m_ptrNewChainTB1 != m_ptrFirstBlock) { //update children for new chain blocks CXTPSyntaxEditLexTextBlock* pTB_chi = m_ptrNewChainTB2->m_ptrNext; for (; pTB_chi; pTB_chi = pTB_chi->m_ptrNext) { if (pTB_chi->m_ptrParent && pTB_chi->m_ptrParent->IsLookLikeClosed()) { CXTPSyntaxEditLexTextBlock* pTB_Par = pTB_chi->m_ptrPrev; for (; pTB_Par; pTB_Par = pTB_Par->m_ptrPrev) { if (pTB_Par->IsInclude(pTB_chi)) { pTB_chi->m_ptrParent.SetPtr(pTB_Par, TRUE); ASSERT(!pTB_Par->IsLookLikeClosed()); break; } } } } } } void CXTPSyntaxEditLexTextSchema::EndBlocksByParent(CXTPSyntaxEditLexTextBlock* pTBStart, CXTPSyntaxEditLexTextBlock* pTBEnd) { CSingleLock singleLock(GetDataLoker(), TRUE); if (!pTBStart) { return; } CXTPSyntaxEditLexTextBlock* pTB_chi = pTBStart; for (; pTB_chi != pTBEnd->m_ptrNext; pTB_chi = pTB_chi->m_ptrNext) { if (!pTB_chi->m_PosEndLC.IsValidData()) { //ASSERT(pTB_chi->m_ptrParent && pTB_chi->m_ptrParent->m_PosEndLC.IsValidData()); if (pTB_chi->m_ptrParent && pTB_chi->m_ptrParent->m_PosEndLC.IsValidData()) { pTB_chi->m_PosEndLC = pTB_chi->m_ptrParent->m_PosEndLC; } } } } int CXTPSyntaxEditLexTextSchema::RunChildren(CTextIter* pTxtIter, CXTPSyntaxEditLexTextBlockPtr ptrTxtBlock, CXTPSyntaxEditLexClass* pBase, CXTPSyntaxEditLexOnScreenParseCnt* pOnScreenRunCnt) { if (!pTxtIter || !pBase) { ASSERT(FALSE); return xtpEditLPR_Error; } int nRes = 0; CXTPSyntaxEditLexClassPtrArray* pArClasses[3]; pArClasses[0] = pBase->GetChildren(); pArClasses[1] = pBase->GetChildrenDyn(); pArClasses[2] = pBase->GetChildrenSelfRef(); for (int i = 0; i < _countof(pArClasses); i++) { if (pArClasses[i] && pArClasses[i]->GetSize()) { int nResLocal = Run_ClassesUpdate2(pTxtIter, pArClasses[i], ptrTxtBlock, pOnScreenRunCnt); nRes |= nResLocal; if (nRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked|xtpEditLPR_RunFinished|xtpEditLPR_RunRestart)) { break; } } } return nRes; } void CXTPSyntaxEditLexTextSchema::SeekNextEx(CTextIter* pTxtIter, CXTPSyntaxEditLexClass* pRunClass, CXTPSyntaxEditLexOnScreenParseCnt* pOnScreenRunCnt, int nChars ) { if (!pTxtIter || !pRunClass) { ASSERT(FALSE); return; } pTxtIter->SeekNext(nChars); m_nSeekNext_TagWaitChars -= nChars; CXTPSyntaxEditLexObj_ActiveTags* pAT = m_pClassSchema->GetActiveTagsFor(pRunClass); if (pAT && m_nSeekNext_TagWaitChars) { int i = 0; //BOOL bCase = FALSE; //pRunClass->IsCaseSensitive(); CString strTmp; BOOL bTag = FALSE; while (!bTag && !pTxtIter->IsEOF() && m_nSeekNext_TagWaitChars) { //bTag = CXTPSyntaxEditLexClass::Run_Tags1(pTxtIter, pAT, strTmp, bCase, FALSE); // bTag = pAT->FindMinWord(pTxtIter->GetText(1024), strTmp, 1024, TRUE, FALSE); // for test(DEBUG) Only #ifdef DBG_AUTOMAT BOOL bCase = FALSE; //pRunClass->IsCaseSensitive(); CString strTmpX; BOOL bTagX = CXTPSyntaxEditLexClass::Run_Tags1(pTxtIter, pAT, strTmpX, bCase, FALSE); if (bTagX != bTag) { //ASSERT(FALSE); pAT->BuildAutomat(TRUE); bTag = pAT->FindMinWord(pTxtIter->GetText(1024), strTmp, 1024, TRUE, FALSE); } if (bTag) { strTmp.Empty(); bTag = CXTPSyntaxEditLexClass::Run_Tags1(pTxtIter, pAT, strTmp, bCase, FALSE); } #endif if (!bTag) { pTxtIter->SeekNext(1); m_nSeekNext_TagWaitChars--; } if (++i%10 == 0 && IsEventSet(m_evBreakParsing)) { return; } if (pOnScreenRunCnt) { XTP_EDIT_LINECOL lcTextPos = pTxtIter->GetPosLC(); if (lcTextPos.nLine > pOnScreenRunCnt->m_nRowEnd) { return; } } } ASSERT(bTag || pTxtIter->IsEOF() || !m_nSeekNext_TagWaitChars); //---------------------- if (bTag) { m_nSeekNext_TagWaitChars = (int)_tcsclen(strTmp); ASSERT(m_nSeekNext_TagWaitChars > 0); } } } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::GetPrevBlock(BOOL bWithAddRef) { CSingleLock singleLock(GetDataLoker(), TRUE); return m_ptrNewChainTB2.GetInterface(bWithAddRef); } void CXTPSyntaxEditLexTextSchema::UpdateLastSchBlock(CXTPSyntaxEditLexTextBlock* pLastTB, BOOL bPermanently) { CSingleLock singleLock(GetDataLoker(), TRUE); if (!pLastTB || !m_ptrLastSchBlock || bPermanently) { m_ptrLastSchBlock.SetPtr(pLastTB, TRUE); return; } if (pLastTB->m_PosStartLC >= m_ptrLastSchBlock->m_PosStartLC) { m_ptrLastSchBlock.SetPtr(pLastTB, TRUE); } } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::GetLastSchBlock(BOOL bWithAddRef) { CSingleLock singleLock(GetDataLoker(), TRUE); if (m_ptrLastSchBlock && !m_ptrNewChainTB2) { return m_ptrLastSchBlock.GetInterface(bWithAddRef); } if (!m_ptrLastSchBlock && m_ptrNewChainTB2) { return m_ptrNewChainTB2.GetInterface(bWithAddRef); } if (m_ptrLastSchBlock && m_ptrNewChainTB2) { if (m_ptrLastSchBlock->m_PosStartLC < m_ptrNewChainTB2->m_PosStartLC) { return m_ptrNewChainTB2.GetInterface(bWithAddRef); } else { return m_ptrLastSchBlock.GetInterface(bWithAddRef); } } return NULL; } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::GetNewBlock() { CXTPSyntaxEditLexTextBlock* p = new CXTPSyntaxEditLexTextBlock(); return p; } void CXTPSyntaxEditLexTextSchema::GetTextAttributes(XTP_EDIT_TEXTBLOCK& rTB, CXTPSyntaxEditLexTextBlock* pTextBlock) { if (!pTextBlock || !pTextBlock->m_ptrLexClass) { return; } pTextBlock->m_ptrLexClass->GetTextAttributes(rTB); } void CXTPSyntaxEditLexTextSchema::TraceClrBlocks(CXTPSyntaxEditTextBlockArray& arBlocks) { // DEBUG //////////////////////////////////////////////////////////////// #ifdef DBG_TRACE_DRAW_BLOCKS TRACE(_T("\n*** bloks --------------------\n")); for (int i = 0; i < arBlocks.GetSize(); i++) { XTP_EDIT_TEXTBLOCK BlkI = arBlocks[i]; TRACE(_T("(%02d) start =%d, ?end=%d, color=%X \n"), i, BlkI.nPos, BlkI.nNextBlockPos, BlkI.clrBlock.crText); } TRACE(_T("***\n")); #else UNREFERENCED_PARAMETER(arBlocks); #endif // END DEBUG //////////////////////////////////////////////////////////// } void CXTPSyntaxEditLexTextSchema::AddClrBlock(XTP_EDIT_TEXTBLOCK& rClrB, CXTPSyntaxEditTextBlockArray& arBlocks) { #ifdef DBG_TRACE_DRAW_BLOCKS TRACE(_T(" --- ADD --- start =%d, ?end=%d, color=%X \n"), rClrB.nPos, rClrB.nNextBlockPos, rClrB.clrBlock.crText); #endif int nCount = (int)arBlocks.GetSize(); //** A. ** new block is included in the existing block int i; for (i = 0; i < nCount; i++) { XTP_EDIT_TEXTBLOCK& BlkI = arBlocks[i]; if (rClrB.nNextBlockPos < BlkI.nPos || rClrB.nPos >= BlkI.nNextBlockPos ) { continue; } XTP_EDIT_TEXTBLOCK BlkI2;// = BlkI; if (rClrB.nPos >= BlkI.nPos && rClrB.nNextBlockPos <= BlkI.nNextBlockPos) { // override equal block if (rClrB.nPos == BlkI.nPos && rClrB.nNextBlockPos == BlkI.nNextBlockPos) { BlkI = rClrB; //arBlocks[i] = rClrB; return; } // override BEGIN of the existing block if (rClrB.nPos == BlkI.nPos && rClrB.nNextBlockPos < BlkI.nNextBlockPos) { BlkI.nPos = rClrB.nNextBlockPos; //arBlocks[i] = BlkI; arBlocks.InsertAt(i, rClrB); return; } // override END of the existing block if (rClrB.nPos > BlkI.nPos && rClrB.nNextBlockPos == BlkI.nNextBlockPos) { BlkI.nNextBlockPos = rClrB.nPos; //arBlocks[i] = BlkI; arBlocks.InsertAt(i+1, rClrB); return; } BlkI2 = BlkI; // INSERT inside to the existing block BlkI2.nPos = rClrB.nNextBlockPos; BlkI.nNextBlockPos = rClrB.nPos; //arBlocks[i] = BlkI; arBlocks.InsertAt(i+1, BlkI2); arBlocks.InsertAt(i+1, rClrB); return; } } //** B. ** new block is bigger then existing block nCount = (int)arBlocks.GetSize(); BOOL bInserted = FALSE; for (i = nCount-1; i >= 0; i--) { XTP_EDIT_TEXTBLOCK BlkI = arBlocks[i]; if (rClrB.nNextBlockPos > BlkI.nPos && rClrB.nNextBlockPos < BlkI.nNextBlockPos) { BlkI.nPos = rClrB.nNextBlockPos; arBlocks[i] = BlkI; if (!bInserted) { arBlocks.InsertAt(i, rClrB); bInserted = TRUE; } } else if (rClrB.nPos <= BlkI.nPos && rClrB.nNextBlockPos >= BlkI.nNextBlockPos) { arBlocks.RemoveAt(i); } else if (rClrB.nNextBlockPos > BlkI.nPos && rClrB.nNextBlockPos < BlkI.nNextBlockPos ) { BlkI.nNextBlockPos = rClrB.nPos; arBlocks[i] = BlkI; if (!bInserted) { arBlocks.InsertAt(i+1, rClrB); bInserted = TRUE; } } } //---------------- if (!bInserted) { arBlocks.Add(rClrB); } } void CXTPSyntaxEditLexTextSchema::GetRowColors(CTextIter* pTxtIter, int nRow, int nColFrom, int nColTo, const XTP_EDIT_COLORVALUES& clrDefault, CXTPSyntaxEditTextBlockList* rBlocks, CXTPSyntaxEditLexTextBlockPtr* pptrTBStartCache, CXTPSyntaxEditLexTextBlock* pFirstSchTB) { if (!pTxtIter) { ASSERT(FALSE); return; } XTP_EDIT_TEXTBLOCK tmpBlk; tmpBlk.nPos = 0; tmpBlk.nNextBlockPos = 0; tmpBlk.clrBlock = clrDefault; int nLineLen = pTxtIter->GetLineLen(nRow, FALSE); if (!nLineLen) { return; } XTP_EDIT_LINECOL LCStart= {nRow, nColFrom}; XTP_EDIT_LINECOL LCEnd = {nRow, nLineLen}; if (nColTo > 0 && nColTo < nLineLen) { LCEnd.nCol = nColTo; } CXTPSyntaxEditTextBlockArray arBlocks; arBlocks.SetSize(0, 4096); XTP_EDIT_TEXTBLOCK bltTB; bltTB.nPos = 0; CSingleLock singleLock(GetDataLoker()); //BOOL bLocked = TryLockCS(&singleLock, GetDataLoker(), 30, 5); BOOL bLocked = singleLock.Lock(30); //--------------------------------------------------------------------------- CXTPSyntaxEditLexTextBlockPtr ptrTBfirst, ptrTBstart; if (bLocked) { ptrTBfirst = GetBlocks(); if (pFirstSchTB) { ptrTBfirst.SetPtr(pFirstSchTB, TRUE); } if (pptrTBStartCache) { ptrTBstart = *pptrTBStartCache; } if (!ptrTBstart || ptrTBstart == ptrTBfirst || ptrTBstart->IsLookLikeClosed()) { ptrTBstart = ptrTBfirst ? ptrTBfirst->m_ptrNext : NULL; } } //= process first blk ==================================================== // if (ptrTBfirst) { bltTB.clrBlock = clrDefault; bltTB.lf = tmpBlk.lf; GetTextAttributes(bltTB, ptrTBfirst); bltTB.nPos = 0; bltTB.nNextBlockPos = nLineLen; AddClrBlock(bltTB, arBlocks); TraceClrBlocks(arBlocks); } //======================================================================== CXTPSyntaxEditLexTextBlockPtrArray arTBStack; CXTPSyntaxEditLexTextBlockPtr ptrTBStartCache; for (CXTPSyntaxEditLexTextBlock* pTB = ptrTBstart; pTB; pTB = pTB->m_ptrNext) { //BOOL bEndValid = pTB->m_PosEndLC.IsValidData(); //if (bEndValid && // (pTB->m_PosEndLC < LCStart || pTB->m_PosEndLC < pTB->m_PosStartLC) || // !bEndValid && pTB->m_ptrParent) if (pTB->GetPosEndLC() < LCStart || pTB->m_PosEndLC < pTB->m_PosStartLC) { continue; } if (LCEnd < pTB->m_PosStartLC) { break; } XTP_EDIT_LINECOL TB_PosEndLC = pTB->m_PosEndLC; if (!pTB->m_PosEndLC.IsValidData() && !pTB->m_ptrParent) { TB_PosEndLC.nLine = nRow; TB_PosEndLC.nCol = nLineLen; } if (!ptrTBStartCache) { ptrTBStartCache.SetPtr(pTB, TRUE); ASSERT(pTB->m_ptrParent); } CXTPSyntaxEditLexTextBlock* pTBStackLast = NULL; while (pTB->m_ptrNext && pTB->m_ptrNext->m_PosStartLC <= pTB->m_PosStartLC && pTB->m_ptrNext->m_PosEndLC.IsValidData() && pTB->m_PosEndLC.IsValidData() && pTB->m_ptrNext->m_PosEndLC > pTB->m_PosEndLC) { if (arTBStack.GetSize() == 0) { arTBStack.AddPtr(pTB, TRUE); } arTBStack.Add(pTB->m_ptrNext); pTBStackLast = pTB->m_ptrNext; pTB = pTB->m_ptrNext; } int nStackCount = (int)arTBStack.GetSize(); for (;nStackCount >= 0;) { if (nStackCount > 0) { pTB = arTBStack[nStackCount-1]; } nStackCount--; if (nStackCount >= 0) { arTBStack.RemoveAt(nStackCount); TB_PosEndLC = pTB->m_PosEndLC; if (!pTB->m_PosEndLC.IsValidData() /*&& !pTB->m_ptrParent*/) { TB_PosEndLC.nLine = nRow; TB_PosEndLC.nCol = nLineLen; } } //restore default values bltTB.clrBlock = clrDefault; bltTB.lf = tmpBlk.lf; GetTextAttributes(bltTB, pTB); if (pTB->m_PosStartLC > LCStart) { bltTB.nNextBlockPos = TB_PosEndLC.nLine == nRow ? min(TB_PosEndLC.nCol+1, nLineLen) : nLineLen; bltTB.nPos = pTB->m_PosStartLC.nCol; AddClrBlock(bltTB, arBlocks); TraceClrBlocks(arBlocks); } else { bltTB.nNextBlockPos = TB_PosEndLC.nLine == nRow ? min(TB_PosEndLC.nCol+1, nLineLen) : nLineLen; bltTB.nPos = 0; AddClrBlock(bltTB, arBlocks); TraceClrBlocks(arBlocks); } } //-------------------- if (pTBStackLast) { pTB = pTBStackLast; } } //---------------------------------------- if (pptrTBStartCache) { ptrTBstart = *pptrTBStartCache; if (!ptrTBstart || ptrTBstart->IsLookLikeClosed()) { *pptrTBStartCache = ptrTBStartCache; ASSERT(!ptrTBStartCache || !ptrTBStartCache->IsLookLikeClosed()); } } //----------------------------- if (bLocked) { singleLock.Unlock(); } //=========================================================================== int nPos = 0; int i; for (i = 0; i < arBlocks.GetSize(); i++) { XTP_EDIT_TEXTBLOCK BlkI = arBlocks[i]; if (nPos < BlkI.nPos) { tmpBlk.nPos = nPos; tmpBlk.nNextBlockPos = BlkI.nPos; AddClrBlock(tmpBlk, arBlocks); TraceClrBlocks(arBlocks); i++; } nPos = BlkI.nNextBlockPos; } //=========================================================================== if (arBlocks.GetSize() == 0) { tmpBlk.nPos = 0; tmpBlk.nNextBlockPos = nLineLen; arBlocks.Add(tmpBlk); } else { //--------------------------------------------------------------------------- XTP_EDIT_TEXTBLOCK BlkI = arBlocks[arBlocks.GetSize()-1]; if (BlkI.nNextBlockPos < nLineLen) { tmpBlk.nPos = BlkI.nNextBlockPos; tmpBlk.nNextBlockPos = nLineLen; AddClrBlock(tmpBlk, arBlocks); TraceClrBlocks(arBlocks); } } //************************************************************************** // DEBUG //////////////////////////////////////////////////////////////// #ifdef DBG_TRACE_DRAW_BLOCKS TRACE(_T("\n*** DBG_TRACE_DRAW_BLOCKS *** --------------------\n")); TRACE(_T("row=%d, row_len = %d \n"), nRow, nLineLen); #endif // END DEBUG //////////////////////////////////////////////////////////// for (i = 0; i < arBlocks.GetSize(); i++) { XTP_EDIT_TEXTBLOCK& BlkI = arBlocks[i]; rBlocks->AddTail(BlkI); // DEBUG //////////////////////////////////////////////////////////////// #ifdef DBG_TRACE_DRAW_BLOCKS TRACE(_T("(%02d) start =%d, ?end=%d, color=%X \n"), i, BlkI.nPos, BlkI.nNextBlockPos, BlkI.clrBlock.crText); #endif // END DEBUG //////////////////////////////////////////////////////////// } } void CXTPSyntaxEditLexTextSchema::GetCollapsableBlocksInfo(int nRow, CXTPSyntaxEditRowsBlockArray& rArBlocks, CXTPSyntaxEditLexTextBlockPtr* pptrTBStartCache) { static const CString s_strCollapsedText_def = _T("[..]"); rArBlocks.RemoveAll(); CSingleLock singleLock(GetDataLoker()); //BOOL bLocked = TryLockCS(&singleLock, GetDataLoker(), 30); BOOL bLocked = singleLock.Lock(30); if (!bLocked) { return; } XTP_EDIT_ROWSBLOCK tmpCoBlk; //--------------------------------------------------------------------------- ASSERT(bLocked); CXTPSyntaxEditLexTextBlockPtr ptrTBstart; if (pptrTBStartCache) { ptrTBstart = *pptrTBStartCache; } if (!ptrTBstart || ptrTBstart->IsLookLikeClosed()) { ptrTBstart = GetBlocks(); } CXTPSyntaxEditLexTextBlockPtr ptrTBStartCache; for (CXTPSyntaxEditLexTextBlock* pTB = ptrTBstart; pTB; pTB = pTB->m_ptrNext) { if (nRow >= 0 && nRow < pTB->m_PosStartLC.nLine) { break; } XTP_EDIT_LINECOL TB_PosEndLC = pTB->GetPosEndLC(); // pTB->m_PosEndLC; if (nRow < 0 || (nRow >= pTB->m_PosStartLC.nLine && nRow <= TB_PosEndLC.nLine) ) { if (!ptrTBStartCache && pTB->m_ptrParent) { ptrTBStartCache.SetPtr(pTB, TRUE); } if (pTB->m_PosStartLC.nLine < TB_PosEndLC.nLine && pTB->m_ptrParent ) { CXTPSyntaxEditLexClass* pLexClass = pTB->m_ptrLexClass; ASSERT(pLexClass); int nCollapsable = pLexClass->IsCollapsable(); if (pLexClass && nCollapsable && (nCollapsable == 2 || !pTB->m_bEndByParent && TB_PosEndLC != XTP_EDIT_LINECOL::MAXPOS)) { tmpCoBlk.lcStart = pTB->m_PosStartLC; tmpCoBlk.lcEnd = TB_PosEndLC; CXTPSyntaxEditLexVariantPtr ptrLVtext; ptrLVtext = pLexClass->GetAttribute(XTPLEX_ATTR_COLLAPSEDTEXT, FALSE); if (ptrLVtext && ptrLVtext->IsStrType()) { tmpCoBlk.strCollapsedText = ptrLVtext->GetStr(); } else { tmpCoBlk.strCollapsedText = s_strCollapsedText_def; } rArBlocks.Add(tmpCoBlk); } } } } //---------------------------------------- if (pptrTBStartCache) { ptrTBstart = *pptrTBStartCache; if (!ptrTBstart || ptrTBstart->IsLookLikeClosed()) { *pptrTBStartCache = ptrTBStartCache; ASSERT(!ptrTBStartCache || !ptrTBStartCache->IsLookLikeClosed()); } } } void CXTPSyntaxEditLexTextSchema::ApplyThemeRecursive(CXTPSyntaxEditColorTheme* pTheme, CXTPSyntaxEditLexClassPtrArray* ptrClasses) { // if pTheme == NULL - Restore default values only const static CString strAttrPref = XTPLEX_ATTR_TXTPREFIX; ASSERT(ptrClasses); int nCount = ptrClasses ? (int)ptrClasses->GetSize() : 0; for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = ptrClasses->GetAt(i); if (!ptrC) { ASSERT(FALSE); continue; } // Traverse the tree ApplyThemeRecursive(pTheme, ptrC->GetChildren()); ApplyThemeRecursive(pTheme, ptrC->GetChildrenDyn()); //------------------------------------------------------- const CString strCName = ptrC->GetClassName(); // restore default attributes (colors) CXTPSyntaxEditLexClassPtr ptrCDefault = m_pClassSchema->GetPreBuildClass(strCName); ASSERT(ptrCDefault); if (ptrCDefault) { ptrC->CopyAttributes(ptrCDefault, XTPLEX_ATTR_TXTPREFIX); } CXTPSyntaxEditColorInfo* pColors = pTheme ? pTheme->GetColorInfo(strCName, pTheme->GetFileName()) : NULL; if (!pColors) { continue; } // Apply new attributes (colors) POSITION posParam = pColors->GetFirstParamNamePosition(); while (posParam) { static const int c_nClrPrefLen = (int)_tcsclen(XTPLEX_ATTR_COLORPREFIX); CString strParamName = pColors->GetNextParamName(posParam); DWORD dwValue = pColors->GetHexParam(strParamName); CString strAttrName = strAttrPref + strParamName; if (_tcsnicmp(strAttrName, XTPLEX_ATTR_COLORPREFIX, c_nClrPrefLen) == 0) { dwValue = XTP_EDIT_RGB_INT2CLR(dwValue); } CXTPSyntaxEditLexVariant lvAttr((int)dwValue); ptrC->SetAttribute(strAttrName, lvAttr); } } } void CXTPSyntaxEditLexTextSchema::ApplyTheme(CXTPSyntaxEditColorTheme* pTheme) { // if pTheme == NULL - Restore default values only CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); CXTPSyntaxEditLexClassPtrArray* ptrClassesFull = m_pClassSchema->GetClasses(FALSE); CXTPSyntaxEditLexClassPtrArray* ptrClassesShort = m_pClassSchema->GetClasses(TRUE); ApplyThemeRecursive(pTheme, ptrClassesFull); ApplyThemeRecursive(pTheme, ptrClassesShort); } //////////////////////////////////////////////////////////////////////////// // CXTPSyntaxEditLexClassSchema CXTPSyntaxEditLexClassSchema::CXTPSyntaxEditLexClassSchema() { XTPGetLexAutomatMemMan()->Lock(); } CXTPSyntaxEditLexClassSchema::~CXTPSyntaxEditLexClassSchema() { XTPGetLexAutomatMemMan()->Unlok(); } void CXTPSyntaxEditLexClassSchema::AddPreBuildClass(CXTPSyntaxEditLexClass* pClass) { CXTPSyntaxEditLexClassPtr ptrC(pClass, TRUE); m_arPreBuildClassesList.Add(ptrC); } CXTPSyntaxEditLexClassPtrArray* CXTPSyntaxEditLexClassSchema::GetChildrenFor(CXTPSyntaxEditLexClass* pClass, BOOL& rbSelfChild) { rbSelfChild = FALSE; CXTPSyntaxEditLexClassPtrArray arChildren; BOOL bForFile = pClass == NULL; int nChidrenOpt = xtpEditOptChildren_Any; CStringArray arChidrenData; CString strParentName; if (pClass) { pClass->GetChildrenOpt(nChidrenOpt, arChidrenData); strParentName = pClass->GetClassName(); } if (nChidrenOpt == xtpEditOptChildren_No) { return NULL; } int nCCount = (int)m_arPreBuildClassesList.GetSize(); for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = m_arPreBuildClassesList[i]; int nParentOpt; CStringArray arParentData; ptrC->GetParentOpt(nParentOpt, arParentData); CString strCName = ptrC->GetClassName(); if (bForFile && nParentOpt == xtpEditOptParent_file) { arChildren.Add(ptrC); } else if (!bForFile && nParentOpt == xtpEditOptParent_direct) { ASSERT(pClass); if (nChidrenOpt == xtpEditOptChildren_List) { if (Find_noCase(arChidrenData, strCName) < 0) { continue; } } int nNCount = (int)arParentData.GetSize(); for (int n = 0; n < nNCount; n++) { CString strCN = arParentData[n]; if (strCN.CompareNoCase(strParentName) == 0) { if (strCName.CompareNoCase(strParentName) == 0) { rbSelfChild = TRUE; } else { arChildren.Add(ptrC); } break; } } } } //-------------------------------- CXTPSyntaxEditLexClassPtrArray* pArChildren = NULL; if (arChildren.GetSize()) { pArChildren = new CXTPSyntaxEditLexClassPtrArray; if (pArChildren) { pArChildren->Append(arChildren); } } return pArChildren; } int CXTPSyntaxEditLexClassSchema::CanBeParentDynForChild(CString strParentName, CXTPSyntaxEditLexClass* pCChild) { if (!pCChild) { ASSERT(FALSE); return FALSE; } int nParentOpt; CStringArray arParentData; pCChild->GetParentOpt(nParentOpt, arParentData); if (nParentOpt != xtpEditOptParent_dyn) { return -1; } int nCCount = (int)m_arPreBuildClassesList.GetSize(), n; for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = m_arPreBuildClassesList[i]; CString strCName = ptrC->GetClassName(); int nNCount = (int)arParentData.GetSize(); for (n = 0; n < nNCount; n++) { CString strCN = arParentData[n]; if (strParentName.CompareNoCase(strCN) == 0) { return TRUE; } } //------------------------------------------------------- if (nParentOpt == xtpEditOptParent_dyn ) { int nDataCount = (int)arParentData.GetSize(); for (n = 0; n < nDataCount; n++) { CString strCN = arParentData[n]; if (strCName.CompareNoCase(strCN) == 0) { BOOL bCanDyn = CanBeParentDynForChild(strParentName, ptrC); if (bCanDyn) { return TRUE; } } } } } return FALSE; } CXTPSyntaxEditLexClass* CXTPSyntaxEditLexClassSchema::GetPreBuildClass(const CString& strName) { int nCCount = (int)m_arPreBuildClassesList.GetSize(); for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = m_arPreBuildClassesList[i]; const CString strCName = ptrC->GetClassName(); if (strName.CompareNoCase(strCName) == 0) { return ptrC.Detach(); } } return NULL; } void CXTPSyntaxEditLexClassSchema::GetDynParentsList(CXTPSyntaxEditLexClass* pClass, CStringArray& rarDynParents, CStringArray& rarProcessedClasses) { if (!pClass) { ASSERT(FALSE); return; } CString strClassName = pClass->GetClassName(); if (Find_noCase(rarProcessedClasses, strClassName) >= 0) { return; } rarProcessedClasses.Add(strClassName); int nParentOpt; CStringArray arParentData; pClass->GetParentOpt(nParentOpt, arParentData); if (nParentOpt == xtpEditOptParent_file) { return; } ConcatenateArrays_noCase(rarDynParents, arParentData); int nNCount = (int)arParentData.GetSize(); for (int n = 0; n < nNCount; n++) { CString strParent1 = arParentData[n]; if (strClassName.CompareNoCase(strParent1) == 0) { continue; } CXTPSyntaxEditLexClassPtr ptrC = GetPreBuildClass(strParent1); if (ptrC) { GetDynParentsList(ptrC, rarDynParents, rarProcessedClasses); } else { //TRACE } } } CXTPSyntaxEditLexClassPtrArray* CXTPSyntaxEditLexClassSchema::GetDynChildrenFor(CXTPSyntaxEditLexClass* pClass, BOOL& rbSelfChild) { rbSelfChild = FALSE; int nChidrenOpt = xtpEditOptChildren_Any; CStringArray arChidrenData; if (pClass) { pClass->GetChildrenOpt(nChidrenOpt, arChidrenData); } if (nChidrenOpt == xtpEditOptChildren_No) { return NULL; } if (!pClass) return NULL; CString strMainCName = pClass->GetClassName(); CStringArray arMainParents; CStringArray arProcessedClasses; GetDynParentsList(pClass, arMainParents, arProcessedClasses); CXTPSyntaxEditLexClassPtrArray arDynChildren; int nCCount = (int)m_arPreBuildClassesList.GetSize(); for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = m_arPreBuildClassesList[i]; CString strCName = ptrC->GetClassName(); if (nChidrenOpt == xtpEditOptChildren_List) { if (Find_noCase(arChidrenData, strCName) < 0) { continue; } } int nCanRes = CanBeParentDynForChild(strMainCName, ptrC); if (nCanRes > 0) { if (strMainCName.CompareNoCase(strCName) == 0) { rbSelfChild = TRUE; } else { arDynChildren.Add(ptrC); } continue; } if (nCanRes < 0) { continue; } int nMPCount = (int)arMainParents.GetSize(); for (int n = 0; n < nMPCount; n++) { CString strMPName = arMainParents[n]; if (CanBeParentDynForChild(strMPName, ptrC)) { arDynChildren.Add(ptrC); break; } } } //-------------------------------- CXTPSyntaxEditLexClassPtrArray* pArDynChildren = NULL; if (arDynChildren.GetSize()) { pArDynChildren = new CXTPSyntaxEditLexClassPtrArray; if (pArDynChildren) { pArDynChildren->Append(arDynChildren); } } return pArDynChildren; } CXTPSyntaxEditLexObj_ActiveTags* CXTPSyntaxEditLexClassSchema::GetActiveTagsFor( CXTPSyntaxEditLexClass* pTopClass) { if (!pTopClass) { ASSERT(FALSE); return NULL; } return pTopClass->GetActiveTags(); } BOOL CXTPSyntaxEditLexClassSchema::Copy(CXTPSyntaxEditLexClassSchema* pDest) { if (!pDest) { ASSERT(FALSE); return FALSE; } //------------------------------------------------------------------------ int nCount = (int)m_arPreBuildClassesList.GetSize(); int i; for (i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrC0 = m_arPreBuildClassesList.GetAt(i); if (!ptrC0) { continue; } CXTPSyntaxEditLexClassPtr ptrC0_new = ptrC0->Clone(this); if (!ptrC0_new) { return FALSE; } pDest->m_arPreBuildClassesList.Add(ptrC0_new); } //------------------------------------------------------------------------ nCount = (int)m_arClassesTreeFull.GetSize(); for (i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCfile = m_arClassesTreeFull.GetAt(i); if (!ptrCfile) { continue; } CXTPSyntaxEditLexClassPtr ptrCFnew = ptrCfile->Clone(this); if (!CopyChildrenFor(FALSE, ptrCFnew, ptrCfile, 0)) { return FALSE; } int nStartCount = 0; ptrCFnew->BuildActiveTags(nStartCount); // //CXTPSyntaxEditLexVariantPtrArray* ptrAT = ptrCFnew->BuildActiveTags(nStartCount); // //ConcatenateLVArrays(&pDest->m_arAllActiveTagsFull, ptrAT, nStartCount); pDest->m_arClassesTreeFull.Add(ptrCFnew); } //------------------------------------------------------------------------ BOOL bResShortTree = pDest->Build_ShortTree(); //-* Post Build processing ---------------------------- if (!PostBuild_Step(&pDest->m_arClassesTreeShort)) { return FALSE; } if (!PostBuild_Step(&pDest->m_arClassesTreeFull)) { return FALSE; } return bResShortTree; } BOOL CXTPSyntaxEditLexClassSchema::Build() { CXTPSyntaxEditLexClass::CloseClasses(&m_arClassesTreeFull); CXTPSyntaxEditLexClass::CloseClasses(&m_arClassesTreeShort); int nClassID = 1; BOOL bUnused; CXTPSyntaxEditLexClassPtrArray* ptrArCfile = GetChildrenFor(NULL, bUnused); int nCount = ptrArCfile ? (int)ptrArCfile->GetSize() : 0; for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCfile = ptrArCfile->GetAt(i); CXTPSyntaxEditLexClassPtr ptrCFnew = GetNewClass(TRUE); if (!ptrCFnew) { delete ptrArCfile; return FALSE; } ptrCFnew->CopyFrom(ptrCfile); CXTPSyntaxEditLexVariant lvID(nClassID++); ptrCFnew->SetAttribute(XTPLEX_ATTRCLASSID, lvID); #ifdef DBG_TRACE_LOAD_CLASS_SCH ptrCFnew->Dump(_T("")); #endif CString strCNnew = ptrCFnew->GetClassName(); CStringArray arAddedStack; arAddedStack.Add(strCNnew); if (!Build_ChildrenFor(FALSE, ptrCFnew, arAddedStack, nClassID, 0)) { delete ptrArCfile; return FALSE; } arAddedStack.RemoveAll(); if (!Build_ChildrenFor(TRUE, ptrCFnew, arAddedStack, nClassID, 0)) { delete ptrArCfile; return FALSE; } int nStartCount = 0; ptrCFnew->BuildActiveTags(nStartCount); //CXTPSyntaxEditLexVariantPtrArray* ptrAT = ptrCFnew->BuildActiveTags(nStartCount); //ConcatenateLVArrays(&m_arAllActiveTagsFull, ptrAT, nStartCount); m_arClassesTreeFull.Add(ptrCFnew); } delete ptrArCfile; #ifdef DBG_TRACE_LOAD_CLASS_SCH // m_arAllActiveTagsFull.Dump(_T("AllActiveTags FULL=: ")); #endif if (!Build_ShortTree()) { return FALSE; } //-* Post Build processing ---------------------------- if (!PostBuild_Step(&m_arClassesTreeShort)) { return FALSE; } if (!PostBuild_Step(&m_arClassesTreeFull)) { return FALSE; } //---------------------- //BOOL bAsc = TRUE, bNoCase = FALSE; //SortTagsInLexVarArray(m_arAllActiveTagsFull, bAsc, bNoCase); //SortTagsInLexVarArray(m_arAllActiveTagsShort, bAsc, bNoCase); // m_arAllActiveTagsFull.BuildAutomat(); // m_arAllActiveTagsShort.BuildAutomat(); //-* Post Build END ------------------------------------------------------ #ifdef _DEBUG AfxDump(XTPGetLexAutomatMemMan()); #endif //------------------------------------------------------------------------ return TRUE; } BOOL CXTPSyntaxEditLexClassSchema::Build_ShortTree() { #ifdef DBG_TRACE_LOAD_CLASS_SCH TRACE(_T("\n****************** Short classes Tree ********************** \n")); #endif int nCount = (int)m_arClassesTreeFull.GetSize(); for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCfile = m_arClassesTreeFull.GetAt(i); if (!ptrCfile || ptrCfile->GetAttribute_BOOL(XTPLEX_ATTR_PARSEONSCREEN, FALSE)) { continue; } CXTPSyntaxEditLexClassPtr ptrCFnew = GetNewClass(TRUE); if (!ptrCFnew) { return FALSE; } ptrCFnew->CopyFrom(ptrCfile); #ifdef DBG_TRACE_LOAD_CLASS_SCH ptrCFnew->Dump(_T("")); #endif if (!CopyChildrenFor(TRUE, ptrCFnew, ptrCfile, 0)) { return FALSE; } int nStartCount = 0; ptrCFnew->BuildActiveTags(nStartCount); //CXTPSyntaxEditLexVariantPtrArray* ptrAT = ptrCFnew->BuildActiveTags(nStartCount); //ConcatenateLVArrays(&m_arAllActiveTagsShort, ptrAT, nStartCount); m_arClassesTreeShort.Add(ptrCFnew); } #ifdef DBG_TRACE_LOAD_CLASS_SCH // m_arAllActiveTagsShort.Dump(_T("AllActiveTags Short=: ")); #endif return TRUE; } BOOL CXTPSyntaxEditLexClassSchema::CopyChildrenFor(BOOL bShort, CXTPSyntaxEditLexClass* pCDest, CXTPSyntaxEditLexClass* pCSrc, int nLevel) { #ifdef DBG_TRACE_LOAD_CLASS_SCH CString strTraceOffset0, strTraceOffset; for (int t = 0; t <= nLevel; t++) { strTraceOffset0 += _T(" "); } #endif CXTPSyntaxEditLexClassPtrArray* pArClasses[3]; pArClasses[0] = pCSrc->GetChildren(); pArClasses[1] = pCSrc->GetChildrenDyn(); pArClasses[2] = pCSrc->GetChildrenSelfRef(); for (int nC = 0; nC < _countof(pArClasses); nC++) { BOOL bDynamic = (nC == 1); BOOL bSelf = (nC == 2); #ifdef DBG_TRACE_LOAD_CLASS_SCH if (bDynamic) { strTraceOffset = strTraceOffset0 + _T("dyn: "); } else if (bSelf) { strTraceOffset = strTraceOffset0 + _T("self: "); } else { strTraceOffset = strTraceOffset0; } #endif int nCount = pArClasses[nC] ? (int)pArClasses[nC]->GetSize() : 0; for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCsrc = pArClasses[nC]->GetAt(i); if (!ptrCsrc || bShort && ptrCsrc->GetAttribute_BOOL(XTPLEX_ATTR_PARSEONSCREEN, FALSE)) { continue; } if (bSelf) { pCDest->AddChild(pCDest, FALSE); #ifdef DBG_TRACE_LOAD_CLASS_SCH pCDest->Dump(strTraceOffset); #endif } else { CXTPSyntaxEditLexClassPtr ptrCnew = GetNewClass(FALSE); if (!ptrCnew) { return FALSE; } ptrCnew->CopyFrom(ptrCsrc); pCDest->AddChild(ptrCnew, bDynamic); #ifdef DBG_TRACE_LOAD_CLASS_SCH ptrCnew->Dump(strTraceOffset); #endif ASSERT(pCSrc != ptrCsrc); if (!CopyChildrenFor(bShort, ptrCnew, ptrCsrc, nLevel+1)) { return FALSE; } } } } return TRUE; } BOOL CXTPSyntaxEditLexClassSchema::Build_ChildrenFor(BOOL bDynamic, CXTPSyntaxEditLexClass* pCBase, CStringArray& rarAdded, int& rnNextClassID, int nLevel) { if (!pCBase) { ASSERT(FALSE); return FALSE; } #ifdef DBG_TRACE_LOAD_CLASS_SCH CString strTraceOffset; for (int t = 0; t <= nLevel; t++) { strTraceOffset += _T(" "); } if (bDynamic) { strTraceOffset += _T("dyn: "); } #endif BOOL bSelfChild = FALSE; CXTPSyntaxEditLexClassPtrArray* ptrArChildren; if (bDynamic) { ptrArChildren = GetDynChildrenFor(pCBase, bSelfChild); } else { ptrArChildren = GetChildrenFor(pCBase, bSelfChild); } int nCount = ptrArChildren ? (int)ptrArChildren->GetSize() : 0; for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCsrc = ptrArChildren->GetAt(i); CString strCNsrc = ptrCsrc->GetClassName(); if (nLevel == 0) { rarAdded.RemoveAll(); } //int nFIdx = Find_noCase(rarAdded, strCNsrc); //if (nFIdx >= 0) int nClsCount = FindStrCount(rarAdded, strCNsrc, FALSE); int nRecurrenceDepth = ptrCsrc->GetAttribute_int(XTPLEX_ATTR_RECURRENCEDEPTH, TRUE, 1);; if (nClsCount >= nRecurrenceDepth) { //CXTPSyntaxEditLexClassPtr ptrC(pCBase->FindParent(strCNsrc), TRUE); //if (ptrC) { // pCBase->GetChildrenSelfRef()->Add(ptrC); //#ifdef DBG_TRACE_LOAD_CLASS_SCH // strTraceOffset += _T("self: "); // ptrC->Dump(strTraceOffset); //#endif //} continue; } rarAdded.Add(strCNsrc); CXTPSyntaxEditLexClassPtr ptrCnew = GetNewClass(FALSE); if (!ptrCnew) { delete ptrArChildren; return FALSE; } ptrCnew->CopyFrom(ptrCsrc); CXTPSyntaxEditLexVariant lvID(rnNextClassID++); ptrCnew->SetAttribute(XTPLEX_ATTRCLASSID, lvID); pCBase->AddChild(ptrCnew, bDynamic); #ifdef DBG_TRACE_LOAD_CLASS_SCH ptrCnew->Dump(strTraceOffset); #endif Build_ChildrenFor(bDynamic, ptrCnew, rarAdded, rnNextClassID, nLevel+1); Build_ChildrenFor(!bDynamic, ptrCnew, rarAdded, rnNextClassID, nLevel+1); int nStackCount = (int)rarAdded.GetSize(); if (nStackCount > 0) { rarAdded.RemoveAt(nStackCount - 1); } } delete ptrArChildren; //---------------------------------- if (bSelfChild) { if (pCBase->AddChild(pCBase, bDynamic)) { #ifdef DBG_TRACE_LOAD_CLASS_SCH strTraceOffset += _T("self: "); pCBase->Dump(strTraceOffset); #endif } } return TRUE; } BOOL CXTPSyntaxEditLexClassSchema::PostBuild_Step(CXTPSyntaxEditLexClassPtrArray* pArClasses) { if (!pArClasses) { return TRUE; } int nCount = (int)pArClasses->GetSize(); for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = pArClasses->GetAt(i); ptrC->SortTags(); CXTPSyntaxEditLexClassPtrArray* ptrCh1 = ptrC->GetChildren(); CXTPSyntaxEditLexClassPtrArray* ptrCh2 = ptrC->GetChildrenDyn(); if (!PostBuild_Step(ptrCh1)) { return FALSE; } if (!PostBuild_Step(ptrCh2)) { return FALSE; } } return TRUE; } void CXTPSyntaxEditLexClassSchema::Close() { RemoveAll(); } void CXTPSyntaxEditLexClassSchema::RemoveAll() { CXTPSyntaxEditLexClass::CloseClasses(&m_arPreBuildClassesList); CXTPSyntaxEditLexClass::CloseClasses(&m_arClassesTreeFull); CXTPSyntaxEditLexClass::CloseClasses(&m_arClassesTreeShort); } CXTPSyntaxEditLexClassPtrArray* CXTPSyntaxEditLexClassSchema::GetClasses(BOOL bShortSch) { return bShortSch? &m_arClassesTreeShort: &m_arClassesTreeFull; } CXTPSyntaxEditLexClassPtrArray* CXTPSyntaxEditLexClassSchema::GetPreBuildClasses() { return &m_arPreBuildClassesList; } CXTPSyntaxEditLexClass* CXTPSyntaxEditLexClassSchema::GetNewClass(BOOL bForFile) { if (bForFile) { return new CXTPSyntaxEditLexClass_file(); } return new CXTPSyntaxEditLexClass(); } //////////////////////////////////////////////////////////////////////////// // CXTPSyntaxEditLexParseContext //class CXTPSyntaxEditLexParseContext : public CXTPInternalUnknown //CXTPSyntaxEditLexParseContext::CXTPSyntaxEditLexParseContext(CXTPSyntaxEditLexTextBlock* pBlock) : // CXTPInternalUnknown(pBlock) //{ // ASSERT(pBlock); // // m_pTextBlock = pBlock; //} // //CXTPSyntaxEditLexParseContext::~CXTPSyntaxEditLexParseContext() //{ //} // //void CXTPSyntaxEditLexParseContext::Set(LPCTSTR pcszParopPath, CXTPSyntaxEditLexVariant* pVar) //{ // if (pVar == NULL) { // m_mapVars.RemoveKey(pcszParopPath); // // } // else { // CXTPSyntaxEditLexVariantPtr ptrVar = new CXTPSyntaxEditLexVariant(*pVar); // // m_mapVars.SetAt(pcszParopPath, ptrVar); // } //} // //CXTPSyntaxEditLexVariant* CXTPSyntaxEditLexParseContext::Get(LPCTSTR pcszParopPath) //{ // CXTPSyntaxEditLexVariantPtr ptrVar; // // if (m_mapVars.Lookup(pcszParopPath, ptrVar)) { // return ptrVar.Detach(); // } // return NULL; //} // // //CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexParseContext::GetTextBlock() //{ // if (m_pTextBlock) { // m_pTextBlock->InternalAddRef(); // } // return m_pTextBlock; //} // //void CXTPSyntaxEditLexParseContext::Close() //{ // m_pTextBlock = NULL; // m_mapVars.RemoveAll(); //} //////////////////////////////////////////////////////////////////////////// // CXTPSyntaxEditLexTextBlock CXTPSyntaxEditLexTextBlock::CXTPSyntaxEditLexTextBlock() //: //m_parseContext(this) { m_PosStartLC.nLine = 0; m_PosStartLC.nCol = 0; m_PosEndLC.nLine = 0; m_PosEndLC.nCol = 0; m_nStartTagLen = 0; m_nEndTagXLCLen = 0; m_bEndByParent = FALSE; } CXTPSyntaxEditLexTextBlock::~CXTPSyntaxEditLexTextBlock() { } void CXTPSyntaxEditLexTextBlock::Close() { m_ptrLexClass = NULL; m_ptrParent = NULL; m_ptrPrev = NULL; m_ptrNext= NULL; m_ptrLastChild = NULL; } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextBlock::GetPrevChild(CXTPSyntaxEditLexTextBlock* pChild, BOOL bWithAddRef) { while (pChild && pChild != this) { if (!pChild->m_ptrPrev) { return NULL; } pChild = pChild->m_ptrPrev; if (pChild && (CXTPSyntaxEditLexTextBlock*)pChild->m_ptrParent == this) { if (bWithAddRef) { pChild->InternalAddRef(); } return pChild; } } return NULL; } int CXTPSyntaxEditLexTextBlock::EndChildren(CXTPSyntaxEditLexTextSchema* pTxtSch, BOOL bEndByParent) { int nCount = 0; //CSingleLock singleLock(GetDataLoker(), TRUE); CXTPSyntaxEditLexTextBlock* pChTB = m_ptrLastChild; while (pChTB) { if (!pChTB->m_PosEndLC.IsValidData()) { pChTB->m_PosEndLC = m_PosEndLC; pChTB->m_nEndTagXLCLen = m_nEndTagXLCLen; pChTB->m_bEndByParent = bEndByParent; nCount++; if (pTxtSch) { pTxtSch->SendEvent_OnTextBlockParsed(pChTB); } nCount += pChTB->EndChildren(pTxtSch, bEndByParent); } pChTB = GetPrevChild(pChTB, FALSE); } return nCount; } BOOL CXTPSyntaxEditLexTextBlock::IsLookLikeClosed() const { if (!m_ptrLexClass && !m_ptrPrev && !m_ptrNext && !m_ptrLastChild && !m_ptrParent) { return TRUE; } return FALSE; } BOOL CXTPSyntaxEditLexTextBlock::IsInclude(CXTPSyntaxEditLexTextBlock* pTB2) const { if (!pTB2) { ASSERT(FALSE); return FALSE; } ASSERT(m_PosStartLC.IsValidData() && pTB2->m_PosStartLC.IsValidData()); if (m_PosStartLC <= pTB2->m_PosStartLC && m_PosEndLC >= pTB2->m_PosEndLC && m_PosEndLC.IsValidData() && pTB2->m_PosEndLC.IsValidData() ) { return TRUE; } return FALSE; } BOOL CXTPSyntaxEditLexTextBlock::IsEqualLexClasses(CXTPSyntaxEditLexTextBlock* pTB2) const { if (!m_ptrLexClass || !pTB2 || !pTB2->m_ptrLexClass) { ASSERT(FALSE); return FALSE; } CString strThisClass = m_ptrLexClass->GetClassName(); CString strTB2Class = pTB2->m_ptrLexClass->GetClassName(); int nCmpRes = strThisClass.CompareNoCase(strTB2Class); return nCmpRes==0; } //////////////////////////////////////////////////////////////////////////// // CXTPSyntaxEditLexAnalyser CXTPSyntaxEditLexParser::CXTPSyntaxEditLexParser() { m_pParseThread = NULL; m_nParseThreadPriority = THREAD_PRIORITY_NORMAL; // THREAD_PRIORITY_BELOW_NORMAL // THREAD_PRIORITY_ABOVE_NORMAL; // m_SinkMT.SetOuter(this); m_pConnect = new CXTPNotifyConnection; m_ptrTextSchema = 0; m_pSchOptions_default = new CXTPSyntaxEditLexParserSchemaOptions(); } CXTPSyntaxEditLexParser::~CXTPSyntaxEditLexParser() { Close(); ASSERT(m_ptrTextSchema == 0); #ifdef XTP_DBG_DUMP_OBJ afxDump.SetDepth( 1 ); #endif CMDTARGET_RELEASE(m_pConnect); CMDTARGET_RELEASE(m_pSchOptions_default); RemoveAllOptions(); } void CXTPSyntaxEditLexParser::RemoveAllOptions() { POSITION pos = m_mapSchOptions.GetStartPosition(); while (pos) { CXTPSyntaxEditLexParserSchemaOptions* pOptions = NULL; CString key; m_mapSchOptions.GetNextAssoc(pos, key, pOptions); CMDTARGET_RELEASE(pOptions); } m_mapSchOptions.RemoveAll(); } CXTPNotifyConnection* CXTPSyntaxEditLexParser::GetConnection() { return m_pConnect; } CXTPSyntaxEditLexParser::CXTPSyntaxEditParseThreadParams::CXTPSyntaxEditParseThreadParams() { ptrBuffer = NULL; } void CXTPSyntaxEditLexParser::CXTPSyntaxEditParseThreadParams::AddParseZone(const CXTPSyntaxEditTextRegion& rZone) { const int cnEpsilon = XTP_EDIT_XLC(3, 0); int nCount = (int)arInvalidZones.GetSize(); for (int i = 0; i < nCount; i++) { CXTPSyntaxEditTextRegion zoneI = arInvalidZones[i]; if (rZone.m_posEnd >= zoneI.m_posStart && rZone.m_posStart <= zoneI.m_posStart || rZone.m_posEnd.GetXLC()+cnEpsilon >= zoneI.m_posStart.GetXLC() && rZone.m_posStart <= zoneI.m_posStart ) { zoneI.m_posStart = rZone.m_posStart; arInvalidZones[i] = zoneI; return; } else if (rZone.m_posStart <= zoneI.m_posEnd && rZone.m_posEnd >= zoneI.m_posEnd || rZone.m_posStart.GetXLC()-cnEpsilon <= zoneI.m_posEnd.GetXLC() && rZone.m_posEnd >= zoneI.m_posEnd ) { zoneI.m_posEnd = rZone.m_posEnd; arInvalidZones[i] = zoneI; return; } else if (rZone.m_posStart >= zoneI.m_posStart && rZone.m_posEnd <= zoneI.m_posEnd) { return; //nothing } } arInvalidZones.Add(rZone); } void CXTPSyntaxEditLexParser::Close() { CSingleLock singLockMain(&m_csParserData); CloseParseThread(); m_SinkMT.UnadviseAll(); CMDTARGET_RELEASE(m_ptrTextSchema); } void CXTPSyntaxEditLexParser::SelfCloseParseThread() { ASSERT(m_pParseThread); if (m_pParseThread) { m_pParseThread = NULL; m_PThreadParams.evExitThread.ResetEvent(); ASSERT(m_PThreadParams.arInvalidZones.GetSize() == 0); if (m_ptrTextSchema) { m_ptrTextSchema->GetBreakParsingEvent()->ResetEvent(); } } } //=========================================================================== //#pragma warning(push) #pragma warning(disable: 4702) // warning C4702: unreachable code //---------------------------- void CXTPSyntaxEditLexParser::CloseParseThread() { StopParseInThread(); CSingleLock singLockMain(&m_csParserData); if (m_pParseThread) { HANDLE hThread = NULL; try { hThread = m_pParseThread->m_hThread; } catch (...) { TRACE(_T("ERROR! Parse Thread is not exist. [CloseParseThread()]\n")); } m_pParseThread = NULL; DWORD dwThreadRes = WAIT_TIMEOUT; for (int i = 0; i < 10 && dwThreadRes == WAIT_TIMEOUT; i++) { m_PThreadParams.evParseRun.ResetEvent(); m_PThreadParams.evExitThread.SetEvent(); if (m_ptrTextSchema) { m_ptrTextSchema->GetBreakParsingEvent()->SetEvent(); } if (hThread) { dwThreadRes = ::WaitForSingleObject(hThread, 20*1000); } else { Sleep(5000); break; } } if (dwThreadRes == WAIT_TIMEOUT && hThread) { ::TerminateThread(hThread, 0); TRACE(_T("ERROR! Parser thread was not ended by normal way. It was terminated. \n")); } m_PThreadParams.evExitThread.ResetEvent(); m_PThreadParams.arInvalidZones.RemoveAll(); if (m_ptrTextSchema) { m_ptrTextSchema->GetBreakParsingEvent()->ResetEvent(); } } } //#pragma warning(pop) //=========================================================================== CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::GetBlocks() { return m_ptrFirstBlock.GetInterface(TRUE); } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::FindNearestTextBlock(XTP_EDIT_LINECOL posText) { CSingleLock singleLock(GetDataLoker(), TRUE); //--------------------------------------------------------------------------- CXTPSyntaxEditLexTextBlockPtr ptrTBstart = GetBlocks(); CXTPSyntaxEditLexTextBlock* pTBnearest = ptrTBstart; for (CXTPSyntaxEditLexTextBlock* pTB = ptrTBstart; pTB; pTB = pTB->m_ptrNext) { if (posText < pTB->m_PosStartLC) { break; } pTBnearest = pTB; } //-------------------------- while (pTBnearest && pTBnearest->m_ptrPrev && pTBnearest->m_PosStartLC == pTBnearest->m_ptrPrev->m_PosStartLC) { pTBnearest = pTBnearest->m_ptrPrev; } //-------------------------- if (pTBnearest) { pTBnearest->InternalAddRef(); } return pTBnearest; } BOOL CXTPSyntaxEditLexTextSchema::UpdateTBNearest(CXTPSyntaxEditLexTextBlock* pNarestTB1, int nLineDiff, int nColDiff, XTP_EDIT_LINECOL posFrom, XTP_EDIT_LINECOL posTo, int eEditAction ) { int nResult = xtpEditUTBNothing; CXTPSyntaxEditLexTextBlock* pTB; for (pTB = pNarestTB1; pTB; pTB = pTB->m_ptrParent) { ASSERT(pTB != pTB->m_ptrParent); //------------------------------------------------------------- BOOL bIsBlockStartIntersected = eEditAction == xtpEditActDelete && pTB->m_PosStartLC >= posFrom && pTB->m_PosStartLC < posTo || eEditAction == xtpEditActInsert && pTB->m_PosStartLC < posFrom && posFrom.GetXLC() < pTB->GetStartTagEndXLC(); if (bIsBlockStartIntersected) { nResult |= xtpEditUTBReparse; if (pTB == pNarestTB1) { nResult |= xtpEditUTBNearestUpdated; } // set empty pTB->m_PosEndLC.nLine = pTB->m_PosStartLC.nLine; pTB->m_PosEndLC.nCol = pTB->m_PosStartLC.nCol-1; continue; } //------------------------------------------------------------- BOOL bIsEditingFullyInside = eEditAction == xtpEditActInsert && pTB->GetStartTagEndXLC() <= posFrom.GetXLC() && posFrom.GetXLC() <= pTB->GetEndTagBeginXLC() || eEditAction == xtpEditActDelete && pTB->GetStartTagEndXLC() <= posFrom.GetXLC() && posTo.GetXLC() <= pTB->GetEndTagBeginXLC(); if (bIsEditingFullyInside) { if (pTB == pNarestTB1) { nResult |= xtpEditUTBNearestUpdated; } BOOL bEmpty = FALSE; pTB->m_PosEndLC.nLine += nLineDiff; if (pTB->m_PosEndLC.nLine < pTB->m_PosStartLC.nLine) { // set empty bEmpty = TRUE; pTB->m_PosEndLC.nLine = pTB->m_PosStartLC.nLine; pTB->m_PosEndLC.nCol = pTB->m_PosStartLC.nCol-1; } int nELine = eEditAction == xtpEditActInsert ? posTo.nLine : posFrom.nLine; if (!bEmpty && pTB->m_PosEndLC.nLine == nELine) { pTB->m_PosEndLC.nCol += nColDiff; if (pTB->m_PosEndLC.nCol < 0) { pTB->m_PosEndLC.nCol = 0; } } continue; } //------------------------------------------------------------- BOOL bIsBlockEndIntersected = eEditAction == xtpEditActDelete && (!(posTo.GetXLC() <= pTB->GetEndTagBeginXLC() || posFrom.GetXLC() > pTB->GetEndTagEndXLC() ) ) || eEditAction == xtpEditActInsert && posFrom.GetXLC() > pTB->GetEndTagBeginXLC() && posFrom.GetXLC() <= pTB->GetEndTagEndXLC(); if (bIsBlockEndIntersected) { nResult |= xtpEditUTBReparse; if (pTB == pNarestTB1) { nResult |= xtpEditUTBNearestUpdated; } // set empty pTB->m_PosEndLC.nLine = 0; pTB->m_PosEndLC.nCol = 0; continue; } } //-------------------- return nResult; } int CXTPSyntaxEditLexTextSchema::UpdateTextBlocks(XTP_EDIT_LINECOL posFrom, XTP_EDIT_LINECOL posTo, int eEditAction ) { CSingleLock singleLock(GetDataLoker()); //BOOL bLocked = TryLockCS(&singleLock, GetDataLoker(), 5000, 50); BOOL bLocked = singleLock.Lock(5000); if (!bLocked) { ASSERT(FALSE); TRACE(_T("ERROR! Cannot enter critical section. [Dead lock, hang up???] CXTPSyntaxEditLexTextSchema::UpdateTextBlocks() \n")); return xtpEditUTBError; } CXTPSyntaxEditLexTextBlockPtr ptrNarestTB1 = FindNearestTextBlock(posFrom); if (!ptrNarestTB1) { return xtpEditUTBNothing; } int nLineDiff = posTo.nLine - posFrom.nLine; int nColDiff = posTo.nCol - posFrom.nCol; ASSERT(nLineDiff >= 0); if (eEditAction == xtpEditActDelete) { nLineDiff *= -1; nColDiff *= -1; } //- (1)- update FullyInside nearest and parents blocks int nURes = UpdateTBNearest(ptrNarestTB1, nLineDiff, nColDiff, posFrom, posTo, eEditAction); //- (2)- update block after nearest CXTPSyntaxEditLexTextBlock* pTB = (nURes & xtpEditUTBNearestUpdated) ? ptrNarestTB1->m_ptrNext : ptrNarestTB1; for (; pTB; pTB = pTB->m_ptrNext) { //------------------------------------------------------------- BOOL bIsBlockStartIntersected = eEditAction == xtpEditActDelete && (!(posTo <= pTB->m_PosStartLC || posFrom.GetXLC() >= pTB->GetStartTagEndXLC()) ) || eEditAction == xtpEditActInsert && pTB->m_PosStartLC < posFrom && posFrom.GetXLC() < pTB->GetStartTagEndXLC(); if (bIsBlockStartIntersected) { nURes |= xtpEditUTBReparse; // set empty pTB->m_PosEndLC.nLine = pTB->m_PosStartLC.nLine; pTB->m_PosEndLC.nCol = pTB->m_PosStartLC.nCol-1; continue; } //------------------------------------------------------------- BOOL bIsEditingFullyInside = eEditAction == xtpEditActInsert && pTB->GetStartTagEndXLC() <= posFrom.GetXLC() && posFrom.GetXLC() <= pTB->GetEndTagBeginXLC() || eEditAction == xtpEditActDelete && pTB->GetStartTagEndXLC() <= posFrom.GetXLC() && posTo.GetXLC() <= pTB->GetEndTagBeginXLC(); // ??? +- 1; if (bIsEditingFullyInside) { BOOL bEmpty = FALSE; pTB->m_PosEndLC.nLine += nLineDiff; if (pTB->m_PosEndLC.nLine < pTB->m_PosStartLC.nLine) { // set empty bEmpty = TRUE; pTB->m_PosEndLC.nLine = pTB->m_PosStartLC.nLine; pTB->m_PosEndLC.nCol = pTB->m_PosStartLC.nCol-1; } int nELine = eEditAction == xtpEditActInsert ? posTo.nLine : posFrom.nLine; if (!bEmpty && pTB->m_PosEndLC.nLine == nELine) { pTB->m_PosEndLC.nCol += nColDiff; if (pTB->m_PosEndLC.nCol < 0) { pTB->m_PosEndLC.nCol = 0; } } continue; } //------------------------------------------------------------- BOOL bIsBlockEndIntersected = eEditAction == xtpEditActDelete && (!(posTo.GetXLC() <= pTB->GetEndTagBeginXLC() || posFrom.GetXLC() > pTB->GetEndTagEndXLC() ) ) || eEditAction == xtpEditActInsert && posFrom.GetXLC() > pTB->GetEndTagBeginXLC() && posFrom.GetXLC() <= pTB->GetEndTagEndXLC(); if (bIsBlockEndIntersected) { nURes |= xtpEditUTBReparse; // set empty pTB->m_PosEndLC.nLine = 0; pTB->m_PosEndLC.nCol = 0; continue; } //------------------------------------------------------------------- BOOL bIsBlockOutside = eEditAction == xtpEditActInsert && pTB->m_PosStartLC >= posFrom || eEditAction == xtpEditActDelete && pTB->m_PosStartLC >= posTo; //----------------------------- int nELine = eEditAction == xtpEditActInsert ? posTo.nLine : posFrom.nLine; if (bIsBlockOutside && nLineDiff == 0 && pTB->m_PosStartLC.nLine != nELine && pTB->m_PosEndLC.nLine != nELine) { break; } //------------------------------------------------------------------- if (bIsBlockOutside ) { pTB->m_PosStartLC.nLine += nLineDiff; pTB->m_PosEndLC.nLine += nLineDiff; if (pTB->m_PosStartLC.nLine == nELine) { pTB->m_PosStartLC.nCol += nColDiff; } if (pTB->m_PosEndLC.nLine == nELine) { pTB->m_PosEndLC.nCol += nColDiff; } } //------------------------------------------------------------------- } return nURes; } BOOL CXTPSyntaxEditLexTextSchema::LoadClassSchema(CXTPSyntaxEditLexClassInfoArray* arClassInfo) { CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); RemoveAll(); m_pClassSchema->RemoveAll(); int nCCount = (int)arClassInfo->GetSize(); for (int i = 0; i < nCCount; i++) { const XTP_EDIT_LEXCLASSINFO& infoClass = arClassInfo->GetAt(i); CXTPSyntaxEditLexClassPtr ptrLexClass = m_pClassSchema->GetNewClass(FALSE); if (!ptrLexClass) { return FALSE; } ptrLexClass->m_strClassName = infoClass.csClassName; int nPCount = (int)infoClass.arPropertyDesc.GetSize(); for (int k = 0; k < nPCount; k++) { const XTP_EDIT_LEXPROPINFO& infoProp = infoClass.arPropertyDesc[k]; if (!ptrLexClass->SetProp(&infoProp)) { ASSERT(FALSE); } } m_pClassSchema->AddPreBuildClass(ptrLexClass); #ifdef DBG_TRACE_LOAD_CLASS_SCH { BOOL bEmpty = ptrLexClass->IsEmpty() && ptrLexClass->m_Parent.eOpt != xtpEditOptParent_file; LPCTSTR cszPref = bEmpty ? _T("* !EMPTY! (it is not used)* ") : _T("* "); ptrLexClass->Dump(cszPref); } #endif } return TRUE; //BOOL bRes = m_pClassSchema->Build(); //return bRes; } void CXTPSyntaxEditLexTextSchema::BuildIfNeed() { CSingleLock singleLockCls(GetClassSchLoker(), TRUE); CSingleLock singleLock(GetDataLoker(), TRUE); CXTPSyntaxEditLexClassPtrArray* ptrArCfile = m_pClassSchema->GetClasses(FALSE); if (!ptrArCfile || ptrArCfile->GetSize() == 0) { m_pClassSchema->Build(); } } BOOL CXTPSyntaxEditLexTextSchema::IsFileExtSupported(const CString& strExt) { CXTPSyntaxEditLexClassPtr ptrTopCls = GetTopClassForFileExt(strExt); return ptrTopCls != NULL; } CXTPSyntaxEditLexClass* CXTPSyntaxEditLexTextSchema::GetTopClassForFileExt(const CString& strExt) { CString strPropName = _T("IsExt=") + strExt; CXTPSyntaxEditLexClassPtrArray arTopClasses; CXTPSyntaxEditLexClassPtrArray* ptrArCfile = m_pClassSchema->GetClasses(TRUE); int nCount = ptrArCfile ? (int)ptrArCfile->GetSize() : 0; int i; if (nCount == 0) { BOOL bUnused; ptrArCfile = m_pClassSchema->GetChildrenFor(NULL, bUnused); nCount = ptrArCfile ? (int)ptrArCfile->GetSize() : 0; for (i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCfile = ptrArCfile->GetAt(i); CXTPSyntaxEditLexClassPtr ptrCFnew = m_pClassSchema->GetNewClass(TRUE); if (ptrCFnew) { ptrCFnew->CopyFrom(ptrCfile); arTopClasses.AddPtr(ptrCFnew, TRUE); } } SAFE_DELETE(ptrArCfile); ptrArCfile = &arTopClasses; } nCount = ptrArCfile ? (int)ptrArCfile->GetSize() : 0; for (i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrCfile = ptrArCfile->GetAt(i); CXTPSyntaxEditLexVariantPtr ptrRes = ptrCfile->PropV(strPropName); if (!ptrRes || ptrRes->m_nObjType != xtpEditLVT_valInt) { ASSERT(FALSE); continue; } if (ptrRes->m_nValue) { return ptrCfile.Detach(); } } return NULL; } CXTPSyntaxEditLexTextSchema* CXTPSyntaxEditLexParser::GetTextSchema() { return m_ptrTextSchema; } void CXTPSyntaxEditLexParser::SetTextSchema(CXTPSyntaxEditLexTextSchema* pTextSchema) { CSingleLock singLockMain(&m_csParserData); CloseParseThread(); if (m_ptrTextSchema) { m_ptrTextSchema->RemoveAll(); } m_SinkMT.UnadviseAll(); CMDTARGET_RELEASE(m_ptrTextSchema); RemoveAllOptions(); if (pTextSchema) { pTextSchema->BuildIfNeed(); m_ptrTextSchema = pTextSchema->Clone(); CXTPNotifyConnection* ptrConn = m_ptrTextSchema ? m_ptrTextSchema->GetConnection() : NULL; if (ptrConn) { m_SinkMT.Advise(ptrConn, xtpEditOnParserStarted, &XTPSyntaxEditLexAnalyser::CXTPSyntaxEditLexParser::OnParseEvent_NotificationHandler); m_SinkMT.Advise(ptrConn, xtpEditOnTextBlockParsed, &XTPSyntaxEditLexAnalyser::CXTPSyntaxEditLexParser::OnParseEvent_NotificationHandler); m_SinkMT.Advise(ptrConn, xtpEditOnParserEnded, &XTPSyntaxEditLexAnalyser::CXTPSyntaxEditLexParser::OnParseEvent_NotificationHandler); } } #ifdef _DEBUG AfxDump(XTPGetLexAutomatMemMan()); #endif } BOOL CXTPSyntaxEditLexParser::GetTokensForAutoCompleate(CXTPSyntaxEditLexTokensDefArray& rArTokens, BOOL bAppend) { CSingleLock singLockMain(&m_csParserData); if (!bAppend) { rArTokens.RemoveAll(); } CXTPSyntaxEditLexTextSchema* ptrTxtSch = GetTextSchema(); CXTPSyntaxEditLexClassSchema* ptrClsSch = ptrTxtSch ? ptrTxtSch->GetClassSchema() : NULL; CXTPSyntaxEditLexClassPtrArray* ptrArCls = ptrClsSch ? ptrClsSch->GetPreBuildClasses() : NULL; if (!ptrArCls) { return FALSE; } //-------------------------------------------------- int nCCount = (int)ptrArCls->GetSize(); for (int i = 0; i < nCCount; i++) { CXTPSyntaxEditLexTokensDef tmpTkDef; CXTPSyntaxEditLexClassPtr ptrCls = ptrArCls->GetAt(i); CXTPSyntaxEditLexVariantPtr ptrTags = ptrCls->PropV(_T("token:tag")); if (!ptrTags) { continue; } GetStrsFromLVArray(ptrTags, tmpTkDef.m_arTokens); //-------------------- CXTPSyntaxEditLexVariantPtr ptrSartSeps = ptrCls->PropV(_T("token:start:separators")); CXTPSyntaxEditLexVariantPtr ptrEndSeps = ptrCls->PropV(_T("token:end:separators")); if (ptrSartSeps) { GetStrsFromLVArray(ptrSartSeps, tmpTkDef.m_arStartSeps); } if (ptrEndSeps) { GetStrsFromLVArray(ptrEndSeps, tmpTkDef.m_arEndSeps); } //================= rArTokens.Add(tmpTkDef); } return TRUE; } void CXTPSyntaxEditLexParser::GetStrsFromLVArray(CXTPSyntaxEditLexVariant* pLVArray, CStringArray& rArStrs) const { if (!pLVArray || pLVArray->m_nObjType != xtpEditLVT_LVArrayPtr || !pLVArray->m_ptrLVArrayPtr) { ASSERT(FALSE); return; } int nCount = (int)pLVArray->m_ptrLVArrayPtr->GetSize(); for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexVariantPtr ptrLVVal = pLVArray->m_ptrLVArrayPtr->GetAt(i); ASSERT(ptrLVVal); if (ptrLVVal && ptrLVVal->m_nObjType == xtpEditLVT_valStr) { for (int k = 0; k < ptrLVVal->m_arStrVals.GetSize(); k++) { CString strVal = ptrLVVal->m_arStrVals[k]; ASSERT(strVal.GetLength()); if (strVal.GetLength()) { rArStrs.Add(strVal); } } } } } //////////////////////////////////////////////////////////////////////////// CXTPSyntaxEditLexParser::CXTPSyntaxEditParseThreadParams* CXTPSyntaxEditLexParser::GetParseInThreadParams() { return &m_PThreadParams; } void CXTPSyntaxEditLexParser::StartParseInThread(CXTPSyntaxEditBufferManager* pBuffer, const XTP_EDIT_LINECOL* pLCStart, const XTP_EDIT_LINECOL* pLCEnd, int eEdinAction, BOOL bRunWithoutWait) { UNREFERENCED_PARAMETER(eEdinAction); DBG_TRACE_TIME(1, _T("### ### ### StartParseInThread time = ")); CSingleLock singLockMain(&m_csParserData); if (!m_ptrTextSchema) { return; } CSingleLock singLockPrm(&m_PThreadParams.lockThreadParams); //if (IsCSLocked(m_PThreadParams.lockThreadParams)) { if (IsMutexLocked(&m_PThreadParams.lockThreadParams)) { DBG_TRACE_PARSE_START_STOP(_T("- Parser set BREAK Event. \n")); VERIFY( m_ptrTextSchema->GetBreakParsingEvent()->SetEvent() ); } if (!singLockPrm.Lock()) { ASSERT(FALSE); return; } m_PThreadParams.ptrBuffer = pBuffer; CXTPSyntaxEditTextRegion invZone; if (pLCStart && !pLCEnd && pLCStart->GetXLC() == XTP_EDIT_XLC(1, 0) ) { invZone.Set(pLCStart, pLCEnd); m_PThreadParams.arInvalidZones.RemoveAll(); m_PThreadParams.AddParseZone(invZone); } else if (pLCStart || pLCEnd) { invZone.Set(pLCStart, pLCEnd); m_PThreadParams.AddParseZone(invZone); } if (!m_pParseThread) {// create thread m_pParseThread = AfxBeginThread(ThreadParseProc, this, m_nParseThreadPriority); if (!m_pParseThread) { ASSERT(FALSE); return; } } if (!SetParseThreadPriority(m_nParseThreadPriority)) { // try to start a new thread StartParseInThread(pBuffer, pLCStart, pLCEnd, eEdinAction, bRunWithoutWait); } CString sDBGpos = DBG_TraceIZone(pLCStart, pLCEnd); DBG_TRACE_PARSE_START_STOP(_T("- Parser set START Event. Add invalid Zone [ %s ] \n"), (LPCTSTR)sDBGpos); if (bRunWithoutWait) { VERIFY( m_PThreadParams.evRunWithoutWait.SetEvent() ); } VERIFY( m_PThreadParams.evParseRun.SetEvent() ); } void CXTPSyntaxEditLexParser::StopParseInThread() { DBG_TRACE_TIME(1, _T("### ### ### STOP Parse In Thread time = ")); CSingleLock singLockMain(&m_csParserData); if (!m_ptrTextSchema) { return; } CSingleLock singLockPrm(&m_PThreadParams.lockThreadParams); CEvent* pBreakEvent = m_ptrTextSchema->GetBreakParsingEvent(); ASSERT(pBreakEvent); if (!pBreakEvent) return; if (IsMutexLocked(&m_PThreadParams.lockThreadParams)) { VERIFY( pBreakEvent->SetEvent() ); DBG_TRACE_PARSE_START_STOP(_T("- STOP Parser set BREAK Event. \n")); } if (!singLockPrm.Lock()) { ASSERT(FALSE); return; } if (IsEventSet(*pBreakEvent)) { VERIFY( pBreakEvent->ResetEvent() ); DBG_TRACE_PARSE_START_STOP(_T("- STOP Parser REset BREAK Event. \n")); } DBG_TRACE_PARSE_START_STOP(_T("- STOP Parser finished. \n")); } int CXTPSyntaxEditLexParser::GetParseThreadPriority() { try { if (m_pParseThread) { int nPriority = m_pParseThread->GetThreadPriority(); return nPriority; } } catch (...) { m_pParseThread = NULL; TRACE(_T("ERROR! Parse Thread is not exist. \n")); }; return m_nParseThreadPriority; } BOOL CXTPSyntaxEditLexParser::SetParseThreadPriority(int nPriority) { m_nParseThreadPriority = nPriority; try { if (m_pParseThread) { if (m_nParseThreadPriority != m_pParseThread->GetThreadPriority()) { m_pParseThread->SetThreadPriority(m_nParseThreadPriority); } } } catch (...) { TRACE(_T("ERROR! Parse Thread is not exist. \n")); m_pParseThread = NULL; return FALSE; } return TRUE; } void CXTPSyntaxEditLexParser::OnBeforeEditChanged() { //CSingleLock singLockMain(&m_csParserData); StopParseInThread(); } void CXTPSyntaxEditLexParser::OnEditChanged(const XTP_EDIT_LINECOL& posFrom, const XTP_EDIT_LINECOL& posTo, int eEditAction, CXTPSyntaxEditBufferManager* pBuffer) { DBG_TRACE_TIME(1, _T("### ### ### OnEditChanged time = ")); CSingleLock singLockMain(&m_csParserData); if (!m_ptrTextSchema) { return; } if (!pBuffer) { ASSERT(FALSE); return; } m_ptrTextSchema->UpdateTextBlocks(posFrom, posTo, eEditAction); BOOL bThreadParse = GetSchemaOptions(pBuffer->GetFileExt())->m_bEditReparceInSeparateThread; if (bThreadParse) { StartParseInThread(pBuffer, &posFrom, &posTo, eEditAction, FALSE); } else { CXTPSyntaxEditTextIterator txtIter(pBuffer); m_ptrTextSchema->RunParseUpdate(TRUE, &txtIter, &posFrom, &posTo); } } void CXTPSyntaxEditLexParser::OnParseEvent_NotificationHandler(XTP_NOTIFY_CODE Event, WPARAM wParam, LPARAM lParam) { if (Event == xtpEditOnTextBlockParsed) { CXTPSyntaxEditLexTextBlockPtr ptrTBended; CXTPSyntaxEditLexTextSchema* ptrTextSch = GetTextSchema(); ptrTBended = ptrTextSch ? ptrTextSch->GetLastParsedBlock(wParam) : NULL; if (ptrTBended) { m_pConnect->SendEvent(Event, (WPARAM)(CXTPSyntaxEditLexTextBlock*)ptrTBended, 0); } } else { m_pConnect->SendEvent(Event, wParam, lParam); } } UINT CXTPSyntaxEditLexParser::ThreadParseProc(LPVOID pParentParser) { DBG_TRACE_PARSE_START_STOP(_T("*** Parser Thread is started. %08x\n"), ::GetCurrentThreadId()); if (!pParentParser) { ASSERT(FALSE); return 111; } // try { CXTPSyntaxEditLexParserPtr ptrParser((CXTPSyntaxEditLexParser*)pParentParser, TRUE); CXTPSyntaxEditLexParser::CXTPSyntaxEditParseThreadParams* pPRMs = NULL; pPRMs = ptrParser->GetParseInThreadParams(); if (!pPRMs) { ASSERT(FALSE); return 222; } CSingleLock lockPRMs(&pPRMs->lockThreadParams, TRUE); HANDLE arWaiters[] = {pPRMs->evParseRun, pPRMs->evExitThread}; HANDLE hRunWithoutWait = pPRMs->evRunWithoutWait; DWORD dwSelfCloseTimeout_ms = ptrParser->GetSchemaOptions( pPRMs->ptrBuffer->GetFileExt())->m_dwParserThreadIdleLifeTime_ms; DWORD dwWaitFilter_ms = ptrParser->GetSchemaOptions( pPRMs->ptrBuffer->GetFileExt())->m_dwEditReparceTimeout_ms; lockPRMs.Unlock(); DWORD dwWaitRes = 0; do { dwWaitRes = WaitForMultipleObjects(2, arWaiters, FALSE, dwSelfCloseTimeout_ms); if (dwWaitRes == WAIT_TIMEOUT) { CSingleLock lockPRMs1(&pPRMs->lockThreadParams, TRUE); if (pPRMs->arInvalidZones.GetSize() == 0) { ptrParser->SelfCloseParseThread(); return 1; } else { continue; } } //=== Wait Filter === (for keyboard input) if (dwWaitRes == WAIT_OBJECT_0 && !IsEventSet(hRunWithoutWait)) { do { dwWaitRes = WaitForMultipleObjects(2, arWaiters, FALSE, dwWaitFilter_ms); } while (dwWaitRes == WAIT_OBJECT_0 && !IsEventSet(hRunWithoutWait)); if (dwWaitRes == WAIT_TIMEOUT) { dwWaitRes = WAIT_OBJECT_0; } } //=== Wait Filter === (for keyboard input) if (dwWaitRes == WAIT_OBJECT_0) { //*** CSingleLock lockPRMs2(&pPRMs->lockThreadParams, TRUE); //*** // Update Options dwSelfCloseTimeout_ms = ptrParser->GetSchemaOptions( pPRMs->ptrBuffer->GetFileExt())->m_dwParserThreadIdleLifeTime_ms; dwWaitFilter_ms = ptrParser->GetSchemaOptions( pPRMs->ptrBuffer->GetFileExt())->m_dwEditReparceTimeout_ms; // END Update Options CXTPSyntaxEditTextIterator txtIter(pPRMs->ptrBuffer); CXTPSyntaxEditLexTextSchema* ptrTextSch = ptrParser->GetTextSchema(); if (!ptrTextSch) { continue; } CEvent* pBreakEvent = ptrTextSch->GetBreakParsingEvent(); ASSERT(pBreakEvent); int nZonesCount = 0; BOOL bParseRestedBlock = FALSE; BOOL bBreaked = FALSE; do { if (IsEventSet(*pBreakEvent)) { VERIFY( pBreakEvent->ResetEvent() ); DBG_TRACE_PARSE_START_STOP(_T("* Parser Start BREAKED. \n")); break; } XTP_EDIT_LINECOL* pLCStart = NULL; XTP_EDIT_LINECOL* pLCEnd = NULL; CXTPSyntaxEditTextRegion iZone; nZonesCount = (int)pPRMs->arInvalidZones.GetSize(); //bParseRestedBlock = FALSE; //nZonesCount > 0; if (nZonesCount) { iZone = pPRMs->arInvalidZones[nZonesCount-1]; if (iZone.m_posStart.IsValidData()) { pLCStart = &iZone.m_posStart; } if (iZone.m_posEnd.IsValidData()) { pLCEnd = &iZone.m_posEnd; } } CString sDBGpos = DBG_TraceIZone(pLCStart, pLCEnd); DBG_TRACE_PARSE_START_STOP(_T("* Parser Started. Invalid Zone [%s] \n"), sDBGpos); // run parser /*DEBUG*/ DWORD dwTime0 = GetTickCount(); //DEBUG int nParseRes = ptrTextSch->RunParseUpdate(TRUE, &txtIter, pLCStart, pLCEnd, TRUE); if (nParseRes & xtpEditLPR_Error) { //ASSERT(FALSE); //::MessageBeep((UINT)-1); TRACE(_T("Lex Parser ERROR! Try Full reparse. \n")); ptrTextSch->RemoveAll(); XTP_EDIT_LINECOL posLC1 = {1,0}; txtIter.SeekBegin(); nParseRes = ptrTextSch->RunParseUpdate(TRUE, &txtIter, &posLC1, NULL); pPRMs->arInvalidZones.RemoveAll(); nZonesCount = 0; if (nParseRes & xtpEditLPR_RunFinished) { TRACE(_T("Full reparse - (OK) <F I N I S H E D> \n")); } else if (nParseRes & xtpEditLPR_RunBreaked) { TRACE(_T("Full reparse - BREAKED \n")); iZone.Set(NULL, NULL); pPRMs->arInvalidZones.Add(iZone); } else if (nParseRes & xtpEditLPR_Error) { TRACE(_T("Full reparse - ERROR \n")); } nZonesCount = (int)pPRMs->arInvalidZones.GetSize(); } /*DEBUG*/ DWORD dwTime1 = GetTickCount();//DEBUG bBreaked = (nParseRes & xtpEditLPR_RunFinished) == 0 || (nParseRes & (xtpEditLPR_RunBreaked|xtpEditLPR_Error)) > 0 || IsEventSet(*pBreakEvent); VERIFY( pBreakEvent->ResetEvent() ); CXTPSyntaxEditTextRegion zoneValid = ptrTextSch->GetUpdatedTextRegion(); if ((nParseRes&xtpEditLPR_RunFinished) && nZonesCount) { pPRMs->arInvalidZones.RemoveAt(nZonesCount-1); nZonesCount--; //pPRMs->UpdateZones(zoneValid); } //DEBUG { CString sDBGzone = DBG_TraceIZone(&zoneValid.m_posStart, &zoneValid.m_posEnd); //TRACE(_T("- Parser set START Event. Add invalid Zone [ %s ] \n"), sDBGpos); DBG_TRACE_PARSE_START_STOP(_T("* Parser Ended. (result=%x) %s%s%s (%.3f sec) VALID Zone[ %s ] \n"), nParseRes, (nParseRes&xtpEditLPR_RunBreaked) ? _T(" BREAKED ") : _T(""), (nParseRes&xtpEditLPR_Error) ? _T(" ERROR ") : _T(""), (nParseRes&xtpEditLPR_RunFinished) ? _T(" <F I N I S H E D> ") : _T(""), labs(dwTime1-dwTime0)/1000.0, (LPCTSTR)sDBGzone); } } while ((bParseRestedBlock || nZonesCount) && !bBreaked); } } while (dwWaitRes != WAIT_OBJECT_0+1); } // catch(...) { // TRACE(_T("* EXCEPTION!!! CXTPSyntaxEditLexParser::ThreadParseProc(2)\n")); // return 333; // } DBG_TRACE_PARSE_START_STOP(_T("*** Parser Thread is Ended. (%x)\n"), ::GetCurrentThreadId()); return 0; } #ifdef _DEBUG void CXTPSyntaxEditLexTextBlock::Dump( CDumpContext& dc ) const { CObject::Dump( dc ); // Now do the stuff for our specific class. dc << "\t <<TB>>"; dc << " (ref=" << m_dwRef << ") \n"; dc << "\t start(" << m_PosStartLC.nLine << ", " << m_PosStartLC.nCol << ") "; dc << "\t end(" << m_PosEndLC.nLine << ", " << m_PosEndLC.nCol << ") \n"; #if _MSC_VER >= 1300 dc << "\t Parent="; dc.DumpAsHex((INT_PTR)(CXTPSyntaxEditLexTextBlock*)m_ptrParent); dc << ", Prev="; dc.DumpAsHex((INT_PTR)(CXTPSyntaxEditLexTextBlock*)m_ptrPrev); dc << ", Next="; dc.DumpAsHex((INT_PTR)(CXTPSyntaxEditLexTextBlock*)m_ptrNext); dc << ", LastChild="; dc.DumpAsHex((INT_PTR)(CXTPSyntaxEditLexTextBlock*)m_ptrLastChild); #endif } #endif BOOL CXTPSyntaxEditLexTextSchema::RunParseOnScreen(CTextIter* pTxtIter, int nRowStart, int nRowEnd, CXTPSyntaxEditLexTextBlockPtr& rPtrScreenSchFirstTB ) { if (!pTxtIter || nRowStart <= 0 || nRowEnd <= 0) { ASSERT(FALSE); return FALSE; } CSingleLock singleLock(GetDataLoker()); if (!singleLock.Lock(30)) { TRACE(_T("Cannot enter critical section. CXTPSyntaxEditLexTextSchema::RunParseOnScreen() \n")); return FALSE; } //--------------------------------------------------------------------------- //** (1) ** ------------------------- CXTPSyntaxEditLexTextBlockPtr ptrTBParentToRun; BOOL bInit = InitScreenSch(pTxtIter, nRowStart, nRowEnd, rPtrScreenSchFirstTB, ptrTBParentToRun); if (!bInit) { //TRACE(_T("- parser::InitScreenSch return FALSE res.\n")); return FALSE; } XTP_EDIT_LINECOL startLC = {nRowStart, 0}; if (!pTxtIter->SeekPos(startLC)) { return FALSE; } int nParseRes = 0; CXTPSyntaxEditLexOnScreenParseCnt runCnt; runCnt.m_nRowStart = nRowStart; runCnt.m_nRowEnd = nRowEnd; runCnt.m_ptrTBLast = ptrTBParentToRun; //** (2) ** ------------------------- CXTPSyntaxEditLexClassPtrArray* ptrArClasses = m_pClassSchema->GetClasses(FALSE); int nCCount = ptrArClasses ? (int)ptrArClasses->GetSize() : 0; BOOL bRunEOF = TRUE; XTP_EDIT_LINECOL lcTextPos = {0,0}; while (!pTxtIter->IsEOF() && nCCount && bRunEOF) { bRunEOF = !pTxtIter->IsEOF(); nParseRes = Run_OnScreenTBStack(pTxtIter, ptrTBParentToRun, &runCnt); if (nParseRes & (xtpEditLPR_Error|xtpEditLPR_RunBreaked)) // |xtpEditLPR_RunFinished)) { TRACE(_T("- parser::RunParseOnScreen return by erroe or BREAK. \n")); return !(nParseRes&xtpEditLPR_Error); } //** ------------------------------------------------------------- if (!pTxtIter->IsEOF() && !(nParseRes & xtpEditLPR_Iterated)) { SeekNextEx(pTxtIter, ptrTBParentToRun->m_ptrLexClass, &runCnt); } //--------------------------------------------------------------------------- lcTextPos = pTxtIter->GetPosLC(); if (lcTextPos.nLine > runCnt.m_nRowEnd) { break; } //--------------------------------------------------------------------------- if (ptrTBParentToRun->m_ptrParent) { ptrTBParentToRun = ptrTBParentToRun->m_ptrParent; } } return TRUE; } CXTPSyntaxEditLexTextBlockPtr CXTPSyntaxEditLexTextSchema::InitScreenSch_RunTopClass(CTextIter* pTxtIter) { CXTPSyntaxEditLexTextBlockPtr ptrTBtop; CXTPSyntaxEditLexClassPtrArray* ptrClsAr = m_pClassSchema->GetClasses(FALSE); int nCount = ptrClsAr ? (int)ptrClsAr->GetSize() : 0; for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClassPtr ptrC = ptrClsAr->GetAt(i); if (!ptrC) { ASSERT(FALSE); continue; } ASSERT(ptrTBtop == NULL); int nParseRes = ptrC->RunParse(pTxtIter, this, ptrTBtop); if ((nParseRes & xtpEditLPR_StartFound) && ptrTBtop) { return ptrTBtop; } } return NULL; } BOOL CXTPSyntaxEditLexTextSchema::InitScreenSch(CTextIter* pTxtIter, int nRowStart, int nRowEnd, CXTPSyntaxEditLexTextBlockPtr& rPtrScreenSchFirstTB, CXTPSyntaxEditLexTextBlockPtr& rPtrTBParentToRun) { CXTPSyntaxEditLexTextBlockPtr ptrTBstart = GetBlocks(); // process first screen parse in the main thread if (nRowStart == 1 && !ptrTBstart) { rPtrTBParentToRun = rPtrScreenSchFirstTB = InitScreenSch_RunTopClass(pTxtIter); return (rPtrTBParentToRun != NULL); } CXTPSyntaxEditLexTextBlock* pLastSchBlock = GetLastSchBlock(FALSE); if (m_ptrNewChainTB2 && pLastSchBlock && (pLastSchBlock->m_PosEndLC.IsValidData() && nRowStart > pLastSchBlock->m_PosEndLC.nLine || !pLastSchBlock->m_PosEndLC.IsValidData() && nRowStart > pLastSchBlock->m_PosStartLC.nLine) ) { return FALSE; } //======================================================================= CXTPSyntaxEditLexTextBlock* pTBLast = NULL; XTP_EDIT_LINECOL lcStart = {nRowStart, 0}; // (1) --- CXTPSyntaxEditLexTextBlock* pTB; for (pTB = ptrTBstart; pTB; pTB = pTB->m_ptrNext) { if (pTB->m_PosStartLC < lcStart && pTB->GetPosEndLC() >= lcStart || pTB == ptrTBstart ) { pTBLast = pTB; } if (pTB->m_PosStartLC.nLine > nRowEnd) { break; } } // (2) --- CXTPSyntaxEditLexTextBlockPtr ptrTBCopyNext; for (pTB = pTBLast; pTB; pTB = pTB->m_ptrParent) { CXTPSyntaxEditLexTextBlockPtr ptrTBCopy = CopyShortTBtoFull(pTB); if (!ptrTBCopy) { return FALSE; } if (pTB == pTBLast) { rPtrTBParentToRun = ptrTBCopy; if (pTB->m_PosStartLC.nLine <= nRowStart && pTB->m_PosEndLC.nLine >= nRowStart || pTB == ptrTBstart) { pTBLast = pTB; } } else { ptrTBCopy->m_ptrNext = ptrTBCopyNext; ptrTBCopyNext->m_ptrPrev = ptrTBCopy; ptrTBCopyNext->m_ptrParent = ptrTBCopy; } rPtrScreenSchFirstTB = ptrTBCopy; ptrTBCopyNext = ptrTBCopy; } return (rPtrTBParentToRun != NULL); } CXTPSyntaxEditLexTextBlock* CXTPSyntaxEditLexTextSchema::CopyShortTBtoFull(CXTPSyntaxEditLexTextBlock* pTB) { CXTPSyntaxEditLexTextBlockPtr ptrCopyTB = GetNewBlock(); if (!ptrCopyTB || !pTB || !pTB->m_ptrLexClass) { #ifdef XTP_FIXED // sometime popup this assert message. // ASSERT(pTB && pTB->m_ptrLexClass); #else ASSERT(pTB && pTB->m_ptrLexClass); #endif return NULL; } ptrCopyTB->m_PosStartLC = pTB->m_PosStartLC; ptrCopyTB->m_PosEndLC = pTB->m_PosEndLC; int nClassID = pTB->m_ptrLexClass->GetAttribute_int(XTPLEX_ATTRCLASSID, FALSE, -1); ASSERT(nClassID > 0); CXTPSyntaxEditLexClassPtrArray* ptrTopClassesAr = m_pClassSchema->GetClasses(FALSE); ptrCopyTB->m_ptrLexClass = FindLexClassByID(ptrTopClassesAr, nClassID); if (!ptrCopyTB->m_ptrLexClass) { ASSERT(FALSE); return NULL; } return ptrCopyTB.Detach(); } CXTPSyntaxEditLexClass* CXTPSyntaxEditLexTextSchema::FindLexClassByID(CXTPSyntaxEditLexClassPtrArray* pClassesAr, int nClassID) { if (!pClassesAr) { return NULL; } int nCount = (int)pClassesAr->GetSize(); for (int i = 0; i < nCount; i++) { CXTPSyntaxEditLexClass* pC = pClassesAr->GetAt(i, FALSE); int nC_ID = pC->GetAttribute_int(XTPLEX_ATTRCLASSID, FALSE); if (nC_ID == nClassID) { pC->InternalAddRef(); return pC; } //------------------------------------------------------- CXTPSyntaxEditLexClass* pCF2 = FindLexClassByID(pC->GetChildren(), nClassID); if (pCF2) { return pCF2; } pCF2 = FindLexClassByID(pC->GetChildrenDyn(), nClassID); if (pCF2) { return pCF2; } } return NULL; } int CXTPSyntaxEditLexTextSchema::Run_OnScreenTBStack(CTextIter* pTxtIter, CXTPSyntaxEditLexTextBlock* pTBParentToRun, CXTPSyntaxEditLexOnScreenParseCnt* pRunCnt) { if (!pTBParentToRun || !pTBParentToRun->m_ptrLexClass || !pRunCnt) { ASSERT(FALSE); return xtpEditLPR_Error; } CXTPSyntaxEditLexTextBlockPtr ptrTBParentToRun(pTBParentToRun, TRUE); CXTPSyntaxEditLexClassPtr ptrRunClass = pTBParentToRun->m_ptrLexClass; int nPres = 0; BOOL bIterated = FALSE; BOOL bEnded = FALSE; BOOL bRunEOF = TRUE; XTP_EDIT_LINECOL lcTextPos = {0,0}; //** 1 **// Run existing block with children until block end while (!bEnded && (bRunEOF || !pTxtIter->IsEOF()) ) { bRunEOF = !pTxtIter->IsEOF(); BOOL bSkipIterate = FALSE; nPres = ptrRunClass->RunParse(pTxtIter, this, ptrTBParentToRun, pRunCnt); if (nPres & (xtpEditLPR_Error|xtpEditLPR_RunBreaked)) //|xtpEditLPR_RunFinished)) { return nPres; } //--------------------------------------------------------------------------- if (nPres & xtpEditLPR_Iterated) { bSkipIterate = TRUE; bIterated = TRUE; } //--------------------------------------------------------------------------- bEnded = (nPres & xtpEditLPR_EndFound) != 0; if (bEnded) { CSingleLock singleLock(GetDataLoker(), TRUE); ptrTBParentToRun->EndChildren(); //this); DBG_TRACE_PARSE_RUN_BLOCKS(_T("(%08x) ENDED startPos=(%d,%d) endPos=(%d,%d), [%s] {%d}-noEndedStack \n"), (CXTPSyntaxEditLexTextBlock*)ptrTBParentToRun, ptrTBParentToRun->m_PosStartLC.nLine, ptrTBParentToRun->m_PosStartLC.nCol, ptrTBParentToRun->m_PosEndLC.nLine, ptrTBParentToRun->m_PosEndLC.nCol, ptrTBParentToRun->m_ptrLexClass->m_strClassName, m_nNoEndedClassesCount); } //--------------------------------------------------------------------------- if (!bEnded && !bSkipIterate) { SeekNextEx(pTxtIter, ptrRunClass, pRunCnt); } //--------------------------------------------------------------------------- lcTextPos = pTxtIter->GetPosLC(); if (lcTextPos.nLine > pRunCnt->m_nRowEnd) { break; } } // ** end run existing ** // if (!bEnded) { ptrTBParentToRun->m_PosEndLC = pTxtIter->GetPosLC(); ptrTBParentToRun->EndChildren(); //this); return xtpEditLPR_RunFinished; } //=========================================================================== return (bIterated ? xtpEditLPR_Iterated : 0) | (pTxtIter->IsEOF() ? xtpEditLPR_RunFinished : 0); } CXTPSyntaxEditLexParserSchemaOptions::CXTPSyntaxEditLexParserSchemaOptions() { m_bFirstParseInSeparateThread = TRUE; m_bEditReparceInSeparateThread = TRUE; m_bConfigChangedReparceInSeparateThread = TRUE; m_dwMaxBackParseOffset = XTP_EDIT_LEXPARSER_MAXBACKOFFSETDEFAULT; m_dwEditReparceTimeout_ms = XTP_EDIT_LEXPARSER_REPARSETIMEOUTMS; m_dwOnScreenSchCacheLifeTime_sec = XTP_EDIT_LEXPARSER_ONSCREENSCHCACHELIFETIMESEC; m_dwParserThreadIdleLifeTime_ms = XTP_EDIT_LEXPARSER_THREADIDLELIFETIMESEC * 1000; } CXTPSyntaxEditLexParserSchemaOptions::CXTPSyntaxEditLexParserSchemaOptions(const CXTPSyntaxEditLexParserSchemaOptions& rSrc) { m_bFirstParseInSeparateThread = rSrc.m_bFirstParseInSeparateThread; m_bEditReparceInSeparateThread = rSrc.m_bEditReparceInSeparateThread; m_bConfigChangedReparceInSeparateThread = rSrc.m_bConfigChangedReparceInSeparateThread; m_dwMaxBackParseOffset = rSrc.m_dwMaxBackParseOffset; m_dwEditReparceTimeout_ms = rSrc.m_dwEditReparceTimeout_ms; m_dwOnScreenSchCacheLifeTime_sec = rSrc.m_dwOnScreenSchCacheLifeTime_sec; m_dwParserThreadIdleLifeTime_ms = rSrc.m_dwParserThreadIdleLifeTime_ms; } const CXTPSyntaxEditLexParserSchemaOptions& CXTPSyntaxEditLexParserSchemaOptions::operator=(const CXTPSyntaxEditLexParserSchemaOptions& rSrc) { m_bFirstParseInSeparateThread = rSrc.m_bFirstParseInSeparateThread; m_bEditReparceInSeparateThread = rSrc.m_bEditReparceInSeparateThread; m_bConfigChangedReparceInSeparateThread = rSrc.m_bConfigChangedReparceInSeparateThread; m_dwMaxBackParseOffset = rSrc.m_dwMaxBackParseOffset; m_dwEditReparceTimeout_ms = rSrc.m_dwEditReparceTimeout_ms; m_dwOnScreenSchCacheLifeTime_sec = rSrc.m_dwOnScreenSchCacheLifeTime_sec; m_dwParserThreadIdleLifeTime_ms = rSrc.m_dwParserThreadIdleLifeTime_ms; return *this; } BOOL CXTPSyntaxEditLexParser::ReadSchemaOptions(const CString& strExt, CXTPSyntaxEditLexTextSchema* pTextSchema, CXTPSyntaxEditLexParserSchemaOptions* pOpt) { if (pOpt) { *pOpt = *m_pSchOptions_default; } if (!pTextSchema || !pOpt) { ASSERT(FALSE); return FALSE; } CXTPSyntaxEditLexClassPtr ptrTopCls = pTextSchema->GetTopClassForFileExt(strExt); if (!ptrTopCls) { return FALSE; } pOpt->m_bFirstParseInSeparateThread = ptrTopCls->GetAttribute_BOOL( XTPLEX_ATTRG_FIRSTPARSEINSEPARATETHREAD, FALSE, TRUE); pOpt->m_bEditReparceInSeparateThread = ptrTopCls->GetAttribute_BOOL( XTPLEX_ATTRG_EDITREPARCEINSEPARATETHREAD, FALSE, TRUE); pOpt->m_bConfigChangedReparceInSeparateThread = ptrTopCls->GetAttribute_BOOL( XTPLEX_ATTRG_CONFIGCHANGEDREPARCEINSEPARATETHREAD, FALSE, TRUE); pOpt->m_dwMaxBackParseOffset = (DWORD)ptrTopCls->GetAttribute_int( XTPLEX_ATTRG_MAXBACKPARSEOFFSET, FALSE, XTP_EDIT_LEXPARSER_MAXBACKOFFSETDEFAULT); pOpt->m_dwEditReparceTimeout_ms = (DWORD)ptrTopCls->GetAttribute_int( XTPLEX_ATTRG_EDITREPARCETIMEOUT_MS, FALSE, XTP_EDIT_LEXPARSER_REPARSETIMEOUTMS); pOpt->m_dwOnScreenSchCacheLifeTime_sec = (DWORD)ptrTopCls->GetAttribute_int( XTPLEX_ATTRG_ONSCREENSCHCACHELIFETIME_SEC, FALSE, XTP_EDIT_LEXPARSER_ONSCREENSCHCACHELIFETIMESEC); pOpt->m_dwParserThreadIdleLifeTime_ms = (DWORD)ptrTopCls->GetAttribute_int( XTPLEX_ATTRG_PARSERTHREADIDLELIFETIME_SEC, FALSE, XTP_EDIT_LEXPARSER_THREADIDLELIFETIMESEC); if (pOpt->m_dwParserThreadIdleLifeTime_ms != INFINITE) { pOpt->m_dwParserThreadIdleLifeTime_ms *= 1000; } if (pOpt->m_dwParserThreadIdleLifeTime_ms == 0) { pOpt->m_dwParserThreadIdleLifeTime_ms = INFINITE; } return TRUE; } const CXTPSyntaxEditLexParserSchemaOptions* CXTPSyntaxEditLexParser::GetSchemaOptions(const CString& strExt) { CSingleLock singLockMain(&m_csParserData); if (!m_ptrTextSchema) { RemoveAllOptions(); } CXTPSyntaxEditLexParserSchemaOptions* pOptions = NULL; if (m_mapSchOptions.Lookup(strExt, pOptions)) { ASSERT(pOptions); return pOptions; } else if (m_ptrTextSchema) { pOptions = new CXTPSyntaxEditLexParserSchemaOptions(); if (ReadSchemaOptions(strExt, m_ptrTextSchema, pOptions)) { m_mapSchOptions.SetAt(strExt, pOptions); return pOptions; } else { CMDTARGET_RELEASE(pOptions); } } return m_pSchOptions_default; }
25.126533
141
0.668491
11Zero
0733f85dcd68299e7d441edff00d18c459dddfab
5,888
cpp
C++
DynacoeSrc/srcs/Dynacoe/Image.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
1
2015-11-06T18:10:11.000Z
2015-11-06T18:10:11.000Z
DynacoeSrc/srcs/Dynacoe/Image.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
8
2018-01-25T03:54:32.000Z
2018-09-17T01:55:35.000Z
DynacoeSrc/srcs/Dynacoe/Image.cpp
jcorks/Dynacoe
2d606620e8072d8ae76aa2ecdc31512ac90362d9
[ "Apache-2.0", "MIT", "Libpng", "FTL", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu) All rights reserved. This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe) Dynacoe was released under the MIT License, as detailed below. 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 <Dynacoe/Image.h> #include <Dynacoe/Modules/Graphics.h> #include <Dynacoe/Dynacoe.h> #include <Dynacoe/Util/RefBank.h> #include <cstdint> #include <cmath> using namespace std; using namespace Dynacoe; static int badTexture = -1; class FreeTexture : public RefBank<int>::AccountRemover { public: void operator()(const int & id) { if (id != badTexture) Graphics::GetRenderer()->RemoveTexture(id); } }; static RefBank<int> * textureBank = nullptr; static FreeTexture * textureRemover = nullptr; Image::Frame::Frame(int textureObject) { if (!textureBank) { badTexture = Graphics::GetRenderer()->AddTexture(16, 16, nullptr); textureBank = new RefBank<int>(); textureRemover = new FreeTexture; textureBank->SetAccountRemover(textureRemover); if (textureObject == -1) textureObject = badTexture; } textureBank->Deposit(textureObject); object = textureObject; } Image::Frame::Frame() : Frame(badTexture) {} Image::Frame::Frame(uint32_t w, uint32_t h) : Frame(Graphics::GetRenderer()->AddTexture(w, h, nullptr)) {} Image::Frame::Frame(uint32_t w, uint32_t h, const std::vector<uint8_t> & data) : Frame(w, h) { SetData(data); } Image::Frame::Frame(const Frame & other) : Frame(other.object) {} Image::Frame::~Frame() { if (object != -1) textureBank->Withdraw(object); } Image::Frame & Image::Frame::operator=(const Image::Frame & other) { textureBank->Deposit(other.object); object = other.object; return *this; } std::vector<uint8_t> Image::Frame::GetData() const { std::vector<uint8_t> out; // Original texture size may not be current image size. uint32_t w = Width(); uint32_t h = Height(); out.resize(h * w * 4); Graphics::GetRenderer()->GetTexture(object, &out[0]); return out; } void Image::Frame::SetData(const std::vector<uint8_t> & data) { uint32_t w, h; w = Width(); h = Height(); if (data.size() != w*h*4) { Console::Error() << "Image::Frame::SetData : given data does not match image dimensions. Ignoring request.\n"; return; } Graphics::GetRenderer()->UpdateTexture(object, &data[0]); } uint32_t Image::Frame::Width() const { return Graphics::GetRenderer()->GetTextureWidth(object); } uint32_t Image::Frame::Height() const { return Graphics::GetRenderer()->GetTextureHeight(object); } std::vector<Image::Frame> Image::Frame::Detilize(uint32_t ws, uint32_t hs) const { uint32_t w = Width(); uint32_t h = Height(); uint32_t countW = ceil(w / (float)ws); uint32_t countH = ceil(h / (float)hs); std::vector<uint8_t> subImage; subImage.resize(ws*hs*4); const std::vector<uint8_t> & sourceImage = GetData(); uint8_t * subData = &subImage[0]; uint8_t * subIter = subData; const uint8_t * srcData = &sourceImage[0]; const uint8_t * srcIter = srcData; uint32_t srcIndex; uint32_t srcX; // pixel x of src image uint32_t srcY; // pixel y or src image std::vector<Frame> out; for(uint32_t y = 0; y < countH; ++y) { for(uint32_t x = 0; x < countW; ++x) { subIter = subData; srcX = x*ws; srcY = y*hs; for(uint32_t subY = 0; subY < hs; ++subY, ++srcY) { srcX = x*ws; for(uint32_t subX = 0; subX < ws; ++subX, ++srcX) { if (srcY >= h) continue; if (srcX >= w) continue; srcIter = srcData + (srcX + srcY*w)*4; subIter[0] = srcIter[0]; subIter[1] = srcIter[1]; subIter[2] = srcIter[2]; subIter[3] = srcIter[3]; subIter += 4; } } out.push_back(Frame(ws, hs, subImage)); } } return out; } int Image::Frame::GetHandle() const { return object; } class FrameCounter : public Entity { public: FrameCounter() { frame = 0; } void OnStep() { frame++; } uint64_t frame; }; static FrameCounter * frameCounter = nullptr; Image::Image(const std::string & n) : Asset(n) { if (!frameCounter) { frameCounter = Entity::CreateReference<FrameCounter>(); Engine::AttachManager(frameCounter->GetID()); } index = frameCounter->frame; } Image::Frame & Image::CurrentFrame(){ if (!frames.size()) { static Frame bad; return bad; } uint64_t frame = frameCounter->frame - index; return frames[frame%frames.size()]; }
26.763636
118
0.633492
jcorks
0734ddf23edf805925573bd9f0ad8fbd88c8ffe2
295
cpp
C++
src/common/copypaste_obj.cpp
krogenth/G2DataGUI
6bf4ef7bc90e72cf8fd33b9028cf00859dd8aa28
[ "MIT" ]
1
2021-04-20T04:34:59.000Z
2021-04-20T04:34:59.000Z
src/common/copypaste_obj.cpp
krogenth/G2DataGUI
6bf4ef7bc90e72cf8fd33b9028cf00859dd8aa28
[ "MIT" ]
3
2020-05-22T12:34:35.000Z
2021-07-02T15:46:42.000Z
src/common/copypaste_obj.cpp
krogenth/G2DataGUI
6bf4ef7bc90e72cf8fd33b9028cf00859dd8aa28
[ "MIT" ]
1
2020-05-20T00:29:38.000Z
2020-05-20T00:29:38.000Z
#include "..\include\common\copypaste_obj.h" void* clipboard = nullptr; std::string objType = ""; void copyObj(void* obj, std::string type) { clipboard = obj; objType = type; } void* pasteObj() { return clipboard; } bool checkObjType(std::string type) { return (objType == type); }
12.826087
44
0.667797
krogenth
0742993b36ef6397637f412029a0acb742b508f6
2,936
cpp
C++
source/smarties/Utils/StatsTracker.cpp
waitong94/smarties
e48fe6a8ba4695e20146cf5ca7c6720989217ed3
[ "MIT" ]
91
2018-07-16T07:54:06.000Z
2022-03-15T09:50:22.000Z
source/smarties/Utils/StatsTracker.cpp
waitong94/smarties
e48fe6a8ba4695e20146cf5ca7c6720989217ed3
[ "MIT" ]
7
2019-04-03T03:14:59.000Z
2021-11-17T09:02:14.000Z
source/smarties/Utils/StatsTracker.cpp
waitong94/smarties
e48fe6a8ba4695e20146cf5ca7c6720989217ed3
[ "MIT" ]
36
2018-07-16T08:08:35.000Z
2022-03-29T02:40:20.000Z
// // smarties // Copyright (c) 2018 CSE-Lab, ETH Zurich, Switzerland. All rights reserved. // Distributed under the terms of the MIT license. // // Created by Guido Novati (novatig@ethz.ch). // #include "StatsTracker.h" #include "Warnings.h" #include "SstreamUtilities.h" #include "../Settings/Bund.h" #include "../Settings/ExecutionInfo.h" #include <cassert> namespace smarties { StatsTracker::StatsTracker(const Uint N, const ExecutionInfo& distrib) : n_stats(N), nThreads(distrib.nThreads), learn_rank(MPICommRank(distrib.learners_train_comm)), cntVec(nThreads, 0), avgVec(nThreads, LDvec(n_stats, 0)), stdVec(nThreads, LDvec(n_stats, 0)) { instMean.resize(n_stats, 0); instStdv.resize(n_stats, 0); } void StatsTracker::track_vector(const Rvec& grad, const Uint thrID) const { assert(n_stats==grad.size()); cntVec[thrID] += 1; for (Uint i=0; i<n_stats; ++i) { avgVec[thrID][i] += grad[i]; stdVec[thrID][i] += grad[i]*grad[i]; } } void StatsTracker::advance() { std::fill(avg.begin(), avg.end(), 0); std::fill(std.begin(), std.end(), 0); cnt = 0; for (Uint i=0; i<nThreads; ++i) { cnt += cntVec[i]; for (Uint j=0; j<n_stats; ++j) { avg[j] += avgVec[i][j]; std[j] += stdVec[i][j]; } cntVec[i] = 0; std::fill(avgVec[i].begin(), avgVec[i].end(), 0); std::fill(stdVec[i].begin(), stdVec[i].end(), 0); } } void StatsTracker::update() { cnt = std::max((long double)2.2e-16, cnt); for (Uint j=0; j<n_stats; ++j) { const Real mean = avg[j] / cnt; const Real sqmean = std[j] / cnt; std[j] = std::sqrt(sqmean); // - mean*mean avg[j] = mean; } } void StatsTracker::printToFile(const std::string& base) { if(!learn_rank) { FILE * pFile; if(!nStep) { // write to log the number of variables, so that it can be then unwrangled pFile = fopen((base + "_outGrad_stats.raw").c_str(), "wb"); float printvals = n_stats +.1; // to be floored to an integer in post fwrite(&printvals, sizeof(float), 1, pFile); } else pFile = fopen((base + "_outGrad_stats.raw").c_str(), "ab"); std::vector<float> printvals(n_stats*2); for (Uint i=0; i<n_stats; ++i) { printvals[i] = avg[i]; printvals[i+n_stats] = std[i]; } fwrite(printvals.data(), sizeof(float), n_stats*2, pFile); fflush(pFile); fclose(pFile); } } void StatsTracker::finalize(const LDvec&oldM, const LDvec&oldS) { instMean = avg; instStdv = std; nStep++; for (Uint i=0; i<n_stats; ++i) { avg[i] = (1-CLIP_LEARNR)*oldM[i] +CLIP_LEARNR*avg[i]; std[i] = (1-CLIP_LEARNR)*oldS[i] +CLIP_LEARNR*std[i]; //stdVec[0][i]=std::max((1-CLIP_LEARNR)*oldstd[i], stdVec[0][i]); } } void StatsTracker::reduce_stats(const std::string& base, const Uint iter) { const LDvec oldsum = avg, oldstd = std; advance(); update(); if(iter % 1000 == 0) printToFile(base); finalize(oldsum, oldstd); } }
26.690909
80
0.621935
waitong94
074893657f6ea499ce38cd58b78e77fb00dc56d3
176
hpp
C++
test cases/cmake/19 advanced options/subprojects/cmOpts/cmMod.hpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
4,047
2015-06-18T10:36:48.000Z
2022-03-31T09:47:02.000Z
test cases/cmake/19 advanced options/subprojects/cmOpts/cmMod.hpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
8,206
2015-06-14T12:20:48.000Z
2022-03-31T22:50:37.000Z
test cases/cmake/19 advanced options/subprojects/cmOpts/cmMod.hpp
kira78/meson
0ae840656c5b87f30872072aa8694667c63c96d2
[ "Apache-2.0" ]
1,489
2015-06-27T04:06:38.000Z
2022-03-29T10:14:48.000Z
#pragma once #include <string> class cmModClass { private: std::string str; public: cmModClass(std::string foo); std::string getStr() const; int getInt() const; };
11.733333
30
0.676136
kira78
074f76db4c4330c64ae25016a36917980816dd8e
1,622
cpp
C++
mysql-server/storage/ndb/src/ndbapi/ndberror_check.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/ndbapi/ndberror_check.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/ndbapi/ndberror_check.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2009, 2017, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <NdbDictionary.hpp> #include "ndberror.c" #include <NdbTap.hpp> TAPTEST(ndberror_check) { int ok= 1; /* check for duplicate error codes */ for(int i = 0; i < NbErrorCodes; i++) { for(int j = i + 1; j < NbErrorCodes; j++) { if (ErrorCodes[i].code == ErrorCodes[j].code) { fprintf(stderr, "Duplicate error code %u\n", ErrorCodes[i].code); ok = 0; } } } return ok; }
33.791667
79
0.711467
silenc3502
0752246cd28c89516c6ed24d8a75050699115d71
1,186
hpp
C++
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/CurveTexture.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
5
2021-05-27T21:50:33.000Z
2022-01-28T11:54:32.000Z
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/CurveTexture.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
null
null
null
climate-change/src/VS-Project/Libraries/godot-cpp-bindings/include/gen/CurveTexture.hpp
jerry871002/CSE201-project
c42cc0e51d0c8367e4d06fc33756ab2ec4118ff4
[ "MIT" ]
1
2021-01-04T21:12:05.000Z
2021-01-04T21:12:05.000Z
#ifndef GODOT_CPP_CURVETEXTURE_HPP #define GODOT_CPP_CURVETEXTURE_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "Texture.hpp" namespace godot { class Curve; class CurveTexture : public Texture { struct ___method_bindings { godot_method_bind *mb__update; godot_method_bind *mb_get_curve; godot_method_bind *mb_set_curve; godot_method_bind *mb_set_width; }; static ___method_bindings ___mb; static void *_detail_class_tag; public: static void ___init_method_bindings(); inline static size_t ___get_id() { return (size_t)_detail_class_tag; } static inline const char *___get_class_name() { return (const char *) "CurveTexture"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums // constants static CurveTexture *_new(); // methods void _update(); Ref<Curve> get_curve() const; void set_curve(const Ref<Curve> curve); void set_width(const int64_t width); }; } #endif
23.72
245
0.766442
jerry871002
07540d3da3c2bc6c01f7efbae4a369df0b7a4229
1,919
cpp
C++
FSE/PhysContactListener.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
17
2017-04-02T00:17:47.000Z
2021-11-23T21:42:48.000Z
FSE/PhysContactListener.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
null
null
null
FSE/PhysContactListener.cpp
Alia5/FSE
e53565aa1bbf0235dfcd2c3209d18b64c1fb2df1
[ "MIT" ]
5
2017-08-06T12:47:18.000Z
2020-08-14T14:16:22.000Z
#include "PhysContactListener.h" #include "FSEObject/FSEObject.h" namespace fse { PhysContactListener::PhysContactListener() { } PhysContactListener::~PhysContactListener() { } void PhysContactListener::BeginContact(b2Contact* contact) { FSEObject * objectA = static_cast<FSEObject*>(contact->GetFixtureA()->GetBody()->GetUserData()); FSEObject * objectB = static_cast<FSEObject*>(contact->GetFixtureB()->GetBody()->GetUserData()); if (objectA != nullptr && objectB != nullptr) { objectA->BeginContact(objectB, contact); objectB->BeginContact(objectA, contact); } } void PhysContactListener::EndContact(b2Contact* contact) { FSEObject * objectA = static_cast<FSEObject*>(contact->GetFixtureA()->GetBody()->GetUserData()); FSEObject * objectB = static_cast<FSEObject*>(contact->GetFixtureB()->GetBody()->GetUserData()); if (objectA != nullptr && objectB != nullptr) { objectA->EndContact(objectB, contact); objectB->EndContact(objectA, contact); } } void PhysContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { FSEObject * objectA = static_cast<FSEObject*>(contact->GetFixtureA()->GetBody()->GetUserData()); FSEObject * objectB = static_cast<FSEObject*>(contact->GetFixtureB()->GetBody()->GetUserData()); if (objectA != nullptr && objectB != nullptr) { objectA->PreSolve(objectB, contact, oldManifold); objectB->PreSolve(objectA, contact, oldManifold); } } void PhysContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { FSEObject * objectA = static_cast<FSEObject*>(contact->GetFixtureA()->GetBody()->GetUserData()); FSEObject * objectB = static_cast<FSEObject*>(contact->GetFixtureB()->GetBody()->GetUserData()); if (objectA != nullptr && objectB != nullptr) { objectA->PostSolve(objectB, contact, impulse); objectB->PostSolve(objectA, contact, impulse); } } }
29.523077
98
0.712871
Alia5
075a2e0253776a5cfbfa84b5f98579518e184fc8
221
hpp
C++
lbench/include/likely.hpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
115
2019-09-28T13:39:41.000Z
2022-03-24T11:08:53.000Z
lbench/include/likely.hpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
120
2018-05-16T23:11:09.000Z
2019-09-25T18:52:49.000Z
lbench/include/likely.hpp
milad621/livehd
370b4274809ef95f880da07a603245bffcadf05e
[ "BSD-3-Clause" ]
44
2019-09-28T07:53:21.000Z
2022-02-13T23:21:12.000Z
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #ifndef likely #define likely(x) __builtin_expect((x), 1) #endif #ifndef unlikely #define unlikely(x) __builtin_expect((x), 0) #endif
24.555556
85
0.751131
milad621
075b5f156f565a1f9be5c2700c0f2b8a57985269
1,610
cpp
C++
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_throw_exception.cpp
dghosef/taco
c5074c359af51242d76724f97bb5fe7d9b638658
[ "MIT" ]
null
null
null
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_throw_exception.cpp
dghosef/taco
c5074c359af51242d76724f97bb5fe7d9b638658
[ "MIT" ]
null
null
null
pochi_libs_and_includes/include/fastinterp/fastinterp_tpl_throw_exception.cpp
dghosef/taco
c5074c359af51242d76724f97bb5fe7d9b638658
[ "MIT" ]
null
null
null
#define POCHIVM_INSIDE_FASTINTERP_TPL_CPP #include "fastinterp_tpl_common.hpp" #include "fastinterp_function_alignment.h" #include "fastinterp_tpl_return_type.h" namespace PochiVM { struct FIThrowExceptionImpl { template<bool isQuickAccess> static constexpr bool cond() { return true; } // Placeholder rules: // constant placeholder 0: stack offset, if the exnAddr is not quickaccess // cpp placeholder 0: the cpp helper that sets std::exception_ptr // boilerplate placeholder 0: continuation to cleanup logic // template<bool isQuickAccess> static void f(uintptr_t stackframe, [[maybe_unused]] uintptr_t qa) noexcept { uintptr_t exnAddr; if constexpr(isQuickAccess) { exnAddr = qa; } else { DEFINE_INDEX_CONSTANT_PLACEHOLDER_0; exnAddr = stackframe + CONSTANT_PLACEHOLDER_0; } using CppFnPrototype = void(*)(uintptr_t) noexcept; DEFINE_BOILERPLATE_FNPTR_PLACEHOLDER_1_NO_TAILCALL(CppFnPrototype); BOILERPLATE_FNPTR_PLACEHOLDER_1(exnAddr); DEFINE_BOILERPLATE_FNPTR_PLACEHOLDER_0(void(*)(uintptr_t) noexcept); BOILERPLATE_FNPTR_PLACEHOLDER_0(stackframe); } static auto metavars() { return CreateMetaVarList( CreateBoolMetaVar("isQuickAccess") ); } }; } // namespace PochiVM // build_fast_interp_lib.cpp JIT entry point // extern "C" void __pochivm_build_fast_interp_library__() { using namespace PochiVM; RegisterBoilerplate<FIThrowExceptionImpl>(); }
25.555556
79
0.685093
dghosef
075fb5c1655e594d033995cff4bcc35fb672c506
681
cpp
C++
1027.cpp
gysss/PAT
1652927317b35f86eb10d399042c2289e65d8d70
[ "Apache-2.0" ]
null
null
null
1027.cpp
gysss/PAT
1652927317b35f86eb10d399042c2289e65d8d70
[ "Apache-2.0" ]
null
null
null
1027.cpp
gysss/PAT
1652927317b35f86eb10d399042c2289e65d8d70
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <stdio.h> #include <cmath> #include <string> using namespace std; int main(int argc, char * argv[]){ int N; char t; cin>>N>>t; int i=sqrt((N+1)/2); for (int j = 0;j<i;j++) { for (int n = 0; n < j; ++n) { cout<<" "; } for (int m = 0; m < 2*i-1-2*j-1; ++m) { cout<<t<<" "; } cout<<t; for (int n = 0; n < j; ++n) { cout<<" "; } cout<<endl; } for (int j = i-2; j >=0; j--) { for (int n = 0; n < j; ++n) { cout<<" "; } for (int m = 0; m < 2*i-1-2*j-1; ++m) { cout<<t<<" "; } cout<<t; for (int n = 0; n < j; ++n) { cout<<" "; } cout<<endl; } cout<<N-(2*i*i-1)<<endl; return 0; }
14.1875
39
0.422907
gysss
79e32a9967b1821e49733abcbbc72c012d7dc10f
1,205
cpp
C++
esp32s-wroom/Webthings-Controller/src/main.cpp
raushanraja/IOTExmaples
1973381b99e4a4bd3303b9e3c2739c7482b27ea4
[ "Unlicense" ]
null
null
null
esp32s-wroom/Webthings-Controller/src/main.cpp
raushanraja/IOTExmaples
1973381b99e4a4bd3303b9e3c2739c7482b27ea4
[ "Unlicense" ]
null
null
null
esp32s-wroom/Webthings-Controller/src/main.cpp
raushanraja/IOTExmaples
1973381b99e4a4bd3303b9e3c2739c7482b27ea4
[ "Unlicense" ]
null
null
null
#include <Arduino.h> #include <WiFi.h> #include <ArduinoHttpClient.h> const char *ssid = "dlink_DWR-920V_7EE5"; const char *password = "nhaza95645"; const int hostPort = 80; const char *hostAddress = "192.168.0.24"; WiFiClient wifi; HttpClient client = HttpClient(wifi, hostAddress, hostPort); int touchInput; int value=0; void setup() { Serial.begin(9600); delay(100); Serial.print("connection to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("WiFi Connected:"); Serial.println(WiFi.localIP()); Serial.println("Starting Communication with WebServer"); } void loop() { touchInput = touchRead(T0); String on = "{\"on\":true}"; String off = "{\"on\":false}"; Serial.println(touchInput); if (touchInput < 15 && touchInput > 10) { String contentType = "text/plain"; Serial.println("making PUT request"); client.put("/things/switc/properties/on", contentType, value==0?on:off); value=value==0?1:0; client.responseBody(); Serial.println(); Serial.println("closing connection"); delay(1); } Serial.flush(); }
21.140351
76
0.661411
raushanraja
79e5443898422e0a129df925d76fc9fa032f0637
2,521
cc
C++
alidns/src/model/SetDNSSLBStatusRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
alidns/src/model/SetDNSSLBStatusRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
alidns/src/model/SetDNSSLBStatusRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/alidns/model/SetDNSSLBStatusRequest.h> using AlibabaCloud::Alidns::Model::SetDNSSLBStatusRequest; SetDNSSLBStatusRequest::SetDNSSLBStatusRequest() : RpcServiceRequest("alidns", "2015-01-09", "SetDNSSLBStatus") { setMethod(HttpRequest::Method::Post); } SetDNSSLBStatusRequest::~SetDNSSLBStatusRequest() {} std::string SetDNSSLBStatusRequest::getDomainName()const { return domainName_; } void SetDNSSLBStatusRequest::setDomainName(const std::string& domainName) { domainName_ = domainName; setParameter("DomainName", domainName); } std::string SetDNSSLBStatusRequest::getType()const { return type_; } void SetDNSSLBStatusRequest::setType(const std::string& type) { type_ = type; setParameter("Type", type); } std::string SetDNSSLBStatusRequest::getAccessKeyId()const { return accessKeyId_; } void SetDNSSLBStatusRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string SetDNSSLBStatusRequest::getUserClientIp()const { return userClientIp_; } void SetDNSSLBStatusRequest::setUserClientIp(const std::string& userClientIp) { userClientIp_ = userClientIp; setParameter("UserClientIp", userClientIp); } std::string SetDNSSLBStatusRequest::getSubDomain()const { return subDomain_; } void SetDNSSLBStatusRequest::setSubDomain(const std::string& subDomain) { subDomain_ = subDomain; setParameter("SubDomain", subDomain); } std::string SetDNSSLBStatusRequest::getLang()const { return lang_; } void SetDNSSLBStatusRequest::setLang(const std::string& lang) { lang_ = lang; setParameter("Lang", lang); } bool SetDNSSLBStatusRequest::getOpen()const { return open_; } void SetDNSSLBStatusRequest::setOpen(bool open) { open_ = open; setParameter("Open", open ? "true" : "false"); }
23.560748
78
0.741372
iamzken
79e8dfbfb1b7f4d7667ae5e17eb5eefe5d1586ea
3,288
cpp
C++
AUT2016/LOG2410/tp5/TP5-A16/Code/MachineBase.cpp
KevPantelakis/turbo-giggle
cb3c089f9284fe4b2b20917c3301054812d32e4b
[ "MIT" ]
null
null
null
AUT2016/LOG2410/tp5/TP5-A16/Code/MachineBase.cpp
KevPantelakis/turbo-giggle
cb3c089f9284fe4b2b20917c3301054812d32e4b
[ "MIT" ]
null
null
null
AUT2016/LOG2410/tp5/TP5-A16/Code/MachineBase.cpp
KevPantelakis/turbo-giggle
cb3c089f9284fe4b2b20917c3301054812d32e4b
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////// // MachineBase.cpp // Implementation of the Class MachineBase // Created on: 27-oct.-2016 15:12:17 // Original author: francois /////////////////////////////////////////////////////////// #include <iostream> #include "MachineBase.h" #include "CircuitLiqComposite.h" #include "Bouilloire.h" #include "Pompe.h" #include "Reservoir.h" #include "Tuyau.h" #include "CircuitSolComposite.h" #include "Transmission.h" #include "Moteur.h" #include "Receptacle.h" #include "Filtre.h" #include "ProgrammeMachine.h" #include "ExecuteurCommandes.h" #include "CommandeTransfertLiqReservBouil.h" #include "CommandeFixerTemperatureLiquide.h" MachineBase::MachineBase() : MachineAbs(FiltrePtr(new Filtre)), m_CircuitEauChaude(new CircuitLiqComposite), m_CircuitThe(new CircuitSolComposite) { // Construire toutes les composantes d'une machine de base // Constuire les elements du circuit d'eau chaude m_CircuitEauChaude->addSousElement( new Reservoir(4.5, 25.0, 20.0, 2200.0) ); m_CircuitEauChaude->addSousElement(new Tuyau(0.25, 5.0)); m_CircuitEauChaude->addSousElement(new Pompe(0.05f, 10.0)); m_CircuitEauChaude->addSousElement(new Tuyau(0.25, 5.0)); m_CircuitEauChaude->addSousElement(new Bouilloire(5.5, 20.0,500.0)); m_CircuitEauChaude->addSousElement(new Tuyau(0.25, 5.0)); // Constuire les elements du circuit de the m_CircuitThe->addSousElement(new Moteur(5.0)); m_CircuitThe->addSousElement(new Receptacle(12.5, 15.0, 100)); m_CircuitThe->addSousElement(new Moteur(0.5)); m_CircuitThe->addSousElement(new Transmission(0.75, 5.0)); } MachineBase::~MachineBase(){ } void MachineBase::infuserThe(float duree){ //m_CircuitThe->operer(duree); //m_CircuitEauChaude->operer(duree); // Constuire un programme pour commander la machine ProgrammeMachine progLiquide; progLiquide.addCommande(new CommandeTransfertLiqReservBouil(150)); progLiquide.addCommande(new CommandeFixerTemperatureLiquide(90)); // Recuperer l'executeur de commande et lui faire executer le programme const ExecuteurCommandes* executeur = ExecuteurCommandes::getInstance(); executeur->executer(&progLiquide, m_CircuitEauChaude.get()); } bool MachineBase::opACircuitLait(){ return false; } bool MachineBase::opACircuitSucre(){ return false; } void MachineBase::opNettoyerCircuitEau(){ m_CircuitEauChaude->nettoyer(); } void MachineBase::opNettoyerCircuitLait(){ } void MachineBase::opNettoyerCircuitSucre(){ } void MachineBase::opNettoyerCircuitThe(){ m_CircuitThe->nettoyer(); } void MachineBase::opNettoyerFiltre(){ m_filtre->nettoyer(); } resultat_test MachineBase::opDiagnostiquerCircuitEau(){ auto tartre = m_CircuitEauChaude->getTartre(); return (tartre < SEUIL_TARTRE_MAX_EAU) ? resultat_test::succes : resultat_test::echec; } resultat_test MachineBase::opDiagnostiquerCircuitLait(){ return resultat_test::succes; } resultat_test MachineBase::opDiagnostiquerCircuitSucre(){ return resultat_test::succes; } resultat_test MachineBase::opDiagnostiquerCircuitThe(){ auto debris = m_CircuitThe->getDebris(); return (debris < SEUIL_DEBRIS_MAX_THE) ? resultat_test::succes : resultat_test::echec; } resultat_test MachineBase::opDiagnostiquerFiltre(){ return resultat_test::succes; }
24.176471
119
0.744526
KevPantelakis
79ebf4f7fc80fba0e2ea0599a01d1ef57f8b53a6
5,109
cpp
C++
Engine/Src/Memory/MemoryProfiler.cpp
felipegodias/PlutoEngine
0ee5304b35f8b5edb0cb6d2635285daff9e35b21
[ "MIT" ]
null
null
null
Engine/Src/Memory/MemoryProfiler.cpp
felipegodias/PlutoEngine
0ee5304b35f8b5edb0cb6d2635285daff9e35b21
[ "MIT" ]
5
2021-12-10T23:27:43.000Z
2021-12-23T00:49:04.000Z
Engine/Src/Memory/MemoryProfiler.cpp
felipegodias/PlutoEngine
0ee5304b35f8b5edb0cb6d2635285daff9e35b21
[ "MIT" ]
null
null
null
#include "Pluto/Engine/Memory/MemoryProfiler.h" #include <algorithm> #include <iostream> #include <map> #include <unordered_map> #include <vector> namespace Pluto::Engine { namespace { size_t totalUsedBytes = 0; template <class Ty> class MPAllocator { public: using value_type = Ty; MPAllocator() noexcept = default; template <class RebindTy> MPAllocator(const MPAllocator<RebindTy>&) noexcept { } // ReSharper disable once CppInconsistentNaming // ReSharper disable once CppMemberFunctionMayBeStatic value_type* allocate(const std::size_t n) { const size_t size = n * sizeof(value_type); totalUsedBytes += size; return static_cast<value_type*>(std::malloc(size)); } // ReSharper disable once CppInconsistentNaming // ReSharper disable once CppMemberFunctionMayBeStatic void deallocate(value_type* p, const std::size_t n) noexcept { const size_t size = n * sizeof(value_type); totalUsedBytes -= size; std::free(p); } }; template <class Ty, class RebindTy> bool operator==(const MPAllocator<Ty>&, const MPAllocator<RebindTy>&) noexcept { return true; } template <class Ty, class RebindTy> bool operator!=(const MPAllocator<Ty>& x, const MPAllocator<RebindTy>& y) noexcept { return !(x == y); } using MPString = std::basic_string<char, std::char_traits<char>, MPAllocator<char>>; template <typename Ty> using MPVector = std::vector<Ty, MPAllocator<Ty>>; template <typename KTy, typename VTy> using MPMap = std::map<KTy, VTy, std::less<KTy>, MPAllocator<std::pair<const KTy, VTy>>>; template <typename KTy, typename VTy> using MPUnorderedMap = std::unordered_map<KTy, VTy, std::hash<KTy>, std::equal_to<KTy>, MPAllocator<std::pair< const KTy, VTy>>>; struct PointerMetaData { size_t size; MPMap<MPString, MPString> tags; explicit PointerMetaData(const size_t size) : size(size) { } friend std::ostream& operator<<(std::ostream& os, const PointerMetaData& pointerMetaData) { os << "<<<<<<<<<<<<<<<<<<<<<<<\n"; os << "Size: " << pointerMetaData.size << " bytes\n"; for (auto& tag : pointerMetaData.tags) { os << tag.first << ": " << tag.second << "\n"; } os << ">>>>>>>>>>>>>>>>>>>>>>>\n"; return os; } }; bool PointerMetaDataComparator(const PointerMetaData* lhs, const PointerMetaData* rhs) { return lhs->size > rhs->size; } MPUnorderedMap<uintptr_t, PointerMetaData> pointersMetaData; } void MemoryProfiler::Track(void* ptr, const size_t size) { totalUsedBytes += size; pointersMetaData.emplace(reinterpret_cast<uintptr_t>(ptr), PointerMetaData(size)); } void MemoryProfiler::Untrack(void* ptr) { if (const auto it = pointersMetaData.find(reinterpret_cast<uintptr_t>(ptr)); it != pointersMetaData.end()) { totalUsedBytes -= it->second.size; pointersMetaData.erase(it); } } void MemoryProfiler::AddTag(void* ptr, const StringView name, const StringView value) { const auto it = pointersMetaData.find(reinterpret_cast<uintptr_t>(ptr)); if (it == pointersMetaData.end()) { return; } MPMap<MPString, MPString>& tags = it->second.tags; MPString nameStr = name.data(); MPString valueStr = value.data(); if (const auto tagsIt = tags.find(nameStr); tagsIt == tags.end()) { tags.emplace(std::move(nameStr), std::move(valueStr)); } else { tagsIt->second = std::move(valueStr); } } size_t MemoryProfiler::GetUsedMemory() { return totalUsedBytes; } void MemoryProfiler::DumpMemorySummary(std::ostream& os) { MPVector<PointerMetaData*> pointerMetaDataHeap; pointerMetaDataHeap.reserve(pointersMetaData.size()); for (auto& [size, pointerMetaData] : pointersMetaData) { pointerMetaDataHeap.push_back(&pointerMetaData); std::push_heap(pointerMetaDataHeap.begin(), pointerMetaDataHeap.end(), PointerMetaDataComparator); } while (pointerMetaDataHeap.empty() == false) { os << *pointerMetaDataHeap.front() << "\n"; std::pop_heap(pointerMetaDataHeap.begin(), pointerMetaDataHeap.end(), PointerMetaDataComparator); pointerMetaDataHeap.pop_back(); } } }
31.732919
118
0.557056
felipegodias
79ed0d94f4ce09d7aca47bbd4d52f7e72f5778b8
6,335
hpp
C++
vox_nav_planning/include/vox_nav_planning/planner_core.hpp
NMBURobotics/vox_nav
7d71c97166ce57680bf2e637cca7c745d55b045a
[ "Apache-2.0" ]
47
2021-06-03T08:46:51.000Z
2022-03-31T08:07:09.000Z
vox_nav_planning/include/vox_nav_planning/planner_core.hpp
BADAL244/vox_nav
cd88c8a921feed65a92355d6246cf6cb8dd27939
[ "Apache-2.0" ]
6
2021-06-06T01:17:38.000Z
2022-01-06T10:01:53.000Z
vox_nav_planning/include/vox_nav_planning/planner_core.hpp
BADAL244/vox_nav
cd88c8a921feed65a92355d6246cf6cb8dd27939
[ "Apache-2.0" ]
10
2021-06-03T08:46:53.000Z
2022-03-04T00:57:51.000Z
// Copyright (c) 2020 Fetullah Atas, Norwegian University of Life Sciences // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef VOX_NAV_PLANNING__PLANNER_CORE_HPP_ #define VOX_NAV_PLANNING__PLANNER_CORE_HPP_ #pragma once // ROS #include <rclcpp/rclcpp.hpp> #include <rclcpp/service.hpp> #include <rclcpp/client.hpp> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <geometry_msgs/msg/pose.hpp> #include <sensor_msgs/msg/point_cloud2.hpp> #include <visualization_msgs/msg/marker_array.hpp> #include <vox_nav_utilities/tf_helpers.hpp> #include <vox_nav_utilities/pcl_helpers.hpp> #include <vox_nav_utilities/planner_helpers.hpp> #include <vox_nav_msgs/srv/get_maps_and_surfels.hpp> // PCL #include <pcl/common/common.h> #include <pcl/common/transforms.h> #include <pcl/conversions.h> #include <pcl/filters/voxel_grid.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> // OMPL GEOMETRIC #include <ompl/geometric/planners/fmt/BFMT.h> #include <ompl/geometric/planners/rrt/RRTstar.h> #include <ompl/geometric/planners/rrt/RRTsharp.h> #include <ompl/geometric/planners/rrt/InformedRRTstar.h> #include <ompl/geometric/planners/rrt/LBTRRT.h> #include <ompl/geometric/planners/rrt/TRRT.h> #include <ompl/geometric/planners/sst/SST.h> #include <ompl/geometric/planners/fmt/FMT.h> #include <ompl/geometric/planners/prm/SPARS.h> #include <ompl/geometric/planners/prm/SPARStwo.h> #include <ompl/geometric/planners/prm/PRMstar.h> #include <ompl/geometric/planners/prm/LazyPRMstar.h> #include <ompl/geometric/planners/AnytimePathShortening.h> #include <ompl/geometric/planners/cforest/CForest.h> #include <ompl/geometric/planners/informedtrees/BITstar.h> #include <ompl/geometric/planners/informedtrees/ABITstar.h> #include <ompl/geometric/planners/informedtrees/AITstar.h> #include <ompl/geometric/SimpleSetup.h> #include <ompl/base/OptimizationObjective.h> // OMPL BASE #include <ompl/base/samplers/ObstacleBasedValidStateSampler.h> #include <ompl/base/OptimizationObjective.h> #include <ompl/base/objectives/PathLengthOptimizationObjective.h> #include <ompl/base/objectives/MaximizeMinClearanceObjective.h> #include <ompl/base/samplers/MaximizeClearanceValidStateSampler.h> #include <ompl/base/objectives/StateCostIntegralObjective.h> #include <ompl/base/spaces/SE2StateSpace.h> #include <ompl/base/spaces/DubinsStateSpace.h> #include <ompl/base/spaces/ReedsSheppStateSpace.h> #include <ompl/base/spaces/SE3StateSpace.h> #include <ompl/tools/benchmark/Benchmark.h> #include <ompl/base/StateSampler.h> // OCTOMAP #include <octomap_msgs/msg/octomap.hpp> #include <octomap_msgs/conversions.h> #include <octomap/octomap.h> #include <octomap/octomap_utils.h> // FCL #include <fcl/config.h> #include <fcl/octree.h> #include <fcl/traversal/traversal_node_octree.h> #include <fcl/collision.h> #include <fcl/broadphase/broadphase.h> #include <fcl/math/transform.h> // STL #include <string> #include <iostream> #include <memory> #include <vector> namespace vox_nav_planning { /** * @brief Base class for creating a planner plugins * */ class PlannerCore { public: using Ptr = std::shared_ptr<PlannerCore>; /** * @brief Construct a new Planner Core object * */ PlannerCore() {} /** * @brief Destroy the Planner Core object * */ virtual ~PlannerCore() {} /** * @brief * * @param parent * @param plugin_name */ virtual void initialize( rclcpp::Node * parent, const std::string & plugin_name) = 0; /** * @brief Method create the plan from a starting and ending goal. * * @param start The starting pose of the robot * @param goal The goal pose of the robot * @return std::vector<geometry_msgs::msg::PoseStamped> The sequence of poses to get from start to goal, if any */ virtual std::vector<geometry_msgs::msg::PoseStamped> createPlan( const geometry_msgs::msg::PoseStamped & start, const geometry_msgs::msg::PoseStamped & goal) = 0; /** * @brief * * @param state * @return true * @return false */ virtual bool isStateValid(const ompl::base::State * state) = 0; /** * @brief Get the Overlayed Start and Goal poses, only x and y are provided for goal , * but internally planner finds closest valid node on octomap and reassigns goal to this pose * * @return std::vector<geometry_msgs::msg::PoseStamped> */ virtual std::vector<geometry_msgs::msg::PoseStamped> getOverlayedStartandGoal() = 0; /** * @brief * */ virtual void setupMap() = 0; protected: rclcpp::Client<vox_nav_msgs::srv::GetMapsAndSurfels>::SharedPtr get_maps_and_surfels_client_; rclcpp::Node::SharedPtr get_maps_and_surfels_client_node_; // octomap acquired from original PCD map std::shared_ptr<octomap::OcTree> original_octomap_octree_; std::shared_ptr<fcl::CollisionObject> original_octomap_collision_object_; std::shared_ptr<fcl::CollisionObject> robot_collision_object_; std::shared_ptr<fcl::CollisionObject> robot_collision_object_minimal_; ompl::geometric::SimpleSetupPtr simple_setup_; // to ensure safety when accessing global var curr_frame_ std::mutex global_mutex_; // the topic to subscribe in order capture a frame std::string planner_name_; // Better t keep this parameter consistent with map_server, 0.2 is a OK default fo this double octomap_voxel_size_; // related to density of created path int interpolation_parameter_; // max time the planner can spend before coming up with a solution double planner_timeout_; // global mutex to guard octomap std::mutex octomap_mutex_; volatile bool is_map_ready_; }; } // namespace vox_nav_planning #endif // VOX_NAV_PLANNING__PLANNER_CORE_HPP_
34.807692
117
0.74412
NMBURobotics
79ed49b1e1df38a0d2a90f155f08875114637b67
1,702
cpp
C++
Siv3D/src/Siv3D/Script/Bind/ScriptLineStyleParameters.cpp
sanyaade-teachings/OpenSiv3D
e4ef5d9676f0048b3ce527779baaff3ad0d3059b
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Script/Bind/ScriptLineStyleParameters.cpp
sanyaade-teachings/OpenSiv3D
e4ef5d9676f0048b3ce527779baaff3ad0d3059b
[ "MIT" ]
null
null
null
Siv3D/src/Siv3D/Script/Bind/ScriptLineStyleParameters.cpp
sanyaade-teachings/OpenSiv3D
e4ef5d9676f0048b3ce527779baaff3ad0d3059b
[ "MIT" ]
null
null
null
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Script.hpp> # include <Siv3D/LineStyle.hpp> namespace s3d { using namespace AngelScript; using ShapeType = LineStyle::Parameters; static void DefaultConstruct(ShapeType* self) { new(self) ShapeType(); } static void CopyConstruct(const LineStyle::Parameters& other, ShapeType* self) { new(self) ShapeType(other); } static void Destruct(ShapeType* self) { self->~Parameters(); } void RegisterLineStyleParameters(asIScriptEngine* engine) { constexpr char TypeName[] = "LineStyleParameters"; int32 r = 0; r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DefaultConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0); r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, "void f(const LineStyleParameters& in)", asFUNCTION(CopyConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0); r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, "void f()", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0); r = engine->RegisterObjectMethod(TypeName, "LineStyleParameters opCall(double) const", asMETHODPR(LineStyle::Parameters, offset, (double) const, LineStyle::Parameters), asCALL_THISCALL); assert(r >= 0); r = engine->RegisterObjectMethod(TypeName, "LineStyleParameters offset(double) const", asMETHODPR(LineStyle::Parameters, offset, (double) const, LineStyle::Parameters), asCALL_THISCALL); assert(r >= 0); } }
34.734694
204
0.701528
sanyaade-teachings
79ef76ba33b022a330ea2f083566be1f81683f7b
2,025
cc
C++
src/utility/11060-dfs-ts.cc
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
2
2019-09-07T17:00:26.000Z
2020-08-05T02:08:35.000Z
src/utility/11060-dfs-ts.cc
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
null
null
null
src/utility/11060-dfs-ts.cc
cbarnson/UVa
0dd73fae656613e28b5aaf5880c5dad529316270
[ "Unlicense", "MIT" ]
null
null
null
// Problem # : 11060 // Title : Beverages // Accepted : No // Date : 20180519 #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <algorithm> #include <bitset> #include <deque> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; typedef vector<vector<int>> vec2d; typedef vector<int> vi; typedef pair<int, int> ii; 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)); } template <typename T> void printInitList(initializer_list<T> l) { for (const auto &i : l) cout << i << ' '; cout << endl; } // variadic function // int sum() { return 0; } // template<typename T, typename... Args> // T sum(T a, Args... args) { return a + sum(args...); } vector<vector<int>> g; vector<int> ts; const int UNVISITED = -1; const int VISITED = 1; int dfs_num[100]; void dfs(int s) { dfs_num[s] = VISITED; for (int i = 0; i < (int)g[s].size(); i++) { int v = g[s][i]; if (dfs_num[v] == UNVISITED) dfs(v); } ts.push_back(s); } int main() { int tc = 1, n, m; while (cin >> n >> m) { // init ts.clear(); g.resize(n); for (auto &i : g) { i.reserve(n); } memset(dfs_num, UNVISITED, sizeof dfs_num); // read for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; g[u].push_back(v); } // process for (int i = 0; i < n; i++) { if (dfs_num[i] == UNVISITED) dfs(i); } // output for (int i = (int)ts.size() - 1; i >= 0; i--) { printf(" %d", ts[i]); } cout << endl; } printf("Case %d: Dilbert should drink beverages in this order: ", tc++); // B1 B2 B3 ... BN. return 0; }
17.307692
74
0.54963
cbarnson
79f1d251fe95783f271c6f7de50452135402a571
2,439
cpp
C++
source/geom/border.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
12
2020-07-08T04:21:44.000Z
2022-03-24T10:02:03.000Z
source/geom/border.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
null
null
null
source/geom/border.cpp
taogashi/mlib
56d0ac08205b3a09cac7ed97209454cc6262c924
[ "Unlicense", "MIT" ]
2
2020-07-22T09:00:40.000Z
2021-06-29T13:54:10.000Z
/*! \file border.cpp Implementation of Border object (c) Mircea Neacsu 2017 */ #include <mlib/border.h> #include <stdio.h> #include <algorithm> #include <utf8/utf8.h> using namespace std; /*! \defgroup geom Geometry \brief Geometry concepts and algorithms */ namespace mlib { /*! \class Border \ingroup geom \brief Representation of a simple, non-intersecting polygon that partitions the 2D space in two regions. The polygon is represented by its vertexes and it is always assumed that there is a segment joining the last point with the first point. A Border object can be stored in a text file where each line represents a vertex. The last vertex defines what is considered the "inside" of the polygon: if the point lays inside the polygon, it is an "island" border. If the last point is outside the polygon, it is a "hole" border. */ /*! Create an empty border object */ Border::Border () { closing.x = 0; closing.y = 0; closing_outside = 0; } /*! Load a border object from a text file. */ Border::Border (const char *fname) { dpoint p; closing.x = 0; closing.y = 0; closing_outside = 0; FILE *f = utf8::fopen (fname, "r"); if (!f) return; while (!feof (f)) { char ln[256]; fgets (ln, sizeof (ln), f); sscanf (ln, "%lf%lf", &p.x, &p.y); vertex.push_back (p); } fclose (f); closing = vertex.back (); vertex.pop_back (); closing_outside = !inside (closing.x, closing.y); } void Border::add (double x, double y) { dpoint p; p.x = x; p.y = y; vertex.push_back (p); } void Border::close (double x, double y) { closing.x = x; closing.y = y; closing_outside = !inside (closing.x, closing.y); } /*! Check if a point is inside the border. \param x - X coordinate of the point \param y - Y coordinate of the point \return true if point is inside the border Algorithm adapted from W. Randolph Franklin <wrf@ecse.rpi.edu> http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html */ bool Border::inside (double x, double y) { int c = 0; deque<dpoint>::iterator pi = vertex.begin (); deque<dpoint>::iterator pj = vertex.end (); if (pi == pj) return 0; //empty border pj--; while (pi != vertex.end ()) { if (((pi->y > y) != (pj->y > y)) && (x < (pj->x - pi->x) * (y - pi->y) / (pj->y - pi->y) + pi->x)) c = !c; pj = pi++; } return (c != closing_outside); } }
19.991803
81
0.633046
taogashi
79f4088c86ce4690e142dedf57370d2a6fd7bc0c
2,682
cpp
C++
third_party/di-cpp14/test/ut/concepts/configurable.cpp
robhendriks/city-defence
6567222087fc74bf374423d4aab5512cbe86ac07
[ "MIT" ]
null
null
null
third_party/di-cpp14/test/ut/concepts/configurable.cpp
robhendriks/city-defence
6567222087fc74bf374423d4aab5512cbe86ac07
[ "MIT" ]
null
null
null
third_party/di-cpp14/test/ut/concepts/configurable.cpp
robhendriks/city-defence
6567222087fc74bf374423d4aab5512cbe86ac07
[ "MIT" ]
1
2022-03-29T02:01:56.000Z
2022-03-29T02:01:56.000Z
// // Copyright (c) 2012-2016 Krzysztof Jusiak (krzysztof at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "boost/di/concepts/configurable.hpp" #include <type_traits> #include "boost/di/aux_/compiler.hpp" #include "boost/di/config.hpp" #include "boost/di/providers/heap.hpp" namespace concepts { test none = [] { class test_config {}; static_expect(std::is_same<config<test_config>::requires_<provider<providable_type(...)>, policies<callable_type(...)>>, configurable<test_config>>::value); }; class config_just_policies { public: static auto policies(...) noexcept { return make_policies(); } }; test just_policies = [] { static_expect( std::is_same<config<config_just_policies>::requires_<provider<providable_type(...)>, policies<callable_type(...)>>, configurable<config_just_policies>>::value); }; class config_just_provider { public: static auto provider(...) noexcept { return providers::heap{}; } }; test just_provider = [] { static_expect( std::is_same<config<config_just_provider>::requires_<provider<providable_type(...)>, policies<callable_type(...)>>, configurable<config_just_provider>>::value); }; class config_private_access { private: static auto policies(...) noexcept { return make_policies(); } static auto provider(...) noexcept { return providers::heap{}; } }; #if !defined(__MSVC__) test private_access = [] { static_expect( std::is_same<config<config_private_access>::requires_<provider<providable_type(...)>, policies<callable_type(...)>>, configurable<config_private_access>>::value); }; #endif class config_inheritance_impl { public: static auto policies(...) noexcept { return make_policies(); } static auto provider(...) noexcept { return providers::heap{}; } }; class config_inheritance : public config_inheritance_impl {}; test inheritance = [] { static_expect(configurable<config_inheritance>::value); }; class config_okay { public: static auto policies(...) noexcept { return make_policies(); } static auto provider(...) noexcept { return providers::heap{}; } }; test okay = [] { static_expect(configurable<config_okay>::value); }; class config_okay_type { public: template <class T> static auto policies(const T&) noexcept { return make_policies(); } template <class T> static auto provider(const T&) noexcept { return providers::heap{}; } }; test okay_type = [] { static_expect(configurable<config_okay_type>::value); }; } // concepts
29.472527
122
0.695377
robhendriks
79f4e5ac69c3de768e4ca56046a8bd91dbe04e16
7,336
cc
C++
chrome/browser/sessions/session_data_deleter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
chrome/browser/sessions/session_data_deleter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/sessions/session_data_deleter.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sessions/session_data_deleter.h" #include <stddef.h> #include <stdint.h> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "build/build_config.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/lifetime/browser_shutdown.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_keep_alive_types.h" #include "chrome/browser/profiles/scoped_profile_keep_alive.h" #include "chrome/browser/ui/startup/startup_browser_creator.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/storage_usage_info.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "mojo/public/cpp/bindings/remote.h" #include "net/cookies/cookie_util.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "services/network/public/mojom/network_context.mojom.h" #include "storage/browser/quota/special_storage_policy.h" namespace { bool OriginMatcher(const url::Origin& origin, storage::SpecialStoragePolicy* policy) { return policy->IsStorageSessionOnly(origin.GetURL()) && !policy->IsStorageProtected(origin.GetURL()); } class SessionDataDeleterInternal : public base::RefCountedThreadSafe<SessionDataDeleterInternal> { public: SessionDataDeleterInternal(Profile* profile, bool delete_only_by_session_only_policy, base::OnceClosure callback); SessionDataDeleterInternal(const SessionDataDeleterInternal&) = delete; SessionDataDeleterInternal& operator=(const SessionDataDeleterInternal&) = delete; void Run(content::StoragePartition* storage_partition, HostContentSettingsMap* host_content_settings_map); private: friend class base::RefCountedThreadSafe<SessionDataDeleterInternal>; ~SessionDataDeleterInternal(); // These functions are used to hold a reference to this object until the // cookie and storage deletions are done. This way the keep alives ensure that // the profile does not shut down during the deletion. void OnCookieDeletionDone(uint32_t count) {} void OnStorageDeletionDone() {} std::unique_ptr<ScopedKeepAlive> keep_alive_; std::unique_ptr<ScopedProfileKeepAlive> profile_keep_alive_; base::OnceClosure callback_; mojo::Remote<network::mojom::CookieManager> cookie_manager_; scoped_refptr<storage::SpecialStoragePolicy> storage_policy_; const bool delete_only_by_session_only_policy_; }; SessionDataDeleterInternal::SessionDataDeleterInternal( Profile* profile, bool delete_only_by_session_only_policy, base::OnceClosure callback) : keep_alive_(std::make_unique<ScopedKeepAlive>( KeepAliveOrigin::SESSION_DATA_DELETER, KeepAliveRestartOption::ENABLED)), profile_keep_alive_(std::make_unique<ScopedProfileKeepAlive>( profile, ProfileKeepAliveOrigin::kSessionDataDeleter)), callback_(std::move(callback)), storage_policy_(profile->GetSpecialStoragePolicy()), delete_only_by_session_only_policy_(delete_only_by_session_only_policy) {} void SessionDataDeleterInternal::Run( content::StoragePartition* storage_partition, HostContentSettingsMap* host_content_settings_map) { if (storage_policy_.get() && storage_policy_->HasSessionOnlyOrigins()) { // Cookies are not origin scoped, so they are handled separately. const uint32_t removal_mask = content::StoragePartition::REMOVE_DATA_MASK_ALL & ~content::StoragePartition::REMOVE_DATA_MASK_COOKIES; // Clear storage and keep this object alive until deletion is done. storage_partition->ClearData( removal_mask, content::StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, base::BindRepeating(&OriginMatcher), /*cookie_deletion_filter=*/nullptr, /*perform_storage_cleanup=*/false, base::Time(), base::Time::Max(), base::BindOnce(&SessionDataDeleterInternal::OnStorageDeletionDone, this)); } storage_partition->GetNetworkContext()->GetCookieManager( cookie_manager_.BindNewPipeAndPassReceiver()); if (!delete_only_by_session_only_policy_) { network::mojom::CookieDeletionFilterPtr filter( network::mojom::CookieDeletionFilter::New()); filter->session_control = network::mojom::CookieDeletionSessionControl::SESSION_COOKIES; cookie_manager_->DeleteCookies( std::move(filter), // Fire and forget. Session cookies will be cleaned up on start as well. // (SQLitePersistentCookieStore::Backend::DeleteSessionCookiesOnStartup) base::DoNothing()); // If the permissions policy feature is enabled, delete the client hint // preferences if (base::FeatureList::IsEnabled(features::kFeaturePolicyForClientHints)) { host_content_settings_map->ClearSettingsForOneType( ContentSettingsType::CLIENT_HINTS); } } if (!storage_policy_.get() || !storage_policy_->HasSessionOnlyOrigins()) return; cookie_manager_->DeleteSessionOnlyCookies( base::BindOnce(&SessionDataDeleterInternal::OnCookieDeletionDone, this)); // Note that from this point on |*this| is kept alive by scoped_refptr<> // references automatically taken by |Bind()|, so when the last callback // created by Bind() is released (after execution of that function), the // object will be deleted. } SessionDataDeleterInternal::~SessionDataDeleterInternal() { if (callback_) std::move(callback_).Run(); } } // namespace SessionDataDeleter::SessionDataDeleter(Profile* profile) : profile_(profile) {} SessionDataDeleter::~SessionDataDeleter() = default; void SessionDataDeleter::DeleteSessionOnlyData(bool skip_session_cookies, base::OnceClosure callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // As this function is creating KeepAlives, it should not be // called during shutdown. DCHECK(!browser_shutdown::IsTryingToQuit()); SessionStartupPref::Type startup_pref_type = StartupBrowserCreator::GetSessionStartupPref( *base::CommandLine::ForCurrentProcess(), profile_) .type; bool delete_only_by_session_only_policy = skip_session_cookies || startup_pref_type == SessionStartupPref::LAST; auto deleter = base::MakeRefCounted<SessionDataDeleterInternal>( profile_, delete_only_by_session_only_policy, std::move(callback)); deleter->Run(profile_->GetDefaultStoragePartition(), HostContentSettingsMapFactory::GetForProfile(profile_)); }
41.92
80
0.756816
zealoussnow
79f856cdd4b92251b567035ef65143e58204e868
8,330
cpp
C++
Simulation/src/manipulator/src/RobotHWInterface.cpp
Cinek28/Manipulator
de42d956edb9c5a26f61cee605023cd71bddc581
[ "MIT" ]
null
null
null
Simulation/src/manipulator/src/RobotHWInterface.cpp
Cinek28/Manipulator
de42d956edb9c5a26f61cee605023cd71bddc581
[ "MIT" ]
null
null
null
Simulation/src/manipulator/src/RobotHWInterface.cpp
Cinek28/Manipulator
de42d956edb9c5a26f61cee605023cd71bddc581
[ "MIT" ]
null
null
null
#include <sstream> #include <std_msgs/Float64.h> #include "RobotHWInterface.h" using namespace hardware_interface; using joint_limits_interface::JointLimits; using joint_limits_interface::PositionJointSoftLimitsHandle; using joint_limits_interface::PositionJointSoftLimitsInterface; using joint_limits_interface::SoftJointLimits; RobotHWInterface::RobotHWInterface(ros::NodeHandle &nh) : nodeHandle(nh) { init(); controllerManager.reset(new controller_manager::ControllerManager(this, nodeHandle)); nodeHandle.param("/manipulator/hardware_interface/rate", rate, 0.1); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::None), KDL::Frame( KDL::Vector(0, 0, 0.13)))); KDL::Frame frame = KDL::Frame(KDL::Rotation::RPY(-KDL::PI/2,0.0,0.0),KDL::Vector(0, 0.00175, 0.0705)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); frame = KDL::Frame(KDL::Rotation::RPY(0.0,0.0,1.283),KDL::Vector(0, -0.6, 0.0)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); frame = KDL::Frame(KDL::Rotation::EulerZYX(0.0,-KDL::PI/2,0.0),KDL::Vector(0.408, 0.005, 0.0)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); frame = KDL::Frame(KDL::Rotation::EulerZYX(-KDL::PI/2,0.0,3*KDL::PI/2),KDL::Vector(0.0, 0.0, -0.129)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); frame = KDL::Frame(KDL::Rotation::EulerZYX(0.0,-KDL::PI/2,0.0),KDL::Vector(0.0643, 0.0, 0.0)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); frame = KDL::Frame(KDL::Rotation::EulerZYX(0.0,KDL::PI/2,0.0),KDL::Vector(0.0, 0.0, -0.15)); kinematicChain.addSegment(KDL::Segment(KDL::Joint(KDL::Joint::RotZ), frame)); jointVelocities = KDL::JntArray(kinematicChain.getNrOfJoints()); // Sub geometry_msgs::Twist twistSub = nodeHandle.subscribe("/spacenav/twist",1,&RobotHWInterface::newVelCallback, this); // // Pub geometry_msgs/PoseStamped // poseStampedPub = nodeHandle.advertise<geometry_msgs::PoseStamped>("/robot_pose", 1); // // jointStatePub = nodeHandle.advertise<sensor_msgs::JointState>("/joint_states", 1); // Pub external controller steering commands: commandPub[0] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/shoulder_rotation_controller/command", 1); commandPub[1] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/forearm_rotation_controller/command", 1); commandPub[2] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/arm_rotation_controller/command", 1); commandPub[3] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/wrist_rotation_controller/command", 1); commandPub[4] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/wrist_pitch_controller/command", 1); commandPub[5] = nodeHandle.advertise<std_msgs::Float64>("/manipulator/gripper_rotation_controller/command", 1); std_msgs::Float64 initial_vel; initial_vel.data = 0.0; for(int i = 0; i < 6; ++i) commandPub[i].publish(initial_vel); nonRealtimeTask = nodeHandle.createTimer(ros::Duration(1.0 / rate), &RobotHWInterface::update, this); } RobotHWInterface::~RobotHWInterface() { } void RobotHWInterface::init() { // Get joint names nodeHandle.getParam("/manipulator/hardware_interface/joints", jointNames); numJoints = jointNames.size(); ROS_INFO("Number of joints: %d", numJoints); // Resize vectors jointPosition.resize(numJoints); jointVelocity.resize(numJoints); jointEffort.resize(numJoints); jointPositionCommands.resize(numJoints); jointVelocityCommands.resize(numJoints); jointEffortCommands.resize(numJoints); // Initialize Controller for (int i = 0; i < numJoints; ++i) { // Create joint state interface JointStateHandle jointStateHandle(jointNames[i], &jointPosition[i], &jointVelocity[i], &jointEffort[i]); jointStateInt.registerHandle(jointStateHandle); // Create position joint interface JointHandle jointPositionHandle(jointStateHandle, &jointPositionCommands[i]); // JointLimits limits; // SoftJointLimits softLimits; // getJointLimits(jointNames[i], nodeHandle, limits); // PositionJointSoftLimitsHandle jointLimitsHandle(jointPositionHandle, limits, softLimits); // positionJointSoftLimitsInterface.registerHandle(jointLimitsHandle); positionJointInt.registerHandle(jointPositionHandle); //Create velocity joint interface: JointHandle jointVelocityHandle(jointStateHandle, &jointVelocityCommands[i]); velocityJointInt.registerHandle(jointVelocityHandle); // Create effort joint interface JointHandle jointEffortHandle(jointStateHandle, &jointEffortCommands[i]); effortJointInt.registerHandle(jointEffortHandle); } registerInterface(&jointStateInt); registerInterface(&velocityJointInt); registerInterface(&positionJointInt); registerInterface(&effortJointInt); // registerInterface(&positionJointSoftLimitsInterface); robot.openPort(0, BAUDRATE); } void RobotHWInterface::update(const ros::TimerEvent &e) { elapsedTime = ros::Duration(e.current_real - e.last_real); read(); controllerManager->update(ros::Time::now(), elapsedTime); write(elapsedTime); } void RobotHWInterface::read() { ManipulatorMsg msg; if(isRobotConnected() && robot.readData(&msg)) { for (int i = 0; i < numJoints; i++) { jointVelocity[i] = (double)(msg.params[i] | (msg.params[i+1] << 8)); } } } void RobotHWInterface::write(ros::Duration elapsed_time) { // positionJointSoftLimitsInterface.enforceLimits(elapsed_time); if(!isRobotConnected() || mode == IDLE) { for(int i = 0; i < numJoints; ++i) { ROS_INFO("Setting command to %s, %d: %f",jointNames[i].c_str(), i, jointVelocities(i)); velocityJointInt.getHandle(jointNames[i]).setCommand(jointVelocities(i)); } } else { ManipulatorMsg msg; uint16_t velocity = 0; msg.type = mode; msg.length = 2*numJoints; msg.checksum = msg.type + msg.length; for (int i = 0; i < numJoints; i++) { // TODO: Write joints velocities/efforts msg.params[i] = (uint8_t)jointVelocities(i); msg.params[i+1] = (uint8_t)((uint16_t)jointVelocities(i) >> 8); msg.checksum += msg.params[i] + msg.params[i+1]; } msg.checksum = ~msg.checksum; robot.sendData(&msg); } } KDL::JntArray RobotHWInterface::solveIndirectKinematics(const geometry_msgs::Twist &msg) { KDL::Twist temp_twist; temp_twist.vel.x(msg.linear.x); temp_twist.vel.y(msg.linear.y); temp_twist.vel.z(msg.linear.z); temp_twist.rot.x(msg.angular.x); temp_twist.rot.y(msg.angular.y); temp_twist.rot.z(msg.angular.z); //Create joint array KDL::JntArray joint_positions = KDL::JntArray(kinematicChain.getNrOfJoints()); for(int i = 0; i < numJoints; ++i) { joint_positions(i)=jointPosition[i]; } // Create the frame that will contain the results KDL::Frame cartpos; KDL::ChainFkSolverPos_recursive fksolver(kinematicChain); KDL::ChainIkSolverVel_pinv iksolver(kinematicChain); //Inverse velocity solver KDL::JntArray joint_velocities = KDL::JntArray(kinematicChain.getNrOfJoints()); iksolver.CartToJnt(joint_positions, temp_twist, joint_velocities); return joint_velocities; } void RobotHWInterface::newVelCallback(const geometry_msgs::Twist &msg) { if(mode == TOOL) { // Calculate indirect kinematics jointVelocities = solveIndirectKinematics(msg); } else { jointVelocities(0) = msg.linear.x; jointVelocities(1) = msg.linear.y; jointVelocities(2) = msg.linear.z; jointVelocities(3) = msg.angular.x; jointVelocities(4) = msg.angular.y; jointVelocities(5) = msg.angular.z; } for (int i = 0; i < 6; ++i) { if(fabs(jointVelocities(i)) < 0.5) jointVelocities(i) = 0.0; std_msgs::Float64 velocity; velocity.data = jointVelocities(i); // commandPub[i].publish(velocity); } }
37.522523
116
0.685714
Cinek28
79f863d8bf49bb62e693ba1c845a5d449f0c6399
2,219
cpp
C++
aws-cpp-sdk-opsworks/source/model/CloudWatchLogsInitialPosition.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-opsworks/source/model/CloudWatchLogsInitialPosition.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-opsworks/source/model/CloudWatchLogsInitialPosition.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/opsworks/model/CloudWatchLogsInitialPosition.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace OpsWorks { namespace Model { namespace CloudWatchLogsInitialPositionMapper { static const int start_of_file_HASH = HashingUtils::HashString("start_of_file"); static const int end_of_file_HASH = HashingUtils::HashString("end_of_file"); CloudWatchLogsInitialPosition GetCloudWatchLogsInitialPositionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == start_of_file_HASH) { return CloudWatchLogsInitialPosition::start_of_file; } else if (hashCode == end_of_file_HASH) { return CloudWatchLogsInitialPosition::end_of_file; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<CloudWatchLogsInitialPosition>(hashCode); } return CloudWatchLogsInitialPosition::NOT_SET; } Aws::String GetNameForCloudWatchLogsInitialPosition(CloudWatchLogsInitialPosition enumValue) { switch(enumValue) { case CloudWatchLogsInitialPosition::start_of_file: return "start_of_file"; case CloudWatchLogsInitialPosition::end_of_file: return "end_of_file"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace CloudWatchLogsInitialPositionMapper } // namespace Model } // namespace OpsWorks } // namespace Aws
31.253521
102
0.657503
Neusoft-Technology-Solutions
79f88c4219d8463f65209cc3fbbaf2d186d25363
20,457
hxx
C++
main/svx/inc/dgdefs_.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/inc/dgdefs_.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/inc/dgdefs_.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #define optlingu_0a SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define insctrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define insctrl_03 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define insctrl_06 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define zoomctrl_03 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define zoomctrl_05 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define pszctrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define selctrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define selctrl_02 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define selctrl_05 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define modctrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_02 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_08 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_09 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_0a SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_11 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_12 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_13 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_35 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_37 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_38 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_39 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_3a SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_3c SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_3d SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_3e SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_3f SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_40 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_41 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_42 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_43 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_44 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_45 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_46 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_47 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_48 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_49 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_4a SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_4e SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_4f SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_53 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_54 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_58 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_59 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_5c SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_5f SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_63 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_64 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_65 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define tbcontrl_66 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_03 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_04 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_05 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_06 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_08 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_09 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_0a SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define linectrl_0e SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define fillctrl_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define fillctrl_03 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define fillctrl_05 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define fillctrl_06 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define fillctrl_08 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_01 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_08 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_10 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_12 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_19 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define itemwin_1f SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define layctrl_09 SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define layctrl_0d SEG_SEGCLASS(STARTING_SEG000,STARTING_CODE) #define pszctrl_03 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define tcovmain_01 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define pszctrl_04 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define pszctrl_05 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define tcovidle_01 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_02 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_17 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_16 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_01 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_18 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_15 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define modctrl_02 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define modctrl_04 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define adritem_07 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define adritem_28 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optgrid_12 SEG_SEGCLASS(STARTWORK_SEG000,STARTWORK_CODE) #define optpath_01 SEG_SEGCLASS(STARTSLICE_SEG000,STARTSLICE_CODE) #define optpath_02 SEG_SEGCLASS(STARTSLICE_SEG000,STARTSLICE_CODE) #define optpath_04 SEG_SEGCLASS(STARTSLICE_SEG000,STARTSLICE_CODE) #define optitems_01 SEG_SEGCLASS(STARTSLICE_SEG001,STARTSLICE_CODE) #define optitems_02 SEG_SEGCLASS(STARTSLICE_SEG001,STARTSLICE_CODE) #define optitems_04 SEG_SEGCLASS(STARTSLICE_SEG001,STARTSLICE_CODE) #define optgenrl_01 SEG_SEGCLASS(STARTSLICE_SEG001,STARTSLICE_CODE) #define optgenrl_02 SEG_SEGCLASS(STARTSLICE_SEG001,STARTSLICE_CODE) #define optgenrl_04 SEG_SEGCLASS(STARTSLICE_SEG002,STARTSLICE_CODE) #define optgenrl_06 SEG_SEGCLASS(STARTSLICE_SEG002,STARTSLICE_CODE) #define optgenrl_08 SEG_SEGCLASS(STARTSLICE_SEG002,STARTSLICE_CODE) #define adritem_25 SEG_SEGCLASS(STARTSLICE_SEG002,STARTSLICE_CODE) #define optgenrl_0b SEG_SEGCLASS(STARTSLICE_SEG003,STARTSLICE_CODE) #define adritem_04 SEG_SEGCLASS(STARTSLICE_SEG003,STARTSLICE_CODE) #define opttypes_01 SEG_SEGCLASS(STARTSLICE_SEG003,STARTSLICE_CODE) #define optlingu_01 SEG_SEGCLASS(STARTSLICE_SEG003,STARTSLICE_CODE) #define optlingu_03 SEG_SEGCLASS(STARTSLICE_SEG003,STARTSLICE_CODE) #define optlingu_05 SEG_SEGCLASS(STARTSLICE_SEG004,STARTSLICE_CODE) #define optlingu_09 SEG_SEGCLASS(STARTSLICE_SEG004,STARTSLICE_CODE) #define optgrid_03 SEG_SEGCLASS(STARTSLICE_SEG005,STARTSLICE_CODE) #define optgrid_07 SEG_SEGCLASS(STARTSLICE_SEG005,STARTSLICE_CODE) #define optgrid_08 SEG_SEGCLASS(STARTSLICE_SEG005,STARTSLICE_CODE) #define optgrid_0a SEG_SEGCLASS(STARTSLICE_SEG006,STARTSLICE_CODE) #define linectrl_0c SEG_SEGCLASS(STARTSLICE_SEG006,STARTSLICE_CODE) #define itemwin_0a SEG_SEGCLASS(STARTSLICE_SEG006,STARTSLICE_CODE) #define linectrl_0d SEG_SEGCLASS(STARTSLICE_SEG006,STARTSLICE_CODE) #define fillctrl_04 SEG_SEGCLASS(STARTSLICE_SEG007,STARTSLICE_CODE) #define optpath_07 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optitems_06 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optitems_07 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optitems_0b SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optgenrl_03 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optgrid_09 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define tbcontrl_36 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define fillctrl_07 SEG_SEGCLASS(CALLOPT_SEG000,CALLOPT_CODE) #define optpath_03 SEG_SEGCLASS(SLICES_SEG000,SLICES_CODE) #define optlingu_04 SEG_SEGCLASS(SLICES_SEG000,SLICES_CODE) #define pszctrl_02 SEG_SEGCLASS(SLICES_SEG001,SLICES_CODE) #define tbcontrl_3b SEG_SEGCLASS(SLICES_SEG001,SLICES_CODE) #define optgenrl_07 SEG_SEGCLASS(SLICES_SEG001,SLICES_CODE) #define optgenrl_0a SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define adritem_06 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define adritem_29 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define optgrid_11 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define optgrid_13 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define insctrl_02 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define tbcontrl_4b SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define tbcontrl_50 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define tbcontrl_55 SEG_SEGCLASS(SLICES_SEG002,SLICES_CODE) #define linectrl_02 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define linectrl_07 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define linectrl_0b SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define fillctrl_02 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define itemwin_02 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define itemwin_09 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define itemwin_11 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define itemwin_1a SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define itemwin_20 SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define layctrl_0a SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define layctrl_0e SEG_SEGCLASS(SLICES_SEG003,SLICES_CODE) #define fntctl_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntctl_07 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntszctl_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntszctl_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntszctl_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntszctl_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define fntszctl_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optpath_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optpath_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_07 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_08 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_09 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_0a SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optdict_0b SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_08 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_09 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_0a SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_0c SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_0d SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optitems_0e SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optspell_07 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgenrl_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgenrl_09 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define adritem_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define adritem_26 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define adritem_27 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define adritem_2a SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define opttypes_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optlingu_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optlingu_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optlingu_07 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optlingu_08 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_0b SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_0c SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_0d SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_0e SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_0f SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_10 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define optgrid_14 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define insctrl_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define insctrl_05 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define zoomctrl_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define zoomctrl_02 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define zoomctrl_06 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define zoomctrl_07 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define selctrl_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define selctrl_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define modctrl_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define tbcontrl_01 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define tbcontrl_03 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define tbcontrl_04 SEG_SEGCLASS(UNUSED_SEG000,UNUSED_CODE) #define tbcontrl_05 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_06 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_07 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_0b SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_0c SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_0d SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_0e SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_0f SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_10 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_14 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_15 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_16 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_17 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_18 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_19 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1a SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1b SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1c SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1d SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1e SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_1f SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_20 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_21 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_22 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_23 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_24 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_25 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_26 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_27 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_28 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_29 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2a SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2b SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2c SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2d SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2e SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_2f SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_30 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_31 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_32 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_33 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_34 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_4c SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_4d SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_51 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_52 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_56 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_57 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_5a SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_5b SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_5d SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_5e SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_60 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_61 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define tbcontrl_62 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define fillctrl_09 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_03 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_04 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_05 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_06 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_07 SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_0b SEG_SEGCLASS(UNUSED_SEG001,UNUSED_CODE) #define itemwin_0c SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_0d SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_0e SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_0f SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_13 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_14 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_15 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_16 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_17 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_18 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_1b SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_1c SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_1d SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_1e SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_21 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_22 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_23 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_24 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_25 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define itemwin_26 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_01 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_02 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_03 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_04 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_05 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_06 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_07 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_08 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_0b SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_0c SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_0f SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE) #define layctrl_10 SEG_SEGCLASS(UNUSED_SEG002,UNUSED_CODE)
60.523669
67
0.869042
Grosskopf
79fff03ba80e9f795aa6cc52ecc9a519bc916b80
1,847
cpp
C++
scorpio_arm_ros_control/src/hardware.cpp
applejenny66/goldpaint
cbb368d2d21cc1e26177314eb1e6fceb7c6e6c8d
[ "MIT" ]
null
null
null
scorpio_arm_ros_control/src/hardware.cpp
applejenny66/goldpaint
cbb368d2d21cc1e26177314eb1e6fceb7c6e6c8d
[ "MIT" ]
1
2020-08-10T05:33:02.000Z
2020-08-10T05:33:02.000Z
scorpio_arm_ros_control/src/hardware.cpp
applejenny66/goldpaint
cbb368d2d21cc1e26177314eb1e6fceb7c6e6c8d
[ "MIT" ]
1
2021-05-20T09:08:05.000Z
2021-05-20T09:08:05.000Z
#include "scorpio_arm_ros_control/hardware_transmission_interface.h" void HwTmIntf::hw_data_init_() { hw_data_.jnt_curr_pos_.clear(); hw_data_.jnt_curr_vel_.clear(); hw_data_.jnt_curr_eff_.clear(); hw_data_.jnt_cmd_pos_.clear(); hw_data_.jnt_cmd_vel_.clear(); hw_data_.jnt_cmd_eff_.clear(); hw_data_.act_curr_pos_.clear(); hw_data_.act_curr_vel_.clear(); hw_data_.act_curr_eff_.clear(); hw_data_.act_cmd_pos_.clear(); hw_data_.act_cmd_vel_.clear(); hw_data_.act_cmd_eff_.clear(); hw_data_.jnt_curr_pos_.resize(n_dof_); hw_data_.jnt_curr_vel_.resize(n_dof_); hw_data_.jnt_curr_eff_.resize(n_dof_); hw_data_.jnt_cmd_pos_.resize(n_dof_); hw_data_.jnt_cmd_vel_.resize(n_dof_); hw_data_.jnt_cmd_eff_.resize(n_dof_); hw_data_.act_curr_pos_.resize(n_dof_); hw_data_.act_curr_vel_.resize(n_dof_); hw_data_.act_curr_eff_.resize(n_dof_); hw_data_.act_cmd_pos_.resize(n_dof_); hw_data_.act_cmd_vel_.resize(n_dof_); hw_data_.act_cmd_eff_.resize(n_dof_); } void HwTmIntf::hw_register_() { for(size_t i = 0; i < n_dof_; i++) { hw_data_.jnt_state_interface_.registerHandle( hardware_interface::JointStateHandle( jnt_names_[i], &hw_data_.jnt_curr_pos_[i], &hw_data_.jnt_curr_vel_[i], &hw_data_.jnt_curr_eff_[i])); hw_data_.jnt_pos_interface_.registerHandle( hardware_interface::JointHandle( hw_data_.jnt_state_interface_.getHandle(jnt_names_[i]), &hw_data_.jnt_cmd_pos_[i])); hw_data_.jnt_vel_interface_.registerHandle( hardware_interface::JointHandle( hw_data_.jnt_state_interface_.getHandle(jnt_names_[i]), &hw_data_.jnt_cmd_vel_[i])); } registerInterface(&hw_data_.jnt_state_interface_); registerInterface(&hw_data_.jnt_pos_interface_); registerInterface(&hw_data_.jnt_vel_interface_); }
27.984848
68
0.750406
applejenny66
0302acb3cb76ec9f92d2dce3bd8efdd63ce082c2
2,065
cpp
C++
wpilibc/src/main/native/cpp/Compressor.cpp
lhvy/allwpilib
cc31079a1123498faf1acfb7f12b5976c6a686af
[ "BSD-3-Clause" ]
39
2021-06-18T03:22:30.000Z
2022-03-21T15:23:43.000Z
wpilibc/src/main/native/cpp/Compressor.cpp
lhvy/allwpilib
cc31079a1123498faf1acfb7f12b5976c6a686af
[ "BSD-3-Clause" ]
10
2021-06-18T03:22:19.000Z
2022-03-18T22:14:15.000Z
wpilibc/src/main/native/cpp/Compressor.cpp
lhvy/allwpilib
cc31079a1123498faf1acfb7f12b5976c6a686af
[ "BSD-3-Clause" ]
4
2021-08-19T19:20:04.000Z
2022-03-08T07:33:18.000Z
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "frc/Compressor.h" #include <hal/FRCUsageReporting.h> #include <hal/Ports.h> #include <wpi/sendable/SendableBuilder.h> #include <wpi/sendable/SendableRegistry.h> #include "frc/Errors.h" using namespace frc; Compressor::Compressor(int module, PneumaticsModuleType moduleType) : m_module{PneumaticsBase::GetForType(module, moduleType)} { if (!m_module->ReserveCompressor()) { throw FRC_MakeError(err::ResourceAlreadyAllocated, "{}", module); } SetClosedLoopControl(true); HAL_Report(HALUsageReporting::kResourceType_Compressor, module + 1); wpi::SendableRegistry::AddLW(this, "Compressor", module); } Compressor::Compressor(PneumaticsModuleType moduleType) : Compressor{PneumaticsBase::GetDefaultForType(moduleType), moduleType} {} Compressor::~Compressor() { m_module->UnreserveCompressor(); } void Compressor::Start() { SetClosedLoopControl(true); } void Compressor::Stop() { SetClosedLoopControl(false); } bool Compressor::Enabled() const { return m_module->GetCompressor(); } bool Compressor::GetPressureSwitchValue() const { return m_module->GetPressureSwitch(); } double Compressor::GetCompressorCurrent() const { return m_module->GetCompressorCurrent(); } void Compressor::SetClosedLoopControl(bool on) { m_module->SetClosedLoopControl(on); } bool Compressor::GetClosedLoopControl() const { return m_module->GetClosedLoopControl(); } void Compressor::InitSendable(wpi::SendableBuilder& builder) { builder.SetSmartDashboardType("Compressor"); builder.AddBooleanProperty( "Closed Loop Control", [=]() { return GetClosedLoopControl(); }, [=](bool value) { SetClosedLoopControl(value); }); builder.AddBooleanProperty( "Enabled", [=] { return Enabled(); }, nullptr); builder.AddBooleanProperty( "Pressure switch", [=]() { return GetPressureSwitchValue(); }, nullptr); }
28.287671
78
0.743341
lhvy
03033a70d7d6c863f038d38a0f8745b2ede7df17
4,817
hpp
C++
query_optimizer/logical/TableReference.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
query_optimizer/logical/TableReference.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
query_optimizer/logical/TableReference.hpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ #ifndef QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_LOGICAL_TABLE_REFERENCE_HPP_ #define QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_LOGICAL_TABLE_REFERENCE_HPP_ #include <memory> #include <string> #include <vector> #include "query_optimizer/OptimizerTree.hpp" #include "query_optimizer/expressions/AttributeReference.hpp" #include "query_optimizer/logical/Logical.hpp" #include "query_optimizer/logical/LogicalType.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { class CatalogRelation; namespace optimizer { class OptimizerContext; namespace logical { /** \addtogroup OptimizerLogical * @{ */ class TableReference; typedef std::shared_ptr<const TableReference> TableReferencePtr; /** * @brief Leaf logical operator that represents a reference to * a catalog relation. */ class TableReference : public Logical { public: LogicalType getLogicalType() const override { return LogicalType::kTableReference; } std::string getName() const override { return "TableReference"; } /** * @return The catalog relation which the operator scans. */ const CatalogRelation* catalog_relation() const { return catalog_relation_; } /** * @return The relation alias. */ const std::string& relation_alias() const { return relation_alias_; } /** * @return The references to the attributes in the relation. */ const std::vector<expressions::AttributeReferencePtr>& attribute_list() const { return attribute_list_; } LogicalPtr copyWithNewChildren( const std::vector<LogicalPtr> &new_children) const override; std::vector<expressions::AttributeReferencePtr> getOutputAttributes() const override { return attribute_list_; } std::vector<expressions::AttributeReferencePtr> getReferencedAttributes() const override { return getOutputAttributes(); } /** * @brief Generates a AttributeRerference for each CatalogAttribute in the \p * catalog_relation and creates a TableReference on it. * * @param catalog_relation The catalog relation to be scanned. * @param relation_alias The relation alias. This is stored here for the printing purpose only. * @param optimizer_context The OptimizerContext for the query. * @return An immutable TableReference. */ static TableReferencePtr Create(const CatalogRelation *catalog_relation, const std::string &relation_alias, OptimizerContext *optimizer_context) { DCHECK(!relation_alias.empty()); return TableReferencePtr( new TableReference(catalog_relation, relation_alias, optimizer_context)); } protected: void getFieldStringItems( std::vector<std::string> *inline_field_names, std::vector<std::string> *inline_field_values, std::vector<std::string> *non_container_child_field_names, std::vector<OptimizerTreeBaseNodePtr> *non_container_child_fields, std::vector<std::string> *container_child_field_names, std::vector<std::vector<OptimizerTreeBaseNodePtr>> *container_child_fields) const override; private: TableReference(const CatalogRelation *catalog_relation, const std::string &relation_alias, OptimizerContext *optimizer_context); // Constructor where the attribute list is explicitly given. TableReference( const CatalogRelation *catalog_relation, const std::string &relation_alias, const std::vector<expressions::AttributeReferencePtr> &attribute_list) : catalog_relation_(catalog_relation), relation_alias_(relation_alias), attribute_list_(attribute_list) {} const CatalogRelation *catalog_relation_; const std::string relation_alias_; std::vector<expressions::AttributeReferencePtr> attribute_list_; DISALLOW_COPY_AND_ASSIGN(TableReference); }; /** @} */ } // namespace logical } // namespace optimizer } // namespace quickstep #endif /* QUICKSTEP_QUERY_OPTIMIZER_EXPRESSIONS_LOGICAL_TABLE_REFERENCE_HPP_ */
33.451389
97
0.744032
Hacker0912
03059a397b411fb7e5880a29eb03be4cbaefedf9
2,601
hpp
C++
libs/pika/async_cuda/include/pika/async_cuda/cuda_event.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
13
2022-01-17T12:01:48.000Z
2022-03-16T10:03:14.000Z
libs/pika/async_cuda/include/pika/async_cuda/cuda_event.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
163
2022-01-17T17:36:45.000Z
2022-03-31T17:42:57.000Z
libs/pika/async_cuda/include/pika/async_cuda/cuda_event.hpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
4
2022-01-19T08:44:22.000Z
2022-01-31T23:16:21.000Z
// Copyright (c) 2020 John Biddiscombe // Copyright (c) 2020 Teodor Nikolov // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/async_cuda/cuda_exception.hpp> #include <pika/async_cuda/custom_gpu_api.hpp> #include <boost/lockfree/stack.hpp> namespace pika::cuda::experimental::detail { // a pool of cudaEvent_t objects. // Since allocation of a cuda event passes into the cuda runtime // it might be an expensive operation, so we pre-allocate a pool // of them at startup. struct cuda_event_pool { static constexpr int initial_events_in_pool = 128; static cuda_event_pool& get_event_pool() { static cuda_event_pool event_pool_; return event_pool_; } // create a bunch of events on initialization cuda_event_pool() : free_list_(initial_events_in_pool) { for (int i = 0; i < initial_events_in_pool; ++i) { add_event_to_pool(); } } // on destruction, all objects in stack will be freed ~cuda_event_pool() { cudaEvent_t event; bool ok = true; while (ok) { ok = free_list_.pop(event); if (ok) check_cuda_error(cudaEventDestroy(event)); } } inline bool pop(cudaEvent_t& event) { // pop an event off the pool, if that fails, create a new one while (!free_list_.pop(event)) { add_event_to_pool(); } return true; } inline bool push(cudaEvent_t event) { return free_list_.push(event); } private: void add_event_to_pool() { cudaEvent_t event; // Create an cuda_event to query a CUDA/CUBLAS kernel for completion. // Timing is disabled for performance. [1] // // [1]: CUDA Runtime API, section 5.5 cuda_event Management check_cuda_error( cudaEventCreateWithFlags(&event, cudaEventDisableTiming)); free_list_.push(event); } // pool is dynamically sized and can grow if needed boost::lockfree::stack<cudaEvent_t, boost::lockfree::fixed_sized<false>> free_list_; }; } // namespace pika::cuda::experimental::detail
29.896552
81
0.576701
pika-org
0306b8266d2e2748f1549e9e751e5f9551a5fa87
1,091
hpp
C++
AudioKit/Core/Devoloop/FFTReal/FFTRealSelect.hpp
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
206
2020-10-28T12:47:49.000Z
2022-03-26T14:09:30.000Z
AudioKit/Core/Devoloop/FFTReal/FFTRealSelect.hpp
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
7
2020-10-29T10:29:23.000Z
2021-08-07T00:22:03.000Z
AudioKit/Core/Devoloop/FFTReal/FFTRealSelect.hpp
ethi1989/AudioKit
97acc8da6dfb75408b2276998073de7a4511d480
[ "MIT" ]
30
2020-10-28T16:11:40.000Z
2021-12-28T01:15:23.000Z
/***************************************************************************** FFTRealSelect.hpp By Laurent de Soras --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined(ffft_FFTRealSelect_CURRENT_CODEHEADER) #error Recursive inclusion of FFTRealSelect code header. #endif #define ffft_FFTRealSelect_CURRENT_CODEHEADER #if !defined(ffft_FFTRealSelect_CODEHEADER_INCLUDED) #define ffft_FFTRealSelect_CODEHEADER_INCLUDED namespace ffft { template <int P> float *FFTRealSelect<P>::sel_bin(float *e_ptr, float *o_ptr) { return (o_ptr); } template <> inline float *FFTRealSelect<0>::sel_bin(float *e_ptr, float *o_ptr) { return (e_ptr); } } #endif #undef ffft_FFTRealSelect_CURRENT_CODEHEADER
24.795455
79
0.662695
ethi1989
0307638490f51f2f3ee12d67be17b4211ab1146f
6,917
cpp
C++
uwsim_resources/uwsim_osgworks/src/osgwTools/CameraConfigObject.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
1
2020-11-30T09:55:33.000Z
2020-11-30T09:55:33.000Z
uwsim_resources/uwsim_osgworks/src/osgwTools/CameraConfigObject.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
null
null
null
uwsim_resources/uwsim_osgworks/src/osgwTools/CameraConfigObject.cpp
epsilonorion/usv_lsa_sim_copy
d189f172dc1d265b7688c7dc8375a65ac4a9c048
[ "Apache-2.0" ]
2
2020-11-21T19:50:54.000Z
2020-12-27T09:35:29.000Z
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * osgWorks is (C) Copyright 2009-2012 by Kenneth Mark Bryden * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <osgwTools/CameraConfigObject.h> #include <osgwTools/Version.h> #include <osgDB/ReadFile> #include <osg/Object> #include <osgViewer/Viewer> #include <osg/Matrixd> #include <vector> #include <string> #include <osg/io_utils> namespace osgwTools { CameraConfigInfo::CameraConfigInfo() : _version( 1 ) { } CameraConfigInfo::CameraConfigInfo( const osgwTools::CameraConfigInfo& rhs, const osg::CopyOp& ) : _viewOffset( rhs._viewOffset ), _projectionOffset( rhs._projectionOffset ), _version( rhs._version ) { } CameraConfigInfo::~CameraConfigInfo() { } CameraConfigObject::CameraConfigObject() : _version( 1 ) { } CameraConfigObject::CameraConfigObject( const osgwTools::CameraConfigObject& rhs, const osg::CopyOp& copyop ) : _version( rhs._version ), _slaveConfigInfo( rhs._slaveConfigInfo ) { } CameraConfigObject::~CameraConfigObject() { } void CameraConfigObject::take( const osgViewer::Viewer& viewer ) { if( viewer.getNumSlaves() == 0 ) return; if( _slaveConfigInfo.size() != viewer.getNumSlaves() ) _slaveConfigInfo.resize( viewer.getNumSlaves() ); unsigned int idx; for( idx=0; idx<viewer.getNumSlaves(); idx++ ) { _slaveConfigInfo[ idx ] = new osgwTools::CameraConfigInfo; osgwTools::CameraConfigInfo* cci( _slaveConfigInfo[ idx ].get() ); const osg::View::Slave& slave = viewer.getSlave( idx ); cci->_viewOffset = slave._viewOffset; cci->_projectionOffset = slave._projectionOffset; } } void CameraConfigObject::store( osgViewer::Viewer& viewer ) { osg::Camera* masterCamera = viewer.getCamera(); // // What follows is taken from View::setUpViewAcrossAllScreens() // and modified as needed to work with what we're doing. // osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"View::setUpViewAcrossAllScreens() : Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return; } osg::DisplaySettings* ds = masterCamera->getDisplaySettings() != NULL ? masterCamera->getDisplaySettings() : #if( OSGWORKS_OSG_VERSION > 20907 ) // 2.9.7 2/22/2010 // r11399, 4/30/2010 Changed DisplaySetting::instance() to return a ref_ptr<>& rathern than a raw C pointer to enable apps to delete the singleton or assign their own. // 2.9.8 6/18/2010 osg::DisplaySettings::instance().get(); #else osg::DisplaySettings::instance(); #endif double fovy, aspectRatio, zNear, zFar; masterCamera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar); osg::GraphicsContext::ScreenIdentifier si; si.readDISPLAY(); // displayNum has not been set so reset it to 0. if (si.displayNum<0) si.displayNum = 0; unsigned int numScreens = wsi->getNumScreens(si); if( numScreens != _slaveConfigInfo.size() ) { osg::notify( osg::WARN ) << "Number of screens not equal to number of config slaves." << std::endl; return; } for(unsigned int i=0; i<numScreens; ++i) { si.screenNum = i; unsigned int width, height; wsi->getScreenResolution(si, width, height); #if ( OSGWORKS_OSG_VERSION >= 20906 ) osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits(ds); #else osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; #endif traits->hostName = si.hostName; traits->displayNum = si.displayNum; traits->screenNum = si.screenNum; traits->screenNum = i; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->windowDecoration = false; traits->doubleBuffer = true; traits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setGraphicsContext(gc.get()); osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(gc.get()); if (gw) { osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<gw<<std::endl; gw->getEventQueue()->getCurrentEventState()->setWindowRectangle(traits->x, traits->y, traits->width, traits->height ); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } camera->setViewport(new osg::Viewport(0, 0, traits->width, traits->height)); GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer(buffer); camera->setReadBuffer(buffer); const osgwTools::CameraConfigInfo* cci = _slaveConfigInfo[ i ].get(); viewer.addSlave( camera.get(), cci->_projectionOffset, cci->_viewOffset ); } viewer.assignSceneDataToCameras(); } bool configureViewer( osgViewer::Viewer& viewer, const std::string& configFile ) { std::string fileName; if( !configFile.empty() ) fileName = configFile; else { const char* buffer( getenv( "OSGW_VIEWER_CONFIG" ) ); if( buffer != NULL ) fileName = std::string( buffer ); } if( fileName.empty() ) { osg::notify( osg::INFO ) << "configureViewer: No Viewer config file." << std::endl; return( false ); } osg::ref_ptr< osgwTools::CameraConfigObject > cco = dynamic_cast< osgwTools::CameraConfigObject* >( osgDB::readObjectFile( fileName ) ); if( !cco.valid() ) { osg::notify( osg::WARN ) << "configureViewer: Can't load config object from \"" << fileName << "\"." << std::endl; return( false ); } cco->store( viewer ); return( true ); } // namespace osgwTools }
30.879464
179
0.649414
epsilonorion
030c764d3f6d932ee9ce1aa1681ac08679c89877
3,821
cpp
C++
tests/src/step_refiner_constant_factor.test.cpp
Rookfighter/optimization-cpp
482122c9bef39f30e57af69c93d99853005f14f7
[ "MIT" ]
null
null
null
tests/src/step_refiner_constant_factor.test.cpp
Rookfighter/optimization-cpp
482122c9bef39f30e57af69c93d99853005f14f7
[ "MIT" ]
null
null
null
tests/src/step_refiner_constant_factor.test.cpp
Rookfighter/optimization-cpp
482122c9bef39f30e57af69c93d99853005f14f7
[ "MIT" ]
null
null
null
/// step_refiner_constant_factor.test.cpp /// /// Author: Fabian Meyer /// Created On: 22 Jan 2021 /// License: MIT #include <lsqcpp/lsqcpp.hpp> #include "eigen_require.hpp" #include "parabolic_error.hpp" using namespace lsqcpp; TEMPLATE_TEST_CASE("constant factor step refiner", "[step refiner]", float, double) { using Scalar = TestType; using Parameter = ConstantStepFactorParameter<Scalar>; SECTION("parameter") { SECTION("construction") { SECTION("default") { Parameter param; REQUIRE(param.factor() == static_cast<Scalar>(1)); } SECTION("parametrized A") { Parameter param(14); REQUIRE(param.factor() == static_cast<Scalar>(14)); } } SECTION("setter") { SECTION("factor") { Parameter param; REQUIRE(param.factor() == static_cast<Scalar>(1)); param.setFactor(7); REQUIRE(param.factor() == static_cast<Scalar>(7)); } } } SECTION("refinement") { SECTION("dynamic size problem") { constexpr int Inputs = Eigen::Dynamic; constexpr int Outputs = Eigen::Dynamic; using InputVector = Eigen::Matrix<Scalar, Inputs, 1>; using OutputVector = Eigen::Matrix<Scalar, Outputs, 1>; using JacobiMatrix = Eigen::Matrix<Scalar, Outputs, Inputs>; using GradientVector = Eigen::Matrix<Scalar, Inputs, 1>; using StepVector = Eigen::Matrix<Scalar, Inputs, 1>; using Refiner = NewtonStepRefiner<Scalar, Inputs, Outputs, ConstantStepFactor>; constexpr auto eps = static_cast<Scalar>(1e-6); InputVector xval; OutputVector fval; JacobiMatrix jacobian; GradientVector gradient; StepVector step(4); ParabolicError objective; step << static_cast<Scalar>(1), static_cast<Scalar>(2.5), static_cast<Scalar>(-5.25), static_cast<Scalar>(21.4); Parameter param(static_cast<Scalar>(2.5)); Refiner refiner(param); StepVector expected = step * static_cast<Scalar>(2.5); refiner(xval, fval, jacobian, gradient, objective, step); REQUIRE_MATRIX_APPROX(expected, step, eps); } SECTION("fixed size problem") { constexpr int Inputs = 4; constexpr int Outputs = 2; using InputVector = Eigen::Matrix<Scalar, Inputs, 1>; using OutputVector = Eigen::Matrix<Scalar, Outputs, 1>; using JacobiMatrix = Eigen::Matrix<Scalar, Outputs, Inputs>; using GradientVector = Eigen::Matrix<Scalar, Inputs, 1>; using StepVector = Eigen::Matrix<Scalar, Inputs, 1>; using Refiner = NewtonStepRefiner<Scalar, Inputs, Outputs, ConstantStepFactor>; constexpr auto eps = static_cast<Scalar>(1e-6); InputVector xval; OutputVector fval; JacobiMatrix jacobian; GradientVector gradient; StepVector step(4); ParabolicError objective; step << static_cast<Scalar>(1), static_cast<Scalar>(2.5), static_cast<Scalar>(-5.25), static_cast<Scalar>(21.4); Parameter param(static_cast<Scalar>(2.5)); Refiner refiner(param); StepVector expected = step * static_cast<Scalar>(2.5); refiner(xval, fval, jacobian, gradient, objective, step); REQUIRE_MATRIX_APPROX(expected, step, eps); } } }
33.226087
91
0.55509
Rookfighter
030ce6dbf389eb5f37eb6b9f4ba2d0213d5fdf49
478
hpp
C++
src/la/cublas.hpp
ltalirz/nlcglib
b95467d23681477519e203e84313ad872d28bd62
[ "BSD-3-Clause" ]
6
2021-03-09T14:45:26.000Z
2022-03-08T14:41:58.000Z
src/la/cublas.hpp
ltalirz/nlcglib
b95467d23681477519e203e84313ad872d28bd62
[ "BSD-3-Clause" ]
10
2020-09-09T19:51:32.000Z
2022-03-23T13:05:57.000Z
src/la/cublas.hpp
ltalirz/nlcglib
b95467d23681477519e203e84313ad872d28bd62
[ "BSD-3-Clause" ]
1
2022-03-08T11:28:49.000Z
2022-03-08T11:28:49.000Z
#pragma once #include <cublas_v2.h> #include <iostream> namespace cublas { struct cublasHandle { private: static cublasHandle_t& _get() { static cublasHandle_t handle{nullptr}; return handle; } public: static cublasHandle_t& get() { cublasHandle_t& handle = _get(); if(!handle) { cublasCreate(&handle); } return handle; } static void destroy() { if(!_get()) cublasDestroy(_get()); _get() = nullptr; } }; } // cublas
14.058824
42
0.625523
ltalirz
030ddb6598e2b08de39b4ac40f0bc07a25c0ecb7
1,062
cpp
C++
Labs/Lab_4/main.cpp
benjaminmao123/UCR-CS012
c2292162a79bb711156f93e9c08af2a61079838d
[ "Apache-2.0" ]
null
null
null
Labs/Lab_4/main.cpp
benjaminmao123/UCR-CS012
c2292162a79bb711156f93e9c08af2a61079838d
[ "Apache-2.0" ]
null
null
null
Labs/Lab_4/main.cpp
benjaminmao123/UCR-CS012
c2292162a79bb711156f93e9c08af2a61079838d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "Distance.h" using namespace std; int main() { Distance d1; cout << "d1: " << d1 << endl; Distance d2 = Distance(2, 5.9); Distance d3 = Distance(3.75); cout << "d2: " << d2 << endl; cout << "d3: " << d3 << endl; //test init helper function Distance d4 = Distance(5, 19.34); Distance d5 = Distance(100); cout << "d4: " << d4 << endl; cout << "d5: " << d5 << endl; //test add (<12 inches) cout << "d4 + d5: " << (d4 + d5) << endl; //test add (>12 inches) cout << "d2 + d4: " << (d2 + d4) << endl; //test sub (0 ft) cout << "d3 - d1: " << (d3 - d1) << endl; //test sub (0 ft, negative conversion) cout << "d1 - d3: " << (d1 - d3) << endl; //test sub (positive ft & inch) cout << "d4 - d2: " << (d4 - d2) << endl; //test sub (negative ft & inch) cout << "d2 - d4: " << (d2 - d4) << endl; //test sub (negative ft, positive inch) cout << "d4 - d5: " << (d4 - d5) << endl; //test sub (positive ft, negative inch) cout << "d5 - d2: " << (d5 - d2) << endl; return 0; }
23.6
43
0.504708
benjaminmao123