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
fd38913ee6929ff670690ff8689318fe63932139
1,315
cpp
C++
cpp/301-310/Minimum Height Trees.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/301-310/Minimum Height Trees.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/301-310/Minimum Height Trees.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { vector<int> res; if(n <= 2) { for(int i = 0;i < n;i++) res.push_back(i); return res; } int k = 0; vector<set<int>> myvec(n, set<int>()); queue<int> myqueue; for(auto e : edges) { myvec[e.first].insert(e.second); myvec[e.second].insert(e.first); } for(int i = 0;i < n;i++) { if(myvec[i].size() == 1) { myqueue.push(i); k++; } } while(1) { int j = myqueue.size(); for(int i = 0;i < j;i++) { int v = myqueue.front(); myqueue.pop(); for(auto e : myvec[v]) { myvec[e].erase(v); if(myvec[e].size() == 1) { myqueue.push(e); k++; } } } if(n == k) break; } while(!myqueue.empty()) { res.push_back(myqueue.front()); myqueue.pop(); } sort(res.begin(), res.end()); return res; } };
25.784314
74
0.349049
KaiyuWei
fd3ad24c832a34d09a560531df4cb453e20a6f4e
2,552
hpp
C++
Lib/Chip/MKL36Z4.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
376
2015-07-17T01:41:20.000Z
2022-03-26T04:02:49.000Z
Lib/Chip/MKL36Z4.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
59
2015-07-03T21:30:13.000Z
2021-03-05T11:30:08.000Z
Lib/Chip/MKL36Z4.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
53
2015-07-14T12:17:06.000Z
2021-06-04T07:28:40.000Z
#pragma once #include <Chip/CM0+/Freescale/MKL36Z4/FTFA_FlashConfig.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/DMA.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FTFA.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/DMAMUX0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/I2S0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PIT.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/TPM0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/TPM1.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/TPM2.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/ADC0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/RTC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/DAC0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/LPTMR0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/TSI0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SIM.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PORTA.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PORTB.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PORTC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PORTD.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PORTE.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/LCD.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/MCG.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/OSC0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/I2C0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/I2C1.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/UART0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/UART1.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/UART2.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/CMP0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SPI0.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SPI1.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/LLWU.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/PMC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SMC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/RCM.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/GPIOA.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/GPIOB.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/GPIOC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/GPIOD.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/GPIOE.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SystemControl.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/SysTick.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/NVIC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/MTB.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/MTBDWT.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/ROM.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/MCM.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FGPIOA.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FGPIOB.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FGPIOC.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FGPIOD.hpp> #include <Chip/CM0+/Freescale/MKL36Z4/FGPIOE.hpp>
47.259259
59
0.774295
cjsmeele
fd3de0284634f25e8345852b89225993adb5fd8c
21,395
cpp
C++
SpockLib/c_view.cpp
zachmakesgames/Spock
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
[ "MIT" ]
null
null
null
SpockLib/c_view.cpp
zachmakesgames/Spock
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
[ "MIT" ]
null
null
null
SpockLib/c_view.cpp
zachmakesgames/Spock
bb5a6a9b4ce2c86fe49c08b7aa1ae633b95443e4
[ "MIT" ]
null
null
null
#include "c_view.h" c_view::c_view(c_instance *instance, c_device *device, int x, int y) : m_instance(instance), m_device(device), m_closing_callback(nullptr), m_resize_callback(nullptr), m_extent_2D({}) { VkResult result; //Set up the window this->m_extent_2D.height= y; this->m_extent_2D.width= x; this->m_window= glfwCreateWindow(x, y, m_instance->get_instance_name().c_str(), NULL, NULL); result= glfwCreateWindowSurface(*this->m_instance->get_instance(), this->m_window, NULL, &this->m_window_surface); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error with glfwCreateWindowSurface: " << result << std::endl; #endif throw std::exception("Could not create GLFW window surface"); } //Check for surface support, vulkan will complain if we dont VkBool32 supported_surface= false; result= vkGetPhysicalDeviceSurfaceSupportKHR(*this->m_device->get_physical_device(), this->m_device->get_graphics_queue_family_index(), this->m_window_surface, &supported_surface); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan could not determine if surface is supported: " << result << std::endl; #endif throw std::exception("Could not create GLFW window surface"); } if (!supported_surface) { #ifdef DEBUG std::cout << "SURFACE IS NOT SUPPORTED!!!!" << std::endl; #endif throw std::exception("GLFW surface is not supported by this device"); } //Check which formats are available //First find out how many there are uint32_t format_count= -1; vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, nullptr); VkSurfaceFormatKHR *supported_formats= new VkSurfaceFormatKHR[format_count]; //Then populate the formats vkGetPhysicalDeviceSurfaceFormatsKHR(*this->m_device->get_physical_device(), this->m_window_surface, &format_count, supported_formats); #ifdef DEBUG std::cout << "Found " << format_count << " supported formats" << std::endl; for (int i= 0; i < format_count; i++) { switch (supported_formats[i].format) { case VK_FORMAT_R8G8B8A8_UNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_UNORM" << std::endl; break; case VK_FORMAT_R8G8B8A8_SNORM: std::cout << "Format: VK_FORMAT_R8G8B8A8_SNORM" << std::endl; break; case VK_FORMAT_R8G8B8A8_USCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_USCALED" << std::endl; break; case VK_FORMAT_R8G8B8A8_SSCALED: std::cout << "Format: VK_FORMAT_R8G8B8A8_SSCALED" << std::endl; break; case VK_FORMAT_R8G8B8A8_UINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_UINT" << std::endl; break; case VK_FORMAT_R8G8B8A8_SINT: std::cout << "Format: VK_FORMAT_R8G8B8A8_SINT" << std::endl; break; case VK_FORMAT_R8G8B8A8_SRGB: std::cout << "Format: VK_FORMAT_R8G8B8A8_SRGB" << std::endl; break; case VK_FORMAT_B8G8R8A8_UNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_UNORM" << std::endl; break; case VK_FORMAT_B8G8R8A8_SNORM: std::cout << "Format: VK_FORMAT_B8G8R8A8_SNORM" << std::endl; break; case VK_FORMAT_B8G8R8A8_USCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_USCALED" << std::endl; break; case VK_FORMAT_B8G8R8A8_SSCALED: std::cout << "Format: VK_FORMAT_B8G8R8A8_SSCALED" << std::endl; break; case VK_FORMAT_B8G8R8A8_UINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_UINT" << std::endl; break; case VK_FORMAT_B8G8R8A8_SINT: std::cout << "Format: VK_FORMAT_B8G8R8A8_SINT" << std::endl; break; case VK_FORMAT_B8G8R8A8_SRGB: std::cout << "Format: VK_FORMAT_B8G8R8A8_SRGB" << std::endl; break; } switch (supported_formats[i].colorSpace) { case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR: std::cout << "Colorspace: VK_COLOR_SPACE_SRGB_NONLINEAR_KHR" << std::endl; break; case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_LINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_BT709_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_LINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_BT709_NONLINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT709_NONLINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_BT2020_LINEAR_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_BT2020_LINEAR_EXT" << std::endl; break; case VK_COLOR_SPACE_HDR10_ST2084_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_ST2084_EXT" << std::endl; break; case VK_COLOR_SPACE_DOLBYVISION_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_DOLBYVISION_EXT" << std::endl; break; case VK_COLOR_SPACE_HDR10_HLG_EXT: std::cout << "Colorspace: VK_COLOR_SPACE_HDR10_HLG_EXT" << std::endl; break; } } #endif //Check which present modes are available uint32_t present_mode_count= -1; vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, nullptr); VkPresentModeKHR *present_modes= new VkPresentModeKHR[present_mode_count]; //Then populate the present modes vkGetPhysicalDeviceSurfacePresentModesKHR(*this->m_device->get_physical_device(), this->m_window_surface, &present_mode_count, present_modes); #ifdef DEBUG std::cout << "Found " << present_mode_count << " presentation modes" << std::endl; for (int i= 0; i < present_mode_count; i++) { switch (present_modes[i]) { case VK_PRESENT_MODE_IMMEDIATE_KHR: std::cout << "VK_PRESENT_MODE_IMMEDIATE_KHR" << std::endl; break; case VK_PRESENT_MODE_MAILBOX_KHR: std::cout << "VK_PRESENT_MODE_MAILBOX_KHR" << std::endl; break; case VK_PRESENT_MODE_FIFO_KHR: std::cout << "VK_PRESENT_MODE_FIFO_KHR" << std::endl; break; case VK_PRESENT_MODE_FIFO_RELAXED_KHR: std::cout << "VK_PRESENT_MODE_FIFO_RELAXED_KHR" << std::endl; break; case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR" << std::endl; break; case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR: std::cout << "VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR" << std::endl; break; } } #endif //Set up the swap chain creation info ///TODO: set this up more dynamically this->m_swapchain_create_info.sType= VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; this->m_swapchain_create_info.pNext= nullptr; this->m_swapchain_create_info.flags= 0; this->m_swapchain_create_info.surface= this->m_window_surface; this->m_swapchain_create_info.minImageCount= this->m_swapchain_image_count; //VkFormat selectedFormat= this->GetImageFormat(); this->m_swapchain_create_info.imageFormat= VK_FORMAT_B8G8R8A8_SRGB; this->m_swapchain_create_info.imageColorSpace= VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;// this->GetColorSpaceFromFormat(selectedFormat); this->m_swapchain_create_info.presentMode= VK_PRESENT_MODE_IMMEDIATE_KHR; ///TODO: Add method to use different present modes this->m_swapchain_create_info.imageExtent= this->m_extent_2D; this->m_swapchain_create_info.imageArrayLayers= 1; this->m_swapchain_create_info.imageUsage= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; this->m_swapchain_create_info.preTransform= VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; this->m_swapchain_create_info.compositeAlpha= VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; this->m_swapchain_create_info.imageSharingMode= VK_SHARING_MODE_EXCLUSIVE; this->m_swapchain_create_info.queueFamilyIndexCount= this->m_device->get_graphics_queue_family_index(); this->m_swapchain_create_info.pQueueFamilyIndices= nullptr; this->m_swapchain_create_info.oldSwapchain= VK_NULL_HANDLE; this->m_swapchain_create_info.clipped= VK_TRUE; result= vkCreateSwapchainKHR(*this->m_device->get_logical_device(), &this->m_swapchain_create_info, nullptr, &this->m_swapchain); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the swapchain: " << result << std::endl; #endif throw std::exception("Could not create swapchain"); } //Next get the swapchain images result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_swapchain_image_count, nullptr); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error getting the present image count: " << result << std::endl; #endif throw std::exception("Could not get swapchain images"); } if (this->m_present_image_count < this->m_swapchain_image_count) { #ifdef DEBUG std::cout << "Did not get the number of requested swap chain images!" << std::endl; #endif throw std::exception("Swapchain/present image count mismatch"); } this->m_present_images= new VkImage[this->m_present_image_count]; result= vkGetSwapchainImagesKHR(*this->m_device->get_logical_device(), this->m_swapchain, &this->m_present_image_count, this->m_present_images); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error getting the present images: " << result << std::endl; #endif throw std::exception("Error creating swapchain images"); } //Set up Present Views this->m_present_image_views= new VkImageView[this->m_present_image_count]; this->m_present_image_view_create_info= new VkImageViewCreateInfo[this->m_present_image_count]; for (int i= 0; i < this->m_present_image_count; i++) { this->m_present_image_view_create_info[i].sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; this->m_present_image_view_create_info[i].pNext= nullptr; this->m_present_image_view_create_info[i].flags= 0; this->m_present_image_view_create_info[i].viewType= VK_IMAGE_VIEW_TYPE_2D; this->m_present_image_view_create_info[i].format= VK_FORMAT_B8G8R8A8_SRGB; //need to correlate this to the available formats above? //this->m_present_image_view_create_info[i].format= this->GetImageFormat(); //There, now its linked to the available formats this->m_present_image_view_create_info[i].components.r= VK_COMPONENT_SWIZZLE_R; this->m_present_image_view_create_info[i].components.g= VK_COMPONENT_SWIZZLE_G; this->m_present_image_view_create_info[i].components.b= VK_COMPONENT_SWIZZLE_B; this->m_present_image_view_create_info[i].components.a= VK_COMPONENT_SWIZZLE_A; this->m_present_image_view_create_info[i].subresourceRange.aspectMask= VK_IMAGE_ASPECT_COLOR_BIT; this->m_present_image_view_create_info[i].subresourceRange.baseMipLevel= 0; this->m_present_image_view_create_info[i].subresourceRange.levelCount= 1; this->m_present_image_view_create_info[i].subresourceRange.baseArrayLayer= 0; this->m_present_image_view_create_info[i].subresourceRange.layerCount= 1; this->m_present_image_view_create_info[i].image= this->m_present_images[i]; result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_present_image_view_create_info[i], nullptr, &this->m_present_image_views[i]); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating image view " << i << ": " << result << std::endl; #endif throw std::exception("Could not create image view"); } } //Set up the depth stencil this->m_extent_3D= { this->m_extent_2D.width, this->m_extent_2D.height, 1 }; this->m_image_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; this->m_image_create_info.pNext= nullptr; this->m_image_create_info.flags= 0; this->m_image_create_info.imageType= VK_IMAGE_TYPE_2D; this->m_image_create_info.format= VK_FORMAT_D32_SFLOAT_S8_UINT; this->m_image_create_info.extent= this->m_extent_3D; this->m_image_create_info.mipLevels= 1; this->m_image_create_info.arrayLayers= 1; this->m_image_create_info.samples= VK_SAMPLE_COUNT_1_BIT; this->m_image_create_info.tiling= VK_IMAGE_TILING_OPTIMAL; this->m_image_create_info.usage= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; this->m_image_create_info.sharingMode= VK_SHARING_MODE_EXCLUSIVE; this->m_image_create_info.queueFamilyIndexCount= 0; this->m_image_create_info.pQueueFamilyIndices= nullptr; this->m_image_create_info.initialLayout= VK_IMAGE_LAYOUT_UNDEFINED; this->m_depth_stencil_image= {}; result= vkCreateImage(*this->m_device->get_logical_device(), &this->m_image_create_info, nullptr, &this->m_depth_stencil_image); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the depth stencil: " << result << std::endl; #endif throw std::exception("Could not create depth stencil image"); } //Get information about what memory requirements the depth stencil needs vkGetImageMemoryRequirements(*this->m_device->get_logical_device(), this->m_depth_stencil_image, &this->m_stencil_requirements); VkPhysicalDeviceMemoryProperties memProperties= {}; ///TODO: Do this in the Device class earlier and save for later use vkGetPhysicalDeviceMemoryProperties(*this->m_device->get_physical_device(), &memProperties); //Find memory that is device local uint32_t memoryIndex= -1; for (unsigned int i= 0; i < memProperties.memoryTypeCount; i++) { VkMemoryType memType= memProperties.memoryTypes[i]; VkMemoryPropertyFlags memFlags= memType.propertyFlags; if ((this->m_stencil_requirements.memoryTypeBits & (1 << i)) != 0) { if ((memFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) { memoryIndex= i; break; } } } if (memoryIndex < 0) { throw std::exception("No device memory??!!"); } //Set up the memory allocation info struct this->m_stencil_memory_alloc_info.sType= VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; this->m_stencil_memory_alloc_info.pNext= nullptr; this->m_stencil_memory_alloc_info.allocationSize= this->m_stencil_requirements.size; this->m_stencil_memory_alloc_info.memoryTypeIndex= memoryIndex; //Then allocate the memory this->m_stencil_memory= new VkDeviceMemory(); result= vkAllocateMemory(*this->m_device->get_logical_device(), &this->m_stencil_memory_alloc_info, nullptr, this->m_stencil_memory); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error allocating memory for the depth stencil: " << result << std::endl; #endif throw std::exception("Could not allocate memory for depth stencil"); } //And bind the memory result= vkBindImageMemory(*this->m_device->get_logical_device(), this->m_depth_stencil_image, *this->m_stencil_memory, 0); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error binding the depth stencil image memory: " << result << std::endl; #endif throw std::exception("Could not bind stnecil image memory"); } // //Then set up the image view this->m_image_view_create_info.sType= VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; this->m_image_view_create_info.pNext= nullptr; this->m_image_view_create_info.flags= 0; this->m_image_view_create_info.image= this->m_depth_stencil_image; this->m_image_view_create_info.viewType= VK_IMAGE_VIEW_TYPE_2D; this->m_image_view_create_info.format= this->m_image_create_info.format; this->m_image_view_create_info.components.r= VK_COMPONENT_SWIZZLE_IDENTITY; this->m_image_view_create_info.components.g= VK_COMPONENT_SWIZZLE_IDENTITY; this->m_image_view_create_info.components.b= VK_COMPONENT_SWIZZLE_IDENTITY; this->m_image_view_create_info.components.a= VK_COMPONENT_SWIZZLE_IDENTITY; this->m_image_view_create_info.subresourceRange.aspectMask= VK_IMAGE_ASPECT_DEPTH_BIT; this->m_image_view_create_info.subresourceRange.baseMipLevel= 0; this->m_image_view_create_info.subresourceRange.levelCount= 1; this->m_image_view_create_info.subresourceRange.baseArrayLayer= 0; this->m_image_view_create_info.subresourceRange.layerCount= 1; this->m_image_view= new VkImageView(); result= vkCreateImageView(*this->m_device->get_logical_device(), &this->m_image_view_create_info, nullptr, this->m_image_view); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the image view: " << result << std::endl; #endif throw std::exception("Could not create image view"); } // //Then set up render passes //copied this from sample code developed by Dr. Mike Bailey at Oregon State University //Doesn't really need to be changed yet so I'm attributing the original author because reasons // need 2 - one for the color and one for the depth/stencil VkAttachmentDescription vad[2]; //vad[0].format= VK_FORMAT_B8G8R8A8_UNORM; vad[0].format= VK_FORMAT_B8G8R8A8_SRGB; //vad[0].format= this->GetImageFormat(); vad[0].samples= VK_SAMPLE_COUNT_1_BIT; vad[0].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR; vad[0].storeOp= VK_ATTACHMENT_STORE_OP_STORE; vad[0].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE; vad[0].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE; vad[0].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED; vad[0].finalLayout= VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; vad[0].flags= 0; //vad[0].flags= VK_ATTACHMENT_DESCRIPTION_MAT_ALIAS_BIT; vad[1].format= VK_FORMAT_D32_SFLOAT_S8_UINT; //Note this is not using GetImageFormat because the depth format is different vad[1].samples= VK_SAMPLE_COUNT_1_BIT; vad[1].loadOp= VK_ATTACHMENT_LOAD_OP_CLEAR; vad[1].storeOp= VK_ATTACHMENT_STORE_OP_DONT_CARE; vad[1].stencilLoadOp= VK_ATTACHMENT_LOAD_OP_DONT_CARE; vad[1].stencilStoreOp= VK_ATTACHMENT_STORE_OP_DONT_CARE; vad[1].initialLayout= VK_IMAGE_LAYOUT_UNDEFINED; vad[1].finalLayout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; vad[1].flags= 0; VkAttachmentReference colorReference; colorReference.attachment= 0; colorReference.layout= VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkAttachmentReference depthReference; depthReference.attachment= 1; depthReference.layout= VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; VkSubpassDescription vsd; vsd.flags= 0; vsd.pipelineBindPoint= VK_PIPELINE_BIND_POINT_GRAPHICS; vsd.inputAttachmentCount= 0; vsd.pInputAttachments= (VkAttachmentReference*)nullptr; vsd.colorAttachmentCount= 1; vsd.pColorAttachments= &colorReference; vsd.pResolveAttachments= (VkAttachmentReference*)nullptr; vsd.pDepthStencilAttachment= &depthReference; vsd.preserveAttachmentCount= 0; vsd.pPreserveAttachments= (uint32_t*)nullptr; this->m_render_pass_create_info.sType= VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; this->m_render_pass_create_info.pNext= nullptr; this->m_render_pass_create_info.flags= 0; this->m_render_pass_create_info.attachmentCount= 2; this->m_render_pass_create_info.pAttachments= vad; this->m_render_pass_create_info.subpassCount= 1; this->m_render_pass_create_info.pSubpasses= &vsd; this->m_render_pass_create_info.dependencyCount= 0; this->m_render_pass_create_info.pDependencies= nullptr; this->m_render_passes= new VkRenderPass(); result= vkCreateRenderPass(*this->m_device->get_logical_device(), &this->m_render_pass_create_info, nullptr, this->m_render_passes); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the render pass: " << result << std::endl; #endif throw std::exception("Could not create render passes"); } // //Finally set up the frame buffer this->m_framebuffers= new VkFramebuffer[this->m_framebuffer_count]; this->m_framebuffer_create_info.sType= VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; this->m_framebuffer_create_info.pNext= nullptr; this->m_framebuffer_create_info.flags= 0; this->m_framebuffer_create_info.renderPass= *this->m_render_passes; this->m_framebuffer_create_info.attachmentCount= 2; this->m_framebuffer_create_info.pAttachments= this->m_framebuffer_attachments; this->m_framebuffer_create_info.width= this->m_extent_2D.width; this->m_framebuffer_create_info.height= this->m_extent_2D.height; this->m_framebuffer_create_info.layers= 1; this->m_framebuffer_attachments[0]= this->m_present_image_views[0]; this->m_framebuffer_attachments[1]= *this->m_image_view; result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[0]); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the first frame buffer: " << result << std::endl; #endif throw std::exception("Could not create first frame buffer"); } this->m_framebuffer_attachments[0]= this->m_present_image_views[1]; this->m_framebuffer_attachments[1]= *this->m_image_view; result= vkCreateFramebuffer(*this->m_device->get_logical_device(), &this->m_framebuffer_create_info, nullptr, &this->m_framebuffers[1]); if (result != VK_SUCCESS) { #ifdef DEBUG std::cout << "Vulkan encountered an error creating the second frame buffer: " << result << std::endl; #endif throw std::exception("Could not create second frame buffer"); } } VkSwapchainKHR *c_view::get_swapchain() { return &this->m_swapchain; } VkExtent2D c_view::get_extent_2D() { return this->m_extent_2D; } VkRenderPass *c_view::get_render_pass() { return this->m_render_passes; } VkFramebuffer *c_view::get_frame_buffers(int *out_count) { if (out_count != nullptr) { *out_count= this->m_framebuffer_count; } return this->m_framebuffers; } void c_view::set_closing_callback(std::function<void()> new_callback) { this->m_closing_callback= new_callback; } void c_view::set_resize_callback(std::function<void(int, int)> new_callback) { this->m_resize_callback= new_callback; } void c_view::resize(int x, int y) { ///TODO: implement this }
43.222222
181
0.783454
zachmakesgames
fd40420eed3530e8d6555fb6d2d9a3aea4dc90af
4,550
cc
C++
content/browser/devtools/shared_worker_devtools_agent_host.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
content/browser/devtools/shared_worker_devtools_agent_host.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
content/browser/devtools/shared_worker_devtools_agent_host.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.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 "content/browser/devtools/shared_worker_devtools_agent_host.h" #include "content/browser/devtools/devtools_session.h" #include "content/browser/devtools/protocol/inspector_handler.h" #include "content/browser/devtools/protocol/network_handler.h" #include "content/browser/devtools/protocol/protocol.h" #include "content/browser/devtools/protocol/schema_handler.h" #include "content/browser/devtools/shared_worker_devtools_manager.h" #include "content/browser/shared_worker/shared_worker_host.h" #include "content/browser/shared_worker/shared_worker_instance.h" #include "content/browser/shared_worker/shared_worker_service_impl.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" namespace content { SharedWorkerDevToolsAgentHost::SharedWorkerDevToolsAgentHost( SharedWorkerHost* worker_host, const base::UnguessableToken& devtools_worker_token) : DevToolsAgentHostImpl(devtools_worker_token.ToString()), state_(WORKER_NOT_READY), worker_host_(worker_host), devtools_worker_token_(devtools_worker_token), instance_(new SharedWorkerInstance(*worker_host->instance())) { NotifyCreated(); } SharedWorkerDevToolsAgentHost::~SharedWorkerDevToolsAgentHost() { SharedWorkerDevToolsManager::GetInstance()->AgentHostDestroyed(this); } BrowserContext* SharedWorkerDevToolsAgentHost::GetBrowserContext() { if (!worker_host_) return nullptr; RenderProcessHost* rph = RenderProcessHost::FromID(worker_host_->process_id()); return rph ? rph->GetBrowserContext() : nullptr; } std::string SharedWorkerDevToolsAgentHost::GetType() { return kTypeSharedWorker; } std::string SharedWorkerDevToolsAgentHost::GetTitle() { return instance_->name(); } GURL SharedWorkerDevToolsAgentHost::GetURL() { return instance_->url(); } bool SharedWorkerDevToolsAgentHost::Activate() { return false; } void SharedWorkerDevToolsAgentHost::Reload() { } bool SharedWorkerDevToolsAgentHost::Close() { if (worker_host_) worker_host_->TerminateWorker(); return true; } bool SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->AddHandler(std::make_unique<protocol::InspectorHandler>()); session->AddHandler( std::make_unique<protocol::NetworkHandler>(GetId(), GetIOContext())); session->AddHandler(std::make_unique<protocol::SchemaHandler>()); session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr); if (state_ == WORKER_READY) session->AttachToAgent(EnsureAgent()); return true; } void SharedWorkerDevToolsAgentHost::DetachSession(DevToolsSession* session) { // Destroying session automatically detaches in renderer. } void SharedWorkerDevToolsAgentHost::DispatchProtocolMessage( DevToolsSession* session, const std::string& message) { session->DispatchProtocolMessage(message); } bool SharedWorkerDevToolsAgentHost::Matches(SharedWorkerHost* worker_host) { return instance_->Matches(*worker_host->instance()); } void SharedWorkerDevToolsAgentHost::WorkerReadyForInspection() { DCHECK_EQ(WORKER_NOT_READY, state_); DCHECK(worker_host_); state_ = WORKER_READY; for (DevToolsSession* session : sessions()) session->AttachToAgent(EnsureAgent()); } void SharedWorkerDevToolsAgentHost::WorkerRestarted( SharedWorkerHost* worker_host) { DCHECK_EQ(WORKER_TERMINATED, state_); DCHECK(!worker_host_); state_ = WORKER_NOT_READY; worker_host_ = worker_host; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetReloadedAfterCrash(); for (DevToolsSession* session : sessions()) session->SetRenderer(worker_host_->process_id(), nullptr); } void SharedWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); DCHECK(worker_host_); state_ = WORKER_TERMINATED; for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(-1, nullptr); worker_host_ = nullptr; agent_ptr_.reset(); } const blink::mojom::DevToolsAgentAssociatedPtr& SharedWorkerDevToolsAgentHost::EnsureAgent() { DCHECK_EQ(WORKER_READY, state_); DCHECK(worker_host_); if (!agent_ptr_) worker_host_->BindDevToolsAgent(mojo::MakeRequest(&agent_ptr_)); return agent_ptr_; } } // namespace content
33.455882
80
0.781099
zipated
fd4388dfd1ea017870625c4dc6aeff347a5b6371
4,640
cpp
C++
ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp
HellicarAndLewis/ProjectTimeCone
8074c202d943c156168b0e550f8615cd350a6d98
[ "MIT" ]
3
2015-01-17T11:57:10.000Z
2019-10-25T08:01:28.000Z
ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp
HellicarAndLewis/ProjectTimeCone
8074c202d943c156168b0e550f8615cd350a6d98
[ "MIT" ]
null
null
null
ProjectTimeConeLib/src/ProjectTimeCone/Initialisation/Initialiser.cpp
HellicarAndLewis/ProjectTimeCone
8074c202d943c156168b0e550f8615cd350a6d98
[ "MIT" ]
1
2018-10-19T04:57:29.000Z
2018-10-19T04:57:29.000Z
#include "Initialiser.h" using namespace ofxMachineVision; namespace ProjectTimeCone { namespace Initialisation { #pragma mark CameraController //-------------------------------------------------------------- CameraController::CameraController(int index, ofPtr<ofxMachineVision::Grabber::Simple> grabber) { this->index = index; this->grabber = grabber; this->setAllFromThis = false; this->load(); } //-------------------------------------------------------------- void CameraController::onControlChange(ofxUIEventArgs & args) { if(args.widget->getName() == "Exposure") { this->setExposure(this->exposure, true); } else if (args.widget->getName() == "Gain") { this->setGain(this->gain, true); } else if (args.widget->getName() == "Focus") { this->setFocus(this->focus, true); } } //-------------------------------------------------------------- void CameraController::setExposure(float exposure, bool setOthers) { this->exposure = exposure; this->grabber->setExposure(exposure); if (setOthers && this->setAllFromThis) { this->onExposureChangeAll(exposure); } this->save(); } //-------------------------------------------------------------- void CameraController::setGain(float gain, bool setOthers) { this->gain = gain; this->grabber->setGain(gain); if (setOthers && this->setAllFromThis) { this->onGainChangeAll(gain); } this->save(); } //-------------------------------------------------------------- void CameraController::setFocus(float focus, bool setOthers) { this->focus = focus; this->grabber->setFocus(focus); if (setOthers && this->setAllFromThis) { this->onFocusChangeAll(focus); } this->save(); } //-------------------------------------------------------------- string CameraController::getFilename() const { return "../../../Data/camera" + ofToString(this->index) + ".xml"; } //-------------------------------------------------------------- void CameraController::load() { if (this->xml.load(this->getFilename())) { ; this->setExposure(this->xml.getValue<float>("//Exposure"), false); this->setGain(this->xml.getValue<float>("//Gain"), false); this->setFocus(this->xml.getValue<float>("//Focus"), false); xml.setTo("//CameraSettings"); } else { this->xml.clear(); this->xml.addChild("CameraSettings"); this->xml.setTo("//CameraSettings"); this->xml.addValue("Exposure", ofToString(this->exposure)); this->xml.addValue("Gain", ofToString(this->gain)); this->xml.addValue("Focus", ofToString(this->focus)); this->exposure = 500; this->focus = 0; this->gain = 0; } } //-------------------------------------------------------------- void CameraController::save() { this->xml.setTo("//CameraSettings"); this->xml.setValue("Exposure", ofToString(this->exposure)); this->xml.setValue("Gain", ofToString(this->gain)); this->xml.setValue("Focus", ofToString(this->focus)); this->xml.save(this->getFilename()); } #pragma mark Initialiser //--------- void Initialiser::LoadCameras(std::vector<ofPtr<CameraController>> & controllers, std::function<void (ofPtr<CameraController>)> functor, int width, int height) { //order is a vector where // - order of vector is order of devices // - content of vector is index of devices vector<int> order; try { ofFile load(ORDER_FILENAME, ofFile::ReadOnly, true); int count = load.getPocoFile().getSize() / sizeof(int); order.resize(count); load.read((char*) &order[0], sizeof(int) * count); load.close(); } catch(...) { ofSystemAlertDialog("Couldn't load camera order, please place save.bin into data folder."); std::exit(1); } videoInput deviceEnumerator; auto deviceCount = deviceEnumerator.listDevices(); if (deviceCount != order.size()) { ofSystemAlertDialog("We've saved the order for a different number of cameras"); std::exit(1); } controllers.resize(deviceCount); int index = 0; for(auto deviceIndex : order) { auto device = DevicePtr(new Device::VideoInputDevice(1280, 720)); auto grabber = ofPtr<Grabber::Simple>(new Grabber::Simple(device)); grabber->open(deviceIndex); grabber->startCapture(); auto controller = ofPtr<CameraController>(new CameraController(index, grabber)); functor(controller); controllers[index] = controller; index++; } } //--------- void Initialiser::FillDevelopmentScreens() { ofSetWindowPosition(1920,0); ofSetWindowShape(1080 * 2, 1920); } } }
32.907801
139
0.578664
HellicarAndLewis
fd4408ee86a9d054d4044866ece60bfb2d85b646
2,937
cc
C++
webserver/libwebserv/request_utils.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
webserver/libwebserv/request_utils.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
webserver/libwebserv/request_utils.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2015 The Android Open Source Project // // 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 <libwebserv/request_utils.h> #include <utility> #include <base/bind.h> #include <brillo/streams/memory_stream.h> #include <brillo/streams/stream_utils.h> #include <libwebserv/request.h> #include <libwebserv/response.h> namespace libwebserv { namespace { struct RequestDataContainer { std::unique_ptr<Request> request; std::unique_ptr<Response> response; GetRequestDataSuccessCallback success_callback; GetRequestDataErrorCallback error_callback; std::vector<uint8_t> data; }; void OnCopySuccess(std::shared_ptr<RequestDataContainer> container, brillo::StreamPtr /* in_stream */, brillo::StreamPtr out_stream, uint64_t /* size_copied */) { // Close/release the memory stream so we can work with underlying data buffer. out_stream->CloseBlocking(nullptr); out_stream.reset(); container->success_callback.Run(std::move(container->request), std::move(container->response), std::move(container->data)); } void OnCopyError(std::shared_ptr<RequestDataContainer> container, brillo::StreamPtr /* in_stream */, brillo::StreamPtr /* out_stream */, const brillo::Error* error) { container->error_callback.Run(std::move(container->request), std::move(container->response), error); } } // anonymous namespace void GetRequestData(std::unique_ptr<Request> request, std::unique_ptr<Response> response, const GetRequestDataSuccessCallback& success_callback, const GetRequestDataErrorCallback& error_callback) { auto container = std::make_shared<RequestDataContainer>(); auto in_stream = request->GetDataStream(); auto out_stream = brillo::MemoryStream::CreateRef(&container->data, nullptr); container->request = std::move(request); container->response = std::move(response); container->success_callback = success_callback; container->error_callback = error_callback; brillo::stream_utils::CopyData(std::move(in_stream), std::move(out_stream), base::Bind(&OnCopySuccess, container), base::Bind(&OnCopyError, container)); } } // namespace libwebserv
38.142857
80
0.677562
emersion
fd475727ae2c507e53318e34ee7a5ba5fe66d3e7
4,400
cpp
C++
dwarf/SB/Game/zCamMarker.cpp
stravant/bfbbdecomp
2126be355a6bb8171b850f829c1f2731c8b5de08
[ "OLDAP-2.7" ]
1
2021-01-05T11:28:55.000Z
2021-01-05T11:28:55.000Z
dwarf/SB/Game/zCamMarker.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
null
null
null
dwarf/SB/Game/zCamMarker.cpp
sonich2401/bfbbdecomp
5f58b62505f8929a72ccf2aa118a1539eb3a5bd6
[ "OLDAP-2.7" ]
1
2022-03-30T15:15:08.000Z
2022-03-30T15:15:08.000Z
typedef struct xCamAsset; typedef struct zCamMarker; typedef struct xSerial; typedef struct _tagxCamFollowAsset; typedef struct xBase; typedef struct xVec3; typedef struct _tagxCamShoulderAsset; typedef struct xLinkAsset; typedef struct xBaseAsset; typedef struct _tagp2CamStaticAsset; typedef struct _tagp2CamStaticFollowAsset; typedef enum _tagTransType; typedef struct _tagxCamPathAsset; typedef int32(*type_1)(xBase*, xBase*, uint32, float32*, xBase*); typedef int32(*type_4)(xBase*, xBase*, uint32, float32*, xBase*); typedef float32 type_0[4]; typedef uint32 type_2[2]; typedef uint8 type_3[3]; struct xCamAsset : xBaseAsset { xVec3 pos; xVec3 at; xVec3 up; xVec3 right; xVec3 view_offset; int16 offset_start_frames; int16 offset_end_frames; float32 fov; float32 trans_time; _tagTransType trans_type; uint32 flags; float32 fade_up; float32 fade_down; union { _tagxCamFollowAsset cam_follow; _tagxCamShoulderAsset cam_shoulder; _tagp2CamStaticAsset cam_static; _tagxCamPathAsset cam_path; _tagp2CamStaticFollowAsset cam_staticFollow; }; uint32 valid_flags; uint32 markerid[2]; uint8 cam_type; uint8 pad[3]; }; struct zCamMarker : xBase { xCamAsset* asset; }; struct xSerial { }; struct _tagxCamFollowAsset { float32 rotation; float32 distance; float32 height; float32 rubber_band; float32 start_speed; float32 end_speed; }; struct xBase { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; xLinkAsset* link; int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*); }; struct xVec3 { float32 x; float32 y; float32 z; }; struct _tagxCamShoulderAsset { float32 distance; float32 height; float32 realign_speed; float32 realign_delay; }; struct xLinkAsset { uint16 srcEvent; uint16 dstEvent; uint32 dstAssetID; float32 param[4]; uint32 paramWidgetAssetID; uint32 chkAssetID; }; struct xBaseAsset { uint32 id; uint8 baseType; uint8 linkCount; uint16 baseFlags; }; struct _tagp2CamStaticAsset { uint32 unused; }; struct _tagp2CamStaticFollowAsset { float32 rubber_band; }; enum _tagTransType { eTransType_None, eTransType_Interp1, eTransType_Interp2, eTransType_Interp3, eTransType_Interp4, eTransType_Linear, eTransType_Interp1Rev, eTransType_Interp2Rev, eTransType_Interp3Rev, eTransType_Interp4Rev, eTransType_Total }; struct _tagxCamPathAsset { uint32 assetID; float32 time_end; float32 time_delay; }; int32(*zCamMarkerEventCB)(xBase*, xBase*, uint32, float32*, xBase*); int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam); void zCamMarkerLoad(zCamMarker* m, xSerial* s); void zCamMarkerSave(zCamMarker* m, xSerial* s); void zCamMarkerInit(xBase* b, xCamAsset* asset); // zCamMarkerEventCB__FP5xBaseP5xBaseUiPCfP5xBase // Start address: 0x310910 int32 zCamMarkerEventCB(xBase* to, uint32 toEvent, float32* toParam) { // Line 47, Address: 0x310910, Func Offset: 0 // Line 51, Address: 0x310914, Func Offset: 0x4 // Line 59, Address: 0x310948, Func Offset: 0x38 // Line 60, Address: 0x310954, Func Offset: 0x44 // Line 62, Address: 0x31095c, Func Offset: 0x4c // Line 63, Address: 0x310960, Func Offset: 0x50 // Line 64, Address: 0x310968, Func Offset: 0x58 // Line 67, Address: 0x310970, Func Offset: 0x60 // Line 72, Address: 0x310978, Func Offset: 0x68 // Line 71, Address: 0x31097c, Func Offset: 0x6c // Line 72, Address: 0x310980, Func Offset: 0x70 // Func End, Address: 0x310988, Func Offset: 0x78 } // zCamMarkerLoad__FP10zCamMarkerP7xSerial // Start address: 0x310990 void zCamMarkerLoad(zCamMarker* m, xSerial* s) { // Line 38, Address: 0x310990, Func Offset: 0 // Func End, Address: 0x310998, Func Offset: 0x8 } // zCamMarkerSave__FP10zCamMarkerP7xSerial // Start address: 0x3109a0 void zCamMarkerSave(zCamMarker* m, xSerial* s) { // Line 29, Address: 0x3109a0, Func Offset: 0 // Func End, Address: 0x3109a8, Func Offset: 0x8 } // zCamMarkerInit__FP5xBaseP9xCamAsset // Start address: 0x3109b0 void zCamMarkerInit(xBase* b, xCamAsset* asset) { // Line 10, Address: 0x3109b0, Func Offset: 0 // Line 12, Address: 0x3109c4, Func Offset: 0x14 // Line 17, Address: 0x3109cc, Func Offset: 0x1c // Line 18, Address: 0x3109d8, Func Offset: 0x28 // Line 21, Address: 0x3109e0, Func Offset: 0x30 // Line 23, Address: 0x3109ec, Func Offset: 0x3c // Line 24, Address: 0x3109f0, Func Offset: 0x40 // Func End, Address: 0x310a04, Func Offset: 0x54 }
22
69
0.76
stravant
fd47afe859506578fb0db6362b231e20b435202e
2,634
cpp
C++
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-k8sfilter/src/serializer/K8sfilterJsonObject.cpp
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * k8sfilter API * k8sfilter API generated from k8sfilter.yang * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/polycube-network/swagger-codegen.git * branch polycube */ /* Do not edit this file manually */ #include "K8sfilterJsonObject.h" #include <regex> namespace io { namespace swagger { namespace server { namespace model { K8sfilterJsonObject::K8sfilterJsonObject() { m_nameIsSet = false; m_portsIsSet = false; m_nodeportRange = "30000-32767"; m_nodeportRangeIsSet = true; } K8sfilterJsonObject::K8sfilterJsonObject(const nlohmann::json &val) : JsonObjectBase(val) { m_nameIsSet = false; m_portsIsSet = false; m_nodeportRangeIsSet = false; if (val.count("name")) { setName(val.at("name").get<std::string>()); } if (val.count("ports")) { for (auto& item : val["ports"]) { PortsJsonObject newItem{ item }; m_ports.push_back(newItem); } m_portsIsSet = true; } if (val.count("nodeport-range")) { setNodeportRange(val.at("nodeport-range").get<std::string>()); } } nlohmann::json K8sfilterJsonObject::toJson() const { nlohmann::json val = nlohmann::json::object(); if (!getBase().is_null()) { val.update(getBase()); } if (m_nameIsSet) { val["name"] = m_name; } { nlohmann::json jsonArray; for (auto& item : m_ports) { jsonArray.push_back(JsonObjectBase::toJson(item)); } if (jsonArray.size() > 0) { val["ports"] = jsonArray; } } if (m_nodeportRangeIsSet) { val["nodeport-range"] = m_nodeportRange; } return val; } std::string K8sfilterJsonObject::getName() const { return m_name; } void K8sfilterJsonObject::setName(std::string value) { m_name = value; m_nameIsSet = true; } bool K8sfilterJsonObject::nameIsSet() const { return m_nameIsSet; } const std::vector<PortsJsonObject>& K8sfilterJsonObject::getPorts() const{ return m_ports; } void K8sfilterJsonObject::addPorts(PortsJsonObject value) { m_ports.push_back(value); m_portsIsSet = true; } bool K8sfilterJsonObject::portsIsSet() const { return m_portsIsSet; } void K8sfilterJsonObject::unsetPorts() { m_portsIsSet = false; } std::string K8sfilterJsonObject::getNodeportRange() const { return m_nodeportRange; } void K8sfilterJsonObject::setNodeportRange(std::string value) { m_nodeportRange = value; m_nodeportRangeIsSet = true; } bool K8sfilterJsonObject::nodeportRangeIsSet() const { return m_nodeportRangeIsSet; } void K8sfilterJsonObject::unsetNodeportRange() { m_nodeportRangeIsSet = false; } } } } }
18.680851
75
0.69552
francescomessina
fd4c453e0c95352b913e3bcaa07432714103ca73
606
cpp
C++
sprint05/t04/app/src/Soldier.cpp
arni30/marathon-cpp
b8716599a891e2c534f2d63dd662931fe098e36a
[ "MIT" ]
null
null
null
sprint05/t04/app/src/Soldier.cpp
arni30/marathon-cpp
b8716599a891e2c534f2d63dd662931fe098e36a
[ "MIT" ]
null
null
null
sprint05/t04/app/src/Soldier.cpp
arni30/marathon-cpp
b8716599a891e2c534f2d63dd662931fe098e36a
[ "MIT" ]
null
null
null
#include "Soldier.h" Soldier::Soldier(std::string&& name, int health) :m_health(health), m_name(name){ std::cout << "Soldier " << m_name << " was created" << std::endl; } Soldier::~Soldier() { std::cout << "Soldier " << m_name << " was deleted" << std::endl; } void Soldier::setWeapon(Weapon* weapon) { m_weapon = weapon; } int Soldier::getHealth() const { return m_health; } void Soldier::attack(Soldier& other) { other.m_health -= m_weapon->getDamage(); std::cout << m_name << " attacks " << other.m_name << " and deals " << m_weapon->getDamage() << " damage" << std::endl; }
30.3
125
0.618812
arni30
fd4f885e8e2a92839403ee05655e3fa61ab11c12
1,952
cpp
C++
staff/samples/optional/component/src/TasksImpl.cpp
gale320/staff
c90e65a984e9931d803fc88243971639fe3876b7
[ "Apache-2.0" ]
14
2015-04-04T17:42:53.000Z
2021-03-09T11:09:51.000Z
staff/samples/optional/component/src/TasksImpl.cpp
gale320/staff
c90e65a984e9931d803fc88243971639fe3876b7
[ "Apache-2.0" ]
3
2015-07-30T13:22:42.000Z
2017-06-06T15:13:28.000Z
staff/samples/optional/component/src/TasksImpl.cpp
gale320/staff
c90e65a984e9931d803fc88243971639fe3876b7
[ "Apache-2.0" ]
13
2015-04-25T20:43:45.000Z
2021-12-29T07:55:47.000Z
// This file generated by staff_codegen // For more information please visit: http://code.google.com/p/staff/ // Service Implementation #include "TasksImpl.h" namespace samples { namespace optional { TasksImpl::TasksImpl() { } TasksImpl::~TasksImpl() { } void TasksImpl::OnCreate() { // this function is called when service instance is created and registered } void TasksImpl::OnDestroy() { // this function is called immediately before service instance destruction } int TasksImpl::Add(const Task& rstTask) { Task& rstAddedTask = *m_lsTasks.insert(m_lsTasks.end(), rstTask); rstAddedTask.nId = m_lsTasks.size(); return *rstAddedTask.nId; } void TasksImpl::UpdateOwner(int nTaskId, const staff::Optional< int >& rtnOwnerId) { for (TasksList::iterator itTask = m_lsTasks.begin(); itTask != m_lsTasks.end(); ++itTask) { if (itTask->nId == nTaskId) { itTask->tnOwnerId = rtnOwnerId; break; } } } void TasksImpl::UpdateAttachInfo(int nTaskId, const staff::Optional< AttachInfo >& rtnAttachInfo) { for (TasksList::iterator itTask = m_lsTasks.begin(); itTask != m_lsTasks.end(); ++itTask) { if (itTask->nId == nTaskId) { itTask->tstAttachInfo = rtnAttachInfo; break; } } } staff::Optional< AttachInfo > samples::optional::TasksImpl::GetAttachInfo(int nTaskId) { for (TasksList::iterator itTask = m_lsTasks.begin(); itTask != m_lsTasks.end(); ++itTask) { if (itTask->nId == nTaskId) { return itTask->tstAttachInfo; } } return staff::Optional< AttachInfo >(); } ::samples::optional::TasksList TasksImpl::GetAllTasks() const { return m_lsTasks; } staff::Optional< std::list<std::string> > TasksImpl::EchoOpt( const staff::Optional< std::list<std::string> >& opt) { return opt; } std::list< staff::Optional<std::string> > TasksImpl::EchoOpt2( const std::list< staff::Optional<std::string> >& opt) { return opt; } } }
19.717172
97
0.674693
gale320
fd5134bdb38c6445f558d74504981cf0649ff898
45,308
cc
C++
src/main/cpp/controller/controller.cc
rdfostrich/cobra
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
[ "MIT" ]
4
2020-07-02T12:11:41.000Z
2021-11-03T13:44:57.000Z
src/main/cpp/controller/controller.cc
rdfostrich/cobra
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
[ "MIT" ]
6
2021-06-14T11:34:39.000Z
2021-06-29T15:10:16.000Z
src/main/cpp/controller/controller.cc
rdfostrich/cobra
b65ec1aa7b10e990a3b40d86636050377ff2d2d6
[ "MIT" ]
1
2021-05-20T14:16:24.000Z
2021-05-20T14:16:24.000Z
#include <util/StopWatch.hpp> #include "controller.h" #include "snapshot_patch_iterator_triple_id.h" #include "patch_builder_streaming.h" #include "../snapshot/combined_triple_iterator.h" #include "../simpleprogresslistener.h" #include <sys/stat.h> #include <boost/filesystem.hpp> Controller::Controller(string basePath, int8_t kc_opts, bool readonly) : patchTreeManager(new PatchTreeManager(basePath, kc_opts, readonly)), snapshotManager(new SnapshotManager(basePath, readonly)) { struct stat sb; if (!(stat(basePath.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode))) { throw std::invalid_argument("The provided path '" + basePath + "' is not a valid directory."); } } Controller::~Controller() { delete patchTreeManager; delete snapshotManager; } size_t Controller::get_version_materialized_count_estimated(const Triple& triple_pattern, int patch_id) const { return get_version_materialized_count(triple_pattern, patch_id, true).first; } std::pair<size_t, ResultEstimationType> Controller::get_version_materialized_count(const Triple& triple_pattern, int patch_id, bool allowEstimates) const { int snapshot_id = get_corresponding_snapshot_id(patch_id); if(snapshot_id < 0) { return std::make_pair(0, EXACT); } HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id); IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0); size_t snapshot_count = snapshot_it->estimatedNumResults(); if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) { snapshot_count = 0; while (snapshot_it->hasNext()) { snapshot_it->next(); snapshot_count++; } } if(snapshot_id == patch_id) { return std::make_pair(snapshot_count, snapshot_it->numResultEstimation()); } DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id); int patch_tree_id = get_patch_tree_id(patch_id); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); if(patchTree == NULL) { return std::make_pair(snapshot_count, snapshot_it->numResultEstimation()); } std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id); size_t addition_count = patchTree->addition_count(patch_id, triple_pattern); return std::make_pair(snapshot_count - deletion_count_data.first + addition_count, snapshot_it->numResultEstimation()); } TripleIterator* Controller::get_version_materialized(const Triple &triple_pattern, int offset, int patch_id) const { // Find the snapshot int snapshot_id = get_corresponding_snapshot_id(patch_id); if(snapshot_id < 0) { //throw std::invalid_argument("No snapshot was found for version " + std::to_string(patch_id)); return new EmptyTripleIterator(); } HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id); // Simple case: We are requesting a snapshot, delegate lookup to that snapshot. IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset); if(snapshot_id == patch_id) { return new SnapshotTripleIterator(snapshot_it); } DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id); // Otherwise, we have to prepare an iterator for a certain patch int patch_tree_id = get_patch_tree_id(patch_id); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); if(patchTree == NULL) { return new SnapshotTripleIterator(snapshot_it); } PositionedTripleIterator* deletion_it = NULL; long added_offset = 0; bool check_offseted_deletions = true; // Limit the patch id to the latest available patch id // int max_patch_id = patchTree->get_max_patch_id(); // if (patch_id > max_patch_id) { // patch_id = max_patch_id; // } std::pair<PatchPosition, Triple> deletion_count_data = patchTree->deletion_count(triple_pattern, patch_id); // This loop continuously determines new snapshot iterators until it finds one that contains // no new deletions with respect to the snapshot iterator from last iteration. // This loop is required to handle special cases like the one in the ControllerTest::EdgeCase1. // As worst-case, this loop will take O(n) (n:dataset size), as an optimization we can look // into storing long consecutive chains of deletions more efficiently. while(check_offseted_deletions) { if (snapshot_it->hasNext()) { // We have elements left in the snapshot we should apply deletions to // Determine the first triple in the original snapshot and use it as offset for the deletion iterator TripleID *tripleId = snapshot_it->next(); Triple firstTriple(tripleId->getSubject(), tripleId->getPredicate(), tripleId->getObject()); deletion_it = patchTree->deletion_iterator_from(firstTriple, patch_id, triple_pattern); deletion_it->getPatchTreeIterator()->set_early_break(true); // Calculate a new offset, taking into account deletions. PositionedTriple first_deletion_triple; long snapshot_offset = 0; if (deletion_it->next(&first_deletion_triple, true)) { snapshot_offset = first_deletion_triple.position; } else { // The exact snapshot triple could not be found as a deletion if (patchTree->get_spo_comparator()->compare(firstTriple, deletion_count_data.second) < 0) { // If the snapshot triple is smaller than the largest deletion, // set the offset to zero, as all deletions will come *after* this triple. // Note that it should impossible that there would exist a deletion *before* this snapshot triple, // otherwise we would already have found this triple as a snapshot triple before. // If we would run into issues because of this after all, we could do a backwards step with // deletion_it and see if we find a triple matching the pattern, and use its position. snapshot_offset = 0; } else { // If the snapshot triple is larger than the largest deletion, // set the offset to the total number of deletions. snapshot_offset = deletion_count_data.first; } } long previous_added_offset = added_offset; added_offset = snapshot_offset; // Make a new snapshot iterator for the new offset // TODO: look into reusing the snapshot iterator and applying a relative offset (NOTE: I tried it before, it's trickier than it seems...) delete snapshot_it; snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset + added_offset); // Check if we need to loop again check_offseted_deletions = previous_added_offset < added_offset; if(check_offseted_deletions) { delete deletion_it; deletion_it = NULL; } } else { check_offseted_deletions = false; } } return new SnapshotPatchIteratorTripleID(snapshot_it, deletion_it, patchTree->get_spo_comparator(), snapshot, triple_pattern, patchTree, patch_id, offset, deletion_count_data.first); } std::pair<size_t, ResultEstimationType> Controller::get_delta_materialized_count(const Triple &triple_pattern, int patch_id_start, int patch_id_end, bool allowEstimates) const { int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start); int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end); int patch_tree_id_end = get_patch_tree_id(patch_id_end); int patch_tree_id_start = get_patch_tree_id(patch_id_start); // S_start <- P <- P_end if(snapshot_id_start == patch_id_start){ DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict); size_t count = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern); return std::make_pair(count, EXACT); } //P_start -> P -> S_end else if(snapshot_id_end == patch_id_end){ DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict); size_t count = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern); return std::make_pair(count, EXACT); } // reverse tree and forward tree case P_start -> S <- P_end else if(snapshot_id_start > patch_id_start && snapshot_id_end < patch_id_end) { DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end); PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict); PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict); size_t count = patchTreeForward->deletion_count(triple_pattern, patch_id_end).first + patchTreeForward->addition_count(patch_id_end, triple_pattern) + patchTreeReverse->deletion_count(triple_pattern, patch_id_start).first + patchTreeReverse->addition_count(patch_id_start, triple_pattern); return std::make_pair(count, UP_TO); } else{ if (allowEstimates) { DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_start); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict); size_t count_start = patchTree->deletion_count(triple_pattern, patch_id_start).first + patchTree->addition_count(patch_id_start, triple_pattern); size_t count_end = patchTree->deletion_count(triple_pattern, patch_id_end).first + patchTree->addition_count(patch_id_end, triple_pattern); // There may be an overlap between the delta-triples from start and end. // This overlap is not easy to determine, so we ignore it when possible. // The real count will never be higher this value, because we should subtract the overlap count. return std::make_pair(count_start + count_end, UP_TO); } else { return std::make_pair(get_delta_materialized(triple_pattern, 0, patch_id_start, patch_id_end)->get_count(), EXACT); } } } size_t Controller::get_delta_materialized_count_estimated(const Triple &triple_pattern, int patch_id_start, int patch_id_end) const { return get_delta_materialized_count(triple_pattern, patch_id_start, patch_id_end, true).second; } TripleDeltaIterator* Controller::get_delta_materialized(const Triple &triple_pattern, int offset, int patch_id_start, int patch_id_end) const { if (patch_id_end <= patch_id_start) { return new EmptyTripleDeltaIterator(); } // Find the snapshot int snapshot_id_start = get_corresponding_snapshot_id(patch_id_start); int snapshot_id_end = get_corresponding_snapshot_id(patch_id_end); if (snapshot_id_start < 0 || snapshot_id_end < 0) { return new EmptyTripleDeltaIterator(); } // start = snapshot, end = snapshot if(snapshot_id_start == patch_id_start && snapshot_id_end == patch_id_end) { // TODO: implement this when multiple snapshots are supported throw std::invalid_argument("Multiple snapshots are not supported."); } // start = snapshot, end = patch if(snapshot_id_start == patch_id_start && snapshot_id_end != patch_id_end) { DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end); if (snapshot_id_start == snapshot_id_end) { // Return iterator for the end patch relative to the start snapshot int patch_tree_id = get_patch_tree_id(patch_id_end); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); if(patchTree == NULL) { throw std::invalid_argument("Could not find the given end patch id"); } if (TripleStore::is_default_tree(triple_pattern)) { return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset); } else { return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset); } } else { // TODO: implement this when multiple snapshots are supported throw std::invalid_argument("Multiple snapshots are not supported."); } } // start = patch, end = snapshot if(snapshot_id_start != patch_id_start && snapshot_id_end == patch_id_end) { DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end); if (snapshot_id_start == snapshot_id_end) { // Return iterator for the end patch relative to the start snapshot int patch_tree_id = get_patch_tree_id(patch_id_start); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); if(patchTree == NULL) { throw std::invalid_argument("Could not find the given end patch id"); } if (TripleStore::is_default_tree(triple_pattern)) { return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset); } else { return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset); } } else { // TODO: implement this when multiple snapshots are supported throw std::invalid_argument("Multiple snapshots are not supported."); } // // TODO: implement this when multiple snapshots are supported // throw std::invalid_argument("Multiple snapshots are not supported."); } // start = patch, end = patch if(snapshot_id_start != patch_id_start && snapshot_id_end != patch_id_end) { DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id_end); if (snapshot_id_start == snapshot_id_end) { // Return diff between two patches relative to the same snapshot int patch_tree_id_end = get_patch_tree_id(patch_id_end); int patch_tree_id_start = get_patch_tree_id(patch_id_start); // forward patch tree (same tree) S <- P_start <- P_end if(snapshot_id_start < patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){ PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict); if(patchTree == NULL) { throw std::invalid_argument("Could not find the given end patch id"); } if (TripleStore::is_default_tree(triple_pattern)) { return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset); } else { return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end))->offset(offset); } } //reverse patch tree (same tree) P_start -> P_end -> S else if(snapshot_id_start > patch_tree_id_start && patch_tree_id_end == patch_tree_id_start){ PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict); if(patchTree == NULL) { throw std::invalid_argument("Could not find the given end patch id"); } if (TripleStore::is_default_tree(triple_pattern)) { return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset); } else { return (new ForwardDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start, patch_id_end, true))->offset(offset); } } // reverse tree and forward tree case P_start -> S <- P_end else{ // int patch_tree_id = get_patch_tree_id(patch_id_start); // PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); // if(patchTree == NULL) { // throw std::invalid_argument("Could not find the given end patch id"); // } // if (TripleStore::is_default_tree(triple_pattern)) { // return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_start))->offset(offset); // } else { // return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_start))->offset(offset); // } // // int patch_tree_id = get_patch_tree_id(patch_id_end); // PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(patch_tree_id, dict); // if(patchTree == NULL) { // throw std::invalid_argument("Could not find the given end patch id"); // } // if (TripleStore::is_default_tree(triple_pattern)) { // return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTree, triple_pattern, patch_id_end))->offset(offset); // } else { // return (new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTree, triple_pattern, patch_id_end))->offset(offset); // } PatchTree* patchTreeReverse = get_patch_tree_manager()->get_patch_tree(patch_tree_id_start, dict); PatchTree* patchTreeForward = get_patch_tree_manager()->get_patch_tree(patch_tree_id_end, dict); if(patchTreeReverse == NULL || patchTreeForward == NULL) { throw std::invalid_argument("Could not find the given patch id"); } if (TripleStore::is_default_tree(triple_pattern)) { return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValue>( new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeReverse, triple_pattern, patch_id_start ), new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValue>(patchTreeForward, triple_pattern, patch_id_end), patchTreeForward->get_spo_comparator()))->offset(offset); } else { return (new BiDiffPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>( new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeReverse, triple_pattern, patch_id_start), new ForwardPatchTripleDeltaIterator<PatchTreeDeletionValueReduced>(patchTreeForward, triple_pattern, patch_id_end), patchTreeForward->get_spo_comparator()))->offset(offset); } } } else { // TODO: implement this when multiple snapshots are supported throw std::invalid_argument("Multiple snapshots are not supported."); } } return nullptr; } std::pair<size_t, ResultEstimationType> Controller::get_version_count(const Triple &triple_pattern, bool allowEstimates) const { // TODO: this will require some changes when we support multiple snapshots. // Find the snapshot an count its elements HDT* snapshot = get_snapshot_manager()->get_snapshot(0); IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0); size_t count = snapshot_it->estimatedNumResults(); if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) { count = 0; while (snapshot_it->hasNext()) { snapshot_it->next(); count++; } } // Count the additions for all versions DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(0); PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(0, dict); if (patchTree != NULL) { count += patchTree->addition_count(0, triple_pattern); } return std::make_pair(count, allowEstimates ? snapshot_it->numResultEstimation() : EXACT); } std::pair<size_t, ResultEstimationType> Controller::get_partial_version_count(const Triple &triple_pattern, bool allowEstimates) const { // TODO: this will require some changes when we support multiple snapshots. int snapshot_id = snapshotManager->get_snapshots().begin()->first; int reverse_patch_tree_id = snapshot_id - 1; int forward_patch_tree_id = snapshot_id + 1; // Find the snapshot an count its elements HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id); DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id); IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0); PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null size_t count = snapshot_it->estimatedNumResults(); if (!allowEstimates && snapshot_it->numResultEstimation() != EXACT) { count = 0; while (snapshot_it->hasNext()) { snapshot_it->next(); count++; } } // Count the additions for all versions if (reverse_patch_tree != NULL) { count += reverse_patch_tree->addition_count(-1, triple_pattern); } if (forward_patch_tree != NULL) { count += forward_patch_tree->addition_count(-1, triple_pattern); } return std::make_pair(count, UP_TO); } size_t Controller::get_version_count_estimated(const Triple &triple_pattern) const { return get_version_count(triple_pattern, true).first; } TripleVersionsIterator* Controller::get_partial_version(const Triple &triple_pattern, int offset) const { int snapshot_id = snapshotManager->get_snapshots().begin()->first; int reverse_patch_tree_id = snapshot_id - 1; int forward_patch_tree_id = snapshot_id + 1; HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id); IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset); DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id); PatchTree* reverse_patch_tree = get_patch_tree_manager()->get_patch_tree(reverse_patch_tree_id, dict); // Can be null PatchTree* forward_patch_tree = get_patch_tree_manager()->get_patch_tree(forward_patch_tree_id, dict); // Can be null // Snapshots have already been offsetted, calculate the remaining offset. // After this, offset will only be >0 if we are past the snapshot elements and at the additions. if (snapshot_it->numResultEstimation() == EXACT) { offset -= snapshot_it->estimatedNumResults(); if (offset <= 0) { offset = 0; } else { delete snapshot_it; snapshot_it = NULL; } } else { IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0); while (tmp_it->hasNext() && offset > 0) { tmp_it->next(); offset--; } delete tmp_it; } return (new TripleVersionsIterator(triple_pattern, snapshot_it, reverse_patch_tree, forward_patch_tree, snapshot_id))->offset(offset); } TripleVersionsIterator* Controller::get_version(const Triple &triple_pattern, int offset) const { // // TODO: this will require some changes when we support multiple snapshots. (probably just a simple merge for all snapshots with what is already here) // // Find the snapshot // int snapshot_id = 0; // HDT* snapshot = get_snapshot_manager()->get_snapshot(snapshot_id); // IteratorTripleID* snapshot_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, offset); // DictionaryManager *dict = get_snapshot_manager()->get_dictionary_manager(snapshot_id); // PatchTree* patchTree = get_patch_tree_manager()->get_patch_tree(snapshot_id, dict); // Can be null, if only snapshot is available // // // Snapshots have already been offsetted, calculate the remaining offset. // // After this, offset will only be >0 if we are past the snapshot elements and at the additions. // if (snapshot_it->numResultEstimation() == EXACT) { // offset -= snapshot_it->estimatedNumResults(); // if (offset <= 0) { // offset = 0; // } else { // delete snapshot_it; // snapshot_it = NULL; // } // } else { // IteratorTripleID *tmp_it = SnapshotManager::search_with_offset(snapshot, triple_pattern, 0); // while (tmp_it->hasNext() && offset > 0) { // tmp_it->next(); // offset--; // } // delete tmp_it; // } // // return (new TripleVersionsIterator(triple_pattern, snapshot_it, patchTree, 0))->offset(offset); return NULL; } bool Controller::append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) { //find largest key smaller or equal to patch_id, this is the patch_tree_id auto it = patchTreeManager->get_patch_trees().lower_bound(patch_id); //gives elements equal to or greater than patch_id if(it == patchTreeManager->get_patch_trees().end() || it->first > patch_id) { if(it == patchTreeManager->get_patch_trees().begin()) { // todo error no smaller element found return -1; } it--; } int patch_tree_id = it->first; return get_patch_tree_manager()->append(patch_it, patch_id, patch_tree_id, check_uniqueness, progressListener, dict); } bool Controller::reverse_append(PatchElementIterator* patch_it, int patch_id, DictionaryManager* dict, bool check_uniqueness, ProgressListener* progressListener) { //find smallest element larger than or equal to patch_id, this is the patch_tree_id int patch_tree_id; if(patchTreeManager->get_patch_trees().find(patch_id) == patchTreeManager->get_patch_trees().end()){ auto iterator = patchTreeManager->get_patch_trees().upper_bound(patch_id); //returns first element bigger than patch_id patch_tree_id = iterator->first; } else{ patch_tree_id = patch_id; } return get_patch_tree_manager()->reverse_append(patch_it, patch_id, patch_tree_id, dict, check_uniqueness, progressListener); } PatchTreeManager* Controller::get_patch_tree_manager() const { return patchTreeManager; } SnapshotManager* Controller::get_snapshot_manager() const { return snapshotManager; } DictionaryManager *Controller::get_dictionary_manager(int patch_id) const { int snapshot_id = get_corresponding_snapshot_id(patch_id); if(snapshot_id < 0) { throw std::invalid_argument("No snapshot has been created yet."); } get_snapshot_manager()->get_snapshot(snapshot_id); // Force a snapshot load return get_snapshot_manager()->get_dictionary_manager(snapshot_id); } int Controller::get_max_patch_id() { get_snapshot_manager()->get_snapshot(0); // Make sure our first snapshot is loaded, otherwise KC might get intro trouble while reorganising since it needs the dict for that. int max_patch_id = get_patch_tree_manager()->get_max_patch_id(get_snapshot_manager()->get_dictionary_manager(0)); if (max_patch_id < 0) { return get_corresponding_snapshot_id(0); } return max_patch_id; } void Controller::cleanup(string basePath, Controller* controller) { // Delete patch files std::map<int, PatchTree*> patches = controller->get_patch_tree_manager()->get_patch_trees(); std::map<int, PatchTree*>::iterator itP = patches.begin(); std::list<int> patchMetadataToDelete; while(itP != patches.end()) { int id = itP->first; std::remove((basePath + PATCHTREE_FILENAME(id, "spo_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "pos_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "pso_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "sop_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "osp_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "spo_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "pos_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "pso_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "sop_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "osp_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(id, "count_additions.tmp")).c_str()); patchMetadataToDelete.push_back(id); itP++; } // Delete snapshot files std::map<int, HDT*> snapshots = controller->get_snapshot_manager()->get_snapshots(); std::map<int, HDT*>::iterator itS = snapshots.begin(); std::list<int> patchDictsToDelete; while(itS != snapshots.end()) { int id = itS->first; std::remove((basePath + SNAPSHOT_FILENAME_BASE(id)).c_str()); std::remove((basePath + SNAPSHOT_FILENAME_BASE(id) + ".index").c_str()); patchDictsToDelete.push_back(id); itS++; } delete controller; // Delete dictionaries std::list<int>::iterator it1; for(it1=patchDictsToDelete.begin(); it1!=patchDictsToDelete.end(); ++it1) { DictionaryManager::cleanup(basePath, *it1); } // Delete metadata files std::list<int>::iterator it2; for(it2=patchMetadataToDelete.begin(); it2!=patchMetadataToDelete.end(); ++it2) { std::remove((basePath + METADATA_FILENAME_BASE(*it2)).c_str()); } } PatchBuilder* Controller::new_patch_bulk() { return new PatchBuilder(this); } PatchBuilderStreaming *Controller::new_patch_stream() { return new PatchBuilderStreaming(this); } bool Controller::replace_patch_tree(string basePath, int patch_tree_id) { // remove old files std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str()); std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str()); //rename temp files std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str()); std::rename((basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str(), (basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str()); std::rename((basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id)).c_str(), (basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str()); return true; } int Controller::get_patch_tree_id(int patch_id)const { // case 1: S <- P <- P // case 2: S <- P <- P S <- P // case 3: S <- P <- P P -> P -> S <- P // case 4: P -> P -> S <- P <- P // return lower tree if reverse tree does not exists // return upper tree if reverse tree does exists std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots(); std::map<int, HDT*>::iterator low, prev; low = loaded_snapshots.lower_bound(patch_id); int low_snapshot_id = -1; int high_snapshot_id = -1; if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) { // empty map return -1; } if (low == loaded_snapshots.end()) { low--; low_snapshot_id = low->first; } else if (low == loaded_snapshots.begin()) { low_snapshot_id = low->first; } else { prev = std::prev(low); high_snapshot_id = low->first; low_snapshot_id = prev->first; } // case 4 if(low_snapshot_id > patch_id){ return low_snapshot_id - 1; } std::map<int, PatchTree*> patches = get_patch_tree_manager()->get_patch_trees(); int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id if(high_snapshot_id >= 0){ // if high snapshot exists auto it = patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id if(it != patches.end()){ // if reverse patch tree exists int dist_to_low = patch_id - low_snapshot_id; int dist_to_high = high_snapshot_id - patch_id; if(dist_to_high < dist_to_low){ // closer to reverse patch tree return high_snapshot_id - 1; // todo make function of reverse patch_tree_id } } } // check if forward chain exists auto it = patches.find(low_patch_tree_id); // todo make function of reverse patch_tree_id if(it == patches.end()){ return -1; } return low_patch_tree_id; } int Controller::get_corresponding_snapshot_id(int patch_id) const { // get snapshot before patch_id // get snapshot after patch_id // if snapshot after patch_id does not exist or snapshot_after does not have reverse tree, return snapshot before patch_id // if reverse does exist, return snapshot id closest to patch_id (in case of tie, return lowest snapshot_id std::map<int, HDT*> loaded_snapshots = get_snapshot_manager()->get_snapshots(); std::map<int, HDT*>::iterator low, prev; low = loaded_snapshots.lower_bound(patch_id); int low_snapshot_id = -1; int high_snapshot_id = -1; if(low == loaded_snapshots.begin() && low == loaded_snapshots.end()) { // empty map return -1; } if (low == loaded_snapshots.end()) { low--; low_snapshot_id = low->first; } else if (low == loaded_snapshots.begin()) { low_snapshot_id = low->first; } else { prev = std::prev(low); high_snapshot_id = low->first; low_snapshot_id = prev->first; } if(high_snapshot_id == patch_id) return high_snapshot_id; else if(low_snapshot_id == patch_id) return low_snapshot_id; else{ std::map<int, PatchTree*> loaded_patches = get_patch_tree_manager()->get_patch_trees(); int low_patch_tree_id = low_snapshot_id + 1 ; // todo make function of forward patch_tree_id if(high_snapshot_id >= 0){ // if high snapshot exists auto it = loaded_patches.find(high_snapshot_id - 1); // todo make function of reverse patch_tree_id if(it != loaded_patches.end()){ // if reverse patch tree exists int dist_to_low = patch_id - low_snapshot_id; int dist_to_high = high_snapshot_id - patch_id; if(dist_to_high < dist_to_low){ // closer to reverse patch tree return high_snapshot_id; } } } return low_snapshot_id;} } bool Controller::copy_patch_tree_files(string basePath, int patch_tree_id) { try { boost::filesystem::path source, target; source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_deletions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_deletions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_deletions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_deletions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_deletions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "spo_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pos_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "pso_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "sop_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "osp_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions"); target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions"); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); // source = basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp"); // target = basePath + TEMP_PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp"); // if (boost::filesystem::exists(source)) // boost::filesystem::copy_file(source, target); source = basePath + METADATA_FILENAME_BASE(patch_tree_id); target = basePath + TEMP_METADATA_FILENAME_BASE(patch_tree_id); if (boost::filesystem::exists(source)) boost::filesystem::copy_file(source, target); } catch (const boost::filesystem::filesystem_error& e){ return false; } return true; } void Controller::remove_forward_chain(std::string basePath, int temp_snapshot_id){ int patch_tree_id = temp_snapshot_id + 1; get_patch_tree_manager()->remove_patch_tree(patch_tree_id); get_snapshot_manager()->remove_snapshot(temp_snapshot_id); std::remove((basePath + PATCHDICT_FILENAME_BASE(temp_snapshot_id)).c_str()); std::remove((basePath + METADATA_FILENAME_BASE(patch_tree_id)).c_str()); std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id)).c_str()); std::remove((basePath + SNAPSHOT_FILENAME_BASE(temp_snapshot_id) + ".index").c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_deletions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "spo_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pos_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "pso_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "sop_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "osp_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions")).c_str()); std::remove((basePath + PATCHTREE_FILENAME(patch_tree_id, "count_additions.tmp")).c_str()); } void Controller::extract_changeset(int patch_tree_id, std::string path_to_files) { patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_additions(get_dictionary_manager(patch_tree_id), path_to_files); patchTreeManager->get_patch_tree(patch_tree_id, get_dictionary_manager(patch_tree_id))->getTripleStore()->extract_deletions(get_dictionary_manager(patch_tree_id), path_to_files); }
55.119221
297
0.677916
rdfostrich
fd513c0e3af24e2511e6d4b399996a53d7b9bcd9
7,120
cc
C++
DPPIR/shuffle/shuffle_test.cc
multiparty/drivacy
bb215831a9114e837ff7b1b75dc2195396a5fffa
[ "MIT" ]
3
2019-09-23T19:01:23.000Z
2020-09-07T22:23:11.000Z
DPPIR/shuffle/shuffle_test.cc
multiparty/drivacy
bb215831a9114e837ff7b1b75dc2195396a5fffa
[ "MIT" ]
4
2020-10-09T14:13:13.000Z
2020-10-09T14:14:25.000Z
DPPIR/shuffle/shuffle_test.cc
multiparty/drivacy
bb215831a9114e837ff7b1b75dc2195396a5fffa
[ "MIT" ]
null
null
null
#include <cassert> // NOLINTNEXTLINE #include <chrono> #include <iostream> #include <string> #include <vector> #include "DPPIR/shuffle/local_shuffle.h" #include "DPPIR/shuffle/parallel_shuffle.h" #include "DPPIR/types/types.h" #define SERVER_COUNT 8 #define TOTAL_COUNT 10000006 // Whether to print intermediate batches. #define PRINT false namespace DPPIR { namespace shuffle { index_t InputCountForServer(server_id_t server) { index_t uniform = TOTAL_COUNT / SERVER_COUNT; if (server == SERVER_COUNT - 1) { uniform = TOTAL_COUNT - (uniform * server); } // Introduce ~1% variance in input size. index_t offset = (TOTAL_COUNT / SERVER_COUNT) / 20; assert(offset < uniform && offset > 0); if (server % 2 == 0) { return uniform + offset; } else { return uniform - offset; } } // Printing utils. template <typename T> void Print(server_id_t sid, const std::string& label, const std::vector<T>& v) { if (PRINT) { std::cout << "(server " << int(sid) << ") " << label << ": ["; for (const auto& q : v) { std::cout << q << ", "; } std::cout << "] @ " << v.size(); std::cout << std::endl; } } template <typename T> void Print2D(server_id_t sid, const std::string& label, const std::vector<std::vector<T>>& v) { if (PRINT) { for (size_t i = 0; i < v.size(); i++) { std::cout << "(server " << int(sid) << ") " << label << " from " << i << ": ["; for (const auto& q : v.at(i)) { std::cout << q << ", "; } std::cout << "] @ " << v.at(i).size(); std::cout << std::endl; } } } // Server struct. struct Server { server_id_t id; // Shufflers. ParallelShuffler pshuffler; LocalShuffler lshuffler; std::vector<key_t> inputs; // Going forward. std::vector<std::vector<key_t>> forward_from_servers; std::vector<key_t> outbox; // Output of shuffling. // Going backward. std::vector<key_t> inbox; std::vector<std::vector<key_t>> backward_from_servers; // Should be == inputs. std::vector<key_t> outputs; // Constructor. Server(server_id_t sid, index_t* server_counts) : id(sid), pshuffler(sid, SERVER_COUNT, SERVER_COUNT), lshuffler(sid), forward_from_servers(SERVER_COUNT, std::vector<key_t>()), backward_from_servers(SERVER_COUNT, std::vector<key_t>()) { // Initialize parallel shuffler. pshuffler.Initialize(server_counts, 0); index_t in_slice = server_counts[sid]; index_t out_slice = pshuffler.GetServerSliceSize(); // Initialize local shuffler. lshuffler.Initialize(out_slice); // Initialize vectors. inputs.reserve(in_slice); outbox = std::vector<key_t>(out_slice, -1); inbox = std::vector<key_t>(out_slice, -1); outputs = std::vector<key_t>(in_slice, -1); for (index_t i = 0; i < in_slice; i++) { inputs.push_back(sid * TOTAL_COUNT + i); } } }; // Measure time for a single preshuffle. void SingleOffline() { // Give every server an input size. std::vector<index_t> input_counts; for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) { input_counts.push_back(InputCountForServer(sid)); } // Create shuffler. ParallelShuffler _pshuffler(SERVER_COUNT - 1, SERVER_COUNT, SERVER_COUNT); LocalShuffler _lshuffler(0); // Time initialization. auto s = std::chrono::steady_clock::now(); _pshuffler.Initialize(&input_counts.at(0), 0); _lshuffler.Initialize(_pshuffler.GetServerSliceSize()); auto e = std::chrono::steady_clock::now(); auto d = std::chrono::duration_cast<std::chrono::milliseconds>(e - s).count(); // Done. std::cout << "Preprocessing: " << d << "ms" << std::endl; std::cout << std::endl; } bool SimpleProtocol() { // Give every server an input size. std::vector<index_t> input_counts; for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) { input_counts.push_back(InputCountForServer(sid)); } // Create server structs. std::vector<Server> servers; servers.reserve(SERVER_COUNT); for (server_id_t sid = 0; sid < SERVER_COUNT; sid++) { servers.emplace_back(sid, &input_counts.at(0)); } // First stage. std::cout << "First stage" << std::endl; for (auto& server : servers) { Print(server.id, "inputs", server.inputs); for (auto& q : server.inputs) { server_id_t tserver = server.pshuffler.ShuffleOne(); servers.at(tserver).forward_from_servers.at(server.id).push_back(q); } server.pshuffler.FinishForward(); } // Print state. for (auto& server : servers) { Print2D(server.id, "forward", server.forward_from_servers); } std::cout << std::endl; // Second stage. std::cout << "Second stage" << std::endl; for (auto& server : servers) { std::vector<key_t> before_shuffle; for (auto& v : server.forward_from_servers) { for (auto& q : v) { index_t target_idx = server.lshuffler.Shuffle(before_shuffle.size()); server.outbox.at(target_idx) = q; before_shuffle.push_back(q); } } server.lshuffler.FinishForward(); Print(server.id, "outbox (no shuffle)", before_shuffle); Print(server.id, "outbox: ", server.outbox); } std::cout << std::endl; // Reverse second stage. std::cout << "Reverse second stage" << std::endl; for (auto& server : servers) { for (index_t idx = 0; idx < server.outbox.size(); idx++) { index_t target_idx = server.lshuffler.Deshuffle(idx); server.inbox.at(target_idx) = server.outbox.at(idx); } server.lshuffler.FinishBackward(); Print(server.id, "inbox (deshuffled)", server.inbox); // Send to servers. index_t acc = 0; for (server_id_t tserver = 0; tserver < SERVER_COUNT; tserver++) { index_t count = server.forward_from_servers.at(tserver).size(); for (index_t i = 0; i < count; i++) { auto& q = server.inbox.at(i + acc); servers.at(tserver).backward_from_servers.at(server.id).push_back(q); } acc += count; } } // Print state. for (auto& server : servers) { Print2D(server.id, "backward", server.backward_from_servers); } std::cout << std::endl; // Reverse first stage. std::cout << "Reverse first stage" << std::endl; for (auto& server : servers) { for (server_id_t tserver = 0; tserver < SERVER_COUNT; tserver++) { auto& v = server.backward_from_servers.at(tserver); for (auto& q : v) { index_t target_idx = server.pshuffler.DeshuffleOne(tserver); server.outputs.at(target_idx) = q; } } server.pshuffler.FinishBackward(); Print(server.id, "output", server.outputs); if (server.outputs != server.inputs) { return false; } } std::cout << std::endl; return true; } } // namespace shuffle } // namespace DPPIR // Main function. int main(int argc, char** argv) { // Start. std::cout << "starting... " << std::endl; // Preprocessing. DPPIR::shuffle::SingleOffline(); // Protocol. if (!DPPIR::shuffle::SimpleProtocol()) { std::cout << "error!" << std::endl; return 1; } // Done. std::cout << "Success!" << std::endl; return 0; }
28.253968
80
0.630478
multiparty
fd51bebb0df2e5fe0b10e900258aebabdf1d932f
384
cpp
C++
src/Scene.cpp
jomoho/SDL_Framework
903b6baff5f18bbf18b9c90861478fb005525527
[ "BSD-2-Clause" ]
null
null
null
src/Scene.cpp
jomoho/SDL_Framework
903b6baff5f18bbf18b9c90861478fb005525527
[ "BSD-2-Clause" ]
null
null
null
src/Scene.cpp
jomoho/SDL_Framework
903b6baff5f18bbf18b9c90861478fb005525527
[ "BSD-2-Clause" ]
null
null
null
// // Created by moritz on 20.08.15. // #include "Scene.h" #include <Box2D/Box2D.h> Scene::Scene(){ b2Vec2 gravity(0.0f, -10.0f); // world = new b2World(gravity); // world->SetDebugDraw(&debugDraw); // debugDraw.SetFlags( b2Draw::e_shapeBit |b2Draw::e_jointBit); } Scene::~Scene() { // delete world; } void Scene::update(float dt) { // world->Step(dt, 6, 2); }
17.454545
66
0.617188
jomoho
fd52725e24f6782dfda7cf00f21ae25e22aabc8f
3,345
hpp
C++
src/route/TopicRouteManager.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
5
2019-04-24T13:37:05.000Z
2021-01-29T16:37:55.000Z
src/route/TopicRouteManager.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
null
null
null
src/route/TopicRouteManager.hpp
ifplusor/rocketmq-client-cpp
fd301f4b064d5035fc72261023a396e2c9126c53
[ "Apache-2.0" ]
1
2021-02-03T03:11:03.000Z
2021-02-03T03:11:03.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 ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_ #define ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_ #include <map> // std::map #include <memory> // std::shared_ptr #include <mutex> // std::mutex #include <set> // std::set #include <string> // std::string #include "utility/MapAccessor.hpp" namespace rocketmq { struct TopicRouteData; class TopicPublishInfo; class TopicSubscribeInfo; class TopicRouteManager { public: std::shared_ptr<TopicRouteData> GetTopicRouteData(const std::string& topic) { return MapAccessor::GetOrDefault(topic_route_table_, topic, nullptr, topic_route_table_mutex_); } void PutTopicRouteData(const std::string& topic, std::shared_ptr<TopicRouteData> topic_route) { MapAccessor::InsertOrAssign(topic_route_table_, topic, topic_route, topic_route_table_mutex_); } bool ContainsBrokerAddress(const std::string& address); std::shared_ptr<TopicPublishInfo> GetTopicPublishInfo(const std::string& topic) { return MapAccessor::GetOrDefault(topic_publish_info_table_, topic, nullptr, topic_publish_info_table_mutex_); } void PutTopicPublishInfo(const std::string& topic, std::shared_ptr<TopicPublishInfo> publish_info) { MapAccessor::InsertOrAssign(topic_publish_info_table_, topic, std::move(publish_info), topic_publish_info_table_mutex_); } std::set<std::string> TopicInPublish() { return MapAccessor::KeySet(topic_publish_info_table_, topic_publish_info_table_mutex_); } std::shared_ptr<TopicSubscribeInfo> GetTopicSubscribeInfo(const std::string& topic) { return MapAccessor::GetOrDefault(topic_subscribe_info_table_, topic, nullptr, topic_subescribe_info_table_mutex_); } void PutTopicSubscribeInfo(const std::string& topic, std::shared_ptr<TopicSubscribeInfo> subscribe_info) { MapAccessor::InsertOrAssign(topic_subscribe_info_table_, topic, std::move(subscribe_info), topic_subescribe_info_table_mutex_); } private: // topic -> TopicRouteData std::map<std::string, std::shared_ptr<TopicRouteData>> topic_route_table_; std::mutex topic_route_table_mutex_; // topic -> TopicPublishInfo std::map<std::string, std::shared_ptr<TopicPublishInfo>> topic_publish_info_table_; std::mutex topic_publish_info_table_mutex_; // topic -> TopicSubscribeInfo std::map<std::string, std::shared_ptr<TopicSubscribeInfo>> topic_subscribe_info_table_; std::mutex topic_subescribe_info_table_mutex_; }; } // namespace rocketmq #endif // ROCKETMQ_ROUTE_TOPICROUTEMANAGER_HPP_
39.352941
118
0.76562
ifplusor
fd541295ab267af73a7a4def844271f4430b93ad
6,306
cpp
C++
src/cpp/constraints.cpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
6
2020-10-29T10:20:48.000Z
2022-03-31T13:39:47.000Z
src/cpp/constraints.cpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
1
2021-11-25T13:15:11.000Z
2021-12-08T09:23:24.000Z
src/cpp/constraints.cpp
laudv/veritas
ba1761cc333b08b4381afa720b24ace065a9f106
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 DTAI Research Group - KU Leuven. * License: Apache License 2.0 * Author: Laurens Devos */ #include "constraints.hpp" namespace veritas { UpdateResult Add::update(Domain& self, Domain& ldom, Domain& rdom) { std::cout << "ADD0 " << "self: " << self << ", l: " << ldom << ", r: " << rdom << std::endl; // self = ldom + rdom FloatT new_self_lo, new_self_hi; FloatT new_ldom_lo, new_ldom_hi; FloatT new_rdom_lo, new_rdom_hi; new_self_lo = std::max(self.lo, ldom.lo+rdom.lo); new_self_hi = std::min(self.hi, ldom.hi+rdom.hi); new_ldom_lo = std::max(ldom.lo, self.lo-rdom.hi); new_ldom_hi = std::min(ldom.hi, self.hi-rdom.lo); new_rdom_lo = std::max(rdom.lo, self.lo-ldom.hi), new_rdom_hi = std::min(rdom.hi, self.hi-ldom.lo); if (new_self_lo > new_self_hi || new_ldom_lo > new_ldom_hi || new_rdom_lo > new_rdom_hi) return INVALID; UpdateResult res = static_cast<UpdateResult>( !(self.lo == new_self_lo && self.hi == new_self_hi && ldom.lo == new_ldom_lo && ldom.hi == new_ldom_hi && rdom.lo == new_rdom_lo && rdom.hi == new_rdom_hi)); self = {new_self_lo, new_self_hi}; ldom = {new_ldom_lo, new_ldom_hi}; rdom = {new_rdom_lo, new_rdom_hi}; std::cout << "ADD1 " << "self: " << self << ", l: " << ldom << ", r: " << rdom << " res=" << res << std::endl; return res; } UpdateResult Eq::update(Domain& ldom, Domain& rdom) { // L == R -> share the same domain FloatT new_lo = std::max(ldom.lo, rdom.lo); FloatT new_hi = std::min(ldom.hi, rdom.hi); //std::cout << "EQ ldom " << ldom << ", rdom " << rdom << std::endl; if (new_lo > new_hi) return INVALID; UpdateResult res = static_cast<UpdateResult>( (ldom.lo != new_lo || ldom.hi != new_hi) || (rdom.lo != new_lo || rdom.hi != new_hi)); ldom.lo = new_lo; rdom.lo = new_lo; ldom.hi = new_hi; rdom.hi = new_hi; //std::cout << "-- ldom " << ldom << ", rdom " << rdom << std::endl; return res; } UpdateResult LtEq::update(Domain& ldom, Domain& rdom) { // LEFT <= RIGHT FloatT new_lo = std::max(ldom.lo, rdom.lo); FloatT new_hi = std::min(ldom.hi, rdom.hi); //std::cout << "LTEQ ldom " << ldom << ", rdom " << rdom << std::endl; if (ldom.lo > new_hi || new_lo > rdom.hi) return INVALID; UpdateResult res = static_cast<UpdateResult>( (ldom.lo != new_lo || ldom.hi != new_hi) || (rdom.lo != new_lo || rdom.hi != new_hi)); ldom = {ldom.lo, new_hi}; rdom = {new_lo, rdom.hi}; //std::cout << "---- ldom " << ldom << ", rdom " << rdom << std::endl; return res; } ConstraintPropagator::ConstraintPropagator(int num_features) : num_features_(num_features) { for (int i = 0; i < num_features_; ++i) { AnyExpr e; e.tag = AnyExpr::VAR; e.parent = -1; exprs_.push_back(e); } } void ConstraintPropagator::copy_from_box(const Box& box) { size_t j = 0; for (int i = 0; i < num_features_; ++i) // box is sorted by item.feat_id { AnyExpr& e = exprs_[i]; e.tag = AnyExpr::VAR; e.dom = {}; if (j < box.size() && box[j].feat_id == i) { e.dom = box[j].domain; ++j; } } for (size_t i = num_features_; i < exprs_.size(); ++i) { AnyExpr& expr = exprs_[i]; if (expr.tag == AnyExpr::CONST) expr.dom = {expr.constant.value, expr.constant.value}; else expr.dom = {}; // reset domain of non-consts } } void ConstraintPropagator::copy_to_box(Box& box) const { size_t j = 0; size_t sz = box.size(); for (int i = 0; i < num_features_; ++i) { if (j < sz && box[j].feat_id == i) { box[j].domain = exprs_[i].dom; ++j; } else if (!exprs_[i].dom.is_everything()) { box.push_back({i, exprs_[i].dom}); // add new domain to box } } // sort newly added domain ids, if any if (sz < box.size()) { std::sort(box.begin(), box.end(), [](const DomainPair& a, const DomainPair& b) { return a.feat_id < b.feat_id; }); } } UpdateResult ConstraintPropagator::aggregate_update_result(std::initializer_list<UpdateResult> l) { UpdateResult res = UNCHANGED; for (auto r : l) { if (r == INVALID) return INVALID; if (r == UPDATED) res = UPDATED; }; return res; } void ConstraintPropagator::eq(int left, int right) { AnyComp c; c.left = left; c.right = right; c.comp.eq = {}; c.tag = AnyComp::EQ; comps_.push_back(c); } void ConstraintPropagator::lteq(int left, int right) { AnyComp c; c.left = left; c.right = right; c.comp.lteq = {}; c.tag = AnyComp::LTEQ; comps_.push_back(c); } int ConstraintPropagator::constant(FloatT value) { AnyExpr e; e.tag = AnyExpr::CONST; e.constant = {value}; e.parent = -1; exprs_.push_back(e); return exprs_.size() - 1; } int ConstraintPropagator::add(int left, int right) { AnyExpr e; e.tag = AnyExpr::ADD; e.add = {left, right}; e.parent = -1; int id = exprs_.size(); exprs_.push_back(e); exprs_.at(left).parent = id; exprs_.at(right).parent = id; return id; } } // namespace veritas
27.417391
88
0.479385
laudv
fd54eedc8a24099c00852574b67811e86b32aabf
54,516
cpp
C++
airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp
docquantum/airavata
4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c
[ "ECL-2.0", "Apache-2.0" ]
74
2015-04-10T02:57:26.000Z
2022-02-28T16:10:03.000Z
airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp
docquantum/airavata
4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c
[ "ECL-2.0", "Apache-2.0" ]
126
2015-04-26T02:55:26.000Z
2022-02-16T22:43:28.000Z
airavata-api/airavata-client-sdks/airavata-cpp-sdk/src/main/resources/lib/airavata/group_resource_profile_model_types.cpp
docquantum/airavata
4ec5fa0aab1b75ca1e98a16648c57cd8abdb4b9c
[ "ECL-2.0", "Apache-2.0" ]
163
2015-01-22T14:05:24.000Z
2022-03-17T12:24:34.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. */ /** * Autogenerated by Thrift Compiler (0.10.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #include "group_resource_profile_model_types.h" #include <algorithm> #include <ostream> #include <thrift/TToString.h> namespace apache { namespace airavata { namespace model { namespace appcatalog { namespace groupresourceprofile { GroupAccountSSHProvisionerConfig::~GroupAccountSSHProvisionerConfig() throw() { } void GroupAccountSSHProvisionerConfig::__set_resourceId(const std::string& val) { this->resourceId = val; } void GroupAccountSSHProvisionerConfig::__set_groupResourceProfileId(const std::string& val) { this->groupResourceProfileId = val; } void GroupAccountSSHProvisionerConfig::__set_configName(const std::string& val) { this->configName = val; } void GroupAccountSSHProvisionerConfig::__set_configValue(const std::string& val) { this->configValue = val; __isset.configValue = true; } uint32_t GroupAccountSSHProvisionerConfig::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_resourceId = false; bool isset_groupResourceProfileId = false; bool isset_configName = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->resourceId); isset_resourceId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileId); isset_groupResourceProfileId = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->configName); isset_configName = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->configValue); this->__isset.configValue = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_resourceId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_groupResourceProfileId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_configName) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t GroupAccountSSHProvisionerConfig::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("GroupAccountSSHProvisionerConfig"); xfer += oprot->writeFieldBegin("resourceId", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->resourceId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->groupResourceProfileId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("configName", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->configName); xfer += oprot->writeFieldEnd(); if (this->__isset.configValue) { xfer += oprot->writeFieldBegin("configValue", ::apache::thrift::protocol::T_STRING, 4); xfer += oprot->writeString(this->configValue); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(GroupAccountSSHProvisionerConfig &a, GroupAccountSSHProvisionerConfig &b) { using ::std::swap; swap(a.resourceId, b.resourceId); swap(a.groupResourceProfileId, b.groupResourceProfileId); swap(a.configName, b.configName); swap(a.configValue, b.configValue); swap(a.__isset, b.__isset); } GroupAccountSSHProvisionerConfig::GroupAccountSSHProvisionerConfig(const GroupAccountSSHProvisionerConfig& other0) { resourceId = other0.resourceId; groupResourceProfileId = other0.groupResourceProfileId; configName = other0.configName; configValue = other0.configValue; __isset = other0.__isset; } GroupAccountSSHProvisionerConfig& GroupAccountSSHProvisionerConfig::operator=(const GroupAccountSSHProvisionerConfig& other1) { resourceId = other1.resourceId; groupResourceProfileId = other1.groupResourceProfileId; configName = other1.configName; configValue = other1.configValue; __isset = other1.__isset; return *this; } void GroupAccountSSHProvisionerConfig::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "GroupAccountSSHProvisionerConfig("; out << "resourceId=" << to_string(resourceId); out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId); out << ", " << "configName=" << to_string(configName); out << ", " << "configValue="; (__isset.configValue ? (out << to_string(configValue)) : (out << "<null>")); out << ")"; } GroupComputeResourcePreference::~GroupComputeResourcePreference() throw() { } void GroupComputeResourcePreference::__set_computeResourceId(const std::string& val) { this->computeResourceId = val; } void GroupComputeResourcePreference::__set_groupResourceProfileId(const std::string& val) { this->groupResourceProfileId = val; } void GroupComputeResourcePreference::__set_overridebyAiravata(const bool val) { this->overridebyAiravata = val; } void GroupComputeResourcePreference::__set_loginUserName(const std::string& val) { this->loginUserName = val; __isset.loginUserName = true; } void GroupComputeResourcePreference::__set_preferredJobSubmissionProtocol(const ::apache::airavata::model::appcatalog::computeresource::JobSubmissionProtocol::type val) { this->preferredJobSubmissionProtocol = val; __isset.preferredJobSubmissionProtocol = true; } void GroupComputeResourcePreference::__set_preferredDataMovementProtocol(const ::apache::airavata::model::data::movement::DataMovementProtocol::type val) { this->preferredDataMovementProtocol = val; __isset.preferredDataMovementProtocol = true; } void GroupComputeResourcePreference::__set_preferredBatchQueue(const std::string& val) { this->preferredBatchQueue = val; __isset.preferredBatchQueue = true; } void GroupComputeResourcePreference::__set_scratchLocation(const std::string& val) { this->scratchLocation = val; __isset.scratchLocation = true; } void GroupComputeResourcePreference::__set_allocationProjectNumber(const std::string& val) { this->allocationProjectNumber = val; __isset.allocationProjectNumber = true; } void GroupComputeResourcePreference::__set_resourceSpecificCredentialStoreToken(const std::string& val) { this->resourceSpecificCredentialStoreToken = val; __isset.resourceSpecificCredentialStoreToken = true; } void GroupComputeResourcePreference::__set_usageReportingGatewayId(const std::string& val) { this->usageReportingGatewayId = val; __isset.usageReportingGatewayId = true; } void GroupComputeResourcePreference::__set_qualityOfService(const std::string& val) { this->qualityOfService = val; __isset.qualityOfService = true; } void GroupComputeResourcePreference::__set_reservation(const std::string& val) { this->reservation = val; __isset.reservation = true; } void GroupComputeResourcePreference::__set_reservationStartTime(const int64_t val) { this->reservationStartTime = val; __isset.reservationStartTime = true; } void GroupComputeResourcePreference::__set_reservationEndTime(const int64_t val) { this->reservationEndTime = val; __isset.reservationEndTime = true; } void GroupComputeResourcePreference::__set_sshAccountProvisioner(const std::string& val) { this->sshAccountProvisioner = val; __isset.sshAccountProvisioner = true; } void GroupComputeResourcePreference::__set_groupSSHAccountProvisionerConfigs(const std::vector<GroupAccountSSHProvisionerConfig> & val) { this->groupSSHAccountProvisionerConfigs = val; __isset.groupSSHAccountProvisionerConfigs = true; } void GroupComputeResourcePreference::__set_sshAccountProvisionerAdditionalInfo(const std::string& val) { this->sshAccountProvisionerAdditionalInfo = val; __isset.sshAccountProvisionerAdditionalInfo = true; } uint32_t GroupComputeResourcePreference::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_computeResourceId = false; bool isset_groupResourceProfileId = false; bool isset_overridebyAiravata = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->computeResourceId); isset_computeResourceId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileId); isset_groupResourceProfileId = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_BOOL) { xfer += iprot->readBool(this->overridebyAiravata); isset_overridebyAiravata = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->loginUserName); this->__isset.loginUserName = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast2; xfer += iprot->readI32(ecast2); this->preferredJobSubmissionProtocol = ( ::apache::airavata::model::appcatalog::computeresource::JobSubmissionProtocol::type)ecast2; this->__isset.preferredJobSubmissionProtocol = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_I32) { int32_t ecast3; xfer += iprot->readI32(ecast3); this->preferredDataMovementProtocol = ( ::apache::airavata::model::data::movement::DataMovementProtocol::type)ecast3; this->__isset.preferredDataMovementProtocol = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->preferredBatchQueue); this->__isset.preferredBatchQueue = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->scratchLocation); this->__isset.scratchLocation = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->allocationProjectNumber); this->__isset.allocationProjectNumber = true; } else { xfer += iprot->skip(ftype); } break; case 10: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->resourceSpecificCredentialStoreToken); this->__isset.resourceSpecificCredentialStoreToken = true; } else { xfer += iprot->skip(ftype); } break; case 11: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->usageReportingGatewayId); this->__isset.usageReportingGatewayId = true; } else { xfer += iprot->skip(ftype); } break; case 12: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->qualityOfService); this->__isset.qualityOfService = true; } else { xfer += iprot->skip(ftype); } break; case 13: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->reservation); this->__isset.reservation = true; } else { xfer += iprot->skip(ftype); } break; case 14: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->reservationStartTime); this->__isset.reservationStartTime = true; } else { xfer += iprot->skip(ftype); } break; case 15: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->reservationEndTime); this->__isset.reservationEndTime = true; } else { xfer += iprot->skip(ftype); } break; case 16: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->sshAccountProvisioner); this->__isset.sshAccountProvisioner = true; } else { xfer += iprot->skip(ftype); } break; case 17: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->groupSSHAccountProvisionerConfigs.clear(); uint32_t _size4; ::apache::thrift::protocol::TType _etype7; xfer += iprot->readListBegin(_etype7, _size4); this->groupSSHAccountProvisionerConfigs.resize(_size4); uint32_t _i8; for (_i8 = 0; _i8 < _size4; ++_i8) { xfer += this->groupSSHAccountProvisionerConfigs[_i8].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.groupSSHAccountProvisionerConfigs = true; } else { xfer += iprot->skip(ftype); } break; case 18: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->sshAccountProvisionerAdditionalInfo); this->__isset.sshAccountProvisionerAdditionalInfo = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_computeResourceId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_groupResourceProfileId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_overridebyAiravata) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t GroupComputeResourcePreference::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("GroupComputeResourcePreference"); xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->computeResourceId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->groupResourceProfileId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("overridebyAiravata", ::apache::thrift::protocol::T_BOOL, 3); xfer += oprot->writeBool(this->overridebyAiravata); xfer += oprot->writeFieldEnd(); if (this->__isset.loginUserName) { xfer += oprot->writeFieldBegin("loginUserName", ::apache::thrift::protocol::T_STRING, 4); xfer += oprot->writeString(this->loginUserName); xfer += oprot->writeFieldEnd(); } if (this->__isset.preferredJobSubmissionProtocol) { xfer += oprot->writeFieldBegin("preferredJobSubmissionProtocol", ::apache::thrift::protocol::T_I32, 5); xfer += oprot->writeI32((int32_t)this->preferredJobSubmissionProtocol); xfer += oprot->writeFieldEnd(); } if (this->__isset.preferredDataMovementProtocol) { xfer += oprot->writeFieldBegin("preferredDataMovementProtocol", ::apache::thrift::protocol::T_I32, 6); xfer += oprot->writeI32((int32_t)this->preferredDataMovementProtocol); xfer += oprot->writeFieldEnd(); } if (this->__isset.preferredBatchQueue) { xfer += oprot->writeFieldBegin("preferredBatchQueue", ::apache::thrift::protocol::T_STRING, 7); xfer += oprot->writeString(this->preferredBatchQueue); xfer += oprot->writeFieldEnd(); } if (this->__isset.scratchLocation) { xfer += oprot->writeFieldBegin("scratchLocation", ::apache::thrift::protocol::T_STRING, 8); xfer += oprot->writeString(this->scratchLocation); xfer += oprot->writeFieldEnd(); } if (this->__isset.allocationProjectNumber) { xfer += oprot->writeFieldBegin("allocationProjectNumber", ::apache::thrift::protocol::T_STRING, 9); xfer += oprot->writeString(this->allocationProjectNumber); xfer += oprot->writeFieldEnd(); } if (this->__isset.resourceSpecificCredentialStoreToken) { xfer += oprot->writeFieldBegin("resourceSpecificCredentialStoreToken", ::apache::thrift::protocol::T_STRING, 10); xfer += oprot->writeString(this->resourceSpecificCredentialStoreToken); xfer += oprot->writeFieldEnd(); } if (this->__isset.usageReportingGatewayId) { xfer += oprot->writeFieldBegin("usageReportingGatewayId", ::apache::thrift::protocol::T_STRING, 11); xfer += oprot->writeString(this->usageReportingGatewayId); xfer += oprot->writeFieldEnd(); } if (this->__isset.qualityOfService) { xfer += oprot->writeFieldBegin("qualityOfService", ::apache::thrift::protocol::T_STRING, 12); xfer += oprot->writeString(this->qualityOfService); xfer += oprot->writeFieldEnd(); } if (this->__isset.reservation) { xfer += oprot->writeFieldBegin("reservation", ::apache::thrift::protocol::T_STRING, 13); xfer += oprot->writeString(this->reservation); xfer += oprot->writeFieldEnd(); } if (this->__isset.reservationStartTime) { xfer += oprot->writeFieldBegin("reservationStartTime", ::apache::thrift::protocol::T_I64, 14); xfer += oprot->writeI64(this->reservationStartTime); xfer += oprot->writeFieldEnd(); } if (this->__isset.reservationEndTime) { xfer += oprot->writeFieldBegin("reservationEndTime", ::apache::thrift::protocol::T_I64, 15); xfer += oprot->writeI64(this->reservationEndTime); xfer += oprot->writeFieldEnd(); } if (this->__isset.sshAccountProvisioner) { xfer += oprot->writeFieldBegin("sshAccountProvisioner", ::apache::thrift::protocol::T_STRING, 16); xfer += oprot->writeString(this->sshAccountProvisioner); xfer += oprot->writeFieldEnd(); } if (this->__isset.groupSSHAccountProvisionerConfigs) { xfer += oprot->writeFieldBegin("groupSSHAccountProvisionerConfigs", ::apache::thrift::protocol::T_LIST, 17); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->groupSSHAccountProvisionerConfigs.size())); std::vector<GroupAccountSSHProvisionerConfig> ::const_iterator _iter9; for (_iter9 = this->groupSSHAccountProvisionerConfigs.begin(); _iter9 != this->groupSSHAccountProvisionerConfigs.end(); ++_iter9) { xfer += (*_iter9).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.sshAccountProvisionerAdditionalInfo) { xfer += oprot->writeFieldBegin("sshAccountProvisionerAdditionalInfo", ::apache::thrift::protocol::T_STRING, 18); xfer += oprot->writeString(this->sshAccountProvisionerAdditionalInfo); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(GroupComputeResourcePreference &a, GroupComputeResourcePreference &b) { using ::std::swap; swap(a.computeResourceId, b.computeResourceId); swap(a.groupResourceProfileId, b.groupResourceProfileId); swap(a.overridebyAiravata, b.overridebyAiravata); swap(a.loginUserName, b.loginUserName); swap(a.preferredJobSubmissionProtocol, b.preferredJobSubmissionProtocol); swap(a.preferredDataMovementProtocol, b.preferredDataMovementProtocol); swap(a.preferredBatchQueue, b.preferredBatchQueue); swap(a.scratchLocation, b.scratchLocation); swap(a.allocationProjectNumber, b.allocationProjectNumber); swap(a.resourceSpecificCredentialStoreToken, b.resourceSpecificCredentialStoreToken); swap(a.usageReportingGatewayId, b.usageReportingGatewayId); swap(a.qualityOfService, b.qualityOfService); swap(a.reservation, b.reservation); swap(a.reservationStartTime, b.reservationStartTime); swap(a.reservationEndTime, b.reservationEndTime); swap(a.sshAccountProvisioner, b.sshAccountProvisioner); swap(a.groupSSHAccountProvisionerConfigs, b.groupSSHAccountProvisionerConfigs); swap(a.sshAccountProvisionerAdditionalInfo, b.sshAccountProvisionerAdditionalInfo); swap(a.__isset, b.__isset); } GroupComputeResourcePreference::GroupComputeResourcePreference(const GroupComputeResourcePreference& other10) { computeResourceId = other10.computeResourceId; groupResourceProfileId = other10.groupResourceProfileId; overridebyAiravata = other10.overridebyAiravata; loginUserName = other10.loginUserName; preferredJobSubmissionProtocol = other10.preferredJobSubmissionProtocol; preferredDataMovementProtocol = other10.preferredDataMovementProtocol; preferredBatchQueue = other10.preferredBatchQueue; scratchLocation = other10.scratchLocation; allocationProjectNumber = other10.allocationProjectNumber; resourceSpecificCredentialStoreToken = other10.resourceSpecificCredentialStoreToken; usageReportingGatewayId = other10.usageReportingGatewayId; qualityOfService = other10.qualityOfService; reservation = other10.reservation; reservationStartTime = other10.reservationStartTime; reservationEndTime = other10.reservationEndTime; sshAccountProvisioner = other10.sshAccountProvisioner; groupSSHAccountProvisionerConfigs = other10.groupSSHAccountProvisionerConfigs; sshAccountProvisionerAdditionalInfo = other10.sshAccountProvisionerAdditionalInfo; __isset = other10.__isset; } GroupComputeResourcePreference& GroupComputeResourcePreference::operator=(const GroupComputeResourcePreference& other11) { computeResourceId = other11.computeResourceId; groupResourceProfileId = other11.groupResourceProfileId; overridebyAiravata = other11.overridebyAiravata; loginUserName = other11.loginUserName; preferredJobSubmissionProtocol = other11.preferredJobSubmissionProtocol; preferredDataMovementProtocol = other11.preferredDataMovementProtocol; preferredBatchQueue = other11.preferredBatchQueue; scratchLocation = other11.scratchLocation; allocationProjectNumber = other11.allocationProjectNumber; resourceSpecificCredentialStoreToken = other11.resourceSpecificCredentialStoreToken; usageReportingGatewayId = other11.usageReportingGatewayId; qualityOfService = other11.qualityOfService; reservation = other11.reservation; reservationStartTime = other11.reservationStartTime; reservationEndTime = other11.reservationEndTime; sshAccountProvisioner = other11.sshAccountProvisioner; groupSSHAccountProvisionerConfigs = other11.groupSSHAccountProvisionerConfigs; sshAccountProvisionerAdditionalInfo = other11.sshAccountProvisionerAdditionalInfo; __isset = other11.__isset; return *this; } void GroupComputeResourcePreference::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "GroupComputeResourcePreference("; out << "computeResourceId=" << to_string(computeResourceId); out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId); out << ", " << "overridebyAiravata=" << to_string(overridebyAiravata); out << ", " << "loginUserName="; (__isset.loginUserName ? (out << to_string(loginUserName)) : (out << "<null>")); out << ", " << "preferredJobSubmissionProtocol="; (__isset.preferredJobSubmissionProtocol ? (out << to_string(preferredJobSubmissionProtocol)) : (out << "<null>")); out << ", " << "preferredDataMovementProtocol="; (__isset.preferredDataMovementProtocol ? (out << to_string(preferredDataMovementProtocol)) : (out << "<null>")); out << ", " << "preferredBatchQueue="; (__isset.preferredBatchQueue ? (out << to_string(preferredBatchQueue)) : (out << "<null>")); out << ", " << "scratchLocation="; (__isset.scratchLocation ? (out << to_string(scratchLocation)) : (out << "<null>")); out << ", " << "allocationProjectNumber="; (__isset.allocationProjectNumber ? (out << to_string(allocationProjectNumber)) : (out << "<null>")); out << ", " << "resourceSpecificCredentialStoreToken="; (__isset.resourceSpecificCredentialStoreToken ? (out << to_string(resourceSpecificCredentialStoreToken)) : (out << "<null>")); out << ", " << "usageReportingGatewayId="; (__isset.usageReportingGatewayId ? (out << to_string(usageReportingGatewayId)) : (out << "<null>")); out << ", " << "qualityOfService="; (__isset.qualityOfService ? (out << to_string(qualityOfService)) : (out << "<null>")); out << ", " << "reservation="; (__isset.reservation ? (out << to_string(reservation)) : (out << "<null>")); out << ", " << "reservationStartTime="; (__isset.reservationStartTime ? (out << to_string(reservationStartTime)) : (out << "<null>")); out << ", " << "reservationEndTime="; (__isset.reservationEndTime ? (out << to_string(reservationEndTime)) : (out << "<null>")); out << ", " << "sshAccountProvisioner="; (__isset.sshAccountProvisioner ? (out << to_string(sshAccountProvisioner)) : (out << "<null>")); out << ", " << "groupSSHAccountProvisionerConfigs="; (__isset.groupSSHAccountProvisionerConfigs ? (out << to_string(groupSSHAccountProvisionerConfigs)) : (out << "<null>")); out << ", " << "sshAccountProvisionerAdditionalInfo="; (__isset.sshAccountProvisionerAdditionalInfo ? (out << to_string(sshAccountProvisionerAdditionalInfo)) : (out << "<null>")); out << ")"; } ComputeResourcePolicy::~ComputeResourcePolicy() throw() { } void ComputeResourcePolicy::__set_resourcePolicyId(const std::string& val) { this->resourcePolicyId = val; } void ComputeResourcePolicy::__set_computeResourceId(const std::string& val) { this->computeResourceId = val; } void ComputeResourcePolicy::__set_groupResourceProfileId(const std::string& val) { this->groupResourceProfileId = val; } void ComputeResourcePolicy::__set_allowedBatchQueues(const std::vector<std::string> & val) { this->allowedBatchQueues = val; __isset.allowedBatchQueues = true; } uint32_t ComputeResourcePolicy::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_resourcePolicyId = false; bool isset_computeResourceId = false; bool isset_groupResourceProfileId = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->resourcePolicyId); isset_resourcePolicyId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->computeResourceId); isset_computeResourceId = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileId); isset_groupResourceProfileId = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->allowedBatchQueues.clear(); uint32_t _size12; ::apache::thrift::protocol::TType _etype15; xfer += iprot->readListBegin(_etype15, _size12); this->allowedBatchQueues.resize(_size12); uint32_t _i16; for (_i16 = 0; _i16 < _size12; ++_i16) { xfer += iprot->readString(this->allowedBatchQueues[_i16]); } xfer += iprot->readListEnd(); } this->__isset.allowedBatchQueues = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_resourcePolicyId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_computeResourceId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_groupResourceProfileId) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t ComputeResourcePolicy::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("ComputeResourcePolicy"); xfer += oprot->writeFieldBegin("resourcePolicyId", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->resourcePolicyId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->computeResourceId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->groupResourceProfileId); xfer += oprot->writeFieldEnd(); if (this->__isset.allowedBatchQueues) { xfer += oprot->writeFieldBegin("allowedBatchQueues", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRING, static_cast<uint32_t>(this->allowedBatchQueues.size())); std::vector<std::string> ::const_iterator _iter17; for (_iter17 = this->allowedBatchQueues.begin(); _iter17 != this->allowedBatchQueues.end(); ++_iter17) { xfer += oprot->writeString((*_iter17)); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(ComputeResourcePolicy &a, ComputeResourcePolicy &b) { using ::std::swap; swap(a.resourcePolicyId, b.resourcePolicyId); swap(a.computeResourceId, b.computeResourceId); swap(a.groupResourceProfileId, b.groupResourceProfileId); swap(a.allowedBatchQueues, b.allowedBatchQueues); swap(a.__isset, b.__isset); } ComputeResourcePolicy::ComputeResourcePolicy(const ComputeResourcePolicy& other18) { resourcePolicyId = other18.resourcePolicyId; computeResourceId = other18.computeResourceId; groupResourceProfileId = other18.groupResourceProfileId; allowedBatchQueues = other18.allowedBatchQueues; __isset = other18.__isset; } ComputeResourcePolicy& ComputeResourcePolicy::operator=(const ComputeResourcePolicy& other19) { resourcePolicyId = other19.resourcePolicyId; computeResourceId = other19.computeResourceId; groupResourceProfileId = other19.groupResourceProfileId; allowedBatchQueues = other19.allowedBatchQueues; __isset = other19.__isset; return *this; } void ComputeResourcePolicy::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "ComputeResourcePolicy("; out << "resourcePolicyId=" << to_string(resourcePolicyId); out << ", " << "computeResourceId=" << to_string(computeResourceId); out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId); out << ", " << "allowedBatchQueues="; (__isset.allowedBatchQueues ? (out << to_string(allowedBatchQueues)) : (out << "<null>")); out << ")"; } BatchQueueResourcePolicy::~BatchQueueResourcePolicy() throw() { } void BatchQueueResourcePolicy::__set_resourcePolicyId(const std::string& val) { this->resourcePolicyId = val; } void BatchQueueResourcePolicy::__set_computeResourceId(const std::string& val) { this->computeResourceId = val; } void BatchQueueResourcePolicy::__set_groupResourceProfileId(const std::string& val) { this->groupResourceProfileId = val; } void BatchQueueResourcePolicy::__set_queuename(const std::string& val) { this->queuename = val; __isset.queuename = true; } void BatchQueueResourcePolicy::__set_maxAllowedNodes(const int32_t val) { this->maxAllowedNodes = val; __isset.maxAllowedNodes = true; } void BatchQueueResourcePolicy::__set_maxAllowedCores(const int32_t val) { this->maxAllowedCores = val; __isset.maxAllowedCores = true; } void BatchQueueResourcePolicy::__set_maxAllowedWalltime(const int32_t val) { this->maxAllowedWalltime = val; __isset.maxAllowedWalltime = true; } uint32_t BatchQueueResourcePolicy::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_resourcePolicyId = false; bool isset_computeResourceId = false; bool isset_groupResourceProfileId = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->resourcePolicyId); isset_resourcePolicyId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->computeResourceId); isset_computeResourceId = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileId); isset_groupResourceProfileId = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->queuename); this->__isset.queuename = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->maxAllowedNodes); this->__isset.maxAllowedNodes = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->maxAllowedCores); this->__isset.maxAllowedCores = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_I32) { xfer += iprot->readI32(this->maxAllowedWalltime); this->__isset.maxAllowedWalltime = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_resourcePolicyId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_computeResourceId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_groupResourceProfileId) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t BatchQueueResourcePolicy::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("BatchQueueResourcePolicy"); xfer += oprot->writeFieldBegin("resourcePolicyId", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->resourcePolicyId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("computeResourceId", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->computeResourceId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->groupResourceProfileId); xfer += oprot->writeFieldEnd(); if (this->__isset.queuename) { xfer += oprot->writeFieldBegin("queuename", ::apache::thrift::protocol::T_STRING, 4); xfer += oprot->writeString(this->queuename); xfer += oprot->writeFieldEnd(); } if (this->__isset.maxAllowedNodes) { xfer += oprot->writeFieldBegin("maxAllowedNodes", ::apache::thrift::protocol::T_I32, 5); xfer += oprot->writeI32(this->maxAllowedNodes); xfer += oprot->writeFieldEnd(); } if (this->__isset.maxAllowedCores) { xfer += oprot->writeFieldBegin("maxAllowedCores", ::apache::thrift::protocol::T_I32, 6); xfer += oprot->writeI32(this->maxAllowedCores); xfer += oprot->writeFieldEnd(); } if (this->__isset.maxAllowedWalltime) { xfer += oprot->writeFieldBegin("maxAllowedWalltime", ::apache::thrift::protocol::T_I32, 7); xfer += oprot->writeI32(this->maxAllowedWalltime); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(BatchQueueResourcePolicy &a, BatchQueueResourcePolicy &b) { using ::std::swap; swap(a.resourcePolicyId, b.resourcePolicyId); swap(a.computeResourceId, b.computeResourceId); swap(a.groupResourceProfileId, b.groupResourceProfileId); swap(a.queuename, b.queuename); swap(a.maxAllowedNodes, b.maxAllowedNodes); swap(a.maxAllowedCores, b.maxAllowedCores); swap(a.maxAllowedWalltime, b.maxAllowedWalltime); swap(a.__isset, b.__isset); } BatchQueueResourcePolicy::BatchQueueResourcePolicy(const BatchQueueResourcePolicy& other20) { resourcePolicyId = other20.resourcePolicyId; computeResourceId = other20.computeResourceId; groupResourceProfileId = other20.groupResourceProfileId; queuename = other20.queuename; maxAllowedNodes = other20.maxAllowedNodes; maxAllowedCores = other20.maxAllowedCores; maxAllowedWalltime = other20.maxAllowedWalltime; __isset = other20.__isset; } BatchQueueResourcePolicy& BatchQueueResourcePolicy::operator=(const BatchQueueResourcePolicy& other21) { resourcePolicyId = other21.resourcePolicyId; computeResourceId = other21.computeResourceId; groupResourceProfileId = other21.groupResourceProfileId; queuename = other21.queuename; maxAllowedNodes = other21.maxAllowedNodes; maxAllowedCores = other21.maxAllowedCores; maxAllowedWalltime = other21.maxAllowedWalltime; __isset = other21.__isset; return *this; } void BatchQueueResourcePolicy::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "BatchQueueResourcePolicy("; out << "resourcePolicyId=" << to_string(resourcePolicyId); out << ", " << "computeResourceId=" << to_string(computeResourceId); out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId); out << ", " << "queuename="; (__isset.queuename ? (out << to_string(queuename)) : (out << "<null>")); out << ", " << "maxAllowedNodes="; (__isset.maxAllowedNodes ? (out << to_string(maxAllowedNodes)) : (out << "<null>")); out << ", " << "maxAllowedCores="; (__isset.maxAllowedCores ? (out << to_string(maxAllowedCores)) : (out << "<null>")); out << ", " << "maxAllowedWalltime="; (__isset.maxAllowedWalltime ? (out << to_string(maxAllowedWalltime)) : (out << "<null>")); out << ")"; } GroupResourceProfile::~GroupResourceProfile() throw() { } void GroupResourceProfile::__set_gatewayId(const std::string& val) { this->gatewayId = val; } void GroupResourceProfile::__set_groupResourceProfileId(const std::string& val) { this->groupResourceProfileId = val; } void GroupResourceProfile::__set_groupResourceProfileName(const std::string& val) { this->groupResourceProfileName = val; __isset.groupResourceProfileName = true; } void GroupResourceProfile::__set_computePreferences(const std::vector<GroupComputeResourcePreference> & val) { this->computePreferences = val; __isset.computePreferences = true; } void GroupResourceProfile::__set_computeResourcePolicies(const std::vector<ComputeResourcePolicy> & val) { this->computeResourcePolicies = val; __isset.computeResourcePolicies = true; } void GroupResourceProfile::__set_batchQueueResourcePolicies(const std::vector<BatchQueueResourcePolicy> & val) { this->batchQueueResourcePolicies = val; __isset.batchQueueResourcePolicies = true; } void GroupResourceProfile::__set_creationTime(const int64_t val) { this->creationTime = val; __isset.creationTime = true; } void GroupResourceProfile::__set_updatedTime(const int64_t val) { this->updatedTime = val; __isset.updatedTime = true; } void GroupResourceProfile::__set_defaultCredentialStoreToken(const std::string& val) { this->defaultCredentialStoreToken = val; __isset.defaultCredentialStoreToken = true; } uint32_t GroupResourceProfile::read(::apache::thrift::protocol::TProtocol* iprot) { apache::thrift::protocol::TInputRecursionTracker tracker(*iprot); uint32_t xfer = 0; std::string fname; ::apache::thrift::protocol::TType ftype; int16_t fid; xfer += iprot->readStructBegin(fname); using ::apache::thrift::protocol::TProtocolException; bool isset_gatewayId = false; bool isset_groupResourceProfileId = false; while (true) { xfer += iprot->readFieldBegin(fname, ftype, fid); if (ftype == ::apache::thrift::protocol::T_STOP) { break; } switch (fid) { case 1: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->gatewayId); isset_gatewayId = true; } else { xfer += iprot->skip(ftype); } break; case 2: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileId); isset_groupResourceProfileId = true; } else { xfer += iprot->skip(ftype); } break; case 3: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->groupResourceProfileName); this->__isset.groupResourceProfileName = true; } else { xfer += iprot->skip(ftype); } break; case 4: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->computePreferences.clear(); uint32_t _size22; ::apache::thrift::protocol::TType _etype25; xfer += iprot->readListBegin(_etype25, _size22); this->computePreferences.resize(_size22); uint32_t _i26; for (_i26 = 0; _i26 < _size22; ++_i26) { xfer += this->computePreferences[_i26].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.computePreferences = true; } else { xfer += iprot->skip(ftype); } break; case 5: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->computeResourcePolicies.clear(); uint32_t _size27; ::apache::thrift::protocol::TType _etype30; xfer += iprot->readListBegin(_etype30, _size27); this->computeResourcePolicies.resize(_size27); uint32_t _i31; for (_i31 = 0; _i31 < _size27; ++_i31) { xfer += this->computeResourcePolicies[_i31].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.computeResourcePolicies = true; } else { xfer += iprot->skip(ftype); } break; case 6: if (ftype == ::apache::thrift::protocol::T_LIST) { { this->batchQueueResourcePolicies.clear(); uint32_t _size32; ::apache::thrift::protocol::TType _etype35; xfer += iprot->readListBegin(_etype35, _size32); this->batchQueueResourcePolicies.resize(_size32); uint32_t _i36; for (_i36 = 0; _i36 < _size32; ++_i36) { xfer += this->batchQueueResourcePolicies[_i36].read(iprot); } xfer += iprot->readListEnd(); } this->__isset.batchQueueResourcePolicies = true; } else { xfer += iprot->skip(ftype); } break; case 7: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->creationTime); this->__isset.creationTime = true; } else { xfer += iprot->skip(ftype); } break; case 8: if (ftype == ::apache::thrift::protocol::T_I64) { xfer += iprot->readI64(this->updatedTime); this->__isset.updatedTime = true; } else { xfer += iprot->skip(ftype); } break; case 9: if (ftype == ::apache::thrift::protocol::T_STRING) { xfer += iprot->readString(this->defaultCredentialStoreToken); this->__isset.defaultCredentialStoreToken = true; } else { xfer += iprot->skip(ftype); } break; default: xfer += iprot->skip(ftype); break; } xfer += iprot->readFieldEnd(); } xfer += iprot->readStructEnd(); if (!isset_gatewayId) throw TProtocolException(TProtocolException::INVALID_DATA); if (!isset_groupResourceProfileId) throw TProtocolException(TProtocolException::INVALID_DATA); return xfer; } uint32_t GroupResourceProfile::write(::apache::thrift::protocol::TProtocol* oprot) const { uint32_t xfer = 0; apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot); xfer += oprot->writeStructBegin("GroupResourceProfile"); xfer += oprot->writeFieldBegin("gatewayId", ::apache::thrift::protocol::T_STRING, 1); xfer += oprot->writeString(this->gatewayId); xfer += oprot->writeFieldEnd(); xfer += oprot->writeFieldBegin("groupResourceProfileId", ::apache::thrift::protocol::T_STRING, 2); xfer += oprot->writeString(this->groupResourceProfileId); xfer += oprot->writeFieldEnd(); if (this->__isset.groupResourceProfileName) { xfer += oprot->writeFieldBegin("groupResourceProfileName", ::apache::thrift::protocol::T_STRING, 3); xfer += oprot->writeString(this->groupResourceProfileName); xfer += oprot->writeFieldEnd(); } if (this->__isset.computePreferences) { xfer += oprot->writeFieldBegin("computePreferences", ::apache::thrift::protocol::T_LIST, 4); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->computePreferences.size())); std::vector<GroupComputeResourcePreference> ::const_iterator _iter37; for (_iter37 = this->computePreferences.begin(); _iter37 != this->computePreferences.end(); ++_iter37) { xfer += (*_iter37).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.computeResourcePolicies) { xfer += oprot->writeFieldBegin("computeResourcePolicies", ::apache::thrift::protocol::T_LIST, 5); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->computeResourcePolicies.size())); std::vector<ComputeResourcePolicy> ::const_iterator _iter38; for (_iter38 = this->computeResourcePolicies.begin(); _iter38 != this->computeResourcePolicies.end(); ++_iter38) { xfer += (*_iter38).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.batchQueueResourcePolicies) { xfer += oprot->writeFieldBegin("batchQueueResourcePolicies", ::apache::thrift::protocol::T_LIST, 6); { xfer += oprot->writeListBegin(::apache::thrift::protocol::T_STRUCT, static_cast<uint32_t>(this->batchQueueResourcePolicies.size())); std::vector<BatchQueueResourcePolicy> ::const_iterator _iter39; for (_iter39 = this->batchQueueResourcePolicies.begin(); _iter39 != this->batchQueueResourcePolicies.end(); ++_iter39) { xfer += (*_iter39).write(oprot); } xfer += oprot->writeListEnd(); } xfer += oprot->writeFieldEnd(); } if (this->__isset.creationTime) { xfer += oprot->writeFieldBegin("creationTime", ::apache::thrift::protocol::T_I64, 7); xfer += oprot->writeI64(this->creationTime); xfer += oprot->writeFieldEnd(); } if (this->__isset.updatedTime) { xfer += oprot->writeFieldBegin("updatedTime", ::apache::thrift::protocol::T_I64, 8); xfer += oprot->writeI64(this->updatedTime); xfer += oprot->writeFieldEnd(); } if (this->__isset.defaultCredentialStoreToken) { xfer += oprot->writeFieldBegin("defaultCredentialStoreToken", ::apache::thrift::protocol::T_STRING, 9); xfer += oprot->writeString(this->defaultCredentialStoreToken); xfer += oprot->writeFieldEnd(); } xfer += oprot->writeFieldStop(); xfer += oprot->writeStructEnd(); return xfer; } void swap(GroupResourceProfile &a, GroupResourceProfile &b) { using ::std::swap; swap(a.gatewayId, b.gatewayId); swap(a.groupResourceProfileId, b.groupResourceProfileId); swap(a.groupResourceProfileName, b.groupResourceProfileName); swap(a.computePreferences, b.computePreferences); swap(a.computeResourcePolicies, b.computeResourcePolicies); swap(a.batchQueueResourcePolicies, b.batchQueueResourcePolicies); swap(a.creationTime, b.creationTime); swap(a.updatedTime, b.updatedTime); swap(a.defaultCredentialStoreToken, b.defaultCredentialStoreToken); swap(a.__isset, b.__isset); } GroupResourceProfile::GroupResourceProfile(const GroupResourceProfile& other40) { gatewayId = other40.gatewayId; groupResourceProfileId = other40.groupResourceProfileId; groupResourceProfileName = other40.groupResourceProfileName; computePreferences = other40.computePreferences; computeResourcePolicies = other40.computeResourcePolicies; batchQueueResourcePolicies = other40.batchQueueResourcePolicies; creationTime = other40.creationTime; updatedTime = other40.updatedTime; defaultCredentialStoreToken = other40.defaultCredentialStoreToken; __isset = other40.__isset; } GroupResourceProfile& GroupResourceProfile::operator=(const GroupResourceProfile& other41) { gatewayId = other41.gatewayId; groupResourceProfileId = other41.groupResourceProfileId; groupResourceProfileName = other41.groupResourceProfileName; computePreferences = other41.computePreferences; computeResourcePolicies = other41.computeResourcePolicies; batchQueueResourcePolicies = other41.batchQueueResourcePolicies; creationTime = other41.creationTime; updatedTime = other41.updatedTime; defaultCredentialStoreToken = other41.defaultCredentialStoreToken; __isset = other41.__isset; return *this; } void GroupResourceProfile::printTo(std::ostream& out) const { using ::apache::thrift::to_string; out << "GroupResourceProfile("; out << "gatewayId=" << to_string(gatewayId); out << ", " << "groupResourceProfileId=" << to_string(groupResourceProfileId); out << ", " << "groupResourceProfileName="; (__isset.groupResourceProfileName ? (out << to_string(groupResourceProfileName)) : (out << "<null>")); out << ", " << "computePreferences="; (__isset.computePreferences ? (out << to_string(computePreferences)) : (out << "<null>")); out << ", " << "computeResourcePolicies="; (__isset.computeResourcePolicies ? (out << to_string(computeResourcePolicies)) : (out << "<null>")); out << ", " << "batchQueueResourcePolicies="; (__isset.batchQueueResourcePolicies ? (out << to_string(batchQueueResourcePolicies)) : (out << "<null>")); out << ", " << "creationTime="; (__isset.creationTime ? (out << to_string(creationTime)) : (out << "<null>")); out << ", " << "updatedTime="; (__isset.updatedTime ? (out << to_string(updatedTime)) : (out << "<null>")); out << ", " << "defaultCredentialStoreToken="; (__isset.defaultCredentialStoreToken ? (out << to_string(defaultCredentialStoreToken)) : (out << "<null>")); out << ")"; } }}}}} // namespace
38.773826
184
0.686551
docquantum
fd5600d4de12c6ffe705171681fb34b5fab1cf0e
764
cpp
C++
dynamic-programming/C++/0063-unique-paths-ii/main.cpp
ljyljy/LeetCode-Solution-in-Good-Style
0998211d21796868061eb22e2cbb9bcd112cedce
[ "Apache-2.0" ]
1
2020-03-09T00:45:32.000Z
2020-03-09T00:45:32.000Z
dynamic-programming/C++/0063-unique-paths-ii/main.cpp
Eddiehugh/LeetCode-Solution-Well-Formed
bdc1e7153de737b84890153434bf8df5838d0be5
[ "Apache-2.0" ]
null
null
null
dynamic-programming/C++/0063-unique-paths-ii/main.cpp
Eddiehugh/LeetCode-Solution-Well-Formed
bdc1e7153de737b84890153434bf8df5838d0be5
[ "Apache-2.0" ]
1
2021-06-17T09:21:54.000Z
2021-06-17T09:21:54.000Z
#include <iostream> #include <vector> using namespace std; class Solution { public: int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) { int m = obstacleGrid.size(); if (m == 0) { return 0; } int n = obstacleGrid[0].size(); vector<long> dp(n + 1, 0); if (obstacleGrid[0][0] == 1) { return 0; } // 注意:这里是索引为 1 的位置 dp[1] = 1; // 下面这两行赋值比较关键 for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (obstacleGrid[i][j] == 1) { dp[j + 1] = 0; } else { dp[j + 1] += dp[j]; } } } return dp[n]; } };
21.828571
69
0.39267
ljyljy
fd56b6f69cb56a982b035873e8b501012f623a25
29,721
cpp
C++
Common/src/song.cpp
danfrz/PLEBTracker
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
[ "MIT" ]
86
2016-04-13T16:39:02.000Z
2022-03-20T17:35:09.000Z
Common/src/song.cpp
danfrz/PLEBTracker
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
[ "MIT" ]
19
2016-04-14T07:38:19.000Z
2021-04-12T21:58:08.000Z
Common/src/song.cpp
danfrz/PLEBTracker
f6aa7078c3f39e9c8b025e70e7dbeab19119e213
[ "MIT" ]
8
2018-06-04T22:02:06.000Z
2022-01-19T05:34:19.000Z
#include "song.h" #include <iostream> Song::Song(bool fill_defaults) { bytes_per_row = 0x1CB0; interrow_resolution = 0x18; for(int i = 9; i < SONGNAME_LENGTH+1; i++) songname[i] = 0; songname[0]='s'; songname[1]='o'; songname[2]='n'; songname[3]='g'; songname[4]=' '; songname[5]='n'; songname[6]='a'; songname[7]='m'; songname[8]='e'; instruments = new Instrument*[256]; num_instruments = 0; tracks = 4; patterns = new Pattern*[256]; num_patterns = 0; //Either 1 or 0; will be same as num_instruments. either work. for(int i = num_patterns; i < 256; i++) { instruments[i] = NULL; patterns[i] = NULL; } orders = new unsigned char[256]; num_orders=0; waveEntries = 0; waveTable = new unsigned short[512]; for(int i = 0; i < 512; i++) waveTable[i] = 0; pulseEntries = 0; pulseTable = new unsigned short[512]; for(int i = 0; i < 512; i++) pulseTable[i] = 0; filterEntries = 0; filterTable = new unsigned short[512]; for(int i = 0; i < 512; i++) filterTable[i] = 0; if(fill_defaults) { num_instruments = 1; Instrument *defaultInst = new Instrument(); instruments[0] = defaultInst; Pattern *defaultPat = new Pattern(tracks, 64); patterns[0] = defaultPat; num_patterns = 1; num_orders = 1; orders[0] = 0; waveEntries = 1; waveTable[0] = 0x0100; pulseEntries = 2; pulseTable[0] = 0x0000; pulseTable[1] = 0xFF00; filterEntries = 3; filterTable[0] = 0xF000; filterTable[1] = 0x0000; filterTable[2] = 0xFF01; } } Song::Song(std::istream &in) { patterns = NULL; instruments = NULL; orders = new unsigned char[256]; waveTable = new unsigned short[512]; pulseTable = new unsigned short[512]; filterTable = new unsigned short[512]; input(in); } Song::~Song() { for(int i = 0; i < num_instruments; i++) delete instruments[i]; for(int i = 0; i < num_patterns; i++) delete patterns[i]; delete [] instruments; delete [] patterns; delete [] orders; delete [] waveTable; delete [] pulseTable; delete [] filterTable; } std::ostream &Song::output(std::ostream &out) const { out.write(songname, SONGNAME_LENGTH+1); out.write((char*)&bytes_per_row, sizeof(short)); out.write((char*)&interrow_resolution, sizeof(char)); out.write((char*)&tracks, sizeof(char)); out.write((char*)&num_orders, sizeof(char)); out.write((char*)orders, num_orders); out.write((char*)&waveEntries, sizeof(short)); out.write((char*)waveTable, waveEntries*sizeof(short)); out.write((char*)&pulseEntries, sizeof(short)); out.write((char*)pulseTable, pulseEntries*sizeof(short)); out.write((char*)&filterEntries, sizeof(short)); out.write((char*)filterTable, filterEntries*sizeof(short)); out.write((char*)&num_instruments, sizeof(char)); for(int i = 0; i < num_instruments; i++) (instruments[i])->output(out); out.write((char*)&num_patterns, sizeof(char)); for(int i = 0; i < num_patterns; i++) (patterns[i])->output(out); return out; } std::istream &Song::input(std::istream &in) { if(instruments) delete [] instruments; if(patterns) delete [] patterns; in.read(songname, SONGNAME_LENGTH+1); in.read((char*)&bytes_per_row, sizeof(short)); in.read((char*)&interrow_resolution, sizeof(char)); in.read((char*)&tracks, sizeof(char)); in.read((char*)&num_orders, sizeof(char)); in.read((char*)orders, num_orders); in.read((char*)&waveEntries, sizeof(short)); in.read((char*)waveTable, waveEntries*sizeof(short)); for(int i = waveEntries; i < 512; i++) waveTable[i] = 0; in.read((char*)&pulseEntries, sizeof(short)); in.read((char*)pulseTable, pulseEntries*sizeof(short)); for(int i = pulseEntries; i < 512; i++) pulseTable[i] = 0; in.read((char*)&filterEntries, sizeof(short)); in.read((char*)filterTable, filterEntries*sizeof(short)); for(int i = filterEntries; i < 512; i++) filterTable[i] = 0; instruments = new Instrument*[256]; in.read((char*)&num_instruments, sizeof(char)); for(int i = 0; i < num_instruments; i++) instruments[i] = new Instrument(in); for(int i = num_instruments; i < 256; i++) instruments[i] = NULL; patterns = new Pattern*[256]; in.read((char*)&num_patterns, sizeof(char)); for(int i = 0; i < num_patterns; i++) patterns[i] = new Pattern(in); for(int i = num_patterns; i < 256; i++) patterns[i] = NULL; return in; } void Song::copyCommutable(Song *other) { //Copy things that are necessary for any of the objects of the song to operate //Instruments, Wavetable, Pulsetable, metadata //Copy the wave table from this song into the other song unsigned short *otrwavebl = other->getWaveTable(); for(int i = 0; i < waveEntries; i++) other->setWaveEntry(i,waveTable[i]); other->waveEntries = waveEntries; //Copy the pulse table from this song into the other song unsigned short *otrpulsebl = other->getPulseTable(); for(int i = 0; i < pulseEntries; i++) other->setPulseEntry(i,pulseTable[i]); other->pulseEntries = pulseEntries; unsigned short *otrfilterbl = other->getFilterTable(); for(int i = 0; i < filterEntries; i++) other->setFilterEntry(i,filterTable[i]); other->filterEntries = filterEntries; //Copy important song data to the other song other->setInterRowResolution(interrow_resolution); other->setBytesPerRow(bytes_per_row); other->setTrackNum(tracks); //Copy instruments for(int i = 0; i < num_instruments; i++) other->addInstrument(new Instrument(*instruments[i])); } Song *Song::makeExcerpt(unsigned char orderstart, unsigned char orderend, unsigned char rowstart, unsigned char rowend) { unsigned int len = 0; for(int orderi = orderstart; orderi <= orderend; orderi++) len += getPatternByOrder(orderi)->numRows(); len -= rowstart; len -= getPatternByOrder(orderend)->numRows() - orderend+1; Song *out = new Song(false); copyCommutable(out); Pattern *first, *last; if(orderstart == orderend) //play only one order { first = new Pattern(*getPatternByOrder(orderstart)); first->chop(rowstart, rowend); out->addPattern(first); out->insertOrder(0,0); } else //play multiple orders { //Copy over the first and last patterns first = new Pattern(*getPatternByOrder(orderstart)); last = new Pattern(*getPatternByOrder(orderend)); //Chop them to specification first->chop(rowstart, first->numRows()-1); last->chop(0,rowend); //Add the first pattern out->addPattern(first); out->insertOrder(0,0); //Add the final pattern at the end out->addPattern(last); out->insertOrder(1,1); //The last order will continue to be pushed back by the insertion of other orders on it's location for(int orderi = orderstart+1, i = 1; orderi < orderend; orderi++, i++) { //Have to create new patterns because Song will //run destructor: the patters would be double-freed out->addPattern(new Pattern(*getPatternByOrder(orderi))); out->insertOrder(i,i+1); } } return out; } Song *Song::makeExcerpt(unsigned int length, unsigned char orderstart, unsigned char rowstart) { //Acc is used to accumulate how many rows have been added already until length has been reached unsigned char rowend, orderend; unsigned int acc = getPatternByOrder(orderstart)->numRows() - rowstart; unsigned char orderi = orderstart; //Loop through following orders until acc >= length while (acc < length && ++orderi < num_orders) { acc += getPatternByOrder(orderi)->numRows(); } //Make the ending order the last order that filled acc to length if(orderi >= num_orders) orderend = num_orders-1; else orderend = orderi; if(orderstart == orderend) //If there is only one order in this excerpt { //cut off rowend at wherever makes the length rowend = rowstart + length; if(rowend >= getPatternByOrder(orderstart)->numRows()) rowend = getPatternByOrder(orderstart)->numRows()-1; } else { //cut off rowend at the max row of the last order's pattern plus (length - acc) rowend = length - (acc - getPatternByOrder(orderend)->numRows()); } return makeExcerpt(orderstart, orderend, rowstart, rowend); } void Song::setName(const char *name, int length) { if(length > SONGNAME_LENGTH) length = SONGNAME_LENGTH; for(int i = 0; i < length; i++) songname[i] = name[i]; } bool Song::insertOrder(unsigned char dest, unsigned char pattern) { if(pattern >= num_patterns) return false; if(dest >num_orders) return false; for(int i=(num_orders++)-1; i >= dest; i--) orders[i+1] = orders[i]; orders[dest] = pattern; return true; } bool Song::removeOrder(unsigned char ordr) { if(ordr >= num_orders || num_orders == 1) return false; num_orders--; for(int i=ordr; i < num_orders; i++) orders[i] = orders[i+1]; return true; } void Song::setTrackNum(const unsigned newtracks) { tracks = newtracks; //loop through every pattern and change tracks for(int i = 0; i < num_patterns; i++) patterns[i]->setTrackNum(newtracks); } bool Song::newPattern(unsigned int tracks, unsigned int rows) { if(num_patterns == 255) return false; Pattern *newPat = new Pattern(tracks,rows); patterns[num_patterns++] = newPat; return true; } bool Song::clonePattern(unsigned char src) { if(num_patterns == 255) return false; Pattern *source = patterns[src]; Pattern *newPat = new Pattern(*source); patterns[num_patterns++] = newPat; return true; } bool Song::clearPattern(unsigned char ptrn) { patterns[ptrn]->clear(); } bool Song::removePattern(unsigned char ptrn) { if(ptrn >= num_patterns || num_patterns == 1) return false; delete patterns[ptrn]; for(int i = ptrn+1; i < num_patterns; i++) patterns[i-1] = patterns[i]; num_patterns--; patterns[num_patterns] = NULL; //then update orders to the new pattern indicies! //Set to the first pattern //so that it stands out and it would stand out looking through order list for(int i = 0; i < num_orders; i++) if(orders[i] > ptrn) orders[i]--; return true; } void Song::addPattern(Pattern *ptrn) { if(num_patterns == 0xFF) return; patterns[num_patterns] = ptrn; num_patterns++; } bool Song::newInstrument() { if(num_instruments == 255) return false; Instrument *defaultInst = new Instrument(); instruments[num_instruments++] = defaultInst; return true; } bool Song::cloneInstrument(unsigned char inst) { if(num_instruments == 255) return false; Instrument *srcInst = instruments[inst]; Instrument *newInst = new Instrument(*srcInst); instruments[num_instruments++] = newInst; return true; } bool Song::removeInstrument(unsigned char inst) { if(inst >= num_instruments || num_instruments == 1) return false; delete instruments[inst]; inst+=1; while(inst < num_instruments) instruments[inst-1] = instruments[inst++]; num_instruments--; //then update patterns with new instrument indicies for(int i = 0; i < num_patterns; i++) patterns[i]->purgeInstrument(inst); return true; } void Song::addInstrument(Instrument *inst) { instruments[num_instruments++]=inst; } bool Song::insertWaveEntry(unsigned short index, unsigned short entry) { if(waveEntries == 0xFFFF) return false; for(unsigned short last = ++waveEntries; last > index; last--) waveTable[last] = waveTable[last-1]; fixWaveJumps(index, 1); waveTable[index] = entry; return true; } //The entry is a jump function whose value might be changed //by the insertion or deletion of other entries. bool isJumpFunc_Volatile(const unsigned short &wave) { unsigned char func = (wave & 0xFF00) >> 8; switch(func) { case 0xFF: case 0xFC: case 0xFD: return true; } return false; } void Song::fixWaveJumps(const unsigned short &index, short difference) { if(difference == 0) return; //FIX WAVE INDEXES FOR INSTRUMENTS unsigned char instwav; if(difference > 0) { for(unsigned char i = 0; i < num_instruments; i++) { instwav = instruments[i]->getWaveIndex(); // > 0 because the first instrument's wave pointer shouldn't // realistically change due to insertions at index 0 if(instwav > 0 && instwav > index && instwav < 0xFFFF-difference) { instruments[i]->setWaveIndex(instwav+difference); } } } else { for(unsigned char i = 0; i < num_instruments; i++) { instwav = instruments[i]->getWaveIndex(); if(instwav > index) { if(instwav >= -difference) instruments[i]->setWaveIndex(instwav +difference); else instruments[i]->setWaveIndex(0); } } } //FIX WAVE JUMPS IN WAVE TABLE unsigned short jumptype; unsigned short dest; if(difference > 0) { for(unsigned short i = 0; i < waveEntries; i++) { if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it { jumptype = waveTable[i] & 0xFF00; if( (i < waveEntries-1) && ((waveTable[i+1]&0xFF00) == jumptype))//Long jump { dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF); if(dest > index && dest < 0xFFFF-difference) { dest += difference; waveTable[i] = jumptype | ((dest & 0xFF00) >> 8); waveTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = waveTable[i] & 0xFF; if(dest > index) { if(dest >= 0xFF - difference) { if(waveEntries < 0xFFFF) { dest += difference; waveTable[i] &= 0xFF00; waveTable[i] |= ((dest & 0xFF00) >> 8); insertWaveEntry(i+1,jumptype | (dest & 0xFF)); } } else waveTable[i]+=difference; } } } } } else //difference negative { for(unsigned short i = 0; i < waveEntries; i++) { if( isJumpFunc_Volatile(waveTable[i]))//is jump, correct it { jumptype = waveTable[i] & 0xFF00; if( (i < waveEntries-1) && ((waveTable[i+1] & 0xFF00) == jumptype) )//Long jump { dest = ((waveTable[i] & 0xFF) << 8) | (waveTable[i+1] & 0xFF); if(dest > index && dest >= -difference) { dest += difference; waveTable[i] = jumptype | ((dest & 0xFF00) >> 8); waveTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = waveTable[i] & 0xFF; if(dest > index) { if(dest >= -difference) waveTable[i]+= difference; else waveTable[i] &= 0xFF00; } } } } } //FIX WAVE JUMPS IN PATTERNS: 7XX Pattern *p; for(int i = 0; i < num_patterns; i++) { p = patterns[i]; for(int trk = 0; trk < p->numTracks(); trk++) { for(int row = 0; row < p->numRows(); row++) { unsigned int entry = p->at(trk,row); if((entry & 0xF00) == 0x700) { unsigned char wavejump = entry & 0xFF; if(difference > 0) { if(wavejump > 0 &&wavejump >= index && wavejump < 0xFF-difference) { wavejump +=difference; } } else { if(wavejump > index) { if(wavejump >= -difference) wavejump +=difference; else wavejump = 0; } } entry &= ~0xFF; entry |= wavejump; p->setAt(trk,row,entry); } } } } } bool Song::removeWaveEntry(unsigned short index) { if(waveEntries == 0) return false; for(unsigned short i = index+1; i < waveEntries; i++) waveTable[i-1] = waveTable[i]; waveTable[--waveEntries] = 0; fixWaveJumps(index, -1); return true; } bool Song::insertPulseEntry(unsigned short index, unsigned short entry) { if(pulseEntries == 0xFFFF) return false; for(unsigned short last = ++pulseEntries; last > index; last--) pulseTable[last] = pulseTable[last-1]; fixPulseJumps(index, 1); pulseTable[index] = entry; return true; } void Song::fixPulseJumps(const unsigned short &index, short difference) { if(difference == 0) return; //Fix instrument pulse index references unsigned short instpls; if(difference > 0) { for(unsigned char i = 0; i < num_instruments; i++) { instpls = instruments[i]->getPulseIndex(); // > 0 because the first instrument's wave pointer shouldn't // realistically change due to insertions at index 0 if(instpls > 0 && instpls > index && instpls < 0xFFFF-difference && instpls != 0xFFFF) { instruments[i]->setPulseIndex(instpls+difference); } } } else { for(unsigned char i = 0; i < num_instruments; i++) { instpls = instruments[i]->getPulseIndex(); if(instpls > index && instpls != 0xFFFF) { if(instpls >= -difference) instruments[i]->setPulseIndex(instpls +difference); else instruments[i]->setPulseIndex(0); } } } //Fix Pulse jumps unsigned short jumptype; unsigned short dest; if(difference > 0) { for(unsigned short i = 0; i < pulseEntries; i++) { if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it { jumptype = pulseTable[i] & 0xFF00; if( (i < pulseEntries-1) && ((pulseTable[i+1]&0xFF00) == jumptype))//Long jump { dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF); if(dest > index && dest < 0xFFFF-difference) { dest += difference; pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8); pulseTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = pulseTable[i] & 0xFF; if(dest > index) { if(dest >= 0xFF - difference) { if(waveEntries < 0xFFFF) { dest += difference; pulseTable[i] &= 0xFF00; pulseTable[i] |= ((dest & 0xFF00) >> 8); insertPulseEntry(i+1,jumptype | (dest & 0xFF)); } } else pulseTable[i]+=difference; } } } } } else //difference negative { for(unsigned short i = 0; i < pulseEntries; i++) { if( isJumpFunc_Volatile(pulseTable[i]))//is jump, correct it { jumptype = pulseTable[i] & 0xFF00; if( (i < pulseEntries-1) && ((pulseTable[i+1] & 0xFF00) == jumptype) )//Long jump { dest = ((pulseTable[i] & 0xFF) << 8) | (pulseTable[i+1] & 0xFF); if(dest > index && dest >= -difference) { dest += difference; pulseTable[i] = jumptype | ((dest & 0xFF00) >> 8); pulseTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = pulseTable[i] & 0xFF; if(dest > index) { if(dest >= -difference) pulseTable[i]+= difference; else pulseTable[i] &= 0xFF00; } } } } } Pattern *p; for(int i = 0; i < num_patterns; i++) { p = patterns[i]; for(int trk = 0; trk < p->numTracks(); trk++) { for(int row = 0; row < p->numRows(); row++) { unsigned int entry = p->at(trk,row); if((entry & 0xF00) == 0x900) { unsigned char plsjump = entry & 0xFF; if(difference > 0) { if(plsjump > 0 && plsjump > index && plsjump < 0xFF-difference) { plsjump +=difference; } } else { if(plsjump > index) { if(plsjump >= -difference) plsjump +=difference; else plsjump = 0; } } entry &= ~0xFF; entry |= plsjump; p->setAt(trk,row,entry); } } } } } bool Song::removePulseEntry(unsigned short index) { if(pulseEntries == 0) return false; for(unsigned short i = index+1; i < pulseEntries; i++) pulseTable[i-1] = pulseTable[i]; pulseTable[--pulseEntries] = 0; fixPulseJumps(index, -1); return true; } bool Song::insertFilterEntry(unsigned short index, unsigned short entry) { if(filterEntries == 0xFFFF) return false; for(unsigned short last = ++filterEntries; last > index; last--) filterTable[last] = filterTable[last-1]; fixFilterJumps(index, 1); filterTable[index] = entry; return true; } void Song::fixFilterJumps(const unsigned short &index, short difference) { if(difference == 0) return; //Fix instrument pulse index references unsigned short instflt; if(difference > 0) { for(unsigned char i = 0; i < num_instruments; i++) { instflt = instruments[i]->getFilterIndex(); // > 0 because the first instrument's wave pointer shouldn't // realistically change due to insertions at index 0 if(instflt > 0 && instflt > index && instflt < 0xFFFF-difference && instflt != 0xFFFF) { instruments[i]->setFilterIndex(instflt+difference); } } } else { for(unsigned char i = 0; i < num_instruments; i++) { instflt = instruments[i]->getFilterIndex(); if(instflt > index && instflt != 0xFFFF) { if(instflt >= -difference) instruments[i]->setFilterIndex(instflt +difference); else instruments[i]->setFilterIndex(0); } } } //Fix Pulse jumps unsigned short jumptype; unsigned short dest; if(difference > 0) { for(unsigned short i = 0; i < filterEntries; i++) { if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it { jumptype = filterTable[i] & 0xFF00; if( (i < filterEntries-1) && ((filterTable[i+1]&0xFF00) == jumptype))//Long jump { dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF); if(dest > index && dest < 0xFFFF-difference) { dest += difference; filterTable[i] = jumptype | ((dest & 0xFF00) >> 8); filterTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = filterTable[i] & 0xFF; if(dest > index) { if(dest >= 0xFF - difference) { if(waveEntries < 0xFFFF) { dest += difference; filterTable[i] &= 0xFF00; filterTable[i] |= ((dest & 0xFF00) >> 8); insertFilterEntry(i+1,jumptype | (dest & 0xFF)); } } else filterTable[i]+=difference; } } } } } else //difference negative { for(unsigned short i = 0; i < filterEntries; i++) { if( isJumpFunc_Volatile(filterTable[i]))//is jump, correct it { jumptype = filterTable[i] & 0xFF00; if( (i < filterEntries-1) && ((filterTable[i+1] & 0xFF00) == jumptype) )//Long jump { dest = ((filterTable[i] & 0xFF) << 8) | (filterTable[i+1] & 0xFF); if(dest > index && dest >= -difference) { dest += difference; filterTable[i] = jumptype | ((dest & 0xFF00) >> 8); filterTable[i+1] = jumptype | (dest & 0xFF); } i++; } else { dest = filterTable[i] & 0xFF; if(dest > index) { if(dest >= -difference) filterTable[i]+= difference; else filterTable[i] &= 0xFF00; } } } } } Pattern *p; for(int i = 0; i < num_patterns; i++) { p = patterns[i]; for(int trk = 0; trk < p->numTracks(); trk++) { for(int row = 0; row < p->numRows(); row++) { unsigned int entry = p->at(trk,row); if((entry & 0xF00) == 0xC00) { unsigned char fltjump = entry & 0xFF; if(difference > 0) { if(fltjump > 0 &&fltjump > index && fltjump < 0xFF-difference) { fltjump +=difference; } } else { if(fltjump > index) { if(fltjump >= -difference) fltjump +=difference; else fltjump = 0; } } entry &= ~0xFF; entry |= fltjump; p->setAt(trk,row,entry); } } } } } bool Song::removeFilterEntry(unsigned short index) { if(filterEntries == 0) return false; for(unsigned short i = index+1; i < filterEntries; i++) filterTable[i-1] = filterTable[i]; filterTable[--filterEntries] = 0; fixFilterJumps(index, -1); return true; }
28.359733
119
0.488611
danfrz
fd56c266e67f9a9621272d0355c7a7fc5be6d34b
1,588
cpp
C++
client.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
client.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
client.cpp
tklam/licensing-server
a583ea02fcd290dd3b0665df4b163c94302f3f0b
[ "MIT" ]
null
null
null
#include "config.h" #include "client.h" #include "zeromq/zhelpers.hpp" #include "crypto.h" LoginRequest::LoginRequest(const std::string & clientIdentity_, const std::string & clientID_, const std::string & ip_): clientIdentity(clientIdentity_), clientID(clientID_), ip(ip_) { } Client::Client(): _id(CLIENT_ID) { } Client::~Client() { } bool Client::connectAndGetAuthToken() { Crypto crypto; crypto.initKeyExchangeParams(); zmq::context_t context(1); zmq::socket_t client(context, ZMQ_DEALER); client.connect(LICENSING_SERVER_ADDRESS); s_sendmore (client, GREETING); //key exchange //1. send public keys to another party s_sendmore(client, crypto.spubHexStr()); //signing public key s_send(client, crypto.epubHexStr()); //ephemeral(temp) public key //2. receive publics keys from another party const std::string spub = s_recv(client); const std::string epub = s_recv(client); //3. generate XPORT (encrypted CEK + digest) crypto.genXport(spub, epub); //4. receiv XPORT from another party const std::string xport = s_recv(client); crypto.decryptXport(xport); //5. send client ID s_send(client, _id); // The communication channel can now be encrypted with CEK std::string ack = s_recv(client); client.disconnect(LICENSING_SERVER_ADDRESS); ack = crypto.decrypt(ack); if (ack == SUCCESSFUL_LOGIN_REPLY) { return true; } else if (ack == FAILED_LOGIN_REPLY) { return false; } return false; }
25.206349
69
0.65806
tklam
fd57609a87c44fed9c4340ddf05369168e5621cc
15,285
cpp
C++
cppVersion/map.cpp
maxgoren/codealong2020
b8ef380900544c3daabd549f89f196e133622b10
[ "MIT" ]
5
2020-06-17T06:27:45.000Z
2021-01-17T19:59:41.000Z
cppVersion/map.cpp
maxgoren/codealong2020
b8ef380900544c3daabd549f89f196e133622b10
[ "MIT" ]
null
null
null
cppVersion/map.cpp
maxgoren/codealong2020
b8ef380900544c3daabd549f89f196e133622b10
[ "MIT" ]
1
2022-03-07T15:22:17.000Z
2022-03-07T15:22:17.000Z
/**************************************************************** * MIT License * * Copyright (c) 2020 Max Goren * * 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. ***************************************************/ Rect::Rect(int x, int y, int w, int h) { this->uL.x = x; this->uL.y = y; this->lR.x = x + w; this->lR.y = y + h; } Rect::Rect() { } Map::Map(int w, int h) { int x, y; this->width = w; this->height = h; //initialize tile grid for (x = 1; x < w - 1; x++) { for (y = 1; y < h - 1; y++) { layout[x][y].blocks = true; layout[x][y].pos.x = x; layout[x][y].pos.y = y; } } } bool Rect::collision(Rect other) { if ((uL.x < other.lR.x) && (lR.x > other.uL.x) && (uL.y < other.lR.y) && (lR.y > other.uL.y)) { return true; //collision } else { return false; } } double Map::isInFov(int x, int y, int px, int py) { double alpha = (px - x) * (px - x); double beta = (py - y) * (py - y); return sqrt((alpha+beta)*1.0); } void Map::digRect(Rect room) { int x, y; for (x = room.uL.x; x < room.lR.x; x++) { for (y = room.uL.y; y < room.lR.y; y++) { this->layout[x][y].blocks = false; this->layout[x][y].isinRoom = room.idNum; this->layout[x][y].value = 10; } } std::cout<<"Dug room "<<room.idNum<<"from x"<<room.uL.x<<" to x "<<room.lR.x<<" and y"<<room.uL.y<<" to "<<room.lR.y<<".\n"; } void Map::genRect(int numRoom, int maxSize) { int i; int posx, posy, possize; int roomsMade = 0; int collisions = 0; Rect* posroom; //screensections; Rect scrSec1(1,1,width/2, height/2 - 1); scrSec1.numItems = 0; scrSec1.numEnts = 0; scrSect.push_back(scrSec1); Rect scrSec2(width/2, 1, width/2 - 1, height/2 - 1); scrSec2.numItems = 0; scrSec2.numEnts = 0; scrSect.push_back(scrSec2); Rect scrSec3(1, height/2, width/2, height/2); scrSec3.numItems = 0; scrSec3.numEnts = 0; scrSect.push_back(scrSec3); Rect scrSec4(width/2, height/2, width/2 - 1, height/2 - 1); scrSec4.numItems = 0; scrSec4.numEnts = 0; scrSect.push_back(scrSec4); std::cout<<"Screen partition complete.\n"; while (roomsMade < numRoom) { possize = getrand(5, maxSize); switch (getrand(1,4)) { case 1: posx = getrand(scrSect[0].uL.x + 1, scrSect[0].lR.x - (possize + 1)); posy = getrand(scrSect[0].uL.y + 1, scrSect[0].lR.y - (possize + 1)); std::cout<<"Room: "<<roomsMade<<" section one selected\n"; break; case 2: posx = getrand(scrSect[1].uL.x + 1, scrSect[1].lR.x - (possize + 1)); posy = getrand(scrSect[1].uL.y + 1, scrSect[1].lR.y - (possize + 1)); std::cout<<"Room: "<<roomsMade<<" section two selected\n"; break; case 3: posx = getrand(scrSect[2].uL.x + 1, scrSect[2].lR.x - (possize + 1)); posy = getrand(scrSect[2].uL.y + 1, scrSect[2].lR.y - (possize + 1)); std::cout<<"Room: "<<roomsMade<<" section three selected\n"; break; case 4: posx = getrand(scrSect[3].uL.x + 1, scrSect[3].lR.x - (possize + 1)); posy = getrand(scrSect[3].uL.y + 1, scrSect[3].lR.y - (possize + 1)); std::cout<<"Room: "<<roomsMade<<" section four selected\n"; break; } std::cout<<"Room: "<<roomsMade<<" posx/posy: "<<posx<<"/"<<posy<<"\n"; posroom = new Rect(posx, posy, possize + (possize/2) , possize); posroom->idNum = roomsMade; std::cout<<"Room: "<<roomsMade<<" object created\n"; posroom->cent.x = (posroom->uL.x + posroom->lR.x) / 2; posroom->cent.y = (posroom->uL.y + posroom->lR.y) / 2; std::cout<<"Room: "<<roomsMade<<" centx/y set: "<<posroom->cent.x<<"/"<<posroom->cent.y<<"\n"; if (roomsMade > 0) { for (auto R = rooms.begin() ; R != rooms.end(); R++) { if (posroom->collision(*R)) { collisions++; } } if (collisions == 0) { digRect(*posroom); rooms.push_back(*posroom); roomsMade++; collisions = 0; std::cout<<"Room "<<posroom->idNum<<"made. x/y: "<<posroom->uL.x<<"/"<<posroom->uL.y<<" x2/y2:"<<posroom->lR.x<<"/"<<posroom->lR.y<<std::endl; } else { std::cout<<collisions<<"Collisions Detected.\n"; collisions = 0; } } else { digRect(*posroom); rooms.push_back(*posroom); roomsMade++; } if (roomsMade == 2) { spy = rooms.at(0).cent.y; spx = rooms.at(0).cent.x; } } if (getrand(1,100) > 50) { connectRooms(rooms); } else { connectRooms2(rooms); } //placePortal(); outline(); } void Map::connectRooms(std::vector<Rect> rooms) { int ax,bx; int ay,by; Rect* start; Rect* fin; int i = 0; int r; for ( r = 0; r < rooms.size() - 1; r++) { start = &rooms[i]; fin = &rooms[i+1]; std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n"; if (start->cent.x <= fin->cent.x) { std::cout<<"if one, condition A\n"; for (ax = start->cent.x; ax <= (fin->cent.x + start->cent.x) / 2; ax++) { layout[ax][start->cent.y].blocks = false; layout[ax][start->cent.y].isinRoom = 77; } for (bx = fin->cent.x; bx >= (fin->cent.x + start->cent.x) / 2; bx--) { layout[bx][fin->cent.y].blocks = false; layout[bx][fin->cent.y].isinRoom = 77; } std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n"; } else { std::cout<<"If one condition B\n"; for (ax = start->cent.x; ax >= (fin->cent.x + start->cent.x) / 2; ax--) { layout[ax][start->cent.y].blocks = false; layout[ax][start->cent.y].isinRoom = 77; } for (bx = fin->cent.x; bx <= (fin->cent.x + start->cent.x) / 2; bx++) { layout[bx][fin->cent.y].blocks = false; layout[bx][fin->cent.y].isinRoom = 77; } std::cout<<"From: X"<<start->cent.x<<" and "<<fin->cent.x<<" to "<<(start->cent.x + fin->cent.x)/2<<"\n"; } if (start->cent.y <= fin->cent.y) { std::cout<<"if two condition A\n"; for (ay = start->cent.y; ay < fin->cent.y; ay++) { layout[ax][ay].blocks = false; layout[ax+1][ay].blocks = false; layout[ax][ay].isinRoom = 77; //77 =pathway } std::cout<<"From: Y"<<start->cent.y<<" to "<<fin->cent.y<<"\n"; } else { std::cout<<"if two, codition B\n"; for (by = fin->cent.y; by <= start->cent.y; by++) { layout[bx][by].blocks = false; layout[bx-1][by].blocks = false; layout[bx][by].isinRoom = 77; } std::cout<<"From: Y"<<fin->cent.y<<" to "<<start->cent.y<<"\n"; } std::cout<<"Connected.\n"; i++; } } void Map::connectRooms2(std::vector<Rect> rooms) { int ax, ay; int bx, by; Rect* start; Rect* fin; int r, i=0; for (r = 0; r < rooms.size() - 1; r++) { start = &rooms[i]; fin = &rooms[i] + 1; std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n"; if (start->cent.y <= fin->cent.y) { std::cout<<"If one, condition A\n"; for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++) { layout[start->cent.x][ay].blocks = false; layout[start->cent.x][ay].isinRoom = 77; /***********************************/ layout[start->cent.x+1][ay].blocks=false; } for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--) { layout[fin->cent.x][by].blocks = false; layout[fin->cent.x][by].isinRoom = 77; /**************************************/ layout[fin->cent.x-1][by].blocks=false; } } else { std::cout<<"If one, condition B\n"; for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--) { layout[start->cent.x][ay].blocks = false; layout[start->cent.x][ay].isinRoom = 77; /***************************************/ layout[start->cent.x-1][ay].blocks = false; } for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++) { layout[fin->cent.x][by].blocks = false; layout[fin->cent.x][by].isinRoom = 77; /***************************************/ layout[fin->cent.x+1][by].blocks=false; } } if (start->cent.x <= fin->cent.x) { std::cout<<"If two, condition A\n"; for (ax = start->cent.x; ax <= fin->cent.x; ax++) { layout[ax][ay].blocks = false; layout[ax][ay].isinRoom = 77; } } else { std::cout<<"If two, condition B\n"; for (bx = fin->cent.x; bx <= start->cent.x; bx++) { layout[bx][by].blocks = false; layout[bx][by].isinRoom = 77; } } std::cout<<"Connection complete.\n"; i++; } } void Map::connectR2R(Rect st, Rect fi) { int ax, ay; int bx, by; Rect* start = &st; Rect* fin = &fi; int r, i=0; std::cout<<"Connecting: "<<start->idNum<<" to "<<fin->idNum<<"\n"; if (start->cent.y <= fin->cent.y) { std::cout<<"If one, condition A\n"; for (ay = start->cent.y; ay <= (start->cent.y + fin->cent.y) / 2; ay++) { layout[start->cent.x][ay].blocks = false; layout[start->cent.x][ay].isinRoom = 77; /***********************************/ layout[start->cent.x+1][ay].blocks=false; } for (by = fin->cent.y; by >= (start->cent.y + fin->cent.y) / 2; by--) { layout[fin->cent.x][by].blocks = false; layout[fin->cent.x][by].isinRoom = 77; /**************************************/ layout[fin->cent.x-1][by].blocks=false; } } else { std::cout<<"If one, condition B\n"; for (ay = start->cent.y; ay >= (start->cent.y + fin->cent.y) / 2; ay--) { layout[start->cent.x][ay].blocks = false; layout[start->cent.x][ay].isinRoom = 77; /***************************************/ layout[start->cent.x-1][ay].blocks = false; } for (by = fin->cent.y; by <= (start->cent.y + fin->cent.y) / 2; by++) { layout[fin->cent.x][by].blocks = false; layout[fin->cent.x][by].isinRoom = 77; /***************************************/ layout[fin->cent.x+1][by].blocks=false; } } if (start->cent.x <= fin->cent.x) { std::cout<<"If two, condition A\n"; for (ax = start->cent.x; ax <= fin->cent.x; ax++) { layout[ax][ay].blocks = false; layout[ax][ay].isinRoom = 77; } } else { std::cout<<"If two, condition B\n"; for (bx = fin->cent.x; bx <= start->cent.x; bx++) { layout[bx][by].blocks = false; layout[bx][by].isinRoom = 77; } } std::cout<<"Connection complete.\n"; } void Map::outline() { int x, y; for (x = 0; x < width; x++) { for (y = 0; y < height; y++) { if (layout[x][y].blocks == false && layout[x+1][y].blocks == true) { layout[x+1][y].border = true; } if (layout[x][y].blocks == false && layout[x][y+1].blocks == true) { layout[x][y+1].border = true; } if (layout[x][y].blocks == false && layout[x-1][y].blocks == true) { layout[x-1][y].border = true; } if (layout[x][y].blocks == false && layout[x][y-1].blocks == true) { layout[x][y-1].border = true; } if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y+1].border==true) { layout[x-1][y+1].border=true; } if (layout[x][y].blocks == false && layout[x-1][y].border == true && layout[x][y-1].border==true) { layout[x-1][y-1].border=true; } if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y-1].border==true) { layout[x+1][y-1].border=true; } if (layout[x][y].blocks == false && layout[x+1][y].border == true && layout[x][y+1].border==true) { layout[x+1][y+1].border=true; } } } } void Map::spawnMonsters(int numBads) { ent *badGuy; int numMonst = 0; int i, randRm, x, y; while (numMonst < 13) { randRm = getrand(0, rooms.size() - 1); if (rooms.at(randRm).numEnts <= 2) { x = getrand(rooms[randRm].uL.x+1, rooms[randRm].lR.x-1); y = getrand(rooms[randRm].uL.y+1, rooms[randRm].lR.y-1); if (layout[x][y].populated == false && layout[x][y].blocks==false) { if (getrand(0,50) < 35) { badGuy = new ent(x, y, "Goblin", 'G', color_from_name("green")); } else { badGuy = new ent(x, y, "Vampire", 'V', color_from_name("flame")); } badGuys.push_back(badGuy); rooms[randRm].numEnts++; layout[x][y].populated = true; layout[x][y].blocks = true; numMonst++; } } } } void Map::placeItems(int numItems) { int sect; int rit; float rp, rh; int itemsMade = 0; Point randPos; Items* item; struct stuff things; while (itemsMade < numItems) { rp = getrandfloat(0.10, 2.25); rh = getrandfloat(4.35, 9.33); rit = getrand(0,22); sect = getrand(0, 3); if (scrSect[sect].numItems < numItems) { randPos.x = getrand(this->scrSect.at(sect).uL.x, this->scrSect.at(sect).lR.x); randPos.y = getrand(this->scrSect.at(sect).uL.y, this->scrSect.at(sect).lR.y); if (this->layout[randPos.x][randPos.y].blocks == false && this->layout[randPos.x][randPos.y].populated == false) { item = new Items(randPos.x,randPos.y, things.things[rit], rh, rp); this->itemList.push_back(item); this->layout[randPos.x][randPos.y].populated = true; itemsMade++; scrSect[sect].numItems++; } } } } void Map::placePortal() { int dx, dy; int dx2, dy2; int distance; int distance2; float dist; std::pair<Rect*,Rect*> closest; Rect far = rooms.back(); Rect* start = &rooms.front(); Rect* next; for (auto r = rooms.begin() + 1; r != rooms.end(); r++) { dx = r->cent.x - start->cent.x; dy = r->cent.y - start->cent.y; dx2 = r->cent.x - far.cent.x; dy2 = r->cent.y - far.cent.y; dist = sqrtf(dx*dx+dy*dy); distance = (int)round(dist); dist = sqrtf(dx2*dx2+dy2*dy2); distance2 = (int)round(dist); std::cout<<r->idNum<<" & "<<start->idNum<<"\n"; std::cout<<"r -> start "<<distance<<"\n"; std::cout<<r->idNum<<" & "<<far.idNum<<"\n"; std::cout<<"r -> finnish "<<distance2<<"\n"; if (distance < distance2) { next = start; } else { next = &far; far = *r; } std::cout<<"winner: "<<r->idNum<<" & "<<next->idNum<<"\n"; } connectR2R(*start,*next); start = next; }
28.948864
149
0.53366
maxgoren
fd5b5642bd20ebde3431ec8c7689553cadf9ad85
4,483
cpp
C++
eiam/src/v20210420/model/UserGroupInformation.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
eiam/src/v20210420/model/UserGroupInformation.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
eiam/src/v20210420/model/UserGroupInformation.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/eiam/v20210420/model/UserGroupInformation.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Eiam::V20210420::Model; using namespace std; UserGroupInformation::UserGroupInformation() : m_userGroupIdHasBeenSet(false), m_userGroupNameHasBeenSet(false), m_lastModifiedDateHasBeenSet(false) { } CoreInternalOutcome UserGroupInformation::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("UserGroupId") && !value["UserGroupId"].IsNull()) { if (!value["UserGroupId"].IsString()) { return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupId` IsString=false incorrectly").SetRequestId(requestId)); } m_userGroupId = string(value["UserGroupId"].GetString()); m_userGroupIdHasBeenSet = true; } if (value.HasMember("UserGroupName") && !value["UserGroupName"].IsNull()) { if (!value["UserGroupName"].IsString()) { return CoreInternalOutcome(Core::Error("response `UserGroupInformation.UserGroupName` IsString=false incorrectly").SetRequestId(requestId)); } m_userGroupName = string(value["UserGroupName"].GetString()); m_userGroupNameHasBeenSet = true; } if (value.HasMember("LastModifiedDate") && !value["LastModifiedDate"].IsNull()) { if (!value["LastModifiedDate"].IsString()) { return CoreInternalOutcome(Core::Error("response `UserGroupInformation.LastModifiedDate` IsString=false incorrectly").SetRequestId(requestId)); } m_lastModifiedDate = string(value["LastModifiedDate"].GetString()); m_lastModifiedDateHasBeenSet = true; } return CoreInternalOutcome(true); } void UserGroupInformation::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_userGroupIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UserGroupId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_userGroupId.c_str(), allocator).Move(), allocator); } if (m_userGroupNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UserGroupName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_userGroupName.c_str(), allocator).Move(), allocator); } if (m_lastModifiedDateHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LastModifiedDate"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_lastModifiedDate.c_str(), allocator).Move(), allocator); } } string UserGroupInformation::GetUserGroupId() const { return m_userGroupId; } void UserGroupInformation::SetUserGroupId(const string& _userGroupId) { m_userGroupId = _userGroupId; m_userGroupIdHasBeenSet = true; } bool UserGroupInformation::UserGroupIdHasBeenSet() const { return m_userGroupIdHasBeenSet; } string UserGroupInformation::GetUserGroupName() const { return m_userGroupName; } void UserGroupInformation::SetUserGroupName(const string& _userGroupName) { m_userGroupName = _userGroupName; m_userGroupNameHasBeenSet = true; } bool UserGroupInformation::UserGroupNameHasBeenSet() const { return m_userGroupNameHasBeenSet; } string UserGroupInformation::GetLastModifiedDate() const { return m_lastModifiedDate; } void UserGroupInformation::SetLastModifiedDate(const string& _lastModifiedDate) { m_lastModifiedDate = _lastModifiedDate; m_lastModifiedDateHasBeenSet = true; } bool UserGroupInformation::LastModifiedDateHasBeenSet() const { return m_lastModifiedDateHasBeenSet; }
30.496599
155
0.7205
suluner
fd5c167fe2de69e059d08716f61869c19ccce090
2,360
cc
C++
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
horance-liu/mnn
d53216e5f3fb60ea1da6f44e72fc0d949974931d
[ "Apache-2.0" ]
4
2021-05-17T02:49:36.000Z
2021-05-18T13:31:33.000Z
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
horance-liu/mnn
d53216e5f3fb60ea1da6f44e72fc0d949974931d
[ "Apache-2.0" ]
1
2021-06-02T03:01:05.000Z
2021-06-02T03:01:05.000Z
src/mnn/kernel/cpu/fully_connected_op_cpu.cc
horance-liu/mnn
d53216e5f3fb60ea1da6f44e72fc0d949974931d
[ "Apache-2.0" ]
4
2021-05-19T01:43:07.000Z
2021-12-09T07:29:34.000Z
/* * Copyright (c) 2021, Horance Liu and the respective contributors * All rights reserved. * * Use of this source code is governed by a Apache 2.0 license that can be found * in the LICENSE file. */ #include "mnn/kernel/cpu/fully_connected_op_cpu.h" namespace mnn { namespace kernels { void fully_connected_op_internal(const Matrix &in_data, const Vector &W, const Vector &bias, Matrix &out_data, const FullyParams &params, const bool layer_parallelize) { for_i(layer_parallelize, in_data.size(), [&](size_t sample) { const Vector &in = in_data[sample]; Vector &out = out_data[sample]; for (size_t i = 0; i < params.out_size_; i++) { out[i] = Float {0}; for (size_t c = 0; c < params.in_size_; c++) { out[i] += W[c * params.out_size_ + i] * in[c]; } if (params.has_bias_) { out[i] += bias[i]; } } }); } void fully_connected_op_internal(const Matrix &prev_out, const Vector &W, Matrix &dW, Matrix &db, Matrix &curr_delta, Matrix &prev_delta, const FullyParams &params, const bool layer_parallelize) { for (size_t sample = 0; sample < prev_out.size(); sample++) { for (size_t c = 0; c < params.in_size_; c++) { // propagate delta to previous layer // prev_delta[c] += current_delta[r] * W_[c * out_size_ + r] prev_delta[sample][c] += vectorize::dot(&curr_delta[sample][0], &W[c * params.out_size_], params.out_size_); } for_(layer_parallelize, 0, params.out_size_, [&](const BlockedRange &r) { // accumulate weight-step using delta // dW[c * out_size + i] += current_delta[i] * prev_out[c] for (size_t c = 0; c < params.in_size_; c++) { vectorize::muladd(&curr_delta[sample][r.begin()], prev_out[sample][c], r.end() - r.begin(), &dW[sample][c * params.out_size_ + r.begin()]); } if (params.has_bias_) { // Vector& db = *in_grad[2]; for (size_t i = r.begin(); i < r.end(); i++) { db[sample][i] += curr_delta[sample][i]; } } }); } } } // namespace kernels } // namespace mnn
35.223881
86
0.54322
horance-liu
fd5d55923e68b941e8e033abfac025a43107741c
1,881
cpp
C++
source/computation-derivatives-gt2s_ga1s.cpp
p-maybank/bayesian-uq
5e3b34aaf33512d94fd417238df5582b3a89170b
[ "BSD-3-Clause" ]
1
2021-07-03T22:53:53.000Z
2021-07-03T22:53:53.000Z
source/computation-derivatives-gt2s_ga1s.cpp
p-maybank/bayesian-uq
5e3b34aaf33512d94fd417238df5582b3a89170b
[ "BSD-3-Clause" ]
null
null
null
source/computation-derivatives-gt2s_ga1s.cpp
p-maybank/bayesian-uq
5e3b34aaf33512d94fd417238df5582b3a89170b
[ "BSD-3-Clause" ]
2
2021-07-03T22:57:22.000Z
2021-10-10T13:29:54.000Z
#include <vector> #include "Eigen/Dense" #include "scalar-typedef.hpp" #include "stable-sde.hpp" #include "data-vector.hpp" #include "vector-io.hpp" #include "computation.hpp" using namespace std; using namespace Eigen; #ifdef USE_DCO_TYPES template<> void Computation<gt2s_ga1s_scalar>::derivatives(Matrix<gt2s_ga1s_scalar, Dynamic, 1>& theta, const Eigen::Matrix<gt2s_ga1s_scalar, Eigen::Dynamic, 1>& x_star, Matrix<double,Dynamic,1> & grad, Matrix<double,Dynamic,Dynamic> & hess, unsigned int & ifail){ const int theta_size = theta.size(); grad.resize(theta_size); hess.resize(theta_size,theta_size); // Create tape if( DCO_GA1S_MODE::global_tape==nullptr) { DCO_GT2S_GA1S_MODE::global_tape = DCO_GT2S_GA1S_MODE::tape_t::create(); } auto pos = DCO_GT2S_GA1S_MODE::global_tape->get_position(); for(int i=0; i<theta_size; i++) { // Register inputs for(int j=0; j<theta_size; j++) { DCO_GT2S_GA1S_MODE::global_tape->register_variable(theta(j)); } dco::derivative(dco::value(theta(i))) = 1.0; // Actual computation to be differentiated gt2s_ga1s_scalar ll = eval(theta, x_star, ifail); DCO_GT2S_GA1S_MODE::global_tape->register_output_variable(ll); dco::derivative(ll) = 1.0; DCO_GT2S_GA1S_MODE::global_tape->interpret_adjoint(); // Fill Jacobian grad(i) = dco::value(dco::derivative(theta(i))); // Fill Hessian for(int j=0; j<theta_size; j++) hess(j, i) = dco::derivative(dco::derivative(theta(j))); dco::derivative(dco::value(theta(i))) = 0.0; DCO_GT2S_GA1S_MODE::global_tape->reset(); } DCO_GT2S_GA1S_MODE::global_tape->reset_to( pos ); DCO_GT2S_GA1S_MODE::tape_t::remove(DCO_GT2S_GA1S_MODE::global_tape); return; } #endif
32.431034
103
0.653907
p-maybank
5b746ac7d9bb646e6168d6c081e3f442cb2d1b9f
366
cpp
C++
src/en/WorldManager.cpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/en/WorldManager.cpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/en/WorldManager.cpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#include "WorldManager.hpp" #include "World.hpp" #include <core/memory/Memory.hpp> namespace ari { namespace en { //! Create a new World World* WorldManager::CreateWorld() { return core::Memory::New<World>(); } //! Destroy a world void WorldManager::DestroyWorld(World* _world) { core::Memory::Delete<World>(_world); } } // en } // ari
15.25
48
0.647541
kochol
5b74ba1b03cad0dd05bb7a7897ff8267b20e34cc
22,705
cc
C++
src/CGContext.cc
hailongz/kk-canvas
f53c994bce49ca4375a27d69c0d08c121ac538ad
[ "MIT" ]
null
null
null
src/CGContext.cc
hailongz/kk-canvas
f53c994bce49ca4375a27d69c0d08c121ac538ad
[ "MIT" ]
null
null
null
src/CGContext.cc
hailongz/kk-canvas
f53c994bce49ca4375a27d69c0d08c121ac538ad
[ "MIT" ]
null
null
null
// // CGContext.cc // KKCanvas // // Created by zhanghailong on 2018/8/17. // Copyright © 2018年 kkmofang.cn. All rights reserved. // #include "kk-config.h" #include "CGContext.h" namespace kk { namespace CG { Palette::Palette(kk::CString name, ...) { va_list va; va_start(va, name); kk::CString key = name; kk::CString value = nullptr; while(1) { if(key == nullptr) { key = va_arg(va, kk::CString); if(key == nullptr) { break; } } if(value == nullptr) { value = va_arg(va, kk::CString); if(value == nullptr) { break; } } _values[key] = ColorFromString(value); key = nullptr; value = nullptr; } va_end(va); } void Palette::set(kk::CString name,Color v) { _values[name] = v; } Color Palette::get(kk::CString name) { Color v = {0,0,0,0}; std::map<kk::String,Color>::iterator i = _values.find(name); if(i != _values.end()) { return i->second; } return v; } Palette Palette::Default("black","#000000", "red","#ff0000", "white","#ffffff", "green","#00ff00", "blue","#0000ff", "magenta","#ff00ff", "yellow","#ffff00", nullptr); Color ColorFromString(kk::CString string) { Color v = {0,0,0,0}; if(string != nullptr) { if(CStringHasPrefix(string, "rgba(")) { #ifdef KK_CG_FLOAT64 sscanf(string, "rgba(%lf,%lf,%lf,%lf)",&v.r,&v.g,&v.b,&v.a); #else sscanf(string, "rgba(%f,%f,%f,%f)",&v.r,&v.g,&v.b,&v.a); #endif v.r = v.r / 255.0f; v.g = v.g / 255.0f; v.b = v.b / 255.0f; } else if(CStringHasPrefix(string, "rgb(")) { #ifdef KK_CG_FLOAT64 sscanf(string, "rgba(%lf,%lf,%lf)",&v.r,&v.g,&v.b); #else sscanf(string, "rgba(%f,%f,%f)",&v.r,&v.g,&v.b); #endif v.r = v.r / 255.0f; v.g = v.g / 255.0f; v.b = v.b / 255.0f; v.a = 1.0f; } else if(CStringHasPrefix(string, "#")) { size_t n = CStringLength(string); if(n == 4) { Uint r = 0,g = 0,b = 0; sscanf(string, "#%1x%1x%1x",&r,&g,&b); v.r = (Float)(r << 8 | r) / 255.0f; v.g = (Float)(g << 8 | r) / 255.0f; v.b = (Float)(b << 8 | r) / 255.0f; v.a = 1.0f; } else if(n == 7) { Uint r = 0,g = 0,b = 0; sscanf(string, "#%2x%2x%2x",&r,&g,&b); v.r = (Float)(r) / 255.0f; v.g = (Float)(g) / 255.0f; v.b = (Float)(b) / 255.0f; v.a = 1.0f; } } else { return Palette::Default.get(string); } } return v; } kk::String StringFromColor(Color v) { char fmt[16] = ""; Uint r = v.r * 255.0; Uint g = v.g * 255.0; Uint b = v.b * 255.0; if(v.a == 1.0f) { snprintf(fmt, sizeof(fmt), "#%2x%2x%2x",r,g,b); } else { snprintf(fmt, sizeof(fmt), "rgba(%u,%u,%u,%g)",r,g,b,v.a); } return fmt; } PatternType PatternTypeFromString(kk::CString string) { if(CStringEqual(string, "repeat-x")){ return PatternTypeRepeatX; } if(CStringEqual(string, "repeat-y")){ return PatternTypeRepeatY; } if(CStringEqual(string, "no-repeat")){ return PatternTypeNoRepeat; } return PatternTypeRepeat; } kk::String StringFromPatternType(PatternType v) { switch (v) { case PatternTypeRepeatX: return "repeat-x"; case PatternTypeRepeatY: return "repeat-y"; case PatternTypeNoRepeat: return "no-repeat"; default: return "repeat"; } } LineCapType LineCapTypeFromString(kk::CString string) { if(CStringEqual(string, "round")) { return LineCapTypeRound; } if(CStringEqual(string, "square")) { return LineCapTypeSquare; } return LineCapTypeButt; } kk::String StringFromLineCapType(LineCapType v) { switch (v) { case LineCapTypeRound: return "round"; case LineCapTypeSquare: return "square"; default: return "butt"; } } LineJoinType LineJoinTypeFromString(kk::CString string) { if(CStringEqual(string, "round")) { return LineJoinTypeRound; } if(CStringEqual(string, "bevel")) { return LineJoinTypeBevel; } return LineJoinTypeMiter; } kk::String StringFromLineJoinType(LineJoinType v) { switch (v) { case LineJoinTypeRound: return "round"; case LineJoinTypeBevel: return "bevel"; default: return "miter"; } } Font FontFromString(kk::CString string) { Font v = {"",14,FontStyleNormal,FontWeightNormal}; std::vector<kk::String> items; CStringSplit(string, " ", items); std::vector<kk::String>::iterator i = items.begin(); while(i != items.end()) { kk::String & s = * i; if(s == "bold") { v.weight = FontWeightBold; } else if(s == "italic") { v.style = FontStyleItalic; } else if(CStringHasSuffix(s.c_str(), "px")) { v.size = atof(s.c_str()); } else { v.family = s; } i ++; } return v; } kk::String StringFromFont(Font v) { std::vector<kk::String> items; if(v.family != "") { items.push_back(v.family); } if(v.weight == FontWeightBold) { items.push_back("bold"); } if(v.style == FontStyleItalic) { items.push_back("italic"); } char fmt[32]; snprintf(fmt, sizeof(fmt), "%gpx",v.size); items.push_back(fmt); return CStringJoin(items, " "); } TextAlign TextAlignFromString(kk::CString string) { if(CStringEqual(string, "end")) { return TextAlignEnd; } if(CStringEqual(string, "center")) { return TextAlignCenter; } if(CStringEqual(string, "left")) { return TextAlignLeft; } if(CStringEqual(string, "right")) { return TextAlignRight; } return TextAlignStart; } kk::String StringFromTextAlign(TextAlign v) { switch (v) { case TextAlignEnd: return "end"; case TextAlignCenter: return "center"; case TextAlignLeft: return "left"; case TextAlignRight: return "right"; default: return "start"; } } TextBaseline TextBaselineFromString(kk::CString string) { if(CStringEqual(string, "top")) { return TextBaselineTop; } if(CStringEqual(string, "hanging")) { return TextBaselineHanging; } if(CStringEqual(string, "middle")) { return TextBaselineMiddle; } if(CStringEqual(string, "ideographic")) { return TextBaselineIdeographic; } if(CStringEqual(string, "bottom")) { return TextBaselineBottom; } return TextBaselineAlphabetic; } kk::String StringFromTextBaseline(TextBaseline v) { switch (v) { case TextBaselineTop: return "top"; case TextBaselineHanging: return "hanging"; case TextBaselineMiddle: return "middle"; case TextBaselineIdeographic: return "ideographic"; case TextBaselineBottom: return "bottom"; default: return "alphabetic"; } } GlobalCompositeOperation GlobalCompositeOperationFromString(kk::CString string) { if(CStringEqual(string, "source-atop")) { return GlobalCompositeOperationSourceAtop; } if(CStringEqual(string, "source-in")) { return GlobalCompositeOperationSourceIn; } if(CStringEqual(string, "source-out")) { return GlobalCompositeOperationSourceOut; } if(CStringEqual(string, "destination-over")) { return GlobalCompositeOperationDestinationOver; } if(CStringEqual(string, "destination-atop")) { return GlobalCompositeOperationDestinationAtop; } if(CStringEqual(string, "destination-in")) { return GlobalCompositeOperationDestinationIn; } if(CStringEqual(string, "destination-out")) { return GlobalCompositeOperationDestinationOut; } if(CStringEqual(string, "destination-lighter")) { return GlobalCompositeOperationDestinationLighter; } if(CStringEqual(string, "destination-copy")) { return GlobalCompositeOperationDestinationCopy; } if(CStringEqual(string, "destination-xor")) { return GlobalCompositeOperationDestinationXOR; } return GlobalCompositeOperationSourceOver; } kk::String StringFromGlobalCompositeOperation(GlobalCompositeOperation v) { switch (v) { case GlobalCompositeOperationSourceAtop: return "source-atop"; case GlobalCompositeOperationSourceIn: return "source-in"; case GlobalCompositeOperationSourceOut: return "source-out"; case GlobalCompositeOperationDestinationOver: return "destination-over"; case GlobalCompositeOperationDestinationAtop: return "destination-atop"; case GlobalCompositeOperationDestinationIn: return "destination-in"; case GlobalCompositeOperationDestinationOut: return "destination-out"; case GlobalCompositeOperationDestinationLighter: return "destination-lighter"; case GlobalCompositeOperationDestinationCopy: return "destination-copy"; case GlobalCompositeOperationDestinationXOR: return "destination-xor"; default: break; } return "source-over"; } Context::Context(Uint width,Uint height):_width(width),_height(height) { _fillColor = {0,0,0,1}; _strokeColor = {0,0,0,1}; _shadowColor = {0,0,0,1}; _shadowBlur = 0; _shadowOffsetX = 0; _shadowOffsetY = 0; _lineCap = LineCapTypeButt; _lineJoin = LineJoinTypeBevel; _lineWidth = 1; _miterLimit = 0; _font = {"",14,FontStyleNormal,FontWeightNormal}; _textAlign = TextAlignStart; _textBaseline = TextBaselineAlphabetic; _globalAlpha = 1.0f; _globalCompositeOperation = GlobalCompositeOperationSourceOver; } kk::Strong Context::getImageData(Uint x,Uint y,Uint width,Uint height) { if(width == 0 || height == 0) { return (kk::Object *) nullptr; } kk::Strong v = createImageData(width, height); ImageData * image = v.as<ImageData>(); if(image != nullptr) { Ubyte * p = image->data(); Ubyte * s = getContextData(); for(Uint r = 0; r < height; r ++) { for(Uint c = 0; c < width; c ++) { if(r + y < _height && c + x < _width) { for(Uint n = 0; n < 4; n ++) { *p = s[((r + y) * _width + (c + x)) * 4 + n]; p ++; } } else { p += 4; } } } } return image; } void Context::putImageData(ImageData * image,Uint x,Uint y,Uint dirtyX,Uint dirtyY,Uint dirtyWidth,Uint dirtyHeight) { if(image == nullptr) { return; } if(dirtyWidth == 0) { dirtyWidth = _width - dirtyX; } if(dirtyHeight == 0) { dirtyHeight = _height - dirtyY; } Uint mWidth = image->width(); Uint width = MIN(mWidth - x,dirtyWidth); Uint height = MIN(image->height() - y,dirtyHeight); Ubyte * p = image->data(); Ubyte * s = getContextData(); for(Uint r = 0; r < height; r ++) { for(Uint c = 0; c < width; c ++) { Uint i_p = ((r + y) * mWidth + (c + x)) * 4; Uint i_s = ((r + dirtyY) * _width + (c + dirtyX)) * 4; for(Uint n = 0; n < 4; n ++) { s[i_s + n] = p[i_p + n]; } } } } void Context::setFillStyle(Style * style) { _fillStyle = style; } Style * Context::fillStyle() { return _fillStyle.as<Style>(); } void Context::setFillColor(Color color) { _fillColor = color; } Color Context::fillColor() { return _fillColor; } void Context::setStrokeStyle(Style * style) { _strokeStyle = style; } Style * Context::strokeStyle() { return _strokeStyle.as<Style>(); } void Context::setStrokeColor(Color color) { _strokeColor = color; } Color Context::strokeColor() { return _strokeColor; } void Context::setShadowColor(Color v) { _shadowColor = v; } Color Context::shadowColor() { return _shadowColor; } void Context::setShadowBlur(Float v) { _shadowBlur = v; } Float Context::shadowBlur() { return _shadowBlur; } void Context::setShadowOffsetX(Float v) { _shadowOffsetX = v; } Float Context::shadowOffsetX() { return _shadowOffsetX; } void Context::setShadowOffsetY(Float v) { _shadowOffsetY = v; } Float Context::shadowOffsetY() { return _shadowOffsetY; } void Context::setLineCap(LineCapType v) { _lineCap = v; } LineCapType Context::lineCap() { return _lineCap; } void Context::setLineJoin(LineJoinType v) { _lineJoin = v; } LineJoinType Context::lineJoin() { return _lineJoin; } void Context::setLineWidth(Float v) { _lineWidth = v; } Float Context::lineWidth() { return _lineWidth; } void Context::setMiterLimit(Float v) { _miterLimit = v; } Float Context::miterLimit() { return _miterLimit; } void Context::setFont(Font v) { _font = v; } Font Context::font() { return _font; } void Context::setTextAlign(TextAlign v) { _textAlign = v; } TextAlign Context::textAlign() { return _textAlign; } void Context::setTextBaseline(TextBaseline v) { _textBaseline = v; } TextBaseline Context::textBaseline() { return _textBaseline; } void Context::setGlobalAlpha(Float v) { _globalAlpha = v; } Float Context::globalAlpha() { return _globalAlpha; } void Context::setGlobalCompositeOperation(GlobalCompositeOperation v) { _globalCompositeOperation = v; } GlobalCompositeOperation Context::globalCompositeOperation() { return _globalCompositeOperation; } Uint Context::width() { return _width; } Uint Context::height() { return _height; } kk::Strong Context::createLinearGradient(Float x0,Float y0, Float x1, Float y1) { return new LinearGradient(x0,y0,x1,y1); } kk::Strong Context::createRadialGradient(Float x0,Float y0,Float r0, Float x1, Float y1, Float r1) { return new RadialGradient(x0,y0,r0,x1,y1,r1); } kk::Strong Context::createPattern(Image * image,PatternType type) { return new Pattern(image,type); } void Context::fillRect(Float x, Float y,Float width,Float height) { rect(x, y, width, height); fill(); } void Context::strokeRect(Float x, Float y,Float width,Float height) { rect(x, y, width, height); stroke(); } kk::Strong Context::createImageData(Uint width,Uint height) { if(width == 0 || height == 0) { return (kk::Object *) nullptr; } return new ImageData(width,height); } Pattern::Pattern(Image * image,PatternType type):_image((kk::Object *) image),_type(type) { } Image * Pattern::image() { return _image.as<Image>(); } PatternType Pattern::type() { return _type; } void Gradient::addColorStop(Float loc,Color color) { _locations.push_back(loc); _colors.push_back(color); } RadialGradient::RadialGradient(Float x0,Float y0,Float r0, Float x1, Float y1, Float r1) :Gradient(), _x0(x0),_y0(y0),_r0(r0), _x1(x1),_y1(y1),_r1(r1) { } LinearGradient::LinearGradient(Float x0,Float y0, Float x1, Float y1) :Gradient(), _x0(x0),_y0(y0), _x1(x1),_y1(y1){ } void ImageData::copyPixels(void * data) { memcpy(data, _data, _width * _height * 4); } Boolean ImageData::isCopyPixels() { return true; } Uint ImageData::width() { return _width; } Uint ImageData::height() { return _height; } Ubyte * ImageData::data() { return _data; } Uint ImageData::size() { return _width * _height * 4; } kk::CString OSImage::src() { return _src.c_str(); } kk::CString OSImage::basePath() { return _basePath.c_str(); } } }
30.192819
126
0.418586
hailongz
5b74f18990a179a8d50db65116d404a890d70e13
480
cpp
C++
tools/cross_pp.cpp
mcarlen/libbiarc
d016a1be643ddcded53411b4f242ac6004b65173
[ "Apache-2.0" ]
null
null
null
tools/cross_pp.cpp
mcarlen/libbiarc
d016a1be643ddcded53411b4f242ac6004b65173
[ "Apache-2.0" ]
1
2019-08-23T09:36:29.000Z
2019-08-26T09:56:38.000Z
tools/cross_pp.cpp
mcarlen/libbiarc
d016a1be643ddcded53411b4f242ac6004b65173
[ "Apache-2.0" ]
1
2019-08-11T21:12:02.000Z
2019-08-11T21:12:02.000Z
#include "../include/Curve.h" int main(int argc, char** argv) { int N; float s, t0, t1; if (argc!=6) { cout << "Usage : " << argv[0] << " s t0 t1 N pkf\n"; exit(0); } s = atof(argv[1]); t0 = atof(argv[2]); t1 = atof(argv[3]); N = atoi(argv[4]); Curve<Vector3> c(argv[5]); c.make_default(); c.normalize(); c.make_default(); for (int i=0;i<N;++i) { float t = t0 + (t1-t0)*(float)i/(float)N; cout << t << " " << c.pp(s, t) << endl; } return 0; }
17.142857
56
0.508333
mcarlen
5b786104818f2dded7183adeed4c73af5a677cb4
2,561
cpp
C++
648-replace-words/648-replace-words.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
648-replace-words/648-replace-words.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
648-replace-words/648-replace-words.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
class Solution { public: class Trie{ public: class Node{ public: Node* links[26] = {NULL}; string str = ""; bool containsKey(char ch){ return (links[ch-'a'] != NULL); } void put(char ch, Node* node){ links[ch-'a'] = node; } Node* get(char ch){ return links[ch-'a']; } void setEnd(string word){ str = word; } }; Node* root; Trie(){ root = new Node(); } void insert(string word){ Node* node = root; for(auto ch : word){ if(!node->containsKey(ch)){ node->put(ch,new Node); } node = node->get(ch); } node->setEnd(word); } string replaceWithPrefix(string word){ Node* node = root; for(auto ch : word){ if(!node->containsKey(ch)){ return word; } node = node->get(ch); //cout << ch <<" "<< node->str <<" "<< word <<"\n"; if(node->str != ""){ return node->str; } } if(node->str != "") return node->str; return word; } }; vector<string> removeDupWord(string str) { // Used to split string around spaces. vector <string> fin; istringstream ss(str); string word; // for storing each word // Traverse through all words // while loop till we get // strings to store in string word while (ss >> word) { // print the read word fin.push_back(word); } return fin; } string replaceWords(vector<string>& dictionary, string sentence) { Trie obj; vector <string> fin = removeDupWord(sentence); for(auto word : dictionary){ obj.insert(word); } for(int i=0;i<fin.size();++i){ fin[i] = obj.replaceWithPrefix(fin[i]); } sentence = ""; for(int i=0;i<fin.size();++i){ sentence += (fin[i] + " "); } sentence.pop_back(); return sentence; } };
25.868687
70
0.385396
shreydevep
5b7a233f651cf3fd113d95f0df596b982066c3b6
4,813
hpp
C++
hpx/util/detail/empty_vtable.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/util/detail/empty_vtable.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/util/detail/empty_vtable.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2011 Thomas Heller // Copyright (c) 2013 Hartmut Kaiser // // 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) #if !BOOST_PP_IS_ITERATING #ifndef HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP #define HPX_FUNCTION_DETAIL_EMPTY_VTABLE_HPP #include <hpx/config/forceinline.hpp> #include <hpx/util/add_rvalue_reference.hpp> #include <boost/ref.hpp> #include <boost/preprocessor/iteration/iterate.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <typeinfo> namespace hpx { namespace util { namespace detail { struct empty_vtable_base { enum { empty = true }; static std::type_info const& get_type() { return typeid(void); } static void static_delete(void ** f) {} static void destruct(void ** f) {} static void clone(void *const* f, void ** dest) {} static void copy(void *const* f, void ** dest) {} // we can safely return an int here as those function will never // be called. static int& construct(void ** f) { hpx::throw_exception(bad_function_call, "empty function object should not be used", "empty_vtable_base::construct", __FILE__, __LINE__); static int t = 0; return t; } static int& get(void **f) { hpx::throw_exception(bad_function_call, "empty function object should not be used", "empty_vtable_base::get", __FILE__, __LINE__); static int t = 0; return t; } static int& get(void *const*f) { hpx::throw_exception(bad_function_call, "empty function object should not be used", "empty_vtable_base::get", __FILE__, __LINE__); static int t = 0; return t; } }; template <typename Sig, typename IArchive, typename OArchive> struct empty_vtable; }}} #define BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF(Z, N, D) \ typename util::add_rvalue_reference<BOOST_PP_CAT(D, N)>::type \ BOOST_PP_CAT(a, N) \ /**/ #if !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION) # include <hpx/util/detail/preprocessed/empty_vtable.hpp> #else #if defined(__WAVE__) && defined(HPX_CREATE_PREPROCESSED_FILES) # pragma wave option(preserve: 1, line: 0, output: "preprocessed/empty_vtable_" HPX_LIMIT_STR ".hpp") #endif #define BOOST_PP_ITERATION_PARAMS_1 \ ( \ 3 \ , ( \ 0 \ , HPX_FUNCTION_ARGUMENT_LIMIT \ , <hpx/util/detail/empty_vtable.hpp> \ ) \ ) \ /**/ #include BOOST_PP_ITERATE() #if defined(__WAVE__) && defined (HPX_CREATE_PREPROCESSED_FILES) # pragma wave option(output: null) #endif #endif // !defined(HPX_USE_PREPROCESSOR_LIMIT_EXPANSION) #undef BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF #endif #else #define N BOOST_PP_ITERATION() namespace hpx { namespace util { namespace detail { template < typename R BOOST_PP_ENUM_TRAILING_PARAMS(N, typename A) , typename IArchive , typename OArchive > struct empty_vtable< R(BOOST_PP_ENUM_PARAMS(N, A)) , IArchive , OArchive > : empty_vtable_base { typedef R (*functor_type)(BOOST_PP_ENUM_PARAMS(N, A)); static vtable_ptr_base< R(BOOST_PP_ENUM_PARAMS(N, A)) , IArchive , OArchive > *get_ptr() { return get_empty_table< R(BOOST_PP_ENUM_PARAMS(N, A)) >::template get<IArchive, OArchive>(); } BOOST_ATTRIBUTE_NORETURN static R invoke(void ** f BOOST_PP_ENUM_TRAILING(N, BOOST_UTIL_DETAIL_EMPTY_VTABLE_ADD_RVALUE_REF, A)) { hpx::throw_exception(bad_function_call, "empty function object should not be used", "empty_vtable::operator()"); } }; }}} #undef N #endif
31.051613
102
0.540204
andreasbuhr
5b7babe6958aa7327c1581dc0a7afa00fc9aab33
1,960
cpp
C++
khr2/controllers/khr2/KHR2_Data.cpp
llessieux/KHR2Webot
f1d7207c12b2a666b023c4a16082601b29ae54bb
[ "MIT" ]
null
null
null
khr2/controllers/khr2/KHR2_Data.cpp
llessieux/KHR2Webot
f1d7207c12b2a666b023c4a16082601b29ae54bb
[ "MIT" ]
null
null
null
khr2/controllers/khr2/KHR2_Data.cpp
llessieux/KHR2Webot
f1d7207c12b2a666b023c4a16082601b29ae54bb
[ "MIT" ]
null
null
null
#include "KHR2_Data.h" bool RCBMotion::SaveToFile(RCBMotion *m,char *filename) { FILE *f = fopen(filename,"wt"); if ( f == NULL ) return false; fprintf(f,"[GraphicalEdit]\n"); fprintf(f,"Type=%d\n",m->m_type); fprintf(f,"Width=500\n"); fprintf(f,"Height=%d\n",30*((m->m_item_count/8) + 1)); fprintf(f,"Items=%d\n",m->m_item_count); fprintf(f,"Links=%d\n",m->m_link_count); fprintf(f,"Start=%d\n",m->m_start); fprintf(f,"Name=%s\n",m->m_name); fprintf(f,"Port=0\n"); fprintf(f,"Ctrl=%d\n",m->m_control); fprintf(f,"\n"); for(int i=0;i<m->m_item_count;i++) { const RCBMotionItem &item = m->m_items[i]; fprintf(f,"[Item%d]\n",i); fprintf(f,"Name=%s\n",item.m_name); fprintf(f,"Width=%d\n",item.m_width); fprintf(f,"Height=%d\n",item.m_height); fprintf(f,"Left=%d\n",item.m_left); fprintf(f,"Top=%d\n",item.m_top); fprintf(f,"Color=%d\n",item.m_color); fprintf(f,"Type=%d\n",item.m_type); fprintf(f,"Prm="); std::list<int>::const_iterator it = item.m_params.begin(); for(int j=0;j<24;j++,it++) { fprintf(f,"%d",*it); if ( j != 23 ) fprintf(f,","); else fprintf(f,"\n"); } fprintf(f,"\n"); } for(int i=0;i<m->m_link_count;i++) { const RCBMotionLink &item = m->m_links[i]; fprintf(f,"[Link%d]\n",i); fprintf(f,"Main=%d\n",item.m_main); fprintf(f,"Origin=%d\n",item.m_origin); fprintf(f,"Final=%d\n",item.m_final); fprintf(f,"Point="); for(unsigned int j=0;j<item.m_points.size();j++) { fprintf(f,"%d",item.m_points[j]); if ( j != item.m_points.size()-1 ) fprintf(f,","); } fprintf(f,"\n"); fprintf(f,"\n"); } fclose(f); return true; }
28.823529
66
0.497959
llessieux
5b829bdb1b036b5ea700ffa3692ecbcf1da3b1ca
674
hpp
C++
ILogger.hpp
kit-cpp-course/yushkov-ia
f08795754beec39a5b0801a0e4bad8f87c9838b4
[ "MIT" ]
null
null
null
ILogger.hpp
kit-cpp-course/yushkov-ia
f08795754beec39a5b0801a0e4bad8f87c9838b4
[ "MIT" ]
null
null
null
ILogger.hpp
kit-cpp-course/yushkov-ia
f08795754beec39a5b0801a0e4bad8f87c9838b4
[ "MIT" ]
null
null
null
#pragma once #include <string> namespace wv { class OperationLogger; /* * Интерфейс для логирования действий */ class ILogger { public: virtual ~ILogger() = default; /* * Записывает строку в лог */ virtual void Log(const std::string& message) const = 0; /* * Записывает строку в лог, добавляя в конец символ конца строки */ virtual void LogLine(const std::string& message) const = 0; /* * Записывает целое число в лог */ virtual void Log(int value) const = 0; /* * Логирует длительность операции */ virtual OperationLogger LogOperation(const std::string& message) const = 0; }; }
18.216216
78
0.626113
kit-cpp-course
5b876d3da54dbd8e01a2d50acf5895694f48e76a
489
hpp
C++
include/boost/hana/group/minus_mcd.hpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
2
2015-05-07T14:29:13.000Z
2015-07-04T10:59:46.000Z
include/boost/hana/group/minus_mcd.hpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
include/boost/hana/group/minus_mcd.hpp
rbock/hana
2b76377f91a5ebe037dea444e4eaabba6498d3a8
[ "BSL-1.0" ]
null
null
null
/*! @file Defines `boost::hana::Group::minus_mcd`. @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_GROUP_MINUS_MCD_HPP #define BOOST_HANA_GROUP_MINUS_MCD_HPP // minus_mcd is in the forward declaration header because it is required by // the instance for builtins #include <boost/hana/group/group.hpp> #endif // !BOOST_HANA_GROUP_MINUS_MCD_HPP
27.166667
78
0.791411
rbock
5b88b9108869ce09833464ed746880ef99723f20
1,039
cpp
C++
20.Valid_Parentheses/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
20.Valid_Parentheses/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
20.Valid_Parentheses/solution_1.cpp
bngit/leetcode-practices
5324aceac708d9b214a7d98d489b8d5dc55c89e9
[ "MIT" ]
null
null
null
#include <cstdlib> #include <vector> #include <string> #include <cassert> #include <algorithm> #include <sstream> #include <map> #include <typeinfo> #include <iostream> #include <stack> using namespace std; class Solution { public: bool isValid(string s) { stack<char> bracket; for (auto &c : s) { if (!bracket.empty()) { if ((bracket.top() == '(' && c == ')') // 这里写成and也是可以的 || (bracket.top() == '[' && c == ']') || (bracket.top() == '{' && c == '}')) { bracket.pop(); } else { if (c == ')' || c == ']' || c == '}') { return false; } else { bracket.push(c); } } } else { bracket.push(c); } } if (!bracket.empty()) { return false; } return true; } };
23.613636
71
0.358999
bngit
5b8935a5a4c773a5f9f74342fae8a901c867b383
5,673
cpp
C++
DiffSamp/src/code/Main/Nearest2D.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
DiffSamp/src/code/Main/Nearest2D.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
DiffSamp/src/code/Main/Nearest2D.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* Nearest2D.cpp Li-Yi Wei 2/7/2013 */ #include <iostream> #include <fstream> #include <string> using namespace std; #include <stdlib.h> #include "Utility.hpp" #include "Exception.hpp" #include "FrameBuffer.hpp" #include "LloydRelaxation.hpp" #include "DelaunayProximity2D.hpp" #include "Random.hpp" int Main(int argc, char **argv) { int min_argc = 8; if(argc < min_argc) { cerr << "Usage: " << argv[0] << " samples-file-name output-file-name dimension domain_size boundary_condition (0 none, 1 toroidal) dot_radius [color_palette_file]" << endl; return 1; } int arg_ctr = 0; const string input_file_name = argv[++arg_ctr]; const string output_file_name = argv[++arg_ctr]; const int dimension = atoi(argv[++arg_ctr]); const float domain_size_y = atof(argv[++arg_ctr]); const float domain_size_x = atof(argv[++arg_ctr]); const DelaunayProximity2D::BoundaryCondition boundary_condition = static_cast<DelaunayProximity2D::BoundaryCondition>(atoi(argv[++arg_ctr])); const float radius = atof(argv[++arg_ctr]); const double very_small = 0; const int tile_boundary = 1; const int region_boundary = 1; const int color_scheme = 0; const string color_palette_file_name = (arg_ctr+1 < argc ? argv[++arg_ctr] : ""); if(dimension != 2) { cerr << "dimension != 2" << endl; return 1; } // samples vector<Sample> samples; if(! Utility::ReadSamples(dimension, input_file_name, samples)) { cerr << "cannot read samples from " << input_file_name << endl; return 1; } // color palette int num_colors = 0; for(unsigned int i = 0; i < samples.size(); i++) { if((samples[i].id+1) > num_colors) { num_colors = (samples[i].id+1); } } num_colors += 2; // query and answer points Random::InitRandomNumberGenerator(); vector<FrameBuffer::P3> palette; { string message = Utility::BuildPalette(num_colors, color_palette_file_name, palette); if(message != "") { cerr << message << endl; return 1; } } // proximity class vector<DelaunayProximity2D::Point2D> points(samples.size()); for(unsigned int i = 0; i < points.size(); i++) { points[i].id = samples[i].id; points[i].x = samples[i].coordinate[1]; points[i].y = samples[i].coordinate[0]; } vector<const DelaunayProximity2D::Point2D *> p_points(points.size()); for(unsigned int i = 0; i < p_points.size(); i++) { p_points[i] = &points[i]; } const DelaunayProximity2D::Box box(0, domain_size_x, 0, domain_size_y); DelaunayProximity2D proximity2D(box, very_small, boundary_condition, p_points); // query point DelaunayProximity2D::Point2D query, result; query.x = Random::UniformRandom()*domain_size_x; query.y = Random::UniformRandom()*domain_size_y; if(! proximity2D.Nearest(query, result)) { cerr << "cannot query (" << query.x << ", " << query.y << ")" << endl; return 1; } // draw { vector<FrameBuffer::L2F> locations(samples.size()); for(unsigned int i = 0; i < locations.size(); i++) { locations[i].color_index = samples[i].id; locations[i].x = samples[i].coordinate[1]; locations[i].y = samples[i].coordinate[0]; if((locations[i].x == result.x) && (locations[i].y == result.y)) { locations[i].color_index = num_colors - 1; } } FrameBuffer::L2F query_f, result_f; query_f.color_index = num_colors - 2; query_f.x = query.x; query_f.y = query.y; result_f.color_index = num_colors - 1; result_f.x = result.x; result_f.y = result.y; locations.push_back(query_f); locations.push_back(result_f); // generate Voronoi vector<LloydRelaxation::VoronoiRegion> regions; const string message = LloydRelaxation::Voronoi(box.x_min, box.x_max, box.y_min, box.y_max, boundary_condition, p_points, regions); if(message != "") { cerr << "error in generating Voronoi " << message << endl; return 1; } vector<FrameBuffer::Tile> tiles(regions.size()); if(tiles.size() != regions.size()) { throw Exception("weird size mismatch"); } for(unsigned int i = 0; i < tiles.size(); i++) { tiles[i].color_index = regions[i].center.id; tiles[i].vertices = vector<FrameBuffer::L2F>(regions[i].ring.size()); for(unsigned int j = 0; j < tiles[i].vertices.size(); j++) { tiles[i].vertices[j].x = regions[i].ring[j].x; tiles[i].vertices[j].y = regions[i].ring[j].y; } } vector<float> region(4); region[2] = 0; region[3] = fabs(domain_size_y); region[0] = 0; region[1] = fabs(domain_size_x); vector<FrameBuffer::Circle> circles; // draw Voronoi if(!FrameBuffer::WriteFIG(locations, tiles, circles, palette, region, radius, tile_boundary, region_boundary, color_scheme, output_file_name)) { cerr << "error in writing " << output_file_name << endl; return 1; } } // done return 0; } int main(int argc, char **argv) { try { return Main(argc, argv); } catch(Exception e) { cerr << "Error : " << e.Message() << endl; return 1; } }
26.759434
180
0.575886
1iyiwei
5b89baef9f25a6bd3f1dc680290ea321cd6196dd
1,427
cpp
C++
problemes/probleme303.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
6
2015-10-13T17:07:21.000Z
2018-05-08T11:50:22.000Z
problemes/probleme303.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
problemes/probleme303.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
#include "problemes.h" #include "utilitaires.h" typedef unsigned long long nombre; typedef std::vector<nombre> vecteur; namespace { bool trinary(nombre n) { while (n % 10 < 3 && n > 10) { n /= 10; } return n % 10 < 3; } nombre f(size_t n) { nombre base = 1; vecteur v; v.emplace_back(0); while (true) { vecteur tmp; for (size_t i = 1; i < 11; ++i) { for (const nombre &f : v) { nombre m = i * base + f; nombre mn = m * n; if (trinary(mn)) return m; else if (trinary(mn % base)) tmp.push_back(m); } } base *= 10; std::sort(tmp.begin(), tmp.end()); std::swap(tmp, v); } } } ENREGISTRER_PROBLEME(303, "Multiples with small digits") { // For a positive integer n, define f(n) as the least positive multiple of n that, written in base 10, uses only // digits ≤ 2. // // Thus f(2)=2, f(3)=12, f(7)=21, f(42)=210, f(89)=1121222. // ∑ // Also, ∑ n=1..100 f(n)/n = 11363107 // // Find ∑ n=1..10000 f(n)/n. size_t limite = 10000; nombre resultat = 0; for (size_t n = 1; n < limite + 1; ++n) { resultat += f(n); } return std::to_string(resultat); }
26.425926
116
0.451997
ZongoForSpeed
5b8accce8f4a6d09fa5094ea799582fe333cadd5
1,120
cpp
C++
Codeforces/20C - Dijkstra.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
2
2021-04-13T00:19:56.000Z
2021-04-13T01:19:45.000Z
Codeforces/20C - Dijkstra.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
null
null
null
Codeforces/20C - Dijkstra.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
1
2020-08-26T12:36:08.000Z
2020-08-26T12:36:08.000Z
#include<bits/stdc++.h> #define INF 0x3f3f3f3f #define i64 long long #define pii pair<i64, i64> using namespace std; struct Edge{ i64 next, weight; }; const int MAXN = 100005; vector<Edge> adj[MAXN]; int back[MAXN]; i64 weight[MAXN]; int N, M; int main(){ cin >> N >> M; for (int i = 1, a, b, w; i <= M; i++){ cin >> a >> b >> w; adj[a].push_back({b, w}); adj[b].push_back({a, w}); } fill(weight, weight + MAXN, LLONG_MAX); weight[1] = 0; back[1] = 1; priority_queue<pii, vector<pii>, greater<pii>> q; q.push({0, 1}); while (!q.empty()){ pii cur = q.top(); q.pop(); if (cur.second == N) break; for (Edge e : adj[cur.second]){ if (cur.first + e.weight < weight[e.next]){ weight[e.next] = cur.first + e.weight; q.push({weight[e.next], e.next}); back[e.next] = cur.second; } } } if (weight[N] == LLONG_MAX){ cout << -1 << endl; return 0; } int cur = N; vector<int> path; while (cur != back[cur]){ path.push_back(cur); cur = back[cur]; } cout << "1 "; for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << " "; cout << endl; }
17.777778
67
0.549107
Joon7891
5b8baff0ff81c8aab079816830a61a3f5713b118
159
cpp
C++
test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
test/com/facebook/buck/android/testdata/android_project/native/cxx/symbols.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
extern "C" { int __attribute__ ((noinline, visibility ("hidden"))) supply_value() { return 42; } int get_value() { return supply_value(); } }
15.9
72
0.610063
Unknoob
5b8e0ad8c2a72e7b0c96728367d7311d9dd0297c
325
cpp
C++
test/StaircaseSimulator_main.cpp
leiz86/staircase_code_simulator
bba297c1c1fbb4921855b0e4f43afb505c1235fa
[ "Apache-2.0" ]
null
null
null
test/StaircaseSimulator_main.cpp
leiz86/staircase_code_simulator
bba297c1c1fbb4921855b0e4f43afb505c1235fa
[ "Apache-2.0" ]
null
null
null
test/StaircaseSimulator_main.cpp
leiz86/staircase_code_simulator
bba297c1c1fbb4921855b0e4f43afb505c1235fa
[ "Apache-2.0" ]
null
null
null
/* * StaircaseSimulator_main.cpp * * Created on: Dec 10, 2017 * Author: leizhang */ #include "StaircaseSimulator.h" int main(int argc, char **argv) { StaircaseSimulator & scs = StaircaseSimulator::GetInstance(); const char testOpts[] = "test"; scs.init(testOpts); scs.run(0); scs.report(1); return 0; }
15.47619
62
0.664615
leiz86
5b901cc7a7352094517dae80b4131606c50d23d6
674
hpp
C++
src/ResolvedResource.hpp
abelsensors/esp32_https_server
e568d8321764cce26ab76976f6489065b3744c7a
[ "MIT" ]
221
2018-06-11T07:47:54.000Z
2022-03-28T17:56:06.000Z
src/ResolvedResource.hpp
abelsensors/esp32_https_server
e568d8321764cce26ab76976f6489065b3744c7a
[ "MIT" ]
128
2017-12-19T18:18:58.000Z
2022-03-22T01:15:26.000Z
src/ResolvedResource.hpp
abelsensors/esp32_https_server
e568d8321764cce26ab76976f6489065b3744c7a
[ "MIT" ]
82
2018-04-29T01:14:47.000Z
2022-03-21T11:32:02.000Z
#ifndef SRC_RESOLVEDRESOURCE_HPP_ #define SRC_RESOLVEDRESOURCE_HPP_ #include "ResourceNode.hpp" #include "ResourceParameters.hpp" namespace httpsserver { /** * \brief This class represents a resolved resource, meaning the result of mapping a string URL to an HTTPNode */ class ResolvedResource { public: ResolvedResource(); ~ResolvedResource(); void setMatchingNode(HTTPNode * node); HTTPNode * getMatchingNode(); bool didMatch(); ResourceParameters * getParams(); void setParams(ResourceParameters * params); private: HTTPNode * _matchingNode; ResourceParameters * _params; }; } /* namespace httpsserver */ #endif /* SRC_RESOLVEDRESOURCE_HPP_ */
21.741935
110
0.759644
abelsensors
5b91ec74d866de7ea3bd980efbbfe012b81f128a
1,153
cpp
C++
cpp/leetcode/PermutationInString.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/PermutationInString.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
cpp/leetcode/PermutationInString.cpp
danyfang/SourceCode
8168f6058648f2a330a7354daf3a73a4d8a4e730
[ "MIT" ]
null
null
null
//Leetcode Problem No 567 Permutation in String //Solution written by Xuqiang Fang on 24 Oct, 2018 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> using namespace std; class Solution{ public: bool checkInclusion(string s1, string s2) { const int n = s1.length(); const int m = s2.length(); int a[26] = {0}; int b[26] = {0}; for(int i=0; i<n; ++i){ a[s1[i]-'a']++; b[s2[i]-'a']++; } if(compare(a,b)) return true; for(int i=n; i<m; ++i){ b[s2[i-n]-'a']--; b[s2[i]-'a']++; if(compare(a,b)) return true; } return false; } private: bool compare(int* a, int* b){ for(int i=0; i<26; ++i){ if(a[i] != b[i]) return false; } return true; } }; int main(){ Solution s; string s1 = "ab"; string s2 = "eidbaooo"; cout << s.checkInclusion(s1, s2) << endl; s2 = "eidboaoo"; cout << s.checkInclusion(s1, s2) << endl; return 0; }
22.607843
50
0.512576
danyfang
5b9206299cc2c3b46c4b7e669684fcc0a484121e
1,684
hpp
C++
src/modules/tvlp/controller_stack.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
20
2019-12-04T01:28:52.000Z
2022-03-17T14:09:34.000Z
src/modules/tvlp/controller_stack.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
115
2020-02-04T21:29:54.000Z
2022-02-17T13:33:51.000Z
src/modules/tvlp/controller_stack.hpp
DerangedMonkeyNinja/openperf
cde4dc6bf3687f0663c11e9e856e26a0dc2b1d16
[ "Apache-2.0" ]
16
2019-12-03T16:41:18.000Z
2021-11-06T04:44:11.000Z
#ifndef _OP_TVLP_CONTROLLER_STACK_HPP_ #define _OP_TVLP_CONTROLLER_STACK_HPP_ #include <string> #include <memory> #include <unordered_map> #include <vector> #include <variant> #include "tl/expected.hpp" namespace openperf::tvlp { namespace model { class tvlp_configuration_t; class tvlp_result_t; struct tvlp_start_t; } // namespace model namespace internal { class controller_t; class controller_stack { using tvlp_controller_ptr = std::shared_ptr<controller_t>; using tvlp_controller_map = std::unordered_map<std::string, tvlp_controller_ptr>; using tvlp_result_ptr = std::shared_ptr<model::tvlp_result_t>; using tvlp_result_map = std::unordered_map<std::string, tvlp_result_ptr>; private: tvlp_controller_map m_controllers; tvlp_result_map m_results; void* m_context; public: controller_stack() = delete; controller_stack(void* context); std::vector<tvlp_controller_ptr> list() const; tl::expected<tvlp_controller_ptr, std::string> create(const model::tvlp_configuration_t&); tl::expected<tvlp_controller_ptr, std::string> get(const std::string& id) const; tl::expected<void, std::string> erase(const std::string& id); tl::expected<tvlp_result_ptr, std::string> start(const std::string&, const model::tvlp_start_t&); tl::expected<void, std::string> stop(const std::string&); std::vector<tvlp_result_ptr> results() const; tl::expected<tvlp_result_ptr, std::string> result(const std::string& id) const; tl::expected<void, std::string> erase_result(const std::string& id); }; } // namespace internal } // namespace openperf::tvlp #endif /* _OP_TVLP_CONTROLLER_STACK_HPP_ */
27.16129
77
0.738124
DerangedMonkeyNinja
5b9966bc6bc25a5787931306782e1eb5f09e8f9f
12,190
cc
C++
source/extensions/transport_sockets/tls/ssl_handshaker.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
null
null
null
source/extensions/transport_sockets/tls/ssl_handshaker.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
11
2019-10-15T23:03:57.000Z
2020-06-14T16:10:12.000Z
source/extensions/transport_sockets/tls/ssl_handshaker.cc
dcillera/envoy
cb54ba8eec26f768f8c1ae412113b07bacde7321
[ "Apache-2.0" ]
7
2019-07-04T14:23:54.000Z
2020-04-27T08:52:51.000Z
#include "source/extensions/transport_sockets/tls/ssl_handshaker.h" #include "envoy/stats/scope.h" #include "source/common/common/assert.h" #include "source/common/common/empty_string.h" #include "source/common/common/hex.h" #include "source/common/http/headers.h" #include "source/extensions/transport_sockets/tls/utility.h" #include "absl/strings/str_replace.h" #include "openssl/err.h" #include "openssl/x509v3.h" using Envoy::Network::PostIoAction; namespace Envoy { namespace Extensions { namespace TransportSockets { namespace Tls { void SslExtendedSocketInfoImpl::setCertificateValidationStatus( Envoy::Ssl::ClientValidationStatus validated) { certificate_validation_status_ = validated; } Envoy::Ssl::ClientValidationStatus SslExtendedSocketInfoImpl::certificateValidationStatus() const { return certificate_validation_status_; } SslHandshakerImpl::SslHandshakerImpl(bssl::UniquePtr<SSL> ssl, int ssl_extended_socket_info_index, Ssl::HandshakeCallbacks* handshake_callbacks) : ssl_(std::move(ssl)), handshake_callbacks_(handshake_callbacks), state_(Ssl::SocketState::PreHandshake) { SSL_set_ex_data(ssl_.get(), ssl_extended_socket_info_index, &(this->extended_socket_info_)); } bool SslHandshakerImpl::peerCertificatePresented() const { bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); return cert != nullptr; } bool SslHandshakerImpl::peerCertificateValidated() const { return extended_socket_info_.certificateValidationStatus() == Envoy::Ssl::ClientValidationStatus::Validated; } absl::Span<const std::string> SslHandshakerImpl::uriSanLocalCertificate() const { if (!cached_uri_san_local_certificate_.empty()) { return cached_uri_san_local_certificate_; } // The cert object is not owned. X509* cert = SSL_get_certificate(ssl()); if (!cert) { ASSERT(cached_uri_san_local_certificate_.empty()); return cached_uri_san_local_certificate_; } cached_uri_san_local_certificate_ = Utility::getSubjectAltNames(*cert, GEN_URI); return cached_uri_san_local_certificate_; } absl::Span<const std::string> SslHandshakerImpl::dnsSansLocalCertificate() const { if (!cached_dns_san_local_certificate_.empty()) { return cached_dns_san_local_certificate_; } X509* cert = SSL_get_certificate(ssl()); if (!cert) { ASSERT(cached_dns_san_local_certificate_.empty()); return cached_dns_san_local_certificate_; } cached_dns_san_local_certificate_ = Utility::getSubjectAltNames(*cert, GEN_DNS); return cached_dns_san_local_certificate_; } const std::string& SslHandshakerImpl::sha256PeerCertificateDigest() const { if (!cached_sha_256_peer_certificate_digest_.empty()) { return cached_sha_256_peer_certificate_digest_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_sha_256_peer_certificate_digest_.empty()); return cached_sha_256_peer_certificate_digest_; } std::vector<uint8_t> computed_hash(SHA256_DIGEST_LENGTH); unsigned int n; X509_digest(cert.get(), EVP_sha256(), computed_hash.data(), &n); RELEASE_ASSERT(n == computed_hash.size(), ""); cached_sha_256_peer_certificate_digest_ = Hex::encode(computed_hash); return cached_sha_256_peer_certificate_digest_; } const std::string& SslHandshakerImpl::sha1PeerCertificateDigest() const { if (!cached_sha_1_peer_certificate_digest_.empty()) { return cached_sha_1_peer_certificate_digest_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_sha_1_peer_certificate_digest_.empty()); return cached_sha_1_peer_certificate_digest_; } std::vector<uint8_t> computed_hash(SHA_DIGEST_LENGTH); unsigned int n; X509_digest(cert.get(), EVP_sha1(), computed_hash.data(), &n); RELEASE_ASSERT(n == computed_hash.size(), ""); cached_sha_1_peer_certificate_digest_ = Hex::encode(computed_hash); return cached_sha_1_peer_certificate_digest_; } const std::string& SslHandshakerImpl::urlEncodedPemEncodedPeerCertificate() const { if (!cached_url_encoded_pem_encoded_peer_certificate_.empty()) { return cached_url_encoded_pem_encoded_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_url_encoded_pem_encoded_peer_certificate_.empty()); return cached_url_encoded_pem_encoded_peer_certificate_; } bssl::UniquePtr<BIO> buf(BIO_new(BIO_s_mem())); RELEASE_ASSERT(buf != nullptr, ""); RELEASE_ASSERT(PEM_write_bio_X509(buf.get(), cert.get()) == 1, ""); const uint8_t* output; size_t length; RELEASE_ASSERT(BIO_mem_contents(buf.get(), &output, &length) == 1, ""); absl::string_view pem(reinterpret_cast<const char*>(output), length); cached_url_encoded_pem_encoded_peer_certificate_ = absl::StrReplaceAll( pem, {{"\n", "%0A"}, {" ", "%20"}, {"+", "%2B"}, {"/", "%2F"}, {"=", "%3D"}}); return cached_url_encoded_pem_encoded_peer_certificate_; } const std::string& SslHandshakerImpl::urlEncodedPemEncodedPeerCertificateChain() const { if (!cached_url_encoded_pem_encoded_peer_cert_chain_.empty()) { return cached_url_encoded_pem_encoded_peer_cert_chain_; } STACK_OF(X509)* cert_chain = SSL_get_peer_full_cert_chain(ssl()); if (cert_chain == nullptr) { ASSERT(cached_url_encoded_pem_encoded_peer_cert_chain_.empty()); return cached_url_encoded_pem_encoded_peer_cert_chain_; } for (int i = 0; i < sk_X509_num(cert_chain); i++) { X509* cert = sk_X509_value(cert_chain, i); bssl::UniquePtr<BIO> buf(BIO_new(BIO_s_mem())); RELEASE_ASSERT(buf != nullptr, ""); RELEASE_ASSERT(PEM_write_bio_X509(buf.get(), cert) == 1, ""); const uint8_t* output; size_t length; RELEASE_ASSERT(BIO_mem_contents(buf.get(), &output, &length) == 1, ""); absl::string_view pem(reinterpret_cast<const char*>(output), length); cached_url_encoded_pem_encoded_peer_cert_chain_ = absl::StrCat( cached_url_encoded_pem_encoded_peer_cert_chain_, absl::StrReplaceAll( pem, {{"\n", "%0A"}, {" ", "%20"}, {"+", "%2B"}, {"/", "%2F"}, {"=", "%3D"}})); } sk_X509_pop_free(cert_chain, X509_free); return cached_url_encoded_pem_encoded_peer_cert_chain_; } absl::Span<const std::string> SslHandshakerImpl::uriSanPeerCertificate() const { if (!cached_uri_san_peer_certificate_.empty()) { return cached_uri_san_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_uri_san_peer_certificate_.empty()); return cached_uri_san_peer_certificate_; } cached_uri_san_peer_certificate_ = Utility::getSubjectAltNames(*cert, GEN_URI); return cached_uri_san_peer_certificate_; } absl::Span<const std::string> SslHandshakerImpl::dnsSansPeerCertificate() const { if (!cached_dns_san_peer_certificate_.empty()) { return cached_dns_san_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_dns_san_peer_certificate_.empty()); return cached_dns_san_peer_certificate_; } cached_dns_san_peer_certificate_ = Utility::getSubjectAltNames(*cert, GEN_DNS); return cached_dns_san_peer_certificate_; } uint16_t SslHandshakerImpl::ciphersuiteId() const { const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl()); if (cipher == nullptr) { return 0xffff; } // From the OpenSSL docs: // SSL_CIPHER_get_id returns |cipher|'s id. It may be cast to a |uint16_t| to // get the cipher suite value. return static_cast<uint16_t>(SSL_CIPHER_get_id(cipher)); } std::string SslHandshakerImpl::ciphersuiteString() const { const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl()); if (cipher == nullptr) { return {}; } return SSL_CIPHER_get_name(cipher); } const std::string& SslHandshakerImpl::tlsVersion() const { if (!cached_tls_version_.empty()) { return cached_tls_version_; } cached_tls_version_ = SSL_get_version(ssl()); return cached_tls_version_; } Network::PostIoAction SslHandshakerImpl::doHandshake() { ASSERT(state_ != Ssl::SocketState::HandshakeComplete && state_ != Ssl::SocketState::ShutdownSent); int rc = SSL_do_handshake(ssl()); if (rc == 1) { state_ = Ssl::SocketState::HandshakeComplete; handshake_callbacks_->onSuccess(ssl()); // It's possible that we closed during the handshake callback. return handshake_callbacks_->connection().state() == Network::Connection::State::Open ? PostIoAction::KeepOpen : PostIoAction::Close; } else { int err = SSL_get_error(ssl(), rc); ENVOY_CONN_LOG(trace, "ssl error occurred while read: {}", handshake_callbacks_->connection(), Utility::getErrorDescription(err)); switch (err) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: return PostIoAction::KeepOpen; // SSL_ERROR_WANT_PRIVATE_KEY_OPERATION is undefined in OpenSSL // case SSL_ERROR_WANT_PRIVATE_KEY_OPERATION: // state_ = Ssl::SocketState::HandshakeInProgress; // return PostIoAction::KeepOpen; default: handshake_callbacks_->onFailure(); return PostIoAction::Close; } } } const std::string& SslHandshakerImpl::serialNumberPeerCertificate() const { if (!cached_serial_number_peer_certificate_.empty()) { return cached_serial_number_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_serial_number_peer_certificate_.empty()); return cached_serial_number_peer_certificate_; } cached_serial_number_peer_certificate_ = Utility::getSerialNumberFromCertificate(*cert.get()); return cached_serial_number_peer_certificate_; } const std::string& SslHandshakerImpl::issuerPeerCertificate() const { if (!cached_issuer_peer_certificate_.empty()) { return cached_issuer_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_issuer_peer_certificate_.empty()); return cached_issuer_peer_certificate_; } cached_issuer_peer_certificate_ = Utility::getIssuerFromCertificate(*cert); return cached_issuer_peer_certificate_; } const std::string& SslHandshakerImpl::subjectPeerCertificate() const { if (!cached_subject_peer_certificate_.empty()) { return cached_subject_peer_certificate_; } bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { ASSERT(cached_subject_peer_certificate_.empty()); return cached_subject_peer_certificate_; } cached_subject_peer_certificate_ = Utility::getSubjectFromCertificate(*cert); return cached_subject_peer_certificate_; } const std::string& SslHandshakerImpl::subjectLocalCertificate() const { if (!cached_subject_local_certificate_.empty()) { return cached_subject_local_certificate_; } X509* cert = SSL_get_certificate(ssl()); if (!cert) { ASSERT(cached_subject_local_certificate_.empty()); return cached_subject_local_certificate_; } cached_subject_local_certificate_ = Utility::getSubjectFromCertificate(*cert); return cached_subject_local_certificate_; } absl::optional<SystemTime> SslHandshakerImpl::validFromPeerCertificate() const { bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { return absl::nullopt; } return Utility::getValidFrom(*cert); } absl::optional<SystemTime> SslHandshakerImpl::expirationPeerCertificate() const { bssl::UniquePtr<X509> cert(SSL_get_peer_certificate(ssl())); if (!cert) { return absl::nullopt; } return Utility::getExpirationTime(*cert); } const std::string& SslHandshakerImpl::sessionId() const { if (!cached_session_id_.empty()) { return cached_session_id_; } SSL_SESSION* session = SSL_get_session(ssl()); if (session == nullptr) { ASSERT(cached_session_id_.empty()); return cached_session_id_; } unsigned int session_id_length = 0; const uint8_t* session_id = SSL_SESSION_get_id(session, &session_id_length); cached_session_id_ = Hex::encode(session_id, session_id_length); return cached_session_id_; } } // namespace Tls } // namespace TransportSockets } // namespace Extensions } // namespace Envoy
35.747801
100
0.750041
dcillera
5b9d03e9935b8a3135870fceae961f323becc7a0
20,861
hpp
C++
main.hpp
mehmetoguzderin/cpp-2021-vulkan
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
[ "CC0-1.0" ]
null
null
null
main.hpp
mehmetoguzderin/cpp-2021-vulkan
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
[ "CC0-1.0" ]
null
null
null
main.hpp
mehmetoguzderin/cpp-2021-vulkan
07e3eba40e9df66ddd3bce8ea266300dc735a3f0
[ "CC0-1.0" ]
null
null
null
/* Inspired by * https://github.com/KhronosGroup/Vulkan-Hpp/tree/master/RAII_Samples * https://github.com/KhronosGroup/Vulkan-Tools/tree/master/cube * https://github.com/KhronosGroup/Vulkan-Samples/tree/master/samples/extensions/raytracing_basic * https://github.com/glfw/glfw/blob/master/tests/triangle-vulkan.c * https://github.com/charles-lunarg/vk-bootstrap/tree/master/example * https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/main.cpp * https://github.com/nvpro-samples/vk_raytracing_tutorial_KHR */ #include <algorithm> #include <cassert> #include <chrono> #include <cinttypes> #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <filesystem> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <memory> #include <numeric> #include <optional> #include <sstream> #include <stdexcept> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define VK_NO_PROTOTYPES #define VULKAN_HPP_TYPESAFE_CONVERSION #define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1 #include "vulkan/vulkan.hpp" #include "vulkan/vulkan_raii.hpp" VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE #define VMA_VULKAN_VERSION 1002000 #define VMA_STATIC_VULKAN_FUNCTIONS 0 #define VMA_DYNAMIC_VULKAN_FUNCTIONS 0 #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" #define GLFW_INCLUDE_NONE #include "GLFW/glfw3.h" #define IMGUI_IMPL_VULKAN_NO_PROTOTYPES #include "imgui.h" #include "imgui_impl_glfw.h" #include "imgui_impl_vulkan.h" #include "glm/ext.hpp" #include "glm/glm.hpp" using namespace glm; #include "glslang/SPIRV/GlslangToSpv.h" #include "CLI/App.hpp" #include "CLI/Config.hpp" #include "CLI/Formatter.hpp" #include "main.h" struct Main { std::string applicationName{"cpp-2021-vulkan"}; double applicationDuration = 0.0; uint64_t frameCount = 0; double frameDuration = 0.0; UniformConstants uniformConstants{{0, 0, 0}}; std::unique_ptr<vk::raii::Context> context; std::unique_ptr<vk::raii::Instance> instance; std::unique_ptr<vk::raii::PhysicalDevice> physicalDevice; uint32_t queueFamilyIndex; std::unique_ptr<vk::raii::Device> device; std::unique_ptr<vk::raii::Queue> queue; std::unique_ptr<vk::raii::CommandPool> commandPool; void commandPoolSubmit(const std::function<void(const vk::raii::CommandBuffer& commandBuffer)> encoder, vk::Fence waitFence = {}, const vk::ArrayProxyNoTemporaries<const vk::PipelineStageFlags>& waitStageMask = {}, const vk::ArrayProxyNoTemporaries<const vk::Semaphore>& waitSemaphores = {}) { vk::CommandBufferAllocateInfo commandBufferAllocateInfo(**commandPool, vk::CommandBufferLevel::ePrimary, 1); auto commandBuffer = std::move(vk::raii::CommandBuffers(*device, commandBufferAllocateInfo).front()); commandBuffer.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); encoder(commandBuffer); commandBuffer.end(); vk::SubmitInfo submitInfo(waitSemaphores, waitStageMask, *commandBuffer); queue->submit(submitInfo, waitFence); queue->waitIdle(); } std::unique_ptr<vk::raii::DescriptorPool> descriptorPool; VmaAllocator allocator; void allocatorCreate() { VmaVulkanFunctions allocatorVulkanFunctions{}; #define VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(functionName) allocatorVulkanFunctions.functionName = instance->getDispatcher()->functionName #define VMA_VULKAN_FUNCTIONS_RAII_DEVICE(functionName) allocatorVulkanFunctions.functionName = device->getDispatcher()->functionName; #define VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(functionName) \ if (instance->getDispatcher()->functionName##KHR == nullptr) \ allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName; \ else \ allocatorVulkanFunctions.functionName##KHR = instance->getDispatcher()->functionName##KHR; #define VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(functionName) \ if (device->getDispatcher()->functionName##KHR == nullptr) \ allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName; \ else \ allocatorVulkanFunctions.functionName##KHR = device->getDispatcher()->functionName##KHR; VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceProperties); VMA_VULKAN_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkAllocateMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFreeMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkMapMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkUnmapMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkFlushMappedMemoryRanges); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkInvalidateMappedMemoryRanges); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkBindImageMemory); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateBuffer); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyBuffer); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCreateImage); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkDestroyImage); VMA_VULKAN_FUNCTIONS_RAII_DEVICE(vkCmdCopyBuffer); VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetBufferMemoryRequirements2); VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkGetImageMemoryRequirements2); VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindBufferMemory2); VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE(vkBindImageMemory2); VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE(vkGetPhysicalDeviceMemoryProperties2); #undef VMA_VULKAN_KHR_FUNCTIONS_RAII_DEVICE #undef VMA_VULKAN_KHR_FUNCTIONS_RAII_INSTANCE #undef VMA_VULKAN_FUNCTIONS_RAII_DEVICE #undef VMA_VULKAN_FUNCTIONS_RAII_INSTANCE VmaAllocatorCreateInfo allocatorCreateInfo{ .flags = 0, .physicalDevice = static_cast<VkPhysicalDevice>(**physicalDevice), .device = static_cast<VkDevice>(**device), .pVulkanFunctions = &allocatorVulkanFunctions, .instance = static_cast<VkInstance>(**instance), .vulkanApiVersion = VK_API_VERSION_1_2, }; if (vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS) { throw std::runtime_error("vmaCreateAllocator(&allocatorCreateInfo, &allocator) != VK_SUCCESS"); }; } void allocatorDestroy() { vmaDestroyAllocator(allocator); } struct Buffer { vk::Buffer buffer; vk::DescriptorBufferInfo descriptor; VmaAllocation allocation; VmaAllocationInfo info; }; Buffer bufferCreate(const vk::BufferCreateInfo bufferCreateInfo, const VmaAllocationCreateInfo allocationCreateInfo) { VkBufferCreateInfo vkBufferCreateInfo = static_cast<VkBufferCreateInfo>(bufferCreateInfo); VkBuffer vkBuffer; VmaAllocation vmaAllocation; VmaAllocationInfo vmaInfo; if (vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS) { throw std::runtime_error( "vmaCreateBuffer(allocator, &vkBufferCreateInfo, &allocationCreateInfo, &vkBuffer, &vmaAllocation, &vmaInfo) != VK_SUCCESS"); } return Buffer{ .buffer = static_cast<vk::Buffer>(vkBuffer), .descriptor = vk::DescriptorBufferInfo(vkBuffer, 0, bufferCreateInfo.size), .allocation = vmaAllocation, .info = vmaInfo, }; } template <typename T> void bufferUse(const Buffer buffer, const std::function<void(T* data)> user) { void* data; if (vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS) throw std::runtime_error("vmaMapMemory(allocator, buffer.allocation, &data) != VK_SUCCESS"); vmaInvalidateAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range); user(reinterpret_cast<T*>(data)); vmaFlushAllocation(allocator, buffer.allocation, 0, buffer.descriptor.range); vmaUnmapMemory(allocator, buffer.allocation); } void bufferDestroy(Buffer& buffer) { vmaDestroyBuffer(allocator, buffer.buffer, buffer.allocation); } struct Image { vk::Image image; std::unique_ptr<vk::raii::ImageView> view; VmaAllocation allocation; VmaAllocationInfo info; }; Image imageCreate(const vk::ImageCreateInfo imageCreateInfo, vk::ImageViewCreateInfo viewCreateInfo, const VmaAllocationCreateInfo allocationCreateInfo) { auto vkImageCreateInfo = static_cast<VkImageCreateInfo>(imageCreateInfo); VkImage vkImage; VmaAllocation allocation; VmaAllocationInfo allocationInfo; if (vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != VK_SUCCESS) throw std::runtime_error( "vmaCreateImage(allocator, &vkImageCreateInfo, &allocationCreateInfo, &vkImage, &allocation, &allocationInfo) != " "VK_SUCCESS"); vk::Image image(vkImage); viewCreateInfo.image = image; return Image{ .image = static_cast<vk::Image>(vkImage), .view = std::make_unique<vk::raii::ImageView>(*device, viewCreateInfo), .allocation = allocation, .info = allocationInfo, }; } void imageDestroy(Image& image) { image.view.reset(); vmaDestroyImage(allocator, image.image, image.allocation); } vk::raii::ShaderModule shaderModuleCreateFromGlslFile(vk::ShaderStageFlagBits shaderStage, std::filesystem::path shaderGlsl) { std::ifstream shaderModuleMainCompInput(shaderGlsl, std::ios::binary); if (shaderModuleMainCompInput.fail()) { throw std::runtime_error("shaderModuleMainCompInput.fail()"); } std::stringstream shaderModuleMainCompStream; shaderModuleMainCompStream << shaderModuleMainCompInput.rdbuf(); std::string shaderSource = shaderModuleMainCompStream.str(); std::vector<unsigned int> shaderSpirv; EShLanguage stage; switch (shaderStage) { case vk::ShaderStageFlagBits::eVertex: stage = EShLangVertex; break; case vk::ShaderStageFlagBits::eTessellationControl: stage = EShLangTessControl; break; case vk::ShaderStageFlagBits::eTessellationEvaluation: stage = EShLangTessEvaluation; break; case vk::ShaderStageFlagBits::eGeometry: stage = EShLangGeometry; break; case vk::ShaderStageFlagBits::eFragment: stage = EShLangFragment; break; case vk::ShaderStageFlagBits::eCompute: stage = EShLangCompute; break; case vk::ShaderStageFlagBits::eRaygenKHR: stage = EShLangRayGen; break; case vk::ShaderStageFlagBits::eAnyHitKHR: stage = EShLangAnyHit; break; case vk::ShaderStageFlagBits::eClosestHitKHR: stage = EShLangClosestHit; break; case vk::ShaderStageFlagBits::eMissKHR: stage = EShLangMiss; break; case vk::ShaderStageFlagBits::eIntersectionKHR: stage = EShLangIntersect; break; case vk::ShaderStageFlagBits::eCallableKHR: stage = EShLangCallable; break; default: throw std::runtime_error("shaderStage"); } const char* shaderStrings[1]{shaderSource.data()}; glslang::TShader shader(stage); shader.setStrings(shaderStrings, 1); EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules); TBuiltInResource buildInResources{.maxLights = 32, .maxClipPlanes = 6, .maxTextureUnits = 32, .maxTextureCoords = 32, .maxVertexAttribs = 64, .maxVertexUniformComponents = 4096, .maxVaryingFloats = 64, .maxVertexTextureImageUnits = 32, .maxCombinedTextureImageUnits = 80, .maxTextureImageUnits = 32, .maxFragmentUniformComponents = 4096, .maxDrawBuffers = 32, .maxVertexUniformVectors = 128, .maxVaryingVectors = 8, .maxFragmentUniformVectors = 16, .maxVertexOutputVectors = 16, .maxFragmentInputVectors = 15, .minProgramTexelOffset = -8, .maxProgramTexelOffset = 7, .maxClipDistances = 8, .maxComputeWorkGroupCountX = 65535, .maxComputeWorkGroupCountY = 65535, .maxComputeWorkGroupCountZ = 65535, .maxComputeWorkGroupSizeX = 1024, .maxComputeWorkGroupSizeY = 1024, .maxComputeWorkGroupSizeZ = 64, .maxComputeUniformComponents = 1024, .maxComputeTextureImageUnits = 16, .maxComputeImageUniforms = 8, .maxComputeAtomicCounters = 8, .maxComputeAtomicCounterBuffers = 1, .maxVaryingComponents = 60, .maxVertexOutputComponents = 64, .maxGeometryInputComponents = 64, .maxGeometryOutputComponents = 128, .maxFragmentInputComponents = 128, .maxImageUnits = 8, .maxCombinedImageUnitsAndFragmentOutputs = 8, .maxCombinedShaderOutputResources = 8, .maxImageSamples = 0, .maxVertexImageUniforms = 0, .maxTessControlImageUniforms = 0, .maxTessEvaluationImageUniforms = 0, .maxGeometryImageUniforms = 0, .maxFragmentImageUniforms = 8, .maxCombinedImageUniforms = 8, .maxGeometryTextureImageUnits = 16, .maxGeometryOutputVertices = 256, .maxGeometryTotalOutputComponents = 1024, .maxGeometryUniformComponents = 1024, .maxGeometryVaryingComponents = 64, .maxTessControlInputComponents = 128, .maxTessControlOutputComponents = 128, .maxTessControlTextureImageUnits = 16, .maxTessControlUniformComponents = 1024, .maxTessControlTotalOutputComponents = 4096, .maxTessEvaluationInputComponents = 128, .maxTessEvaluationOutputComponents = 128, .maxTessEvaluationTextureImageUnits = 16, .maxTessEvaluationUniformComponents = 1024, .maxTessPatchComponents = 120, .maxPatchVertices = 32, .maxTessGenLevel = 64, .maxViewports = 16, .maxVertexAtomicCounters = 0, .maxTessControlAtomicCounters = 0, .maxTessEvaluationAtomicCounters = 0, .maxGeometryAtomicCounters = 0, .maxFragmentAtomicCounters = 8, .maxCombinedAtomicCounters = 8, .maxAtomicCounterBindings = 1, .maxVertexAtomicCounterBuffers = 0, .maxTessControlAtomicCounterBuffers = 0, .maxTessEvaluationAtomicCounterBuffers = 0, .maxGeometryAtomicCounterBuffers = 0, .maxFragmentAtomicCounterBuffers = 1, .maxCombinedAtomicCounterBuffers = 1, .maxAtomicCounterBufferSize = 16384, .maxTransformFeedbackBuffers = 4, .maxTransformFeedbackInterleavedComponents = 64, .maxCullDistances = 8, .maxCombinedClipAndCullDistances = 8, .maxSamples = 4, .maxMeshOutputVerticesNV = 256, .maxMeshOutputPrimitivesNV = 512, .maxMeshWorkGroupSizeX_NV = 32, .maxMeshWorkGroupSizeY_NV = 1, .maxMeshWorkGroupSizeZ_NV = 1, .maxTaskWorkGroupSizeX_NV = 32, .maxTaskWorkGroupSizeY_NV = 1, .maxTaskWorkGroupSizeZ_NV = 1, .maxMeshViewCountNV = 4, .maxDualSourceDrawBuffersEXT = 1, .limits = { .nonInductiveForLoops = 1, .whileLoops = 1, .doWhileLoops = 1, .generalUniformIndexing = 1, .generalAttributeMatrixVectorIndexing = 1, .generalVaryingIndexing = 1, .generalSamplerIndexing = 1, .generalVariableIndexing = 1, .generalConstantMatrixVectorIndexing = 1, }}; if (!shader.parse(&buildInResources, 100, false, messages)) { throw std::runtime_error(std::string("!shader.parse(&buildInResources, 100, false, messages): getInfoLog:\n") + std::string(shader.getInfoLog()) + std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog())); } glslang::TProgram program; program.addShader(&shader); if (!program.link(messages)) { throw std::runtime_error(std::string("!program.link(messages): getInfoLog:\n") + std::string(shader.getInfoLog()) + std::string("\ngetInfoDebugLog:\n") + std::string(shader.getInfoDebugLog())); } glslang::GlslangToSpv(*program.getIntermediate(stage), shaderSpirv); return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), shaderSpirv)); } vk::raii::ShaderModule shaderModuleCreateFromSpirvFile(std::filesystem::path shaderSpirvFile) { std::ifstream shaderModuleMainCompInput(shaderSpirvFile, std::ios::ate | std::ios::binary); if (shaderModuleMainCompInput.fail()) { throw std::runtime_error("shaderModuleMainCompInput.fail()"); } size_t shaderModuleMainCompInputSize = (size_t)shaderModuleMainCompInput.tellg(); std::vector<char> shaderModuleMainCompSpirv(shaderModuleMainCompInputSize); shaderModuleMainCompInput.seekg(0); shaderModuleMainCompInput.read(shaderModuleMainCompSpirv.data(), static_cast<std::streamsize>(shaderModuleMainCompInputSize)); return vk::raii::ShaderModule(*device, vk::ShaderModuleCreateInfo({}, shaderModuleMainCompInputSize, reinterpret_cast<const uint32_t*>(shaderModuleMainCompSpirv.data()))); } Main() = delete; Main(const Main&) = delete; Main& operator=(const Main&) = delete; Main(int argc, char** argv); };
52.1525
143
0.602656
mehmetoguzderin
5b9f95a8c24e74fea5aa9c4adaa61c6ecec9b7d0
329
cpp
C++
SelectionAlgorithm.cpp
LegatAbyssWalker/SortingAlgorithms
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
[ "MIT" ]
null
null
null
SelectionAlgorithm.cpp
LegatAbyssWalker/SortingAlgorithms
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
[ "MIT" ]
null
null
null
SelectionAlgorithm.cpp
LegatAbyssWalker/SortingAlgorithms
ab902e8c7fe1489899263bd2a7f22553d3ed0ede
[ "MIT" ]
null
null
null
#include "SelectionAlgorithm.h" void SelectionAlgorithm::sort() { // Selective sorts the vector // Sorts through every single element in the vector for (int i = 0; i < numbers.size() - 1; i++) { for (int j = i + 1; j < numbers.size(); j++) { if (numbers[i] > numbers[j]) { std::swap(numbers[i], numbers[j]); } } } }
25.307692
70
0.610942
LegatAbyssWalker
5ba2f21372bc93827fa628f632175b0545dc71f5
2,892
cpp
C++
src/Platform/PlatformVideoUtilsCommon.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
9
2020-11-02T17:20:40.000Z
2021-12-25T15:35:36.000Z
src/Platform/PlatformVideoUtilsCommon.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
2
2020-06-27T23:14:13.000Z
2020-11-02T17:28:32.000Z
src/Platform/PlatformVideoUtilsCommon.cpp
mushware/adanaxis-core-app
679ac3e8a122e059bb208e84c73efc19753e87dd
[ "MIT" ]
1
2021-05-12T23:05:42.000Z
2021-05-12T23:05:42.000Z
//%Header { /***************************************************************************** * * File: src/Platform/PlatformVideoUtilsCommon.cpp * * Copyright: Andy Southgate 2002-2007, 2020 * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * ****************************************************************************/ //%Header } 8CRf6CzmJsi8HkHmspv+DQ /* * $Id$ * $Log$ */ #include "PlatformVideoUtils.h" #include "mushGL.h" #include "mushMedia.h" #include "mushPlatform.h" using namespace Mushware; using namespace std; const GLModeDef& PlatformVideoUtils::DefaultModeDef(void) const { U32 modeNum = 0; for (U32 i=2; i < m_modeDefs.size(); ++i) { if (m_modeDefs[i].Width() == 1024 && m_modeDefs[i].Height() == 768) { modeNum = i; } } return m_modeDefs[modeNum]; } Mushware::U32 PlatformVideoUtils::ModeDefFind(const GLModeDef& inModeDef) const { U32 retVal = 0; for (U32 i=1; i<m_modeDefs.size(); ++i) { if (inModeDef == m_modeDefs[i]) { retVal = i; } } return retVal; } const GLModeDef& PlatformVideoUtils::PreviousModeDef(const GLModeDef& inModeDef) const { U32 modeNum = ModeDefFind(inModeDef); if (modeNum == 0) { modeNum = m_modeDefs.size() - 1; } else { --modeNum; } return m_modeDefs[modeNum]; } const GLModeDef& PlatformVideoUtils::NextModeDef(const GLModeDef& inModeDef) const { U32 modeNum = ModeDefFind(inModeDef); ++modeNum; if (modeNum >= m_modeDefs.size()) { modeNum = 0; } return m_modeDefs[modeNum]; } U32 PlatformVideoUtils::NumModesGet(void) const { return m_modeDefs.size(); } void PlatformVideoUtils::RenderModeInfo(U32 inNum) const { throw MushcoreLogicFail("RenderModeInfo deprecated"); }
25.59292
78
0.640041
mushware
5baa6188461759460a685d8ba329c33d962bcbe3
800
hpp
C++
include/threepp/materials/ShadowMaterial.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
include/threepp/materials/ShadowMaterial.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
include/threepp/materials/ShadowMaterial.hpp
maidamai0/threepp
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
[ "MIT" ]
null
null
null
// https://github.com/mrdoob/three.js/blob/r129/src/materials/ShadowMaterial.js #ifndef THREEPP_SHADOWMATERIAL_HPP #define THREEPP_SHADOWMATERIAL_HPP #include "interfaces.hpp" #include "threepp/materials/Material.hpp" namespace threepp { class ShadowMaterial : public virtual Material, public MaterialWithColor { public: [[nodiscard]] std::string type() const override { return "ShadowMaterial"; } static std::shared_ptr<ShadowMaterial> create() { return std::shared_ptr<ShadowMaterial>(new ShadowMaterial()); } protected: ShadowMaterial() : MaterialWithColor(0x000000) { this->transparent = true; }; }; }// namespace threepp #endif//THREEPP_SHADOWMATERIAL_HPP
22.857143
79
0.655
maidamai0
5baae439c5d71695f8feea2e6d6b6e5df206df47
2,020
cc
C++
src/topo/Tree.cc
rkowalewski/fmpi
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
[ "BSD-3-Clause" ]
null
null
null
src/topo/Tree.cc
rkowalewski/fmpi
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
[ "BSD-3-Clause" ]
null
null
null
src/topo/Tree.cc
rkowalewski/fmpi
39a5e9add0d0354c4a2cceeb0a91518bd9f41796
[ "BSD-3-Clause" ]
null
null
null
#include <fmpi/topo/Tree.hpp> #include <fmpi/util/Math.hpp> #include <fmpi/util/NumericRange.hpp> // TLX #include <tlx/math/ffs.hpp> #include <tlx/math/integer_log2.hpp> #include <tlx/math/round_to_power_of_two.hpp> namespace fmpi { static void knomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) { /* Receive from parent */ auto const vr = (me - tree->root + size) % size; auto const radix = static_cast<int>(tree->radix); auto const nr = static_cast<int>(size); int mask = 0x1; while (mask < nr) { if ((vr % (radix * mask)) != 0) { int parent = vr / (radix * mask) * (radix * mask); parent = (parent + tree->root) % nr; tree->src = mpi::Rank{parent}; break; } mask *= radix; } mask /= radix; /* Send data to all children */ while (mask > 0) { for (int r = 1; r < radix; r++) { int child = vr + mask * r; if (child < nr) { child = (child + tree->root) % nr; tree->destinations.push_back(mpi::Rank{child}); } } mask /= radix; } } static void binomial_tree_aux(Tree* tree, mpi::Rank me, uint32_t size) { // cyclically shifted rank int32_t const vr = (me - tree->root + size) % size; auto const nr = static_cast<int>(size); int d = 1; // distance int r = 0; // round if (vr > 0) { r = tlx::ffs(vr) - 1; d <<= r; auto const from = ((vr ^ d) + tree->root) % nr; tree->src = mpi::Rank{from}; } else { d = tlx::round_up_to_power_of_two(nr); } for (d >>= 1; d > 0; d >>= 1, ++r) { if (vr + d < nr) { auto to = (vr + d + tree->root) % nr; tree->destinations.push_back(mpi::Rank{to}); } } } std::unique_ptr<Tree> knomial( mpi::Rank me, mpi::Rank root, uint32_t size, uint32_t radix) { std::unique_ptr<Tree> tree = std::make_unique<Tree>(root, radix); if (radix == 2) { binomial_tree_aux(tree.get(), me, size); } else { knomial_tree_aux(tree.get(), me, size); } return tree; } } // namespace fmpi
25.56962
72
0.567327
rkowalewski
5bacbd5c8ea68a83f1c1dc754f283ab8e189ec98
2,429
hpp
C++
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/vehicles_land/configs/vehicles/taki_malitia.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
// mortar man /* class CUP_O_2b14_82mm_TK_INS : CUP_2b14_82mm_Base { class Turrets : Turrets { class MainTurret : MainTurret { magazines[] = { "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_shells", "8Rnd_82mm_Mo_Flare_white", "8Rnd_82mm_Mo_Smoke_white" }; weapons[] = {"mortar_82mm"}; }; }; }; */ // m2 BTR milita class CUP_O_BTR40_MG_TKM : CUP_BTR40_MG_Base { class Turrets : Turrets { class MainTurret : MainTurret { magazines[] = { "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M", "CUP_200Rnd_TE1_Red_Tracer_127x99_M" }; weapons[] = {"CUP_Vhmg_M2_veh"}; }; }; }; // APC MT-LB-LV class CUP_O_MTLB_pk_TK_MILITIA : CUP_MTLB_Base { class Turrets : Turrets { class MainTurret : MainTurret { magazines[] = { "CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M", "CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M", "CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M", "CUP_2000Rnd_TE1_Green_Tracer_762x54_PKT_M" }; // default: weapons[] = {"CUP_Vhmg_PKT_veh_Noeject"}; weapons[] = {"CUP_Vhmg_PKT_veh"}; // squirty :) }; }; };
36.80303
65
0.575957
SOCOMD
5bb3bbef1b8d4a974b85de8a136d083579370cf0
1,662
cpp
C++
source/Entity.cpp
thejsa/rhythm-run
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
[ "CC-BY-3.0" ]
1
2022-02-01T19:33:21.000Z
2022-02-01T19:33:21.000Z
source/Entity.cpp
thejsa/rhythm-run
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
[ "CC-BY-3.0" ]
null
null
null
source/Entity.cpp
thejsa/rhythm-run
ab11f97e7552c217bfa4a8392ec96aadf0f9f6b1
[ "CC-BY-3.0" ]
null
null
null
/* * Rhythm Run for Nintendo 3DS * Lauren Kelly, 2020, 2021 */ #include <3ds.h> #include <citro2d.h> #include <stdint.h> // Most getters/setters are defined in the header file to enhance performance optimisations #include "Entity.hpp" Entity::Entity(float a_x, float a_y, C2D_SpriteSheet a_spriteSheet, size_t a_spriteIndex = 0, float a_centerX = 0.5f, float a_centerY = 0.5f, float a_scaleX = 1.0f, float a_scaleY = 1.0f, float a_rotation = 0.0f) : spriteSheet(a_spriteSheet) , spriteIndex(a_spriteIndex) { // Load specified sprite from specified spriteSheet C2D_SpriteFromSheet(&sprite, spriteSheet, spriteIndex); // Set position, scale C2D_SpriteSetCenter(&sprite, a_centerX, a_centerY); C2D_SpriteSetPos(&sprite, a_x, a_y); C2D_SpriteSetScale(&sprite, a_scaleX, a_scaleY); C2D_SpriteSetRotation(&sprite, a_rotation); }; void Entity::setSprite(size_t a_index, C2D_SpriteSheet a_spriteSheet = NULL) { spriteIndex = a_index; // If the caller passed a (valid) spritesheet param, use it if (a_spriteSheet != NULL) { spriteSheet = a_spriteSheet; } sprite.image = C2D_SpriteSheetGetImage(spriteSheet, spriteIndex); } Rectangle Entity::getRect() { float xOffset = getCenterXRaw(); float yOffset = getCenterYRaw(); return Rectangle( // top left corner { sprite.params.pos.x - xOffset, sprite.params.pos.y - yOffset }, // lower right corner { sprite.params.pos.x - xOffset + getWidth(), sprite.params.pos.y - yOffset + getHeight() }); } AABB Entity::getAABB() { return AABB(getRect()); }
27.7
91
0.673887
thejsa
5bb7858ca6daee4250c6e31ec816b851e9d6549e
8,804
hpp
C++
source/timemory/components/skeletons.hpp
jrmadsen/TiMEmory
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
[ "MIT" ]
5
2018-01-19T06:18:00.000Z
2019-07-19T16:08:46.000Z
source/timemory/components/skeletons.hpp
jrmadsen/TiMEmory
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
[ "MIT" ]
1
2018-02-09T21:33:08.000Z
2018-02-11T23:39:47.000Z
source/timemory/components/skeletons.hpp
jrmadsen/TiMEmory
8df2055e68da56e2fe57f716ca9b6d27f7eb4407
[ "MIT" ]
2
2019-06-30T00:46:54.000Z
2019-07-09T18:35:45.000Z
// MIT License // // Copyright (c) 2020, The Regents of the University of California, // through Lawrence Berkeley National Laboratory (subject to receipt of any // required approvals from the U.S. Dept. of Energy). All rights reserved. // // 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 components/skeletons.hpp * \headerfile components/skeletons.hpp "timemory/components/skeletons.hpp" * * These provide fake types for heavyweight types w.r.t. templates. In general, * if a component is templated or contains a lot of code, create a skeleton * and in \ref timemory/components/types.hpp use an #ifdef to provide the skeleton * instead. Also, make sure the component file is not directly included. * If the type uses callbacks, emulate the callbacks here. * */ #pragma once #include <cstdint> #include <functional> #include <iostream> #include <string> #include <tuple> #include <type_traits> #include <vector> #include "timemory/ert/types.hpp" // clang-format off namespace tim { namespace device { struct cpu; struct gpu; } } // clang-format on //======================================================================================// // namespace tim { namespace component { namespace skeleton { //--------------------------------------------------------------------------------------// struct base {}; //--------------------------------------------------------------------------------------// template <typename... _Types> struct cuda {}; //--------------------------------------------------------------------------------------// template <typename... _Types> struct nvtx {}; //--------------------------------------------------------------------------------------// template <typename _Kind> struct cupti_activity { using activity_kind_t = _Kind; using kind_vector_type = std::vector<activity_kind_t>; using get_initializer_t = std::function<kind_vector_type()>; static get_initializer_t& get_initializer() { static auto _lambda = []() { return kind_vector_type{}; }; static get_initializer_t _instance = _lambda; return _instance; } }; //--------------------------------------------------------------------------------------// template <typename... _Types> struct cupti_counters { // short-hand for vectors using string_t = std::string; using strvec_t = std::vector<string_t>; /// a tuple of the <devices, events, metrics> using tuple_type = std::tuple<int, strvec_t, strvec_t>; /// function for setting all of device, metrics, and events using get_initializer_t = std::function<tuple_type()>; static get_initializer_t& get_initializer() { static auto _lambda = []() -> tuple_type { return tuple_type{}; }; static get_initializer_t _instance = _lambda; return _instance; } }; //--------------------------------------------------------------------------------------// template <typename... _Types> struct gpu_roofline { using device_t = device::cpu; using clock_type = wall_clock; using ert_data_t = ert::exec_data<clock_type>; using ert_data_ptr_t = std::shared_ptr<ert_data_t>; // short-hand for variadic expansion template <typename _Tp> using ert_config_type = ert::configuration<device_t, _Tp, clock_type>; template <typename _Tp> using ert_counter_type = ert::counter<device_t, _Tp, clock_type>; template <typename _Tp> using ert_executor_type = ert::executor<device_t, _Tp, clock_type>; template <typename _Tp> using ert_callback_type = ert::callback<ert_executor_type<_Tp>>; // variadic expansion for ERT types using ert_config_t = std::tuple<ert_config_type<_Types>...>; using ert_counter_t = std::tuple<ert_counter_type<_Types>...>; using ert_executor_t = std::tuple<ert_executor_type<_Types>...>; using ert_callback_t = std::tuple<ert_callback_type<_Types>...>; static ert_config_t& get_finalizer() { static ert_config_t _instance; return _instance; } }; //--------------------------------------------------------------------------------------// template <size_t N> struct papi_array { using event_list = std::vector<int>; using get_initializer_t = std::function<event_list()>; static get_initializer_t& get_initializer() { static get_initializer_t _instance = []() { return event_list{}; }; return _instance; } }; //--------------------------------------------------------------------------------------// template <int... _Types> struct papi_tuple {}; //--------------------------------------------------------------------------------------// template <typename... _Types> struct cpu_roofline { using device_t = device::cpu; using clock_type = wall_clock; using ert_data_t = ert::exec_data<clock_type>; using ert_data_ptr_t = std::shared_ptr<ert_data_t>; // short-hand for variadic expansion template <typename _Tp> using ert_config_type = ert::configuration<device_t, _Tp, clock_type>; template <typename _Tp> using ert_counter_type = ert::counter<device_t, _Tp, clock_type>; template <typename _Tp> using ert_executor_type = ert::executor<device_t, _Tp, clock_type>; template <typename _Tp> using ert_callback_type = ert::callback<ert_executor_type<_Tp>>; // variadic expansion for ERT types using ert_config_t = std::tuple<ert_config_type<_Types>...>; using ert_counter_t = std::tuple<ert_counter_type<_Types>...>; using ert_executor_t = std::tuple<ert_executor_type<_Types>...>; using ert_callback_t = std::tuple<ert_callback_type<_Types>...>; static ert_config_t& get_finalizer() { static ert_config_t _instance; return _instance; } }; //--------------------------------------------------------------------------------------// template <size_t _N, typename... _Types> struct gotcha { using config_t = void; using get_initializer_t = std::function<config_t()>; static get_initializer_t& get_initializer() { static get_initializer_t _instance = []() {}; return _instance; } }; //--------------------------------------------------------------------------------------// template <typename... _Types> struct caliper {}; //--------------------------------------------------------------------------------------// } // namespace skeleton //--------------------------------------------------------------------------------------// template <typename _Tp, typename _Vp> struct base; //--------------------------------------------------------------------------------------// template <typename _Tp> struct base<_Tp, skeleton::base> { static constexpr bool implements_storage_v = false; using Type = _Tp; using value_type = void; using base_type = base<_Tp, skeleton::base>; }; //--------------------------------------------------------------------------------------// } // namespace component } // namespace tim #if !defined(TIMEMORY_USE_GOTCHA) # if !defined(TIMEMORY_C_GOTCHA) # define TIMEMORY_C_GOTCHA(...) # endif # if !defined(TIMEMORY_DERIVED_GOTCHA) # define TIMEMORY_DERIVED_GOTCHA(...) # endif # if !defined(TIMEMORY_CXX_GOTCHA) # define TIMEMORY_CXX_GOTCHA(...) # endif # if !defined(TIMEMORY_CXX_MEMFUN_GOTCHA) # define TIMEMORY_CXX_MEMFUN_GOTCHA(...) # endif # if !defined(TIMEMORY_C_GOTCHA_TOOL) # define TIMEMORY_C_GOTCHA_TOOL(...) # endif # if !defined(TIMEMORY_CXX_GOTCHA_TOOL) # define TIMEMORY_CXX_GOTCHA_TOOL(...) # endif #endif
32.249084
90
0.57701
jrmadsen
5bb8c970b64a85013e95d0db4749b351bf6490b0
8,033
cc
C++
subprojects/libbeyond-runtime_tflite/src/main.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
subprojects/libbeyond-runtime_tflite/src/main.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
subprojects/libbeyond-runtime_tflite/src/main.cc
nicesj/beyond
a0ccff33caeb2fda4a6c2071adb5581b5a63d0f3
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(NDEBUG) #include <cstdio> #include <cstdlib> #include <cstring> #include <cerrno> #include <getopt.h> #include <unistd.h> #include <beyond/private/beyond_private.h> #include "runtime.h" extern "C" { extern void *_main(int argc, char *argv[]); static void help(void) { fprintf(stderr, "Help message\n" "-----------------------------------------\n" "-h help\n" "-i filename input filename\n" "-t input_tensor type input filename\n" "-m filename model filename\n" "\n"); } // ApplicationContext int main(void) { const option opts[] = { { .name = "help", .has_arg = 0, .flag = nullptr, .val = 'h', }, { .name = "model", .has_arg = 1, .flag = nullptr, .val = 'm', }, { .name = "input", .has_arg = 1, .flag = nullptr, .val = 'i', }, { .name = "type", .has_arg = 1, .flag = nullptr, .val = 't', }, { .name = "size", // Count of input tensor .has_arg = 1, .flag = nullptr, .val = 's', }, // TODO: // Add more options }; static const char *optstr = "-:hm:i:t:s:"; char *model = nullptr; char *type = nullptr; int argc = 0; char **argv = nullptr; beyond_tensor *input = nullptr; beyond_tensor *output = nullptr; FILE *fp = fopen("input.txt", "r"); if (fp != nullptr) { if (fscanf(fp, "%d\n", &argc) == 1 && argc > 0) { if (argc < 0 || static_cast<unsigned int>(argc) > strlen(optstr)) { fprintf(stderr, "Too many arguments: %d\n", argc); _exit(EINVAL); } argv = static_cast<char **>(calloc(argc, sizeof(char *))); if (argv == nullptr) { ErrPrintCode(errno, "calloc"); _exit(ENOMEM); } for (int i = 0; i < argc; i++) { char buffer[1024]; if (fscanf(fp, "%1023s\n", buffer) == 1) { argv[i] = strdup(buffer); } else { ErrPrint("Unable to parse the argument buffer"); argv[i] = nullptr; } } } fclose(fp); fp = nullptr; } int input_size = 0; int input_idx = 0; if (argc > 0 && argv != nullptr) { int c; int idx; while ((c = getopt_long(argc, argv, optstr, opts, &idx)) != -1) { switch (c) { case 'h': help(); _exit(0); break; case 'm': model = strdup(optarg); break; case 's': if (sscanf(optarg, "%d", &input_size) != 1) { fprintf(stderr, "Invalid input size parameter\n"); _exit(EINVAL); } //Temporary max size if (1024 < input_size || input_size < 0) { fprintf(stderr, "Invalid input size(%d) parameter\n", input_size); _exit(EINVAL); } input = static_cast<beyond_tensor *>(calloc(input_size, sizeof(beyond_tensor))); if (input == nullptr) { int ret = errno; ErrPrintCode(errno, "calloc"); _exit(ret); } break; case 'i': if (input_idx == input_size) { fprintf(stderr, "Invalid input tensor, input_size must be given first (%d, %d)\n", input_idx, input_size); _exit(EINVAL); } if (optarg != nullptr) { FILE *fp = fopen(optarg, "r"); if (fp != nullptr) { fseek(fp, 0L, SEEK_END); input[input_idx].size = ftell(fp); fseek(fp, 0L, SEEK_SET); input[input_idx].data = malloc(input[input_idx].size); if (input[input_idx].data == nullptr) { ErrPrintCode(errno, "malloc"); } else { if (fread(input[input_idx].data, input[input_idx].size, 1, fp) != 1) { ErrPrintCode(errno, "fread"); _exit(EIO); } } if (fclose(fp) < 0) { ErrPrintCode(errno, "Unable to close the file pointer"); } } } input_idx++; break; case 't': if (nullptr == input) { fprintf(stderr, "Invalid input(NULL)"); break; } if (strcmp(optarg, "int8") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_INT8; } else if (strcmp(optarg, "int16") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_INT16; } else if (strcmp(optarg, "int32") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_INT32; } else if (strcmp(optarg, "uint8") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_UINT8; } else if (strcmp(optarg, "uint16") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_UINT16; } else if (strcmp(optarg, "uint32") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_UINT32; } else if (strcmp(optarg, "float16") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_FLOAT16; } else if (strcmp(optarg, "float32") == 0) { input[input_idx].type = BEYOND_TENSOR_TYPE_FLOAT32; } break; default: break; } } } if (model == nullptr || input == nullptr || input_idx < input_size) { fprintf(stderr, "Invalid arguments (%d,%d)\n", input_idx, input_size); help(); _exit(1); } optind = 0; opterr = 0; Runtime *runtime = reinterpret_cast<Runtime *>(_main(argc, argv)); if (runtime == nullptr) { _exit(EFAULT); } runtime->LoadModel(model); runtime->Prepare(); runtime->Invoke(input, input_size); int output_size; runtime->GetOutput(output, output_size); // // Runtime has no main loop. // It runs once // // TODO: manipulate the output tensor // runtime->FreeTensor(output, output_size); runtime->Destroy(); free(type); free(model); for (int i = 0; i < input_size; i++) { free(input[i].data); } free(input); if (argc > 0) { for (int i = 0; i < argc; i++) { free(argv[i]); argv[i] = nullptr; } free(argv); argv = nullptr; argc = 0; } _exit(0); } } // extern "C" #endif // NDEBUG
30.777778
126
0.448898
nicesj
5bbd11e7b929fb4ebc121c86d07aa92388bede86
1,954
cpp
C++
spleeter/inference_engine/inference_engine_strategy.cpp
jinay1991/spleeter
ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8
[ "MIT" ]
25
2020-05-16T16:08:30.000Z
2022-03-09T04:58:16.000Z
spleeter/inference_engine/inference_engine_strategy.cpp
jinay1991/spleeter
ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8
[ "MIT" ]
2
2020-08-15T17:28:46.000Z
2021-09-28T16:14:14.000Z
spleeter/inference_engine/inference_engine_strategy.cpp
jinay1991/spleeter
ae21059a369b8d13da7b5581fc8b7b5cb5ac9ec8
[ "MIT" ]
3
2021-07-29T08:05:03.000Z
2022-03-22T14:28:05.000Z
/// /// @file /// @copyright Copyright (c) 2020. MIT License /// #include "spleeter/inference_engine/inference_engine_strategy.h" #include "spleeter/inference_engine/null_inference_engine.h" #include "spleeter/inference_engine/tf_inference_engine.h" #include "spleeter/inference_engine/tflite_inference_engine.h" #include "spleeter/logging/logging.h" namespace spleeter { InferenceEngineStrategy::InferenceEngineStrategy() : inference_engine_type_{InferenceEngineType::kInvalid} {} void InferenceEngineStrategy::SelectInferenceEngine(const InferenceEngineType& inference_engine_type, const InferenceEngineParameters& inference_engine_parameters) { inference_engine_type_ = inference_engine_type; switch (inference_engine_type) { case InferenceEngineType::kTensorFlow: { inference_engine_ = std::make_unique<TFInferenceEngine>(inference_engine_parameters); break; } case InferenceEngineType::kTensorFlowLite: { inference_engine_ = std::make_unique<TFLiteInferenceEngine>(inference_engine_parameters); break; } case InferenceEngineType::kInvalid: default: { inference_engine_ = std::make_unique<NullInferenceEngine>(inference_engine_parameters); LOG(ERROR) << "Received " << inference_engine_type; break; } } } void InferenceEngineStrategy::Init() { inference_engine_->Init(); } void InferenceEngineStrategy::Execute(const Waveform& waveform) { inference_engine_->Execute(waveform); } void InferenceEngineStrategy::Shutdown() { inference_engine_->Shutdown(); } Waveforms InferenceEngineStrategy::GetResults() const { return inference_engine_->GetResults(); } InferenceEngineType InferenceEngineStrategy::GetInferenceEngineType() const { return inference_engine_type_; } } // namespace spleeter
28.735294
113
0.716991
jinay1991
5bc0536983148928798ae84baf6880e890bcda6c
423
hpp
C++
include/geometry/segment.hpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
include/geometry/segment.hpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
include/geometry/segment.hpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#pragma once #include "geometry/line.hpp" class Segment : public Line, public Ordered<Segment> { public: Segment() {} Segment(const Point &a, const Point &b) : Line(a, b) {} Segment(Input &in) : Line(in) {} bool operator<(const Segment &segment) const { return a == segment.a ? b < segment.b : a < segment.a; } Real area() const { return (this->a.x * this->b.y - this->a.y * this->b.x) / 2; } };
21.15
63
0.602837
not522
5bc0960b3dc3a2099c06255085cb44c962ad84b4
1,447
cpp
C++
ex02/Base.cpp
Igors78/cpp06
d50929edcaef218d68ab04b41d4a6693032f83bb
[ "Unlicense" ]
1
2021-11-28T14:16:09.000Z
2021-11-28T14:16:09.000Z
ex02/Base.cpp
Igors78/cpp06
d50929edcaef218d68ab04b41d4a6693032f83bb
[ "Unlicense" ]
null
null
null
ex02/Base.cpp
Igors78/cpp06
d50929edcaef218d68ab04b41d4a6693032f83bb
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Base.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ioleinik <ioleinik@student.42wolfsburg.de> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/28 15:47:22 by ioleinik #+# #+# */ /* Updated: 2021/11/28 15:47:43 by ioleinik ### ########.fr */ /* */ /* ************************************************************************** */ #include "Base.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ /* ** -------------------------------- DESTRUCTOR -------------------------------- */ Base::~Base() { } /* ** --------------------------------- OVERLOAD --------------------------------- */ /* ** --------------------------------- METHODS ---------------------------------- */ /* ** --------------------------------- ACCESSOR --------------------------------- */ /* ************************************************************************** */
37.102564
80
0.12094
Igors78
5bc41a641535e7d8eed059d8775775b59ce17c70
3,943
cpp
C++
src/xray/render/engine/sources/effect_deffer_aref.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/render/engine/sources/effect_deffer_aref.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/render/engine/sources/effect_deffer_aref.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 20.02.2009 // Author : Mykhailo Parfeniuk // Copyright ( C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <xray/render/engine/effect_deffer_aref.h> #include <xray/render/core/effect_compiler.h> namespace xray { namespace render_dx10 { effect_deffer_aref::effect_deffer_aref( bool is_lmapped): effect_deffer_base( false, false, false) { m_blend = FALSE; m_desc.m_version = 1; m_is_lmapped = is_lmapped; } void effect_deffer_aref::compile_blended( effect_compiler& compiler, const effect_compilation_options& options) { shader_defines_list defines; make_defines( defines); if ( m_is_lmapped) { compiler.begin_pass( "lmapE", "lmapE", defines) //.set_depth( TRUE) .set_alpha_blend ( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA) .bind_constant ( "alpha_ref", &m_aref_val) .set_texture ( "t_base", options.tex_list[0]) .def_sampler ( "s_lmap") .set_texture ( "t_lmap", options.tex_list[1]) .def_sampler ( "s_hemi", D3D_TEXTURE_ADDRESS_CLAMP, D3D_FILTER_MIN_MAG_LINEAR_MIP_POINT) .set_texture ( "t_hemi", options.tex_list[2]) .def_sampler ( "s_env", D3D_TEXTURE_ADDRESS_CLAMP) .set_texture ( "t_env", r2_t_envs0) .end_pass(); //C.r_Pass ( "lmapE","lmapE",TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value); //C.r_Sampler ( "s_base", C.L_textures[0] ); //C.r_Sampler ( "s_lmap", C.L_textures[1] ); //C.r_Sampler_clf ( "s_hemi", *C.L_textures[2]); //C.r_Sampler ( "s_env", r2_T_envs0, false,D3DTADDRESS_CLAMP); //C.r_End (); } else { compiler.begin_pass( "vert", "vert", defines) .set_alpha_blend( true, D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA) .bind_constant ( "alpha_ref", &m_aref_val) .set_texture ( "t_base", options.tex_list[0]) .end_pass(); //C.r_Pass ( "vert", "vert", TRUE,TRUE,FALSE,TRUE,D3D_BLEND_SRC_ALPHA, D3D_BLEND_INV_SRC_ALPHA, TRUE, oAREF.value); //C.r_Sampler ( "s_base", C.L_textures[0] ); //C.r_End (); } } void effect_deffer_aref::compile( effect_compiler& compiler, const effect_compilation_options& options) { if ( m_blend) { compiler.begin_technique( /*SE_R2_NORMAL_HQ*/); compile_blended( compiler, options); compiler.end_technique(); compiler.begin_technique( /*SE_R2_NORMAL_LQ*/); compile_blended( compiler, options); compiler.end_technique(); } else { shader_defines_list defines; make_defines( defines); //C.SetParams ( 1,false); //. // codepath is the same, only the shaders differ // ***only pixel shaders differ*** compiler.begin_technique( /*SE_R2_NORMAL_HQ*/); uber_deffer( compiler, "base", "base", true, true, options); compiler.end_technique(); compiler.begin_technique( /*SE_R2_NORMAL_LQ*/); uber_deffer( compiler, "base", "base", false, true, options); compiler.end_technique(); compiler.begin_technique( /*SE_R2_SHADOW*/); //if ( RImplementation.o.HW_smap) // compiler.begin_pass( "shadow_direct_base_aref","shadow_direct_base_aref"); //else compiler.begin_pass ( "shadow_direct_base_aref", "shadow_direct_base_aref", defines) .set_depth ( true, true) .set_alpha_blend( FALSE) .bind_constant ( "alpha_ref", &m_aref_val220) .set_texture ( "t_base", options.tex_list[0]) .end_pass() .end_technique(); } } void effect_deffer_aref::load( memory::reader& mem_reader) { effect::load( mem_reader); if ( 1==m_desc.m_version) { xrP_Integer aref_val; xrPREAD_PROP( mem_reader, xrPID_INTEGER, aref_val); //m_aref_val = aref_val.value; xrP_BOOL blend; xrPREAD_PROP( mem_reader, xrPID_BOOL, blend); m_blend = blend.value != 0; } } } // namespace render } // namespace xray
32.319672
120
0.660918
ixray-team
5bc45115070be632ff4387809bd1a9b96c905e7b
1,281
hpp
C++
src/third.hpp
hobby-dev/sirius
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
[ "MIT" ]
null
null
null
src/third.hpp
hobby-dev/sirius
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
[ "MIT" ]
null
null
null
src/third.hpp
hobby-dev/sirius
8bfdef75f225ba50bde16b3f75c8b6ac09cebb86
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> namespace sirius { // Problem 3: // Implement Serialize and Deserialize methods of List class. Serialize into binary // file. Note: all relationships between elements of the list must be preserved. // Definitions of struct ListNode and class List are provided: //struct ListNode { // ListNode *prev; // ListNode *next; // ListNode *rand; // points to a random element of the list or is NULL // std::string data; //}; // //class List { // // public: // void Serialize(FILE *file); // void Deserialize(FILE *file); // // private: // ListNode *head; // ListNode *tail; // int count; //}; struct ListNode { ListNode *prev{nullptr}; ListNode *next{nullptr}; ListNode *rand{nullptr}; // points to a random element of the list or is NULL std::string data{}; }; class List { public: ~List(); void PushBack(std::string &&value); ListNode *accessNode(uint64_t index); uint64_t Size() { return count; } /** * @param file must be opened with fopen(path, "wb")) */ void Serialize(FILE *file); /** * @param file must be opened with fopen(path, "rb")) */ void Deserialize(FILE *file); private: void cleanup(); ListNode *head{nullptr}; ListNode *tail{nullptr}; uint64_t count{0}; }; }
20.66129
83
0.662763
hobby-dev
5bc5e1a9b900718c300882d1eed2067f504bb910
4,287
cpp
C++
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
goev/Open-Vehicle-Monitoring-System-3
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
[ "MIT" ]
null
null
null
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
goev/Open-Vehicle-Monitoring-System-3
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
[ "MIT" ]
null
null
null
vehicle/OVMS.V3/components/can/src/candump_crtd.cpp
goev/Open-Vehicle-Monitoring-System-3
f2efd1898ec1df19eb730c1eda9a1999a00b36b4
[ "MIT" ]
null
null
null
/* ; Project: Open Vehicle Monitor System ; Module: CAN dump framework ; Date: 18th January 2018 ; ; (C) 2018 Mark Webb-Johnson ; ; 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 "ovms_log.h" //static const char *TAG = "candump-crtd"; #include <errno.h> #include "pcp.h" #include "candump_crtd.h" candump_crtd::candump_crtd() { m_bufpos = 0; } candump_crtd::~candump_crtd() { } const char* candump_crtd::formatname() { return "crtd"; } std::string candump_crtd::get(struct timeval *time, CAN_frame_t *frame) { m_bufpos = 0; char busnumber[2]; busnumber[0]=0; busnumber[1]=0; if (frame->origin) { const char* name = frame->origin->GetName(); if (*name != 0) { while (name[1] != 0) name++; busnumber[0] = *name; } } sprintf(m_buf,"%ld.%06ld %sR%s %0*X", time->tv_sec, time->tv_usec, busnumber, (frame->FIR.B.FF == CAN_frame_std) ? "11":"29", (frame->FIR.B.FF == CAN_frame_std) ? 3 : 8, frame->MsgID); for (int k=0; k<frame->FIR.B.DLC; k++) sprintf(m_buf+strlen(m_buf)," %02x", frame->data.u8[k]); strcat(m_buf,"\n"); return std::string(m_buf); } std::string candump_crtd::getheader(struct timeval *time) { m_bufpos = 0; sprintf(m_buf,"%ld.%06ld CXX OVMS\n", time->tv_sec, time->tv_usec); return std::string(m_buf); } size_t candump_crtd::put(CAN_frame_t *frame, uint8_t *buffer, size_t len) { size_t k; char *b = (char*)buffer; memset(frame,0,sizeof(CAN_frame_t)); for (k=0;k<len;k++) { if ((b[k]=='\r')||(b[k]=='\n')) { //ESP_EARLY_LOGI(TAG,"CRTD GOT CR/LF %02x",b[k]); if (m_bufpos == 0) continue; else break; } m_buf[m_bufpos] = b[k]; if (m_bufpos < CANDUMP_CRTD_MAXLEN) m_bufpos++; } //ESP_EARLY_LOGI(TAG,"CRTD PUT bufpos=%d inlen=%d now=%d",m_bufpos,len,k); if (k>=len) return len; // OK. We have a buffer ready for decoding... // buffer[Start .. k-1] m_buf[m_bufpos] = 0; //ESP_EARLY_LOGI(TAG,"CRTD message buffer is %d bytes",m_bufpos); m_bufpos = 0; // Prepare for next message b = m_buf; // We look for something like // 1524311386.811100 1R11 100 01 02 03 if (!isdigit(b[0])) return k+1; for (;((*b != 0)&&(*b != ' '));b++) {} if (*b == 0) return k+1; b++; char bus = '1'; if (isdigit(*b)) { bus = *b; b++; } if ((b[0]=='R')&&(b[1]=='1')&&(b[2]=='1')) { // R11 incoming CAN frame frame->FIR.B.FF = CAN_frame_std; } else if ((b[0]=='R')&&(b[1]=='2')&&(b[2]=='9')) { // R29 incoming CAN frame frame->FIR.B.FF = CAN_frame_ext; } else return k+1; if (b[3] != ' ') return k+1; b += 4; char *p; errno = 0; frame->MsgID = (uint32_t)strtol(b,&p,16); if ((frame->MsgID == 0)&&(errno != 0)) return k+1; b = p; for (int k=0;k<8;k++) { if (*b==0) break; b++; errno = 0; long d = strtol(b,&p,16); if ((d==0)&&(errno != 0)) break; frame->data.u8[k] = (uint8_t)d; frame->FIR.B.DLC++; b = p; } char cbus[5] = "can"; cbus[3] = bus; cbus[4] = 0; frame->origin = (canbus*)MyPcpApp.FindDeviceByName(cbus); //ESP_EARLY_LOGI(TAG,"CRTD done return=%d",k+1); return k+1; }
24.924419
79
0.605318
goev
5bcacfe1a4fe9b010dae211b326b9cca39bbf3d2
10,990
cpp
C++
src/demeter-win/vs/simple/work.cpp
pcdeadeasy/NetworkDirect
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
[ "MIT" ]
1
2019-06-18T23:31:10.000Z
2019-06-18T23:31:10.000Z
src/demeter-win/vs/simple/work.cpp
pcdeadeasy/NetworkDirect
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
[ "MIT" ]
null
null
null
src/demeter-win/vs/simple/work.cpp
pcdeadeasy/NetworkDirect
4c2ee56604c3493f87313dbb7bc8b1630dceaf39
[ "MIT" ]
1
2019-06-18T21:43:29.000Z
2019-06-18T21:43:29.000Z
#include <libraries/logger/Logger.h> #include <libraries/Winshim/Winshim.h> #include <libraries/ndutil/ndutil.h> #include <libraries/ndutil/ndtestutil.h> #include "params.h" #include "ndscope.h" #include "errors.h" #include "work.h" static void stage8( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile, IND2MemoryRegion* const pMemoryRegion, ND2_ADAPTER_INFO const* const pInfo, IND2CompletionQueue* const pSendCompletionQueue, IND2CompletionQueue* const pRecvCompletionQueue, IND2QueuePair* const pQueuePair ) { LOG_ENTER(); IND2Connector* pConnector = 0; HRESULT hr = pAdapter->CreateConnector(IID_IND2Connector, hOverlappedFile, (void**)&pConnector); LOG("IND2Adapter::CreateConnector -> %08X", hr); if (ND_SUCCESS != hr) throw EX_CREATE_CONNECTOR; try { (*work)( params, pAddress, pAdapter, hOverlappedFile, pMemoryRegion, pInfo, pSendCompletionQueue, pRecvCompletionQueue, pQueuePair, pConnector ); } catch (...) { ULONG ul = pConnector->Release(); LOG("IND2QueuePair::Release -> %u", ul); throw; } ULONG ul = pConnector->Release(); LOG("IND2Connector::Release -> %u", ul); LOG_VOID_RETURN(); } static void stage7( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile, IND2MemoryRegion* const pMemoryRegion, ND2_ADAPTER_INFO const* const pInfo, IND2CompletionQueue* const pSendCompletionQueue, IND2CompletionQueue* const pRecvCompletionQueue ) { LOG_ENTER(); static void* const context = (void*)"CreateQueuePair context"; ULONG const recvQueueDepth = 3; ULONG const sendQueueDepth = 3; ULONG const maxRecvRequestSge = 3; ULONG const maxSendRequestSge = 3; ULONG const inlineDataSize = pInfo->MaxInlineDataSize; IND2QueuePair* pQueuePair = 0; HRESULT const hr = pAdapter->CreateQueuePair( IID_IND2QueuePair, pSendCompletionQueue, pRecvCompletionQueue, context, recvQueueDepth, sendQueueDepth, maxRecvRequestSge, maxSendRequestSge, inlineDataSize, (void**)&pQueuePair ); LOG("IND2Adapter::CreateQueuePair -> %08X", hr); if (ND_SUCCESS != hr) throw EX_CREATE_QUEUE_PAIR; try { stage8( params, work, pAddress, pAdapter, hOverlappedFile, pMemoryRegion, pInfo, pSendCompletionQueue, pRecvCompletionQueue, pQueuePair ); } catch (...) { ULONG ul = pQueuePair->Release(); LOG("IND2QueuePair::Release -> %u", ul); throw; } ULONG ul = pQueuePair->Release(); LOG("IND2QueuePair::Release -> %u", ul); LOG_VOID_RETURN(); } static void stage6( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile, IND2MemoryRegion* const pMemoryRegion, ND2_ADAPTER_INFO const* const pInfo, IND2CompletionQueue* const pSendCompletionQueue ) { LOG_ENTER(); IND2CompletionQueue* pRecvCompletionQueue = 0; HRESULT hr = pAdapter->CreateCompletionQueue( IID_IND2CompletionQueue, hOverlappedFile, pInfo->MaxCompletionQueueDepth, 0, 0, (void**)(&pRecvCompletionQueue) ); LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr); if (ND_SUCCESS != hr) throw EX_CREATE_COMPLETION_QUEUE; try { stage7( params, work, pAddress, pAdapter, hOverlappedFile, pMemoryRegion, pInfo, pSendCompletionQueue, pRecvCompletionQueue ); } catch (...) { ULONG ul = pRecvCompletionQueue->Release(); LOG("IND2CompletionQueue::Release -> %u", ul); throw; } ULONG ul = pRecvCompletionQueue->Release(); LOG("IND2CompletionQueue::Release -> %u", ul); LOG_VOID_RETURN(); } static void stage5( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile, IND2MemoryRegion* const pMemoryRegion, ND2_ADAPTER_INFO const* const pInfo ) { LOG_ENTER(); IND2CompletionQueue* pSendCompletionQueue = 0; HRESULT hr = pAdapter->CreateCompletionQueue( IID_IND2CompletionQueue, hOverlappedFile, pInfo->MaxCompletionQueueDepth, 0, 0, (void**)(&pSendCompletionQueue) ); LOG("IND2Adapter::CreateCompletionQueue -> %08X", hr); if (ND_SUCCESS != hr) throw EX_CREATE_COMPLETION_QUEUE; try { stage6( params, work, pAddress, pAdapter, hOverlappedFile, pMemoryRegion, pInfo, pSendCompletionQueue ); } catch (...) { ULONG ul = pSendCompletionQueue->Release(); LOG("IND2CompletionQueue::Release -> %u", ul); throw; } ULONG ul = pSendCompletionQueue->Release(); LOG("IND2CompletionQueue::Release -> %u", ul); LOG_VOID_RETURN(); } static void stage4( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile, IND2MemoryRegion* const pMemoryRegion ) { LOG_ENTER(); LOG("pMemoryRegion: %p", pMemoryRegion); ND2_ADAPTER_INFO info = { 0 }; info.InfoVersion = ND_VERSION_2; ULONG cbInfo = sizeof(info); HRESULT hr = pAdapter->Query( &info, &cbInfo ); LOG("IND2Adapter::Query -> %08X", hr); if (ND_SUCCESS != hr) throw EX_QUERY; stage5( params, work, pAddress, pAdapter, hOverlappedFile, pMemoryRegion, &info ); LOG_VOID_RETURN(); } static void stage3( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter, HANDLE const hOverlappedFile ) { LOG_ENTER(); IND2MemoryRegion* pMemoryRegion = 0; HRESULT hr = pAdapter->CreateMemoryRegion( IID_IND2MemoryRegion, hOverlappedFile, (void**)&pMemoryRegion ); LOG("IND2Adapter::CreateMemoryRegion -> %08X", hr); if (hr != ND_SUCCESS) throw EX_CREATE_MEMORY_REGION; try { stage4( params, work, pAddress, pAdapter, hOverlappedFile, pMemoryRegion ); } catch (...) { ULONG ul = pMemoryRegion->Release(); LOG("IND2MemoryRegion::Release -> %u", ul); throw; } ULONG ul = pMemoryRegion->Release(); LOG("IND2MemoryRegion::Release -> %u", ul); LOG_VOID_RETURN(); } static void stage2( params_t* const params, work_t work, const struct sockaddr* pAddress, IND2Adapter* const pAdapter ) { LOG_ENTER(); HANDLE hOverlappedFile = 0; HRESULT hr = pAdapter->CreateOverlappedFile( &hOverlappedFile ); LOG("IND2Adapter::CreateOverlappedFile -> %08X", hr); if (hr != ND_SUCCESS) throw EX_CREATE_OVERLAPPED_FILE; try { stage3(params, work, pAddress, pAdapter, hOverlappedFile); } catch (...) { BOOL b = CloseHandle(hOverlappedFile); LOG("CloseHandle -> %d", b); throw; } BOOL b = CloseHandle(hOverlappedFile); LOG("CloseHandle -> %d", b); LOG_VOID_RETURN(); } void work( params_t* const params, work_t work, get_local_address_t get_local_address ) { LOG_ENTER(); struct sockaddr LocalAddress = (*get_local_address)( (LPSTR)params->ip.c_str(), params->port ); IND2Adapter* pAdapter = 0; HRESULT const hr = NdOpenAdapter( IID_IND2Adapter, &LocalAddress, sizeof(LocalAddress), (void**)&pAdapter ); if (ND_SUCCESS != hr) throw EX_OPEN_ADAPTER; try { stage2(params, work, &LocalAddress, pAdapter); } catch (...) { ULONG const ul = pAdapter->Release(); LOG("IND2Adapter::Release -> %u", ul); throw; } ULONG const ul = pAdapter->Release(); LOG("IND2Adapter::Release -> %u", ul); LOG_VOID_RETURN(); } SOCKADDR get_sockaddr(LPSTR AddressString, INT AddressFamily, uint16_t port) { LOG_ENTER(); SOCKADDR saddr; INT AddressLength = (int)sizeof(saddr); // raises an exception on failure therefore no need to look at the return code Win::WSAStringToAddressA( AddressString, AddressFamily, 0, // lpProtocolInfo &saddr, // lpAddress &AddressLength // lpAddressLength ); ((struct sockaddr_in*)&saddr)->sin_port = htons(port); LOG_STRUCT_RETURN(SOCKADDR); return saddr; } void RegisterMemory(IND2MemoryRegion* pMemoryRegion, void* buffer, size_t size) { LOG_ENTER(); OVERLAPPED ov = { 0 }; ULONG const flags = ND_MR_FLAG_ALLOW_LOCAL_WRITE | ND_MR_FLAG_ALLOW_REMOTE_READ | ND_MR_FLAG_ALLOW_REMOTE_WRITE; HRESULT hr = pMemoryRegion->Register( buffer, size, flags, &ov ); LOG("IND2MemoryRegion::Register -> %08X", hr); if (ND_SUCCESS != hr) { if (ND_PENDING != hr) throw EX_REGISTER; uint64_t count = 1; while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE))) { count += 1; } LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count); if (ND_SUCCESS != hr) throw EX_REGISTER_OV; } LOG_VOID_RETURN(); } void DeregisterMemory(IND2MemoryRegion* pMemoryRegion) { // do not throw an exception! LOG_ENTER(); OVERLAPPED ov = { 0 }; HRESULT hr = pMemoryRegion->Deregister(&ov); LOG("IND2MemoryRegion::Deregister -> %08X", hr); if (ND_PENDING == hr) { uint64_t count = 1; while (ND_PENDING == (hr = pMemoryRegion->GetOverlappedResult(&ov, FALSE))) { count += 1; } LOG("IND2MemoryRegion::GetOverlappedResult -> %08X (called %zu times)", hr, count); } LOG_VOID_RETURN(); }
25.322581
91
0.582803
pcdeadeasy
5bcb52b804b9b25039f580f93c65033a8f22c49c
4,933
cpp
C++
chromaprint/audio_processor.cpp
pvinis/music-player
0e7d06c2a648ca9cfaa46418e6536f63ab42d088
[ "BSD-2-Clause" ]
56
2015-04-21T05:35:38.000Z
2021-02-16T13:42:45.000Z
chromaprint/audio_processor.cpp
pvinis/music-player
0e7d06c2a648ca9cfaa46418e6536f63ab42d088
[ "BSD-2-Clause" ]
13
2015-05-09T17:36:27.000Z
2020-02-13T17:44:59.000Z
chromaprint/audio_processor.cpp
pvinis/music-player
0e7d06c2a648ca9cfaa46418e6536f63ab42d088
[ "BSD-2-Clause" ]
27
2015-06-15T14:54:58.000Z
2021-07-22T09:59:40.000Z
/* * Chromaprint -- Audio fingerprinting toolkit * Copyright (C) 2010-2011 Lukas Lalinsky <lalinsky@gmail.com> * * 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 */ #include <assert.h> #include <algorithm> #include <stdio.h> extern "C" { #include "avresample/avcodec.h" } #include "debug.h" #include "audio_processor.h" using namespace std; using namespace Chromaprint; static const int kMinSampleRate = 1000; static const int kMaxBufferSize = 1024 * 16; // Resampler configuration static const int kResampleFilterLength = 16; static const int kResamplePhaseCount = 10; static const int kResampleLinear = 0; static const double kResampleCutoff = 0.8; AudioProcessor::AudioProcessor(int sample_rate, AudioConsumer *consumer) : m_buffer_size(kMaxBufferSize), m_target_sample_rate(sample_rate), m_consumer(consumer), m_resample_ctx(0) { m_buffer = new short[kMaxBufferSize]; m_buffer_offset = 0; m_resample_buffer = new short[kMaxBufferSize]; } AudioProcessor::~AudioProcessor() { if (m_resample_ctx) { av_resample_close(m_resample_ctx); } delete[] m_resample_buffer; delete[] m_buffer; } void AudioProcessor::LoadMono(short *input, int length) { short *output = m_buffer + m_buffer_offset; while (length--) { *output++ = input[0]; input++; } } void AudioProcessor::LoadStereo(short *input, int length) { short *output = m_buffer + m_buffer_offset; while (length--) { *output++ = (input[0] + input[1]) / 2; input += 2; } } void AudioProcessor::LoadMultiChannel(short *input, int length) { short *output = m_buffer + m_buffer_offset; while (length--) { long sum = 0; for (int i = 0; i < m_num_channels; i++) { sum += *input++; } *output++ = (short)(sum / m_num_channels); } } int AudioProcessor::Load(short *input, int length) { assert(length >= 0); assert(m_buffer_offset <= m_buffer_size); length = min(length, m_buffer_size - m_buffer_offset); switch (m_num_channels) { case 1: LoadMono(input, length); break; case 2: LoadStereo(input, length); break; default: LoadMultiChannel(input, length); break; } m_buffer_offset += length; return length; } void AudioProcessor::Resample() { if (!m_resample_ctx) { m_consumer->Consume(m_buffer, m_buffer_offset); m_buffer_offset = 0; return; } int consumed = 0; int length = av_resample(m_resample_ctx, m_resample_buffer, m_buffer, &consumed, m_buffer_offset, kMaxBufferSize, 1); if (length > kMaxBufferSize) { DEBUG() << "Chromaprint::AudioProcessor::Resample() -- Resampling overwrote output buffer.\n"; length = kMaxBufferSize; } m_consumer->Consume(m_resample_buffer, length); int remaining = m_buffer_offset - consumed; if (remaining > 0) { copy(m_buffer + consumed, m_buffer + m_buffer_offset, m_buffer); } else if (remaining < 0) { DEBUG() << "Chromaprint::AudioProcessor::Resample() -- Resampling overread input buffer.\n"; remaining = 0; } m_buffer_offset = remaining; } bool AudioProcessor::Reset(int sample_rate, int num_channels) { if (num_channels <= 0) { DEBUG() << "Chromaprint::AudioProcessor::Reset() -- No audio channels.\n"; return false; } if (sample_rate <= kMinSampleRate) { DEBUG() << "Chromaprint::AudioProcessor::Reset() -- Sample rate less " << "than " << kMinSampleRate << " (" << sample_rate << ").\n"; return false; } m_buffer_offset = 0; if (m_resample_ctx) { av_resample_close(m_resample_ctx); m_resample_ctx = 0; } if (sample_rate != m_target_sample_rate) { m_resample_ctx = av_resample_init( m_target_sample_rate, sample_rate, kResampleFilterLength, kResamplePhaseCount, kResampleLinear, kResampleCutoff); } m_num_channels = num_channels; return true; } void AudioProcessor::Consume(short *input, int length) { assert(length >= 0); assert(length % m_num_channels == 0); length /= m_num_channels; while (length > 0) { int consumed = Load(input, length); input += consumed * m_num_channels; length -= consumed; if (m_buffer_size == m_buffer_offset) { Resample(); if (m_buffer_size == m_buffer_offset) { DEBUG() << "Chromaprint::AudioProcessor::Consume() -- Resampling failed?\n"; return; } } } } void AudioProcessor::Flush() { if (m_buffer_offset) { Resample(); } }
25.692708
118
0.711535
pvinis
5bcbcd2c5d0aea2ba6fe58313f617077b506f975
8,455
cpp
C++
src/chainparams.cpp
barrystyle/myce
906e600642109fb87d43c25b56d0365618e71c7a
[ "MIT" ]
3
2020-02-05T09:54:43.000Z
2020-03-21T06:49:37.000Z
src/chainparams.cpp
barrystyle/myce
906e600642109fb87d43c25b56d0365618e71c7a
[ "MIT" ]
null
null
null
src/chainparams.cpp
barrystyle/myce
906e600642109fb87d43c25b56d0365618e71c7a
[ "MIT" ]
1
2020-02-12T11:38:21.000Z
2020-02-12T11:38:21.000Z
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <consensus/merkle.h> #include <streams.h> #include <tinyformat.h> #include <utilstrencodings.h> #include <arith_uint256.h> #include <util.h> #include <assert.h> #include <chainparamsseeds.h> CBlock MyceLegacyBlock() { CBlock block; CDataStream stream(ParseHex("01000000000000000000000000000000000000000000000000000000000000000000000090eafddb7b64457b5b30f51a6b4f07912281b3b5fa5ebf5dc4149efe6380a58e5885965affff001f4232030001010000005db8535a010000000000000000000000000000000000000000000000000000000000000000ffffffff1400012a104d796365206d61737465726e6f646573ffffffff0100000000000000000000000000"), SER_NETWORK, 70914); stream >> block; return block; } static CBlock CreateGenesisBlock(uint32_t nTimeTx, unsigned int nTimeBlock, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "Myce masternodes"; CMutableTransaction txNew; txNew.nVersion = 1; txNew.nTime = nTimeTx; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 0 << CScriptNum(42) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock genesis; genesis.vtx.push_back(MakeTransactionRef(std::move(txNew))); genesis.nTime = nTimeBlock; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); return genesis; } void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { consensus.vDeployments[d].nStartTime = nStartTime; consensus.vDeployments[d].nTimeout = nTimeout; } /** * Main network */ /** * What makes a good checkpoint block? * + Is surrounded by blocks with reasonable timestamps * (no blocks before with a timestamp after, none after with * timestamp before) * + Contains no strange transactions */ class CMainParams : public CChainParams { public: CMainParams() { strNetworkID = "main"; consensus.nLastPoWBlock = 100; consensus.nInstantSendKeepLock = 24; consensus.nBudgetPaymentsStartBlock = 0; consensus.nBudgetPaymentsCycleBlocks = 16616; consensus.nBudgetPaymentsWindowBlocks = 100; consensus.nBudgetProposalEstablishingTime = 60*60*24; consensus.nSuperblockCycle = 43200; consensus.nSuperblockStartBlock = consensus.nSuperblockCycle; consensus.nGovernanceMinQuorum = 10; consensus.nGovernanceFilterElements = 20000; consensus.BIP34Height = 10; consensus.BIP34Hash = uint256S("0000000000000000000000000000000000000000000000000000000000000000"); consensus.BIP65Height = consensus.nLastPoWBlock; consensus.BIP66Height = consensus.nLastPoWBlock; consensus.powLimit = uint256S("0000ffff00000000000000000000000000000000000000000000000000000000"); consensus.posLimit = uint256S("007ffff000000000000000000000000000000000000000000000000000000000"); consensus.nPowTargetTimespan = 2 * 60; consensus.nPowTargetSpacing = 40; consensus.nPosTargetSpacing = consensus.nPowTargetSpacing; consensus.nPosTargetTimespan = consensus.nPowTargetTimespan; consensus.nMasternodeMinimumConfirmations = 15; consensus.nStakeMinAge = 10 * 60; consensus.nStakeMaxAge = 60 * 60 * 24 * 30; consensus.nModifierInterval = 60 * 20; consensus.nCoinbaseMaturity = 20; consensus.fPowAllowMinDifficultyBlocks = false; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1080; consensus.nMinerConfirmationWindow = 1440; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016. consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017. // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0000000000000000000000000000000000000000000000000000000000000000"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0000000000000000000000000000000000000000000000000000000000000000"); /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 32-bit integer with any alignment. */ pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0x23; pchMessageStart[2] = 0x43; pchMessageStart[3] = 0x65; nDefaultPort = 23511; nPruneAfterHeight = 100000; nMaxReorganizationDepth = 100; genesis = MyceLegacyBlock(); consensus.hashGenesisBlock = genesis.GetHash(); LogPrintf("%s\n", consensus.hashGenesisBlock.ToString().c_str()); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 50); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 85); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 153); base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E}; base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4}; bech32_hrp = "vx"; vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main)); fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; nCollateralLevels = { 0 }; nPoolMaxTransactions = 3; nFulfilledRequestExpireTime = 60*60; strSporkPubKey = "03f012092c5fe9ed406b43316fc87d8ace9e8eb7764999db00ef60009ddddfa723"; strSporkPubKeyOld = "0358d5fb8000c49d38aaab6dc5d0c0a0322eff3090eff026963eb819dc3dec8439"; checkpointData = { }; chainTxData = ChainTxData{ }; /* disable fallback fee on mainnet */ m_fallback_fee_enabled = true; } }; /* * Testnet (v3) */ class CTestNetParams : public CChainParams { public: CTestNetParams() { strNetworkID = "test"; } }; /* * Regression test */ class CRegTestParams : public CChainParams { public: CRegTestParams() { strNetworkID = "regtest"; } }; static std::unique_ptr<CChainParams> globalChainParams; const CChainParams &Params() { assert(globalChainParams); return *globalChainParams; } std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return std::unique_ptr<CChainParams>(new CMainParams()); else if (chain == CBaseChainParams::TESTNET) return std::unique_ptr<CChainParams>(new CTestNetParams()); else if (chain == CBaseChainParams::REGTEST) return std::unique_ptr<CChainParams>(new CRegTestParams()); throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectParams(const std::string& network) { SelectBaseParams(network); globalChainParams = CreateChainParams(network); } void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout); }
38.784404
387
0.720757
barrystyle
5bcc910a7b8c3a895285c00bf8c0fedf97aa5cc5
3,172
cpp
C++
copasi/sbml/unittests/test000101.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
64
2015-03-14T14:06:18.000Z
2022-02-04T23:19:08.000Z
copasi/sbml/unittests/test000101.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
4
2017-08-16T10:26:46.000Z
2020-01-08T12:05:54.000Z
copasi/sbml/unittests/test000101.cpp
SzVarga/COPASI
00451b1a67eeec8272c73791ca861da754a7c4c4
[ "Artistic-2.0" ]
28
2015-04-16T14:14:59.000Z
2022-03-28T12:04:14.000Z
// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and University of // of Connecticut School of Medicine. // All rights reserved. // Copyright (C) 2011 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "test000101.h" #include <iostream> #ifndef WIN32 #include <signal.h> #endif #include <stdexcept> #include <copasi/report/CRootContainer.h> #include <copasi/CopasiDataModel/CDataModel.h> // Since this bug leads to segmentation fault // we need to make sure that the call to abort made by assert does not end the program. // For this we change the signal handler to one that throws an exception. // The current version is specific to linux. If these tests are to be run under windows, // the mechanism for setting the signal handler will probably have to be modified. void test000101::abort_handler(int) { throw std::runtime_error("Received SIGSEGV signal."); } #ifndef WIN32 struct sigaction* test000101::pOldAct = new struct sigaction(); struct sigaction* test000101::pNewAct = new struct sigaction(); #endif void test000101::setUp() { #ifndef WIN32 // set a new action handler for SIGABRT that throws an exception // instead of terminating the program. This is needed to handle failed assertions // in debug versions. pNewAct->sa_handler = &test000101::abort_handler; int x = sigaction(SIGSEGV, test000101::pNewAct, test000101::pOldAct); if (x != 0) { std::cerr << "Setting the signal handler failed." << std::endl; } #endif // Create the root container. CRootContainer::init(0, NULL, false); pDataModel = CRootContainer::addDatamodel(); } void test000101::tearDown() { #ifndef WIN32 CRootContainer::destroy(); // restore the old action handler int x = sigaction(SIGSEGV, test000101::pOldAct, NULL); if (x != 0) { std::cerr << "Resetting the signal handler failed." << std::endl; } #endif } void test000101::test_bug1740() { pDataModel->importSBMLFromString(SBML_STRING); pDataModel->exportSBMLToString(NULL, 3, 1); try { // the second export crashes without a bug fix pDataModel->exportSBMLToString(NULL, 3, 1); } catch (const std::runtime_error& e) { CPPUNIT_ASSERT_MESSAGE("The second export to Level 3 Version 1 failed.", false); } } const char* test000101::SBML_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" level=\"3\" version=\"1\">\n" " <model id=\"Module_1_RL2_1\" name=\"Module_1_RL2\">\n" " <listOfReactions>\n" " <reaction fast=\"false\" id=\"reaction_0\" name=\"reaction_0\" reversible=\"false\">\n" " </reaction>\n" " </listOfReactions>\n" " </model>\n" "</sbml>\n";
33.041667
132
0.634615
SzVarga
5bd03752bc7988a0f3f32e56f8b1a251641428e5
5,548
cpp
C++
tests/job_tests.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
tests/job_tests.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
tests/job_tests.cpp
jacobmcleman/JobBot
1ef82a2f2fbf3321ba3ef4f2a006128bed1388c0
[ "MIT" ]
null
null
null
/************************************************************************** Some short tests to test basic job functionality Author: Jake McLeman ***************************************************************************/ #include <gtest/gtest.h> #include "Job.h" #define UNUSED(thing) (void)thing using namespace JobBot; bool testFunc1HasRun; void TestJobFunc1(Job* job) { UNUSED(job); testFunc1HasRun = true; } TinyJobFunction TestJob1(TestJobFunc1); bool testFunc2HasRun; void TestJobFunc2(Job* job) { UNUSED(job); testFunc2HasRun = true; } HugeJobFunction TestJob2(TestJobFunc2); bool testFunc3GotData; void TestJobFunc3(Job* job) { testFunc3GotData = (job->GetData<int>() == 4); } IOJobFunction TestJob3(TestJobFunc3); bool testFunc4GotData; void TestJobFunc4(Job* job) { testFunc4GotData = (job->GetData<float>() == 25.12f); } GraphicsJobFunction TestJob4(TestJobFunc4); TEST(JobTests, SizeVerification) { ASSERT_EQ((size_t)Job::TARGET_JOB_SIZE, sizeof(Job)) << "Job was incorrect size"; } TEST(JobTests, Create) { Job* job = Job::Create(TestJob1); EXPECT_FALSE(job->IsFinished()) << "Job has not been created correctly"; EXPECT_FALSE(job->InProgress()) << "Job has not been created correctly"; } TEST(JobTests, RunJob) { testFunc1HasRun = false; Job* job = Job::Create(TestJob1); EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed"; EXPECT_FALSE(job->IsFinished()) << "Job is marked as finished before it has run"; job->Run(); EXPECT_TRUE(testFunc1HasRun) << "Job has been run but has not executed job code"; EXPECT_TRUE(job->IsFinished()) << "Job has been run but is not marked as finished"; EXPECT_FALSE(job->InProgress()) << "Job is finished but still marked as in progress"; } TEST(JobTests, Parent) { testFunc1HasRun = false; testFunc2HasRun = false; // Create 2 jobs with job2 as a child of job1 Job* job1 = Job::Create(TestJob1); Job* job2 = Job::CreateChild(TestJob2, job1); // Make sure that nothing has prematurely fired EXPECT_FALSE(testFunc1HasRun) << "Job1 has been prematurely executed"; EXPECT_FALSE(job1->IsFinished()) << "Job1 is marked as finished before it has run"; EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed"; EXPECT_FALSE(job2->IsFinished()) << "Job2 is marked as finished before it has run"; // Run job1 (the parent) job1->Run(); // Job 1 has now run, but should not be marked done because it has a child // that has not finished EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly"; EXPECT_FALSE(job1->IsFinished()) << "Job1 is marked as finished before all of its children have finished"; EXPECT_FALSE(testFunc2HasRun) << "Job2 has been prematurely executed"; EXPECT_FALSE(job2->IsFinished()) << "Job2 is marked as finished before it has run"; // Run job2 (the child) job2->Run(); // Make sure all jobs are now correctly marked as completed EXPECT_TRUE(testFunc1HasRun) << "Job1 has not run correctly"; EXPECT_TRUE(job1->IsFinished()) << "Job1 is not marked as finished even though all child jobs are done"; EXPECT_TRUE(testFunc2HasRun) << "Job2 has not run correctly"; EXPECT_TRUE(job2->IsFinished()) << "Job2 has been run but is not marked as finished"; } TEST(JobTests, Callback) { testFunc1HasRun = false; testFunc2HasRun = false; // Create job1 with a callback function Job* job = Job::Create(TestJob1); job->SetCallback(TestJob2); EXPECT_FALSE(testFunc1HasRun) << "Job has been prematurely executed"; EXPECT_FALSE(job->IsFinished()) << "Job is marked as finished before it has run"; EXPECT_FALSE(testFunc2HasRun) << "Callback has been prematurely executed"; job->Run(); EXPECT_TRUE(testFunc1HasRun) << "Job has been run but has not executed job code"; EXPECT_TRUE(job->IsFinished()) << "Job has been run but is not marked as finished"; EXPECT_TRUE(testFunc2HasRun) << "Job has been run but has not executed callback code"; } TEST(JobTests, Data1) { testFunc3GotData = false; Job* job = Job::Create(TestJob3, 4); EXPECT_FALSE(testFunc3GotData) << "Function somehow already got the data even though it hasn't run yet"; EXPECT_FALSE(job->IsFinished()) << "Job is marked as finished before it has run"; job->Run(); EXPECT_TRUE(testFunc3GotData) << "Function did not correctly recieve the data"; EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished"; } TEST(JobTests, Data2) { testFunc4GotData = false; Job* job = Job::Create(TestJob4, 25.12f); EXPECT_FALSE(testFunc4GotData) << "Function somehow already got the data even though it hasn't run yet"; EXPECT_FALSE(job->IsFinished()) << "Job is marked as finished before it has run"; job->Run(); EXPECT_TRUE(testFunc4GotData) << "Function recieved wrong data"; EXPECT_TRUE(job->IsFinished()) << "Job is not marked as finished"; } TEST(JobTests, JobTypeChecks) { Job* job1 = Job::Create(TestJob1); Job* job2 = Job::Create(TestJob2); EXPECT_FALSE(job1->MatchesType(JobType::Huge)) << "Tiny job was huge"; EXPECT_FALSE(job1->MatchesType(JobType::Misc)) << "Tiny job was misc"; EXPECT_TRUE(job1->MatchesType(JobType::Tiny)) << "Tiny job was not a tiny job"; EXPECT_TRUE(job2->MatchesType(JobType::Huge)) << "Huge job was not huge"; EXPECT_FALSE(job2->MatchesType(JobType::Misc)) << "Huge job was misc"; EXPECT_FALSE(job2->MatchesType(JobType::Tiny)) << "Huge job was tiny"; }
29.354497
79
0.683129
jacobmcleman
5bd1c4c60b0a518115e14cce3ff262dcad624695
1,005
cpp
C++
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
6
2020-03-26T15:07:14.000Z
2022-02-04T06:27:32.000Z
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
1
2020-07-09T06:32:52.000Z
2020-07-09T07:26:47.000Z
examples/make_stereo_panorama.cpp
jonathanventura/spherical-sfm
0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb
[ "MIT" ]
1
2022-03-08T20:30:46.000Z
2022-03-08T20:30:46.000Z
#include <iostream> #include <vector> #include <cmath> #include <fstream> #include <gflags/gflags.h> #include "stereo_panorama_tools.h" using namespace sphericalsfm; using namespace stereopanotools; DEFINE_string(intrinsics, "", "Path to intrinsics (focal centerx centery)"); DEFINE_string(video, "", "Path to video or image search pattern like frame%06d.png"); DEFINE_string(output, "", "Path to output directory"); DEFINE_int32(width, 8192, "Width of output panorama"); DEFINE_bool(loop, true, "Trajectory is a closed loop"); int main( int argc, char **argv ) { gflags::ParseCommandLineFlags(&argc, &argv, true); double focal, centerx, centery; std::ifstream intrinsicsf( FLAGS_intrinsics ); intrinsicsf >> focal >> centerx >> centery; std::cout << "intrinsics : " << focal << ", " << centerx << ", " << centery << "\n"; Intrinsics intrinsics(focal,centerx,centery); make_stereo_panoramas( intrinsics, FLAGS_video, FLAGS_output, FLAGS_width, FLAGS_loop ); }
30.454545
92
0.705473
jonathanventura
5bd4623cc9a5404f3652cce6bd2ce9c8e03da0f5
617
cpp
C++
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
2017/APP5/Q.7.cpp
HemensonDavid/Estudando-C
fb5a33b399b369dce789bf77c06834da71fe0a4d
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int ismedia(int nota1, int nota2, int nota3, int nota4){ int media=(nota1*2)+(nota2*2)+(nota3*3)+(nota4*3)/10; if(media>=60){ return 1; } } int main(){ cout<<"Digite sua nota no 1 bimestre: "; int nota1; cin>> nota1; cout<<"Digite sua nota no 2 bimestre: "; int nota2; cin>> nota2; cout<<"Digite sua nota no 3 bimestre: "; int nota3; cin>> nota3; cout<<"Digite sua nota no 4 bimestre: "; int nota4; cin>> nota4; if(ismedia(nota1,nota2,nota3,nota4)==1){ cout<<"Voce nao passou. "<<endl; }else{ cout<<"voce passou :) "<<endl; } //hemenson }
16.675676
56
0.628849
HemensonDavid
5bd6994380e19f199c9e9f98d6d356ea80f44954
3,721
hpp
C++
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
15
2020-07-20T12:32:38.000Z
2022-03-24T19:24:02.000Z
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
null
null
null
include/tcb_manager.hpp
Qanora/mstack-cpp
a1b6de6983404558e46b87d0e81da715fcdccd55
[ "MIT" ]
5
2020-07-20T12:42:58.000Z
2021-01-16T10:13:39.000Z
#pragma once #include <memory> #include <optional> #include <unordered_map> #include <unordered_set> #include "circle_buffer.hpp" #include "defination.hpp" #include "packets.hpp" #include "socket.hpp" #include "tcb.hpp" #include "tcp_transmit.hpp" namespace mstack { class tcb_manager { private: tcb_manager() : active_tcbs(std::make_shared<circle_buffer<std::shared_ptr<tcb_t>>>()) {} ~tcb_manager() = default; std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>> active_tcbs; std::unordered_map<two_ends_t, std::shared_ptr<tcb_t>> tcbs; std::unordered_set<ipv4_port_t> active_ports; std::unordered_map<ipv4_port_t, std::shared_ptr<listener_t>> listeners; public: tcb_manager(const tcb_manager&) = delete; tcb_manager(tcb_manager&&) = delete; tcb_manager& operator=(const tcb_manager&) = delete; tcb_manager& operator=(tcb_manager&&) = delete; static tcb_manager& instance() { static tcb_manager instance; return instance; } public: int id() { return 0x06; } std::optional<tcp_packet_t> gather_packet() { while (!active_tcbs->empty()) { std::optional<std::shared_ptr<tcb_t>> tcb = active_tcbs->pop_front(); if (!tcb) continue; std::optional<tcp_packet_t> tcp_packet = tcb.value()->gather_packet(); if (tcp_packet) return tcp_packet; } return std::nullopt; } void listen_port(ipv4_port_t ipv4_port, std::shared_ptr<listener_t> listener) { this->listeners[ipv4_port] = listener; active_ports.insert(ipv4_port); } void register_tcb( two_ends_t& two_end, std::optional<std::shared_ptr<circle_buffer<std::shared_ptr<tcb_t>>>> listener) { DLOG(INFO) << "[REGISTER TCB] " << two_end; if (!two_end.remote_info || !two_end.local_info) { DLOG(FATAL) << "[EMPTY TCB]"; } std::shared_ptr<tcb_t> tcb = std::make_shared<tcb_t>(this->active_tcbs, listener, two_end.remote_info.value(), two_end.local_info.value()); tcbs[two_end] = tcb; } void receive(tcp_packet_t in_packet) { two_ends_t two_end = {.remote_info = in_packet.remote_info, .local_info = in_packet.local_info}; if (tcbs.find(two_end) != tcbs.end()) { tcp_transmit::tcp_in(tcbs[two_end], in_packet); } else if (active_ports.find(in_packet.local_info.value()) != active_ports.end()) { register_tcb(two_end, this->listeners[in_packet.local_info.value()]->acceptors); if (tcbs.find(two_end) != tcbs.end()) { tcbs[two_end]->state = TCP_LISTEN; tcbs[two_end]->next_state = TCP_LISTEN; tcp_transmit::tcp_in(tcbs[two_end], in_packet); } else { DLOG(ERROR) << "[REGISTER TCB FAIL]"; } } else { DLOG(ERROR) << "[RECEIVE UNKNOWN TCP PACKET]"; } } }; } // namespace mstack
43.267442
99
0.504703
Qanora
5bdd86a3c1457620c62c505b2444d4cdcf64f68e
4,666
hpp
C++
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Runtime/CompilerServices/RuntimeWrappedException.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Exception #include "System/Exception.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Runtime::Serialization namespace System::Runtime::Serialization { // Forward declaring type: SerializationInfo class SerializationInfo; } // Completed forward declares // Type namespace: System.Runtime.CompilerServices namespace System::Runtime::CompilerServices { // Size: 0x90 #pragma pack(push, 1) // Autogenerated type: System.Runtime.CompilerServices.RuntimeWrappedException class RuntimeWrappedException : public System::Exception { public: // private System.Object m_wrappedException // Size: 0x8 // Offset: 0x88 ::Il2CppObject* m_wrappedException; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // Creating value type constructor for type: RuntimeWrappedException RuntimeWrappedException(::Il2CppObject* m_wrappedException_ = {}) noexcept : m_wrappedException{m_wrappedException_} {} // Creating conversion operator: operator ::Il2CppObject* constexpr operator ::Il2CppObject*() const noexcept { return m_wrappedException; } // private System.Void .ctor(System.Object thrownObject) // Offset: 0x1401DE0 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor(::Il2CppObject* thrownObject) { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(thrownObject))); } // public override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1401E90 // Implemented from: System.Exception // Base method: System.Void Exception::GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) void GetObjectData(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context); // System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) // Offset: 0x1401F9C // Implemented from: System.Exception // Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>(info, context))); } // System.Void .ctor() // Offset: 0x1402090 // Implemented from: System.Exception // Base method: System.Void Exception::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RuntimeWrappedException* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Runtime::CompilerServices::RuntimeWrappedException::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RuntimeWrappedException*, creationType>())); } }; // System.Runtime.CompilerServices.RuntimeWrappedException #pragma pack(pop) static check_size<sizeof(RuntimeWrappedException), 136 + sizeof(::Il2CppObject*)> __System_Runtime_CompilerServices_RuntimeWrappedExceptionSizeCheck; static_assert(sizeof(RuntimeWrappedException) == 0x90); } DEFINE_IL2CPP_ARG_TYPE(System::Runtime::CompilerServices::RuntimeWrappedException*, "System.Runtime.CompilerServices", "RuntimeWrappedException");
60.597403
165
0.747964
darknight1050
5be030ae46f3c7267b32ffaa56e54e1ce0567db1
9,157
cxx
C++
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
9
2015-01-10T04:31:50.000Z
2019-03-04T13:55:08.000Z
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
2
2016-10-19T12:56:47.000Z
2017-06-02T13:55:35.000Z
Dax/LowLevelDax/threshold.cxx
robertmaynard/Sandbox
724c67fd924c29630a49f8501fd9df7a2bbb1ed8
[ "BSD-2-Clause" ]
5
2015-01-05T15:52:50.000Z
2018-02-14T18:08:19.000Z
//Description: //Show how we can threshold any arbitrary dataset inside of dax. #include <dax/cont/DeviceAdapter.h> #include <dax/cont/ArrayHandle.h> #include <dax/cont/ArrayHandleCounting.h> #include <dax/cont/UniformGrid.h> #include <dax/cont/UnstructuredGrid.h> #include <dax/CellTag.h> #include <dax/CellTraits.h> //headers needed for testing #include <dax/cont/testing/TestingGridGenerator.h> //exec headers we need #include <dax/exec/internal/WorkletBase.h> //required for error handling #include <dax/exec/CellVertices.h> #include <algorithm> #include <iostream> #include <numeric> #include <vector> //The functor used to determine if a single cell passes the threshold reqs template<class GridType, class T> struct threshold_cell : public dax::exec::internal::WorkletBase { //we inherit from WorkletBase so that we can throw errors in the exec //env and the control env can find out why the worklet failed //store the cell type that we are working on typedef typename GridType::CellTag CellTag; //determine the topology type that we need in the exec env typedef typename GridType::TopologyStructConstExecution TopologyType; TopologyType Topology; //holds the cell connectivity //hold a portal so that we can get values in the exec env typedef typename dax::cont::ArrayHandle< T >::PortalConstExecution PortalType; PortalType ValuePortal; //holds the array of of what cells pass or fail the threshold reqs typedef typename dax::cont::ArrayHandle< int >::PortalExecution OutPortalType; OutPortalType PassesThreshold; T MinValue; T MaxValue; DAX_CONT_EXPORT threshold_cell(const GridType& grid, dax::cont::ArrayHandle<T> values, T min, T max, dax::cont::ArrayHandle<int> passes): Topology(grid.PrepareForInput()), //upload grid topology to exec env ValuePortal(values.PrepareForInput()), //upload values to exec env MinValue(min), MaxValue(max), PassesThreshold(passes.PrepareForOutput( grid.GetNumberOfCells() )) { } DAX_EXEC_EXPORT void operator()( int cell_index ) const { //get all the point ids for the cell index dax::exec::CellVertices<CellTag> verts = this->Topology.GetCellConnections(cell_index); //for each vertice see if we are between the min and max which is //inclusive on both sides. We hint to the compiler that this is //a fixed size array by using NUM_VERTICES. This can be easily //unrolled if needed int valid = 1; for(int i=0; i < dax::CellTraits<CellTag>::NUM_VERTICES; ++i) { const T value = this->ValuePortal.Get( verts[i] ); valid &= (value >= this->MinValue && value <= this->MaxValue); } this->PassesThreshold.Set(cell_index,valid); } }; //this struct will do the cell sub-setting by being given the input topology //and the cell ids that need to be added to the new output grid template<class GridType, class OutGridType > struct cell_subset: public dax::exec::internal::WorkletBase { //we inherit from WorkletBase so that we can throw errors in the exec //env and the control env can find out why the worklet failed //store the cell type that we are working on typedef typename GridType::CellTag CellTag; //determine the topology type for the input grid typedef typename GridType::TopologyStructConstExecution InTopologyType; InTopologyType InputTopology; //holds the input cell connectivity //determine the topology type for the output grid typedef typename OutGridType::TopologyStructExecution OutTopologyType; OutTopologyType OutputTopology; //holds the output cell connectivity typedef typename dax::cont::ArrayHandle< int >::PortalConstExecution PortalType; PortalType PermutationPortal; DAX_CONT_EXPORT cell_subset(const GridType& grid, OutGridType& outGrid, dax::cont::ArrayHandle<int> permutationIndices): InputTopology(grid.PrepareForInput()), OutputTopology(outGrid.PrepareForOutput( permutationIndices.GetNumberOfValues())), PermutationPortal(permutationIndices.PrepareForInput()) { } DAX_EXEC_EXPORT void operator()( const int index ) const { //map index to original cell id const int cell_index = PermutationPortal.Get(index); dax::exec::CellVertices<CellTag> verts = this->InputTopology.GetCellConnections(cell_index); const int offset = dax::CellTraits<CellTag>::NUM_VERTICES * index; for(int i=0; i < dax::CellTraits<CellTag>::NUM_VERTICES; ++i) { this->OutputTopology.CellConnections.Set(offset+i,verts[i]); } } }; template<class GridType ,class T> void ThresholdExample(GridType grid, std::vector<T> &array, T minValue, T maxValue) { const int numCells = grid.GetNumberOfCells(); //find the default device adapter typedef DAX_DEFAULT_DEVICE_ADAPTER_TAG AdapterTag; //Make it easy to call the DeviceAdapter with the right tag typedef dax::cont::DeviceAdapterAlgorithm<AdapterTag> DeviceAdapter; //make a handle to the std::vector, this actually doesn't copy any memory //but waits for something to call PrepareForInput or PrepareForOutput before //moving the memory to cuda/tbb if required dax::cont::ArrayHandle<T> arrayHandle = dax::cont::make_ArrayHandle(array); //schedule the thresholding on a per cell basis dax::cont::ArrayHandle<int> passesThreshold; threshold_cell<GridType,T> tc(grid, arrayHandle, minValue, maxValue, passesThreshold); DeviceAdapter::Schedule( tc, numCells ); dax::cont::ArrayHandle<int> onlyGoodCellIds; const dax::Id numNewCells = DeviceAdapter::ScanInclusive( passesThreshold, onlyGoodCellIds ); dax::cont::ArrayHandle<int> cellUpperBounds; DeviceAdapter::UpperBounds( onlyGoodCellIds, dax::cont::make_ArrayHandleCounting(0,numNewCells), cellUpperBounds ); //now that we have the good cell ids only //lets extract the topology for those cells by calling cell_subset //first step is to find the cell type for the output grid. Since //the input grid can be any cell type, we need to find the //CanonicalCellTag for the cell type to determine what kind of cell //it will be in an unstructured grid typedef dax::CellTraits<typename GridType::CellTag> CellTraits; typedef typename CellTraits::CanonicalCellTag OutCellType; typedef dax::cont::ArrayContainerControlTagBasic CellContainerTag; //the second step is to copy the grid point coordinates in full //as we are doing cell sub-setting really. The first step is to //get the container tag type from the input point coordinates typedef typename GridType::PointCoordinatesType PointCoordsArrayHandle; typedef typename PointCoordsArrayHandle::ArrayContainerControlTag PointContainerTag; //now determine the out unstructured grid type typedef dax::cont::UnstructuredGrid<OutCellType, CellContainerTag, PointContainerTag> OutGridType; OutGridType outGrid; outGrid.SetPointCoordinates(grid.GetPointCoordinates()); //now time to do the actual cell sub-setting //since we are doing a cell sub-set we don't need to find the subset //of the property that we thresholded on cell_subset<GridType,OutGridType> cs(grid,outGrid,cellUpperBounds); DeviceAdapter::Schedule(cs,cellUpperBounds.GetNumberOfValues()); std::cout << "Input Grid number of cells: " << numCells << std::endl; std::cout << "Output Grid number of cells: " << outGrid.GetNumberOfCells() << std::endl; }; //helper class so we can test on all grid types struct TestOnAllGridTypes { template<typename GridType> DAX_CONT_EXPORT void operator()(const GridType&) const { //grid size is 4*4*4 cells dax::cont::testing::TestGrid<GridType> grid(4); std::vector<float> data_store(5*5*5); //fill the vector with random numbers std::srand(42); //I like this seed :-) std::generate(data_store.begin(),data_store.end(),std::rand); const float sum = std::accumulate(data_store.begin(),data_store.end(),0.0f); const float average = sum / static_cast<float>(data_store.size()); const float max = *(std::max_element(data_store.begin(),data_store.end())); //use the average as the min boundary so we get only a subset ThresholdExample(grid.GetRealGrid(),data_store,average,max); } }; int main(int, char**) { //load up a uniform grid and point based array and threshold //this is a basic example of using the Threshold dax::cont::UniformGrid<> grid; grid.SetExtent( dax::Id3(0,0,0), dax::Id3(4,4,4) ); //use an array which every value will pass std::vector<float> data_store(5*5*5,25); float min=0, max=100; ThresholdExample(grid,data_store,min,max); //next we are going to use the dax testing infastructure to pump this //example through every grid structure and cell type. //so that we show we can threshold voxels, triangles, wedges, verts, etc dax::cont::testing::GridTesting::TryAllGridTypes(TestOnAllGridTypes()); }
36.7751
90
0.719668
robertmaynard
5be09ff0afe0e481f52fc2c48e30d71f5aa1fbc0
1,185
cpp
C++
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
1
2022-03-28T13:57:20.000Z
2022-03-28T13:57:20.000Z
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
null
null
null
testMain.cpp
chuanstudyup/GPSM8N
e0f6bc6fa5484605557c38a4ec5fcfb6c1dd53c9
[ "Apache-2.0" ]
null
null
null
// testMain.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // g++ GPS.cpp testMain.cpp -o testMain /* NMEA examples $GNRMC,083712.40,A,3030.83159,N,11424.56558,E,0.150,,291221,,,A*65\r\n $GNRMC,083712.60,A,3030.83159,N,11424.56559,E,0.157,,291221,,,A*61\r\n $GNRMC,083712.80,A,3030.83158,N,11424.56558,E,0.033,,291221,,,A*6C\r\n $GNGGA,083712.80,3030.83158,N,11424.56558,E,1,10,1.00,49.7,M,-10.6,M,,*5B\r\n */ #include <iostream> #include <math.h> #include "GPS.h" using std::cout; using std::endl; int main() { char buf0[200] = "$GNRMC,083708.20,A,3030."; char buf1[200] = "83171,N,11424.56579,E,0.094,,291221,,,A*68\r\n$GNGGA,0"; char buf2[200] = "83712.80,3030.83158,N,11424.56558,E,1"; char buf3[200] = ",10,1.00,49.7,M,-10.6,M,,*5B\r\n"; GPS gps; gps.parseNAME(buf0); gps.parseNAME(buf1); gps.parseNAME(buf2); gps.parseNAME(buf3); cout <<"Lat:"<< gps.lat << endl; cout <<"Lng:"<< gps.lon << endl; cout <<"Velocity:"<< gps.velocity << endl; cout <<"Course:"<< gps.course << endl; cout << "SVs:" << static_cast<int>(gps.SVs) << endl; cout << "Altitude:" << gps.altitude << endl; cout << "HDOP:" << gps.HDOP << endl; return 0; }
29.625
78
0.61519
chuanstudyup
5be0ae2694bfc8d46a7a0329e74bc69410ee79cc
1,156
cpp
C++
android-31/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/icu/util/ULocale_Category.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JArray.hpp" #include "../../../JString.hpp" #include "./ULocale_Category.hpp" namespace android::icu::util { // Fields android::icu::util::ULocale_Category ULocale_Category::DISPLAY() { return getStaticObjectField( "android.icu.util.ULocale$Category", "DISPLAY", "Landroid/icu/util/ULocale$Category;" ); } android::icu::util::ULocale_Category ULocale_Category::FORMAT() { return getStaticObjectField( "android.icu.util.ULocale$Category", "FORMAT", "Landroid/icu/util/ULocale$Category;" ); } // QJniObject forward ULocale_Category::ULocale_Category(QJniObject obj) : java::lang::Enum(obj) {} // Constructors // Methods android::icu::util::ULocale_Category ULocale_Category::valueOf(JString arg0) { return callStaticObjectMethod( "android.icu.util.ULocale$Category", "valueOf", "(Ljava/lang/String;)Landroid/icu/util/ULocale$Category;", arg0.object<jstring>() ); } JArray ULocale_Category::values() { return callStaticObjectMethod( "android.icu.util.ULocale$Category", "values", "()[Landroid/icu/util/ULocale$Category;" ); } } // namespace android::icu::util
23.12
78
0.697232
YJBeetle
5be406b3951e569d1d65d9f0d519775ff52015e3
1,168
cpp
C++
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
code/components/conhost-v2/src/DrawFPS.cpp
thorium-cfx/fivem
587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c
[ "MIT" ]
null
null
null
#include "StdInc.h" #include <ConsoleHost.h> #include <imgui.h> #include <CoreConsole.h> #include "FpsTracker.h" static InitFunction initFunction([]() { static bool drawFpsEnabled; static bool streamingListEnabled; static bool streamingMemoryEnabled; static ConVar<bool> drawFps("cl_drawFPS", ConVar_Archive, false, &drawFpsEnabled); ConHost::OnShouldDrawGui.Connect([](bool* should) { *should = *should || drawFpsEnabled; }); ConHost::OnDrawGui.Connect([]() { if (!drawFpsEnabled) { return; } auto& io = ImGui::GetIO(); static FpsTracker fpsTracker; fpsTracker.Tick(); ImGui::SetNextWindowBgAlpha(0.0f); ImGui::SetNextWindowPos(ImVec2(ImGui::GetMainViewport()->Pos.x + 10, ImGui::GetMainViewport()->Pos.y + 10), 0, ImVec2(0.0f, 0.0f)); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); if (ImGui::Begin("DrawFps", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) { if (fpsTracker.CanGet()) { ImGui::Text("%llufps", fpsTracker.Get()); } } ImGui::PopStyleVar(); ImGui::End(); }); });
22.901961
186
0.710616
thorium-cfx
5be4b1c6a414d33b6af76f4904a7e05f7c281c00
56
hpp
C++
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__preprocessed_bcc551_bitor.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/preprocessed/bcc551/bitor.hpp>
28
55
0.803571
miathedev
5be9cdbd51e0b4addd5637585abfd4f1db2ec933
769
cpp
C++
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
null
null
null
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
null
null
null
12-10-21/balanced_binary_tree.cpp
ahanavish/GDSC-DSA-Interview-Preparation
d6cfa402dbbe8ed4f5b96f51e2e0fc0e2eabbdaf
[ "MIT" ]
1
2021-11-29T06:10:48.000Z
2021-11-29T06:10:48.000Z
// https://leetcode.com/problems/balanced-binary-tree/ class Solution { public: bool isBalanced(TreeNode *root) { vector<int> ans; int h = is(root, ans); if (check(ans)) return true; else return false; } bool check(vector<int> &ans) { for (int i = 0; i < ans.size(); i++) { if (ans[i] - ans[i + 1] > 1 || ans[i + 1] - ans[i] > 1) return false; i++; } return true; } int is(TreeNode *node, vector<int> &ans) { if (!node) return 0; int l = is(node->left, ans), r = is(node->right, ans); ans.push_back(l); ans.push_back(r); return max(l, r) + 1; } };
19.717949
67
0.443433
ahanavish
5beadd1842d02dfee23f1bd4393c91e0d0bee8e1
2,370
cpp
C++
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
5
2018-12-22T14:49:13.000Z
2022-01-13T07:21:46.000Z
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
null
null
null
qt-creator-opensource-src-4.6.1/src/tools/screenshotcropper/cropimageview.cpp
kevinlq/Qt-Creator-Opensource-Study
b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f
[ "MIT" ]
8
2018-07-17T03:55:48.000Z
2021-12-22T06:37:53.000Z
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "cropimageview.h" #include <QPainter> #include <QMouseEvent> CropImageView::CropImageView(QWidget *parent) : QWidget(parent) { } void CropImageView::mousePressEvent(QMouseEvent *event) { setArea(QRect(event->pos(), m_area.bottomRight())); update(); } void CropImageView::mouseMoveEvent(QMouseEvent *event) { setArea(QRect(m_area.topLeft(), event->pos())); update(); } void CropImageView::mouseReleaseEvent(QMouseEvent *event) { mouseMoveEvent(event); } void CropImageView::setImage(const QImage &image) { m_image = image; setMinimumSize(image.size()); update(); } void CropImageView::setArea(const QRect &area) { m_area = m_image.rect().intersected(area); emit cropAreaChanged(m_area); update(); } void CropImageView::paintEvent(QPaintEvent *event) { Q_UNUSED(event) QPainter p(this); if (!m_image.isNull()) p.drawImage(0, 0, m_image); if (!m_area.isNull()) { p.setPen(Qt::white); p.drawRect(m_area); QPen redDashes; redDashes.setColor(Qt::red); redDashes.setStyle(Qt::DashLine); p.setPen(redDashes); p.drawRect(m_area); } }
27.882353
77
0.659494
kevinlq
5bec9814ab09dd8bd09eb94fab72070f1ee18118
4,071
hpp
C++
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/thermophysicalModels/specie/reaction/reactionRate/thirdBodyEfficiencies/thirdBodyEfficiencies.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2018 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::thirdBodyEfficiencies Description Third body efficiencies \*---------------------------------------------------------------------------*/ #ifndef thirdBodyEfficiencies_HPP #define thirdBodyEfficiencies_HPP #include "scalarList.hpp" #include "speciesTable.hpp" #include "Tuple2.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { // Forward declaration of friend functions and operators class thirdBodyEfficiencies; Ostream& operator<<(Ostream&, const thirdBodyEfficiencies&); /*---------------------------------------------------------------------------*\ Class thirdBodyEfficiencies Declaration \*---------------------------------------------------------------------------*/ class thirdBodyEfficiencies : public scalarList { const speciesTable& species_; public: //- Construct from components inline thirdBodyEfficiencies ( const speciesTable& species, const scalarList& efficiencies ) : scalarList(efficiencies), species_(species) { if (size() != species_.size()) { FatalErrorInFunction << "number of efficiencies = " << size() << " is not equal to the number of species " << species_.size() << exit(FatalError); } } //- Construct from dictionary inline thirdBodyEfficiencies ( const speciesTable& species, const dictionary& dict ) : scalarList(species.size()), species_(species) { if (dict.found("coeffs")) { List<Tuple2<word, scalar> > coeffs(dict.lookup("coeffs")); if (coeffs.size() != species_.size()) { FatalErrorInFunction << "number of efficiencies = " << coeffs.size() << " is not equat to the number of species " << species_.size() << exit(FatalIOError); } forAll(coeffs, i) { operator[](species[coeffs[i].first()]) = coeffs[i].second(); } } else { scalar defaultEff = readScalar(dict.lookup("defaultEfficiency")); scalarList::operator=(defaultEff); } } // Member functions //- Calculate and return M, the concentration of the third-bodies inline scalar M(const scalarList& c) const { scalar M = 0; forAll(*this, i) { M += operator[](i)*c[i]; } return M; } //- Write to stream inline void write(Ostream& os) const { List<Tuple2<word, scalar> > coeffs(species_.size()); forAll(coeffs, i) { coeffs[i].first() = species_[i]; coeffs[i].second() = operator[](i); } os.writeKeyword("coeffs") << coeffs << token::END_STATEMENT << nl; } // Ostream Operator friend Ostream& operator<< ( Ostream& os, const thirdBodyEfficiencies& tbes ) { tbes.write(os); return os; } }; } // End namespace CML #endif
25.12963
83
0.517809
MrAwesomeRocks
5beeb662e275ac7b93836be860aee060f93fdb61
233
cpp
C++
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
3
2022-01-25T07:33:43.000Z
2022-03-30T10:25:09.000Z
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
null
null
null
codes/moderncpp/strtol/strtol02/main.cpp
eric2003/ModernCMake
48fe5ed2f25481a7c93f86af38a692f4563afcaa
[ "MIT" ]
2
2022-01-17T13:39:12.000Z
2022-03-30T10:25:12.000Z
#include <iostream> int main ( int argc, char **argv ) { { if ( argc > 1 ) { long i = strtol( argv[1], NULL, 0 ); std::cout << " i = " << i << std::endl; } } return 0; }
15.533333
52
0.377682
eric2003
5bf1be12a66207f9e5154926b9760b12e52a5f0c
3,920
cpp
C++
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
src/tnl/t_vb_points.cpp
OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
c0e0cfaeefa9e87e4978101fbac7d0372c39f1a3
[ "MIT" ]
null
null
null
/* $Id: t_vb_points.c,v 1.10 2002/10/29 20:29:04 brianp Exp $ */ /* * Mesa 3-D graphics library * Version: 4.1 * * Copyright (C) 1999-2002 Brian Paul All Rights Reserved. * * 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 * BRIAN PAUL 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. * * Authors: * Brian Paul */ #include "mtypes.h" #include "imports.h" #include "t_context.h" #include "t_pipeline.h" struct point_stage_data { GLvector4f PointSize; }; #define POINT_STAGE_DATA(stage) ((struct point_stage_data *)stage->privatePtr) /* * Compute attenuated point sizes */ static GLboolean run_point_stage( GLcontext *ctx, struct gl_pipeline_stage *stage ) { struct point_stage_data *store = POINT_STAGE_DATA(stage); struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; const GLfloat (*eye)[4] = (const GLfloat (*)[4]) VB->EyePtr->data; const GLfloat p0 = ctx->Point.Params[0]; const GLfloat p1 = ctx->Point.Params[1]; const GLfloat p2 = ctx->Point.Params[2]; const GLfloat pointSize = ctx->Point._Size; GLfloat (*size)[4] = store->PointSize.data; GLuint i; if (stage->changed_inputs) { /* XXX do threshold and min/max clamping here? */ for (i = 0; i < VB->Count; i++) { const GLfloat dist = -eye[i][2]; /* GLfloat dist = GL_SQRT(pos[0]*pos[0]+pos[1]*pos[1]+pos[2]*pos[2]);*/ size[i][0] = pointSize / (p0 + dist * (p1 + dist * p2)); } } VB->PointSizePtr = &store->PointSize; return GL_TRUE; } /* If point size attenuation is on we'll compute the point size for * each vertex in a special pipeline stage. */ static void check_point_size( GLcontext *ctx, struct gl_pipeline_stage *d ) { d->active = ctx->Point._Attenuated && !ctx->VertexProgram.Enabled; } static GLboolean alloc_point_data( GLcontext *ctx, struct gl_pipeline_stage *stage ) { struct vertex_buffer *VB = &TNL_CONTEXT(ctx)->vb; struct point_stage_data *store; stage->privatePtr = MALLOC(sizeof(*store)); store = POINT_STAGE_DATA(stage); if (!store) return GL_FALSE; _mesa_vector4f_alloc( &store->PointSize, 0, VB->Size, 32 ); /* Now run the stage. */ stage->run = run_point_stage; return stage->run( ctx, stage ); } static void free_point_data( struct gl_pipeline_stage *stage ) { struct point_stage_data *store = POINT_STAGE_DATA(stage); if (store) { _mesa_vector4f_free( &store->PointSize ); FREE( store ); stage->privatePtr = 0; } } const struct gl_pipeline_stage _tnl_point_attenuation_stage = { "point size attenuation", /* name */ _NEW_POINT, /* build_state_change */ _NEW_POINT, /* run_state_change */ GL_FALSE, /* active */ VERT_BIT_EYE, /* inputs */ VERT_BIT_POINT_SIZE, /* outputs */ 0, /* changed_inputs (temporary value) */ NULL, /* stage private data */ free_point_data, /* destructor */ check_point_size, /* check */ alloc_point_data /* run -- initially set to alloc data */ };
31.36
78
0.688265
OS2World
5bf4a1b12bd0ba842830ce713cef0b21e2e0da15
799
cpp
C++
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
learncpp.com/11_Inheritance/Question03/src/Main.cpp
KoaLaYT/Learn-Cpp
0bfc98c3eca9c2fde5bff609c67d7e273fde5196
[ "MIT" ]
null
null
null
/** * Chapter 11 :: Question 3 * * Fighting with a monster * use almost everything learned by bar * * KoaLaYT 23:15 04/02/2020 * */ #include "Player.h" #include <iostream> #include <string> Player initPlayer() { std::cout << "Enter you name: "; std::string name{}; std::getline(std::cin, name); std::cout << "Welcome, " << name << '\n'; return Player{name}; } int main() { Player p{initPlayer()}; while (!(p.hasWon() || p.isDead())) { p.fightMonster(); } if (p.hasWon()) { std::cout << "You won! And you have " << p.getGold() << " golds!\n"; } if (p.isDead()) { std::cout << "You died at level " << p.getLevel() << " and with " << p.getGold() << " gold.\n"; std::cout << "Too bad you can't take it with you!\n"; } return 0; }
19.02381
72
0.544431
KoaLaYT
5bf54790d03dad868eb1e1f926a2969a61ad40ca
12,838
hpp
C++
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
5
2019-12-27T07:30:03.000Z
2020-10-13T01:08:55.000Z
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
null
null
null
key/key.hpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
1
2020-07-27T22:36:40.000Z
2020-07-27T22:36:40.000Z
/* -------------------------------------------------------------------------------- key/key.hpp copyright(C) kyuhyun park 1993.07.13 -------------------------------------------------------------------------------- */ #ifdef def_key_key_hpp #error 'key/key.hpp' duplicated. #endif #define def_key_key_hpp #ifndef def_pub_config_hpp #include <pub/config.hpp> #endif /* -------------------------------------------------------------------------------- shift keys -------------------------------------------------------------------------------- */ #define def_key_rshift 0x0100 #define def_key_lshift 0x0101 #define def_key_rctrl 0x0102 #define def_key_lctrl 0x0103 #define def_key_ralt 0x0104 #define def_key_lalt 0x0105 #define def_key_rmachine 0x0106 #define def_key_lmachine 0x0107 #define def_key_num_lock 0x0108 #define def_key_caps_lock 0x0109 /* -------------------------------------------------------------------------------- character keys -------------------------------------------------------------------------------- */ #define def_key_a00 0x0200 #define def_key_a01 0x0201 #define def_key_a02 0x0202 #define def_key_a03 0x0203 #define def_key_a04 0x0204 #define def_key_a05 0x0205 #define def_key_a06 0x0206 #define def_key_a07 0x0207 #define def_key_a08 0x0208 #define def_key_a09 0x0209 #define def_key_a10 0x020a #define def_key_a11 0x020b #define def_key_a12 0x020c #define def_key_a13 0x020d #define def_key_a14 0x020e #define def_key_a15 0x020f #define def_key_b00 0x0220 #define def_key_b01 0x0221 #define def_key_b02 0x0222 #define def_key_b03 0x0223 #define def_key_b04 0x0224 #define def_key_b05 0x0225 #define def_key_b06 0x0226 #define def_key_b07 0x0227 #define def_key_b08 0x0228 #define def_key_b09 0x0229 #define def_key_b10 0x022a #define def_key_b11 0x022b #define def_key_b12 0x022c #define def_key_b13 0x022d #define def_key_b14 0x022e #define def_key_b15 0x022f #define def_key_c00 0x0240 #define def_key_c01 0x0241 #define def_key_c02 0x0242 #define def_key_c03 0x0243 #define def_key_c04 0x0244 #define def_key_c05 0x0245 #define def_key_c06 0x0246 #define def_key_c07 0x0247 #define def_key_c08 0x0248 #define def_key_c09 0x0249 #define def_key_c10 0x024a #define def_key_c11 0x024b #define def_key_c12 0x024c #define def_key_c13 0x024d #define def_key_c14 0x024e #define def_key_c15 0x024f #define def_key_d00 0x0260 #define def_key_d01 0x0261 #define def_key_d02 0x0262 #define def_key_d03 0x0263 #define def_key_d04 0x0264 #define def_key_d05 0x0265 #define def_key_d06 0x0266 #define def_key_d07 0x0267 #define def_key_d08 0x0268 #define def_key_d09 0x0269 #define def_key_d10 0x026a #define def_key_d11 0x026b #define def_key_d12 0x026c #define def_key_d13 0x026d #define def_key_d14 0x026e #define def_key_d15 0x026f #define def_key_qwt_q 0x0220 #define def_key_qwt_w 0x0221 #define def_key_qwt_e 0x0222 #define def_key_qwt_r 0x0223 #define def_key_qwt_t 0x0224 #define def_key_qwt_y 0x0225 #define def_key_qwt_u 0x0226 #define def_key_qwt_i 0x0227 #define def_key_qwt_o 0x0228 #define def_key_qwt_p 0x0229 #define def_key_qwt_a 0x0240 #define def_key_qwt_s 0x0241 #define def_key_qwt_d 0x0242 #define def_key_qwt_f 0x0243 #define def_key_qwt_g 0x0244 #define def_key_qwt_h 0x0245 #define def_key_qwt_j 0x0246 #define def_key_qwt_k 0x0247 #define def_key_qwt_l 0x0248 #define def_key_qwt_z 0x0260 #define def_key_qwt_x 0x0261 #define def_key_qwt_c 0x0262 #define def_key_qwt_v 0x0263 #define def_key_qwt_b 0x0264 #define def_key_qwt_n 0x0265 #define def_key_qwt_m 0x0266 /* -------------------------------------------------------------------------------- character keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_0 0x0300 #define def_key_pad_1 0x0301 #define def_key_pad_2 0x0302 #define def_key_pad_3 0x0303 #define def_key_pad_4 0x0304 #define def_key_pad_5 0x0305 #define def_key_pad_6 0x0306 #define def_key_pad_7 0x0307 #define def_key_pad_8 0x0308 #define def_key_pad_9 0x0309 #define def_key_pad_slash 0x030a #define def_key_pad_asterisk 0x030b #define def_key_pad_minus 0x030c #define def_key_pad_plus 0x030d #define def_key_pad_period 0x030e /* -------------------------------------------------------------------------------- special keys -------------------------------------------------------------------------------- */ #define def_key_esc 0x0400 #define def_key_backspace 0x0401 #define def_key_tab 0x0402 #define def_key_enter 0x0403 #define def_key_space 0x0404 #define def_key_insert 0x0405 #define def_key_delete 0x0406 #define def_key_print_screen 0x0407 #define def_key_scroll_lock 0x0408 #define def_key_pause 0x0409 #define def_key_sys_req 0x040a #define def_key_break 0x040b // 0x040c reserved for clear key #define def_key_hangul 0x040d #define def_key_hanja 0x040e /* -------------------------------------------------------------------------------- special keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_enter 0x0503 #define def_key_pad_insert 0x0505 #define def_key_pad_delete 0x0506 #define def_key_pad_clear 0x050c /* -------------------------------------------------------------------------------- movement keys -------------------------------------------------------------------------------- */ #define def_key_up 0x0600 #define def_key_down 0x0601 #define def_key_left 0x0602 #define def_key_right 0x0603 #define def_key_page_up 0x0604 #define def_key_page_down 0x0605 #define def_key_home 0x0606 #define def_key_end 0x0607 /* -------------------------------------------------------------------------------- movement keys on keypad -------------------------------------------------------------------------------- */ #define def_key_pad_up 0x0700 #define def_key_pad_down 0x0701 #define def_key_pad_left 0x0702 #define def_key_pad_right 0x0703 #define def_key_pad_page_up 0x0704 #define def_key_pad_page_down 0x0705 #define def_key_pad_home 0x0706 #define def_key_pad_end 0x0707 /* -------------------------------------------------------------------------------- function keys -------------------------------------------------------------------------------- */ #define def_key_f1 0x0800 #define def_key_f2 0x0801 #define def_key_f3 0x0802 #define def_key_f4 0x0803 #define def_key_f5 0x0804 #define def_key_f6 0x0805 #define def_key_f7 0x0806 #define def_key_f8 0x0807 #define def_key_f9 0x0808 #define def_key_f10 0x0809 #define def_key_f11 0x080a #define def_key_f12 0x080b /* -------------------------------------------------------------------------------- function keys on keypad -------------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------------- additonal defines -------------------------------------------------------------------------------- */ #define def_key_type_null 0x0000u #define def_key_type_shift 0x0100u #define def_key_type_char 0x0200u #define def_key_type_pad_char 0x0300u #define def_key_type_action 0x0400u #define def_key_type_pad_action 0x0500u #define def_key_type_cursor 0x0600u #define def_key_type_pad_cursor 0x0700u #define def_key_type_function 0x0800u #define def_key_type_pad_function 0x0900u #define def_key_mask_rshift 0x0001u #define def_key_mask_lshift 0x0002u #define def_key_mask_rctrl 0x0004u #define def_key_mask_lctrl 0x0008u #define def_key_mask_ralt 0x0010u #define def_key_mask_lalt 0x0020u #define def_key_mask_rmachine 0x0040u #define def_key_mask_lmachine 0x0080u #define def_key_mask_num_lock 0x0100u #define def_key_mask_caps_lock 0x0200u #define def_key_mask_shift (def_key_mask_rshift | def_key_mask_lshift) #define def_key_mask_ctrl (def_key_mask_rctrl | def_key_mask_lctrl) #define def_key_mask_alt (def_key_mask_ralt | def_key_mask_lalt) #define def_key_mask_machine (def_key_mask_rmachine | def_key_mask_lmachine) #define def_key_mask_code_type 0xff00u #define def_key_mask_code_offset 0x00ffu /* -------------------------------------------------------------------------------- */ struct cls_key_frame { bool make_flg; uint16 code_u16; uint16 shifted_u16; uint16 toggled_u16; }; #if (defined def_dos) || (defined def_os2 && !defined def_pm) void key_on(); void key_off(); void key_reset(); bool key_pressed(); void key_get(cls_key_frame*); #endif
45.524823
123
0.426157
drypot
5bfdbaa805eb89ccfca66a4e290910af697b6e15
439
cpp
C++
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
1
2020-03-26T07:09:54.000Z
2020-03-26T07:09:54.000Z
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
modules/cadac/env/wind_constant.cpp
mlouielu/mazu-sim
fd2da3a9f7ca3ca30d3d3f4bbd6966cb68623225
[ "BSD-3-Clause" ]
null
null
null
#include "wind_constant.hh" #include <cstring> cad::Wind_Constant::Wind_Constant(double dvba, double dir, double twind_In, double vertical_wind) : Wind(twind_In, vertical_wind) { snprintf(name, sizeof(name), "Constant Wind"); altitude = 0; vwind = dvba; psiwdx = dir; } cad::Wind_Constant::~Wind_Constant() { } void cad::Wind_Constant::set_altitude(double altitude_in_meter) { altitude = altitude_in_meter; }
18.291667
97
0.710706
mlouielu
7500881c595656b36cf3bf9aa8b7ebdf0d282e2f
8,635
cpp
C++
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
2
2021-11-27T18:35:20.000Z
2022-03-23T08:11:57.000Z
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
null
null
null
http.cpp
kissbeni/tinyhttp
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
[ "Apache-2.0" ]
null
null
null
#include "http.hpp" #include <vector> /*static*/ TCPClientStream TCPClientStream::acceptFrom(short listener) { struct sockaddr_in client; const size_t clientLen = sizeof(client); short sock = accept( listener, reinterpret_cast<struct sockaddr*>(&client), const_cast<socklen_t*>(reinterpret_cast<const socklen_t*>(&clientLen)) ); if (sock < 0) { perror("accept failed"); return {-1}; } return {sock}; } void TCPClientStream::send(const void* what, size_t size) { if (::send(mSocket, what, size, MSG_NOSIGNAL) < 0) throw std::runtime_error("TCP send failed"); } size_t TCPClientStream::receive(void* target, size_t max) { ssize_t len; if ((len = recv(mSocket, target, max, MSG_NOSIGNAL)) < 0) throw std::runtime_error("TCP receive failed"); return static_cast<size_t>(len); } std::string TCPClientStream::receiveLine(bool asciiOnly, size_t max) { std::string res; char ch; while (res.size() < max) { if (recv(mSocket, &ch, 1, MSG_NOSIGNAL) != 1) throw std::runtime_error("TCP receive failed"); if (ch == '\r') continue; if (ch == '\n') break; if (asciiOnly && !isascii(ch)) throw std::runtime_error("Only ASCII characters were allowed"); res.push_back(ch); } return res; } void TCPClientStream::close() { if (mSocket < 0) return; ::close(mSocket); mSocket = -1; } bool HttpRequest::parse(std::shared_ptr<IClientStream> stream) { std::istringstream iss(stream->receiveLine()); std::vector<std::string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results.size() < 2) return false; std::string methodString = results[0]; if (methodString == "GET" ) { mMethod = HttpRequestMethod::GET; } else if (methodString == "POST" ) { mMethod = HttpRequestMethod::POST; } else if (methodString == "PUT" ) { mMethod = HttpRequestMethod::PUT; } else if (methodString == "DELETE" ) { mMethod = HttpRequestMethod::DELETE; } else if (methodString == "OPTIONS") { mMethod = HttpRequestMethod::OPTIONS; } else return false; path = results[1]; ssize_t question = path.find("?"); if (question > 0) { query = path.substr(question); path = path.substr(0, question); } if (query.empty()) std::cout << methodString << " " << path << std::endl; else std::cout << methodString << " " << path << " (Query: " << query << ")" << std::endl; while (true) { std::string line = stream->receiveLine(); if (line.empty()) break; ssize_t sep = line.find(": "); if (sep <= 0) return false; std::string key = line.substr(0, sep), val = line.substr(sep+2); (*this)[key] = val; //std::cout << "HEADER: <" << key << "> set to <" << val << ">" << std::endl; } std::string contentLength = (*this)["Content-Length"]; ssize_t cl = std::atoll(contentLength.c_str()); if (cl > MAX_HTTP_CONTENT_SIZE) throw std::runtime_error("request too large"); if (cl > 0) { char* tmp = new char[cl]; bzero(tmp, cl); stream->receive(tmp, cl); mContent = std::string(tmp, cl); delete[] tmp; #ifdef TINYHTTP_JSON if ( (*this)["Content-Type"] == "application/json" || (*this)["Content-Type"].rfind("application/json;",0) == 0 // some clients gives us extra data like charset ) { std::string error; mContentJson = miniJson::Json::parse(mContent, error); if (!error.empty()) std::cerr << "Content type was JSON but we couldn't parse it! " << error << std::endl; } #endif } return true; } /*static*/ bool HttpHandlerBuilder::isSafeFilename(const std::string& name, bool allowSlash) { static const char allowedChars[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-+@"; for (auto x : name) { if (x == '/' && !allowSlash) return false; bool ok = false; for (size_t i = 0; allowedChars[i] && !ok; i++) ok = allowedChars[i] == x; if (!ok) return false; } return true; } /*static*/ std::string HttpHandlerBuilder::getMimeType(std::string name) { static std::map<std::string, std::string> mMimeDatabase; if (mMimeDatabase.empty()) { mMimeDatabase.insert({"js", "application/javascript"}); mMimeDatabase.insert({"pdf", "application/pdf"}); mMimeDatabase.insert({"gz", "application/gzip"}); mMimeDatabase.insert({"xml", "application/xml"}); mMimeDatabase.insert({"html", "text/html"}); mMimeDatabase.insert({"htm", "text/html"}); mMimeDatabase.insert({"css", "text/css"}); mMimeDatabase.insert({"txt", "text/plain"}); mMimeDatabase.insert({"png", "image/png"}); mMimeDatabase.insert({"jpg", "image/jpeg"}); mMimeDatabase.insert({"jpeg", "image/jpeg"}); mMimeDatabase.insert({"json", "application/json"}); } ssize_t pos = name.rfind("."); if (pos < 0) return "application/octet-stream"; auto f = mMimeDatabase.find(name.substr(pos+1)); if (f == mMimeDatabase.end()) return "application/octet-stream"; return f->second; } HttpServer::HttpServer() { mDefault404Message = HttpResponse{404, "text/plain", "404 not found"}.buildMessage(); mDefault400Message = HttpResponse{400, "text/plain", "400 bad request"}.buildMessage(); } void HttpServer::startListening(uint16_t port) { #ifndef TINYHTTP_FUZZING mSocket = socket(AF_INET, SOCK_STREAM, 0); if (mSocket == -1) throw std::runtime_error("Could not create socket"); struct sockaddr_in remote = {0}; remote.sin_family = AF_INET; remote.sin_addr.s_addr = htonl(INADDR_ANY); remote.sin_port = htons(port); int iRetval; while (true) { iRetval = bind(mSocket, reinterpret_cast<struct sockaddr*>(&remote), sizeof(remote)); if (iRetval < 0) { perror("Failed to bind socket, retrying in 5 seconds..."); usleep(1000 * 5000); } else break; } listen(mSocket, 3); #else mSocket = 0; #endif printf("Waiting for incoming connections...\n"); while (mSocket != -1) { #ifdef TINYHTTP_FUZZING auto stream = std::make_shared<StdinClientStream>(); #else auto stream = std::shared_ptr<IClientStream>(new TCPClientStream{TCPClientStream::acceptFrom(mSocket)}); #endif std::thread th([stream,this]() { ICanRequestProtocolHandover* handover = nullptr; std::unique_ptr<HttpRequest> handoverRequest; try { while (stream->isOpen()) { HttpRequest req; try { if (!req.parse(stream)) { stream->send(mDefault400Message); stream->close(); continue; } } catch (...) { stream->send(mDefault400Message); stream->close(); continue; } auto res = processRequest(req.getPath(), req); if (res) { auto builtMessage = res->buildMessage(); stream->send(builtMessage); if (res->acceptProtocolHandover(&handover)) { handoverRequest = std::make_unique<HttpRequest>(req); break; } goto keep_alive_check; } stream->send(mDefault404Message); keep_alive_check: if (req["Connection"] != "keep-alive") break; } if (handover) handover->acceptHandover(mSocket, *stream.get(), std::move(handoverRequest)); } catch (std::exception& e) { std::cerr << "Exception in HTTP client handler (" << e.what() << ")\n"; } stream->close(); }); #ifdef TINYHTTP_FUZZING th.join(); break; #else th.detach(); #endif } puts("Listen loop shut down"); } void HttpServer::shutdown() { close(mSocket); mSocket = -1; }
30.298246
122
0.550434
kissbeni
7504ec031afcc508c6f5e58eb8b1c0be91f0d33a
9,092
cpp
C++
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
2
2022-03-29T05:34:31.000Z
2022-03-29T06:04:40.000Z
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
null
null
null
MOWER/src/MowerMoves/MowerMoves.cpp
Mrgove10/AutoMower
9f157f27da13b94d0138208efebbe4f26b5d9187
[ "MIT" ]
1
2022-03-29T03:32:22.000Z
2022-03-29T03:32:22.000Z
#include <Arduino.h> #include "pin_definitions.h" #include "Environment_definitions.h" #include "myGlobals_definition.h" #include "MowerMoves/MowerMoves.h" #include "MotionMotor/MotionMotor.h" #include "Utils/Utils.h" #include "Display/Display.h" /** * Mower mouvement stop function */ void MowerStop() { DebugPrintln("Mower Stop", DBG_VERBOSE, true); MotionMotorStop(MOTION_MOTOR_RIGHT); MotionMotorStop(MOTION_MOTOR_LEFT); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower forward move * @param Speed to travel */ void MowerForward(const int Speed) { DebugPrintln("Mower Forward at " + String(Speed) + "%", DBG_VERBOSE, true); MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_FORWARD, Speed); MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_FORWARD, Speed); } /** * Sets/changes Mower speed * @param Speed to travel */ void MowerSpeed(const int Speed) { static int lastSpeed = 0; if (Speed != lastSpeed) { DebugPrintln("Mower speed at " + String(Speed) + "%", DBG_VERBOSE, true); lastSpeed = Speed; } MotionMotorSetSpeed(MOTION_MOTOR_RIGHT, Speed); MotionMotorSetSpeed(MOTION_MOTOR_LEFT, Speed); } /** * Mower reverse move * @param Speed to reverse * @param Duration of reverse (in ms) */ void MowerReverse(const int Speed, const int Duration) { DebugPrintln("Mower Reverse at " + String(Speed) + "%", DBG_VERBOSE, true); MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_REVERSE, Speed); MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_REVERSE, Speed); delay(Duration); MowerStop(); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower turn function * @param Angle to turn in degrees (positive is right turn, negative is left turn) * @param OnSpot turn with action of both wheels * */ void MowerTurn(const int Angle, const bool OnSpot) { // Limit angle to [-360,+360] degrees int LimitedAngle = min(Angle, 360); LimitedAngle = max(LimitedAngle, -360); float turnDuration = float(abs(LimitedAngle) / (MOWER_MOVES_TURN_ANGLE_RATIO)); DebugPrintln("Mower turn of " + String(Angle) + " Deg => " + String(turnDuration, 0) + " ms", DBG_VERBOSE, true); if (LimitedAngle < 0) // Left turn { MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_FORWARD, MOWER_MOVES_TURN_SPEED); if (OnSpot) { MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_REVERSE, MOWER_MOVES_TURN_SPEED); } delay(turnDuration); MotionMotorStop(MOTION_MOTOR_RIGHT); MotionMotorStop(MOTION_MOTOR_LEFT); } else // Right turn { MotionMotorStart(MOTION_MOTOR_LEFT, MOTION_MOTOR_FORWARD, MOWER_MOVES_TURN_SPEED); if (OnSpot) { MotionMotorStart(MOTION_MOTOR_RIGHT, MOTION_MOTOR_REVERSE, MOWER_MOVES_TURN_SPEED); } delay(turnDuration); MotionMotorStop(MOTION_MOTOR_LEFT); MotionMotorStop(MOTION_MOTOR_RIGHT); } } /** * Mower reverse and turn function * @param Angle to turn in degrees (positive is right turn, negative is left turn) * @param Duration of reverse (in ms) * @param OnSpot turn with action of both wheels * */ void MowerReserseAndTurn(const int Angle, const int Duration, const bool OnSpot) { int correctedAngle = Angle; int correctedDuration = Duration; // Check if mower facing downwards, increase turning angle and duration to compensate for tilt angle if (g_pitchAngle < MOTION_MOTOR_PITCH_TURN_CORRECTION_ANGLE) { DebugPrintln("Mower facing downwards (Pitch:" + String(g_pitchAngle) + ") : turn angle and duration corrected", DBG_DEBUG, true); correctedAngle = correctedAngle - int(g_pitchAngle * MOTION_MOTOR_PITCH_TURN_CORRECTION_FACTOR); // pitch angle is negative when going downwards correctedDuration = correctedDuration - int(100 * g_pitchAngle * MOTION_MOTOR_PITCH_TURN_CORRECTION_FACTOR); // pitch angle is negative when going downwards } MowerReverse(MOWER_MOVES_REVERSE, correctedDuration); MowerTurn(correctedAngle, OnSpot); // Wait before any movement is made - To limit mechanical stress delay(150); } /** * Mower checks selected obstacle types and reduces speed if conditions are met * @param SpeedDelta as int: the speed reduction to be applied expressed as a positive value (in absolue %). If multiple conditions are selected, same speed reduction is applied. * @param Front as optional int: sonar measured front distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Left as optional int: sonar measured left distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Right as optional int: sonar measured right distance under which mower needs to slow down. 0 disbales the check. Default is 0 * @param Perimeter as optional int: perimeter wire signal magnitude under which mower needs to slow down. 0 disables the check. Absolute value is used to perform the check (applies to both inside and outside perimeter wire). Default is 0. * @return boolean indicating if the function triggered a speed reduction */ bool MowerSlowDownApproachingObstables(const int SpeedDelta, const int Front, const int Left, const int Right, const int Perimeter) { static unsigned long lastSpeedReduction = 0; bool SpeedReductiontiggered = false; static bool SpeedReductionInProgress = false; // To avoid a jerky mouvement, speed reduction is maintained at least for a set duration // if (millis() - lastSpeedReduction < OBSTACLE_APPROACH_LOW_SPEED_MIN_DURATION) // { // return true; // } // else // { // // SpeedReductionInProgress = false; // } // Check for objects in Front if (Front > 0 && g_SonarDistance[SONAR_FRONT] < Front) { DebugPrintln("Front approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_FRONT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for objects on left side if (Left > 0 && g_SonarDistance[SONAR_LEFT] < Left) { DebugPrintln("Left approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_LEFT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for objects on right side if (Right > 0 && g_SonarDistance[SONAR_RIGHT] < Right) { DebugPrintln("Right approaching object: Slowing down ! (" + String(g_SonarDistance[SONAR_RIGHT]) + "cm)", DBG_DEBUG, true); SpeedReductiontiggered = true; } // Check for Perimeter wire if (Perimeter > 0 && abs(g_PerimeterMagnitudeAvg) > Perimeter) { DebugPrintln("Approaching perimeter: Slowing down ! (" + String(g_PerimeterMagnitude) + ")", DBG_VERBOSE, true); SpeedReductiontiggered = true; } // If at least one of the conditions are met and if motor speed is higher that minimum threshold, reduce speed // Left Motor // if (SpeedReductiontiggered && g_MotionMotorSpeed[MOTION_MOTOR_LEFT] - SpeedDelta > MOTION_MOTOR_MIN_SPEED ) if (SpeedReductiontiggered && !SpeedReductionInProgress) { DebugPrintln("Left motor speed reduced by " + String(SpeedDelta) + "%", DBG_VERBOSE, true); MotionMotorSetSpeed(MOTION_MOTOR_LEFT, - SpeedDelta, true); } // Right Motor // if (SpeedReductiontiggered && g_MotionMotorSpeed[MOTION_MOTOR_RIGHT] - SpeedDelta > MOTION_MOTOR_MIN_SPEED) if (SpeedReductiontiggered && !SpeedReductionInProgress) // if (SpeedReductiontiggered) { DebugPrintln("Right motor speed reduced by " + String(SpeedDelta) + "%", DBG_VERBOSE, true); MotionMotorSetSpeed(MOTION_MOTOR_RIGHT, - SpeedDelta, true); SpeedReductionInProgress = true; } // keep track of when last speed reduction was triggered if (SpeedReductiontiggered) { lastSpeedReduction = millis(); } else { SpeedReductionInProgress = false; } return SpeedReductiontiggered; } /** * Mower arc function : mower moves in given direction with motors running at a different speed, thus turning forming an arc : used for spiral mowing * @param direction forward (MOTION_MOTOR_FORWARD) or reverse (MOTION_MOTOR_REVERSE) * @param leftSpeed Left motor speed (in %) * @param rightSpeed Right motor speed (in %) */ void MowerArc(const int direction, const int leftSpeed, const int rightSpeed) { if (direction == MOTION_MOTOR_FORWARD) { if (leftSpeed != rightSpeed) { DebugPrintln("Mower arc Forward (Left:" + String(leftSpeed) + "%, Right:" + String(rightSpeed) + "%)", DBG_VERBOSE, true); } else { DebugPrintln("Mower Forward @ " + String(leftSpeed) + "%", DBG_VERBOSE, true); } } else { if (leftSpeed != rightSpeed) { DebugPrintln("Mower arc Reverse (Left:" + String(leftSpeed) + "%, Right:" + String(rightSpeed) + "%)", DBG_VERBOSE, true); } else { DebugPrintln("Mower Reverse @ " + String(leftSpeed) + "%", DBG_VERBOSE, true); } } MotionMotorStart(MOTION_MOTOR_RIGHT, direction, rightSpeed); MotionMotorStart(MOTION_MOTOR_LEFT, direction, leftSpeed); } /* void getMeUnstuck() { // stop motor // go back 10 cm // turn right or left (by certain angle) turn(15, true); // go forward } */
34.570342
241
0.723603
Mrgove10
7506f8c3b63aff5e8b7ddfd042bcdccd46e947ac
50,640
cpp
C++
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
element.cpp
orkzking/openxfem
66889ea05ec108332ab8566b510124ee1a3f334d
[ "FTL" ]
null
null
null
/************************************************************************************ Copyright (C) 2005 Stephane BORDAS, Cyrille DUNANT, Vinh Phu NGUYEN, Quang Tri TRUONG, Ravindra DUDDU This file is part of the XFEM C++ Library (OpenXFEM++) written and maintained by above authors. This program is free software; you can redistribute it and/or modify it. 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 license text for more details. Any feedback is welcome. Emails : nvinhphu@gmail.com, ... *************************************************************************************/ // file ELEMENT.CPP #include "element.h" #include "tri_u.h" #include "tri6.h" #include "quad_u.h" #include "plateiso4.h" #include "tetra4.h" #include "mitc4.h" #include "domain.h" #include "timestep.h" #include "timinteg.h" #include "node.h" #include "dof.h" #include "material.h" #include "bodyload.h" #include "gausspnt.h" #include "intarray.h" #include "flotarry.h" #include "flotmtrx.h" #include "diagmtrx.h" #include "enrichmentitem.h" #include "cracktip.h" #include "crackinterior.h" #include "materialinterface.h" #include "enrichmentfunction.h" #include "standardquadrature.h" #include "splitgaussquadrature.h" #include "vertex.h" #include "feinterpol.h" #include "linsyst.h" #include "functors.h" #include "skyline.h" #include <stdlib.h> #include <stdio.h> #include <vector> #include <map> #include <algorithm> #include <iostream> #include "planelast.h" using namespace std; Element :: Element (int n, Domain* aDomain) : FEMComponent (n, aDomain) // Constructor. Creates an element with number n, belonging to aDomain. { material = 0 ; numberOfNodes = 0 ; nodeArray = NULL ; locationArray = NULL ; constitutiveMatrix = NULL ; massMatrix = NULL ; stiffnessMatrix = NULL ; bodyLoadArray = NULL ; gaussPointArray = NULL ; neighbors = NULL ; // XFEM, NVP 2005 numberOfGaussPoints = 0 ; // XFEM, NVP 2005 numOfGPsForJ_Integral = 0 ; // XFEM, NVP 2005-08-13 numberOfIntegrationRules = 0 ; // XFEM, NVP 2005 quadratureRuleArray= NULL ; // XFEM, NVP 2005 standardFEInterpolation = NULL ; // XFEM, NVP 2005 enrichmentFEInterpolation= NULL ; // XFEM, NVP 2005 enrichmentItemListOfElem = NULL ; // XFEM, NVP 2005 checked = false; // XFEM, NVP 2005 isUpdated = false ; // XFEM, NVP 2005-09-03 isMultiMaterial = false ; // one material element //materialIDs = } Element :: ~Element () // Destructor. { delete nodeArray ; delete locationArray ; delete massMatrix ; delete stiffnessMatrix ; delete constitutiveMatrix ; if (gaussPointArray) { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) delete gaussPointArray[i] ; delete gaussPointArray ; } if (quadratureRuleArray) { for (size_t i = 0 ; i < numberOfIntegrationRules ; i++) delete quadratureRuleArray[i] ; delete quadratureRuleArray ; } delete bodyLoadArray ; delete enrichmentItemListOfElem ; delete standardFEInterpolation ; delete enrichmentFEInterpolation ; delete neighbors ; } FloatMatrix* Element :: ComputeTangentStiffnessMatrix () // Computes numerically the tangent stiffness matrix of the receiver, with // the mesh subject to the total displacements D. // Remark: geometrical nonlinarities are not acccounted for. // MODIFIED TO TAKE ACCOUNT FOR MULTIMATERIALS ELEMENT !!! { GaussPoint *gp; FloatMatrix *b,*db,*d; double dV; //test ConstantStiffness? char nlSolverClassName[32] ; NLSolver* nlSolver = this->domain->giveNLSolver(); nlSolver -> giveClassName(nlSolverClassName) ; if (stiffnessMatrix) { delete stiffnessMatrix; } stiffnessMatrix = new FloatMatrix(); Material *mat = this->giveMaterial(); for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i]; b = this->ComputeBmatrixAt(gp); // compute D matrix if(! strcmp(nlSolverClassName,"ConstantStiffness")) d = this->giveConstitutiveMatrix()->GiveCopy(); // NO USED LONGER !!! else d = mat->ComputeConstitutiveMatrix(gp,this); // USE THIS ONE //d->printYourself(); dV = this->computeVolumeAround(gp); db = d->Times(b); stiffnessMatrix->plusProduct(b,db,dV); delete d; delete db; delete b; // SC-Purify-10.09.97 } stiffnessMatrix->symmetrized(); return stiffnessMatrix->GiveCopy(); // fix memory leaks !!! } FloatArray* Element :: ComputeInternalForces (FloatArray* dElem) // Computes the internal force vector of the receiver, with the domain sub- // ject to the displacements D. { GaussPoint *gp; FloatMatrix *b; double dV; Material *mat = this->giveMaterial(); FloatArray *f = new FloatArray(); for(size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i]; b = this->ComputeBmatrixAt(gp); mat -> ComputeStress(dElem,this,gp); dV = this->computeVolumeAround(gp); f->plusProduct(b,gp->giveStressVector(),dV); delete b; } return f; } void Element :: assembleLhsAt (TimeStep* stepN) // Assembles the left-hand side (stiffness matrix) of the receiver to // the linear system' left-hand side, at stepN. { //FloatMatrix* elemLhs ; //Skyline* systLhs ; //IntArray* locArray ; //elemLhs = this -> ComputeLhsAt(stepN) ; //systLhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveLhs() ; //locArray = this -> giveLocationArray() ; //systLhs -> assemble(elemLhs,locArray) ; //delete elemLhs ; } void Element :: assembleRhsAt (TimeStep* stepN) // Assembles the right-hand side (load vector) of the receiver to // the linear system' right-hand side, at stepN. { //FloatArray* elemRhs ; //FloatArray* systRhs ; //IntArray* locArray ; //elemRhs = this -> ComputeRhsAt(stepN) ; //if (elemRhs) { // systRhs = domain -> giveNLSolver() -> giveLinearSystem() -> giveRhs() ; // locArray = this -> giveLocationArray() ; // systRhs -> assemble(elemRhs,locArray) ; // delete elemRhs ;} } void Element :: assembleYourselfAt (TimeStep* stepN) // Assembles the contributions of the receiver to the linear system, at // time step stepN. This may, or may not, require assembling the receiver's // left-hand side. { # ifdef VERBOSE printf ("assembling element %d\n",number) ; # endif //CB - Modified by SC - 25.07.97 //because we ALWAYS reform the system! //if (stepN -> requiresNewLhs()) //CE - Modified by SC - 25.07.97 //this -> assembleLhsAt(stepN) ; //this -> assembleRhsAt(stepN) ; } FloatArray* Element :: ComputeBcLoadVectorAt (TimeStep* stepN) // Computes the load vector due to the boundary conditions acting on the // receiver's nodes, at stepN. Returns NULL if this array contains only // zeroes. // Modified by NVP 2005-09-04 for XFEM implementation. { FloatArray *d, *answer ; FloatMatrix *k; d = this -> ComputeVectorOfPrescribed('d',stepN) ; if(this->domain->isXFEMorFEM() == false && stepN->giveNumber() > 1) { FloatArray *previousDPr; previousDPr = this -> ComputeVectorOfPrescribed ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; d->minus(previousDPr); delete previousDPr; } if (d -> containsOnlyZeroes()) { answer = NULL ; } else { k = this -> GiveStiffnessMatrix() ; answer = k -> Times(d) -> negated() ; delete k ; } delete d ; return answer ; } FloatArray* Element :: ComputeBodyLoadVectorAt (TimeStep* stepN) // Computes numerically the load vector of the receiver due to the body // loads, at stepN. { double dV ; GaussPoint* gp ; FloatArray *answer,*f,*ntf ; FloatMatrix *n,*nt ; if (this -> giveBodyLoadArray() -> isEmpty()) // no loads return NULL ; else { f = this -> ComputeResultingBodyForceAt(stepN) ; if (! f) // nil resultant return NULL ; else { answer = new FloatArray(0) ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; n = this -> ComputeNmatrixAt(gp) ; dV = this -> computeVolumeAround(gp) ; nt = n -> GiveTransposition() ; ntf = nt -> Times(f) -> times(dV) ; answer -> add(ntf) ; delete n ; delete nt ; delete ntf ; } delete f ; return answer ; } } } FloatMatrix* Element :: ComputeConsistentMassMatrix () // Computes numerically the consistent (full) mass matrix of the receiver. { double density,dV ; FloatMatrix *n,*answer ; GaussPoint *gp ; answer = new FloatMatrix() ; density = this -> giveMaterial() -> give('d') ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; n = this -> ComputeNmatrixAt(gp) ; dV = this -> computeVolumeAround(gp) ; answer -> plusProduct(n,n,density*dV) ; delete n ; } return answer->symmetrized() ; } FloatMatrix* Element :: computeLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system. { TimeIntegrationScheme* scheme ; scheme = domain -> giveTimeIntegrationScheme() ; if (scheme -> isStatic()) return this -> ComputeStaticLhsAt (stepN) ; else if (scheme -> isNewmark()) return this -> ComputeNewmarkLhsAt(stepN) ; else { printf ("Error : unknown time integration scheme : %c\n",scheme) ; exit(0) ; return NULL ; //SC } } FloatArray* Element :: ComputeLoadVectorAt (TimeStep* stepN) // Computes the load vector of the receiver, at stepN. { FloatArray* loadVector ; FloatArray* bodyLoadVector = NULL ; FloatArray* bcLoadVector = NULL ; loadVector = new FloatArray(0) ; bodyLoadVector = this -> ComputeBodyLoadVectorAt(stepN) ; if (bodyLoadVector) { loadVector -> add(bodyLoadVector) ; delete bodyLoadVector ; } // BCLoad vector only at the first iteration if (this->domain->giveNLSolver()->giveCurrentIteration() == 1) { bcLoadVector = this -> ComputeBcLoadVectorAt(stepN) ; if (bcLoadVector) { loadVector -> add(bcLoadVector) ; delete bcLoadVector ; } } if (loadVector -> isNotEmpty()) return loadVector ; else { delete loadVector ; return NULL ; } } FloatMatrix* Element :: computeMassMatrix () // Returns the lumped mass matrix of the receiver. { FloatMatrix* consistentMatrix ; consistentMatrix = this -> ComputeConsistentMassMatrix() ; massMatrix = consistentMatrix -> Lumped() ; delete consistentMatrix ; return massMatrix ; } FloatMatrix* Element :: ComputeNewmarkLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system, using Newmark's formula. { FloatMatrix *m,*lhs ; double beta,dt ; if (stepN->giveNumber() == 0) { lhs = this -> GiveStiffnessMatrix() ; } else { beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ; if (beta == 0.0) { printf ("Error: beta = 0.0 in Newmark \n") ; exit(0) ; } else { dt = stepN -> giveTimeIncrement() ; m = this -> giveMassMatrix() -> Times(1.0 / (beta*dt*dt)); lhs = this -> GiveStiffnessMatrix(); lhs->plus(m); delete m; } } return lhs ; } FloatArray* Element :: ComputeNewmarkRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system, using Newmark's formula. { FloatMatrix *K; DiagonalMatrix *M; FloatArray *fExt,*dPred,*rhs,*a,*d,*dElem,*dPrev,*temp; double beta,dt ; fExt = this -> ComputeLoadVectorAt(stepN) ; if (stepN->giveNumber() == 0) { // computes also the true stress state at the intial step, through the internal // forces computation. K = this -> GiveStiffnessMatrix () ; d = this -> ComputeVectorOf ('d',stepN) ; dElem = dxacc->Extract(this->giveLocationArray()); rhs = K -> Times(d) -> add(fExt) -> add (this->ComputeInternalForces(dElem)->negated()); delete d; delete dElem; delete K; } else { dPred = this -> ComputeVectorOf ('D',stepN) ; dPrev = this -> ComputeVectorOf ('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; double aNorm = dxacc->giveNorm(); if (aNorm == 0.) { //means iteration zero (dxacc = 0) dElem = dPred->Minus(dPrev); rhs = (this->ComputeInternalForces(dElem)->negated()) -> add(fExt); delete dElem; } else { M = (DiagonalMatrix*) this -> giveMassMatrix () ; dt = stepN -> giveTimeIncrement() ; beta = domain -> giveTimeIntegrationScheme() -> giveBeta() ; dElem = dxacc->Extract(this->giveLocationArray()); a = dElem->Times(1.0 / (beta*dt*dt)); temp = dPred->Minus(dPrev); temp->add(dElem); rhs = (M->Times(a->negated())) -> add(this->ComputeInternalForces(temp)->negated()) -> add(fExt); delete a ; delete dElem; delete temp; } delete dPred; delete dPrev; } delete fExt ; return rhs ; } int Element :: computeNumberOfDofs () // Returns the total number of dofs of the receiver's nodes. { int n = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) n += this -> giveNode(i+1) -> giveNumberOfDofs() ; return n ; } size_t Element :: computeNumberOfDisplacementDofs () // ************************************************** // Returns the total number of "true" dofs of the receiver's nodes. // just read from the input file, the dofs of each node { size_t n = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { n += this -> giveNode(i+1) -> readInteger("nDofs") ; } return n ; } FloatArray* Element :: ComputeResultingBodyForceAt (TimeStep* stepN) // Computes at stepN the resulting force due to all body loads that act // on the receiver. This force is used by the element for computing its // body load vector. { int n ; BodyLoad* load ; FloatArray *force,*resultant ; resultant = new FloatArray(0) ; int nLoads = this -> giveBodyLoadArray() -> giveSize() ; for (size_t i = 1 ; i <= nLoads ; i++) { n = bodyLoadArray -> at(i) ; load = (BodyLoad*) domain->giveLoad(n) ; force = load -> ComputeForceOn(this,stepN) ; resultant -> add(force) ; delete force ; } if (resultant->giveSize() == 0) { delete resultant ; return NULL ; } else return resultant ; } FloatArray* Element :: computeRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system. { TimeIntegrationScheme* scheme = domain -> giveTimeIntegrationScheme() ; if (scheme -> isStatic()) return this -> ComputeStaticRhsAt (stepN,dxacc) ; else if (scheme -> isNewmark()) return this -> ComputeNewmarkRhsAt(stepN,dxacc) ; else { printf ("Error : unknown time integration scheme : %c\n",scheme) ; assert(false) ; return NULL ; //SC } } FloatMatrix* Element :: ComputeStaticLhsAt (TimeStep* stepN) // Computes the contribution of the receiver to the left-hand side of the // linear system, in a static analysis. // Modified by NVP 21-10-2005 for XFEM update // Only recompute the stiffness matrices for updated elements!!! { //if (stepN->giveNumber() == 1) return this -> ComputeTangentStiffnessMatrix() ; //else //{ // if(isUpdated) /// return this -> ComputeTangentStiffnessMatrix() ; // return stiffnessMatrix->GiveCopy() ; //} } FloatArray* Element :: ComputeStaticRhsAt (TimeStep* stepN, FloatArray* dxacc) // Computes the contribution of the receiver to the right-hand side of the // linear system, in a static analysis. // Modified by NVP 2005-09-05 for XFEM ( crack growth simulation part). { FloatArray *answer,*fInternal,*fExternal,*dElem,*dElemTot; dElem = dxacc->Extract(this->giveLocationArray()); //add delta prescribed displacement vector - SC 29.04.99 if(this->domain->giveNLSolver()->giveCurrentIteration() != 1)// from second iteration on { FloatArray *currentDPr,*previousDPr; currentDPr = this -> ComputeVectorOfPrescribed('d',stepN) ; if( (stepN->giveNumber() > 1) && (this->domain->isXFEMorFEM() == false) ) { previousDPr = this -> ComputeVectorOfPrescribed('d',domain -> giveTimeIntegrationScheme() -> givePreviousStep()) ; dElemTot = (dElem->Plus(currentDPr))->Minus(previousDPr); delete previousDPr; } else { dElemTot = dElem->Plus(currentDPr); } delete currentDPr; } else // first iteration { dElemTot = dElem->Times(1.); } fInternal = this->ComputeInternalForces(dElemTot); fExternal = this->ComputeLoadVectorAt(stepN); answer = fExternal->Minus(fInternal); delete dElem; delete dElemTot; delete fExternal; delete fInternal; return answer; } FloatMatrix* Element :: computeStiffnessMatrix () // Computes numerically the stiffness matrix of the receiver. // NOT USED ANYMORE !!! { double dV ; FloatMatrix *b,*db,*d ; GaussPoint *gp ; stiffnessMatrix = new FloatMatrix() ; for (size_t i = 0 ; this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; b = this -> ComputeBmatrixAt(gp) ; d = this -> giveConstitutiveMatrix() ; dV = this -> computeVolumeAround(gp) ; db = d -> Times(b) ; stiffnessMatrix -> plusProduct(b,db,dV) ; delete b ; delete db ; } return stiffnessMatrix -> symmetrized() ; } FloatArray* Element :: computeStrainVector (GaussPoint* gp, TimeStep* stepN) // Computes the vector containing the strains at the Gauss point gp of // the receiver, at time step stepN. The nature of these strains depends // on the element's type. { FloatMatrix *b ; FloatArray *u,*Epsilon ; b = this -> ComputeBmatrixAt(gp) ; u = this -> ComputeVectorOf('d',stepN) ; Epsilon = b -> Times(u) ; gp -> letStrainVectorBe(Epsilon) ; // gp stores Epsilon, not a copy delete b ; delete u ; return Epsilon ; } /* FloatArray* Element :: computeStressAt(GaussPoint* gp,TimeStep* stepN) // ******************************************************************** // computes stress at Stress point gp. { FloatMatrix *b = this -> ComputeBmatrixAt(gp) ; FloatArray *u = this -> ComputeVectorOf('d',stepN) ; FloatArray *Epsilon = b -> Times(u) ; FloatMatrix *D = this->giveConstitutiveMatrix(); FloatArray *stress = D->Times(Epsilon); delete b ; delete u ; delete Epsilon ; return stress ; }*/ void Element :: computeStrain (TimeStep* stepN) // compute strain vector at stepN { GaussPoint* gp ; for (size_t i = 1 ; i <= this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i-1] ; this -> computeStrainVector(gp,stepN) ; } } FloatArray* Element :: computeStrainIncrement (GaussPoint* gp, FloatArray* dElem) // Returns the vector containing the strains incr. at point 'gp', with the nodal // displacements incr. of the receiver given by dElem. { FloatArray* depsilon; FloatMatrix* b; b = this -> ComputeBmatrixAt(gp); depsilon = b -> Times(dElem); delete b; return depsilon; } FloatArray* Element :: ComputeVectorOf (char u, TimeStep* stepN) // ************************************************************* // Forms the vector containing the values of the unknown 'u' (e.g., the // displacement) of the dofs of the receiver's nodes. // Modified by NVP to take into account the enriched DOFs for XFEM. 2005/07/15 // u = [u1 v1 ...un vn | a1 b1 ..an bn ] { Node *nodeI ; int nDofs ; FloatArray *answer = new FloatArray(this->computeNumberOfDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfTrueDofs () ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ; } if(this->isEnriched() == false) // non-enriched element return answer ; // enriched element size_t numOfTrueDofs ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; numOfTrueDofs = nodeI->giveNumberOfTrueDofs() ; nDofs = nodeI->giveNumberOfDofs() - numOfTrueDofs ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j+numOfTrueDofs)->giveUnknown(u,stepN) ; } return answer ; } FloatArray* Element :: ComputeVectorOfDisplacement (char u, TimeStep* stepN) // ************************************************************************* // computes the "true" displacement vector of the receiver // XFEM implementation. { Node *nodeI ; size_t nDofs ; FloatArray *answer = new FloatArray(this->computeNumberOfDisplacementDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfTrueDofs() ; for (size_t j = 1 ; j <= nDofs ; j++) answer->at(++k) = nodeI->giveDof(j)->giveUnknown(u,stepN) ; } return answer ; } FloatArray* Element :: ComputeVectorOfPrescribed (char u, TimeStep* stepN) // Forms the vector containing the prescribed values of the unknown 'u' // (e.g., the prescribed displacement) of the dofs of the receiver's // nodes. Puts 0 at each free dof. { Node *nodeI ; Dof *dofJ ; FloatArray *answer ; int nDofs ; answer = new FloatArray(this->computeNumberOfDofs()) ; int k = 0 ; for (size_t i = 0 ; i < numberOfNodes ; i++) { nodeI = this->giveNode(i+1) ; nDofs = nodeI->giveNumberOfDofs() ; for (size_t j = 1 ; j <= nDofs ; j++) { dofJ = nodeI->giveDof(j) ; if (dofJ -> hasBc()) answer->at(++k) = dofJ->giveUnknown(u,stepN) ; else answer->at(++k) = 0. ; } } return answer ; } IntArray* Element :: giveBodyLoadArray () // Returns the array which contains the number of every body load that act // on the receiver. { int numberOfLoads ; if (! bodyLoadArray) { numberOfLoads = this -> readIfHas("bodyLoads") ; bodyLoadArray = new IntArray(numberOfLoads) ; for (size_t i = 1 ; i <= numberOfLoads ; i++) bodyLoadArray->at(i) = this->readInteger("bodyLoads",i+1) ; } return bodyLoadArray ; } FloatMatrix* Element :: giveConstitutiveMatrix () // Returns the elasticity matrix {E} of the receiver. { if (! constitutiveMatrix) this -> computeConstitutiveMatrix() ; return constitutiveMatrix ; } IntArray* Element :: giveLocationArray () // Returns the location array of the receiver. // Modified by NVP to take into account the presence of enriched Dofs { if (! locationArray) { this->computeLocationArray(); } return locationArray ; } IntArray* Element :: computeLocationArray () // ****************************************** // Returns the location array of the receiver. // Modified by NVP to take into account the presence of enriched Dofs { IntArray* nodalStandardArray ; // standard scatter vector of node IntArray* nodalEnrichedArray ; // enriched scatter vector of node locationArray = new IntArray(0) ; // total scatter vector of element for(size_t i = 0 ; i < numberOfNodes ; i++) { nodalStandardArray = this->giveNode(i+1)->giveStandardLocationArray() ; locationArray = locationArray -> followedBy(nodalStandardArray) ; } // non-enriched elements if(this->isEnriched() == false) { /* // DEBUG ... std::cout << "Dealing with element " << this->giveNumber() << std::endl ; for(size_t i = 0 ; i < locationArray->giveSize() ; i++) std::cout << (*locationArray)[i] << " " ; std::cout << std::endl ; */ return locationArray ; } // enriched elements for (size_t i = 0 ; i < numberOfNodes ; i++) { nodalEnrichedArray = this -> giveNode(i+1) -> giveEnrichedLocationArray() ; if(nodalEnrichedArray) // enriched node locationArray = locationArray -> followedBy(nodalEnrichedArray) ; } /*// ----------------- DEBUG ONLY 2005-09-29 ------------------------- if(this->isEnriched()) { std::cout << " Location array of element " << this->giveNumber() << " is :" << endl ; for(size_t i = 0 ; i < locationArray->giveSize() ; i++) std::cout << (*locationArray)[i] << " " ; std::cout << std::endl ; } // --------------------------------------------------------------------*/ return locationArray ; } GaussPoint** Element :: giveGaussPointArray() // ******************************************* // 2005-09-03 : modify for crack growth problem // Some elements need changed Gauss Quadrature. { if (gaussPointArray == NULL) this->computeGaussPoints(); else if(isUpdated) this->computeGaussPoints(); return gaussPointArray; } FloatMatrix* Element :: giveMassMatrix () // Returns the mass matrix of the receiver. { if (! massMatrix) this -> computeMassMatrix() ; return massMatrix ; } Material* Element :: giveMaterial () // ********************************** // Returns the material of the receiver. { if (! material) { material = this -> readInteger("mat") ; //std::cout <<this->giveNumber() << " CUC CUT !!! " ; } return domain -> giveMaterial(material) ; } Node* Element :: giveNode (int i) // Returns the i-th node of the receiver. { int n ; if (! nodeArray) nodeArray = new IntArray(numberOfNodes) ; n = nodeArray->at(i) ; if (! n) { n = this -> readInteger("nodes",i) ; nodeArray->at(i) = n ;} return domain -> giveNode(n) ; } IntArray* Element ::giveNodeArray() { if (! nodeArray) { nodeArray = new IntArray(numberOfNodes) ; for (size_t i = 0 ; i < numberOfNodes ; i++) (*nodeArray)[i] = this->readInteger("nodes",i+1) ; } return nodeArray; } size_t Element :: giveNumberOfGaussPoints() // **************************************** { if(numberOfGaussPoints == 0) this->computeGaussPoints(); return numberOfGaussPoints ; } size_t Element :: giveNumOfGPtsForJ_Integral() // ******************************************* { if(numOfGPsForJ_Integral == 0) this->setGaussQuadForJ_Integral(); return numOfGPsForJ_Integral ; } FloatMatrix* Element :: GiveStiffnessMatrix () // ******************************************** // Returns the stiffness matrix of the receiver. // Modification made by NVP for multistep problems (XFEM). // 2005-09-03 { if (! stiffnessMatrix) return this -> ComputeTangentStiffnessMatrix() ; //else if(isUpdated) // return this -> ComputeTangentStiffnessMatrix() ; return stiffnessMatrix->GiveCopy() ; } void Element :: instanciateYourself () // Gets from input file all data of the receiver. { int i ; # ifdef VERBOSE printf ("instanciating element %d\n",number) ; # endif material = this -> readInteger("mat") ; nodeArray = new IntArray(numberOfNodes) ; for (i=1 ; i<=numberOfNodes ; i++) nodeArray->at(i) = this->readInteger("nodes",i) ; this -> giveBodyLoadArray() ; } void Element :: printOutputAt (TimeStep* stepN, FILE* strFile, FILE* s01File) // Performs end-of-step operations. { GaussPoint* gp ; # ifdef VERBOSE printf ("element %d printing output\n",number) ; # endif fprintf (strFile,"element %d :\n",number) ; for (size_t i = 0 ; i < this->giveNumberOfGaussPoints() ; i++) { gp = gaussPointArray[i] ; this -> computeStrainVector(gp,stepN) ; //no computation of the stress vector here, it //has already been done during the calculation //of Finternal!!! gp -> computeStressLevel() ; gp -> printOutput(strFile) ; gp -> printBinaryResults(s01File) ; } } Element* Element :: typed () // Returns a new element, which has the same number than the receiver, // but is typed (PlaneProblem, or Truss2D,..). { Element* newElement ; char type[32] ; this -> readString("class",type) ; newElement = this -> ofType(type) ; return newElement ; } void Element :: updateYourself() // ****************************** // Updates the receiver at end of step. // Modified by NVP for XFEM implementation. 2005-09-05 { # ifdef VERBOSE printf ("updating element %d\n",number) ; # endif if(this->domain->isXFEMorFEM() == false) { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) gaussPointArray[i] -> updateYourself() ; } else { for (size_t i = 0 ; i < numberOfGaussPoints ; i++) gaussPointArray[i] -> updateYourselfForXFEM() ; } delete locationArray ; locationArray = NULL ; } FloatMatrix* Element ::ComputeBmatrixAt(GaussPoint *aGausspoint) // ************************************************************** // Computes the general B matrix of the receiver, B = [Bu Ba] // Including non enriched part and enriched parts if element is enriched // B = [Bu Ba] with // Bu = [N1,x 0 N2,x 0 N3,x 0 // 0 N1,y 0 N2,y 0 N3,y // N1,y N1,x N2,y N2,x N3,y N3,x] // // Ba = [(Nbar1(phi-phiAtNode1)),x 0 (Nbar2(phi-phiAtNode2)),x 0 (Nbar3(phi-phiAtNode3)),x 0 // 0(Nbar1(phi-phiAtNode1)),y 0 (Nbar2(phi-phiAtNode2)),y 0 (Nbar3(phi-phiAtNode3)),y // (Nbar1(phi-phiAtNode1)),y (Nbar1(phi-phiAtNode1)),x ...] { // computes the standard part of B matrix : Bu FloatMatrix *Bu = this->ComputeBuMatrixAt(aGausspoint); // non enriched elements if (this->isEnriched() == false) return Bu; // enriched elements,then computes the enriched part Ba FloatMatrix *Ba = new FloatMatrix(); vector<EnrichmentFunction*> *enrFnVector; // vector of enrichment functions FloatArray *gradPhiGP ; // grad of enr. func. at Gauss points FloatMatrix *temp ; double N,dNdx,dNdy,phiGP,phiNode,dPhidXGP,dPhidYGP ; Mu::Point *Coord = aGausspoint -> giveCoordinates() ; // local coord. of Gauss point // Get the shape functions multiplied with the enr. functions... FloatArray *Nbar = this->giveXFEInterpolation()->evalN(Coord); FloatMatrix *gradNbar = this->giveXFEInterpolation()->evaldNdx(domain,this->giveNodeArray(),Coord); for(size_t i = 0 ; i < numberOfNodes ; i++) { Node* nodeI = this->giveNode(i+1) ; if (nodeI->getIsEnriched()) // this node is enriched, then continue ... { N = (*Nbar)[i]; // shape function Ni dNdx = gradNbar->at(i+1,1) ; // derivative of Ni w.r.t x coord. dNdy = gradNbar->at(i+1,2) ; // derivative of Ni w.r.t y coord. // loop on enrichment items of nodeI list<EnrichmentItem*> *enrItemList = nodeI->giveEnrItemListOfNode(); for (list<EnrichmentItem*>::iterator iter = enrItemList->begin(); iter != enrItemList->end(); ++iter) { // get the enrichment funcs of current enr. item enrFnVector = (*iter)->giveEnrFuncVector(); //loop on vector of enrichment functions ... for(size_t k = 0 ; k < enrFnVector->size() ; k++ ) { EnrichmentFunction* enrFn = (*enrFnVector)[k]; // let Enr. function,enrFn, know for which enr. item it is modeling enrFn->findActiveEnrichmentItem(*iter); // value of enrichment function at gauss point phiGP = enrFn->EvaluateYourSelfAt(aGausspoint); // value of enrichment function at node phiNode = enrFn->EvaluateYourSelfAt(this,nodeI); // grad of enrichment function at Gauss point gradPhiGP = enrFn->EvaluateYourGradAt(aGausspoint); dPhidXGP = (*gradPhiGP)[0] ; // derivative of Phi w.r.t x coord. dPhidYGP = (*gradPhiGP)[1] ; // derivative of Phi w.r.t y coord. double a = dNdx * (phiGP - phiNode) + N * dPhidXGP ; double b = dNdy * (phiGP - phiNode) + N * dPhidYGP ; temp = new FloatMatrix(4,2); temp->at(1,1) = a ; temp->at(1,2) = 0.0 ; temp->at(2,1) = 0.0 ; temp->at(2,2) = b ; temp->at(3,1) = b ; temp->at(3,2) = a ; Ba = Ba->FollowedBy(temp); delete temp ; // Purify, 11-10-05 delete gradPhiGP ; // Purify, 11-10-05 } // end of loop on enr. functions } // end of loop on enr. items } } // end of loop on element nodes FloatMatrix *answer = Bu->FollowedBy(Ba); delete Ba ; // Purify, 11-10-05 delete Nbar ; delete gradNbar ; // Purify, 11-10-05 return answer; } bool Element:: isEnriched() // ************************ // Returns true if element is enriched (at least one node is enriched) // and false otherwise { size_t count = 0 ; for(size_t i = 0 ; i < numberOfNodes ; i++) { if(this->giveNode(i+1)->getIsEnriched()) { count += 1 ; i = numberOfNodes ; } } return (count != 0)? true:false ; } Element* Element :: ofType (char* aClass) // *************************************** // Returns a new element, which has the same number than the receiver, // but belongs to aClass (Tri3_U, Tetra4, ...). { Element* newElement ; if (! strcmp(aClass,"Q4U")) newElement = new Quad4_U(number,domain); else if (! strcmp(aClass,"T3U")) newElement = new Tri3_U(number,domain) ; else if (! strcmp(aClass,"T6U")) newElement = new Tri6_U(number,domain) ; else if (! strcmp(aClass,"PQ4")) newElement = new PlateIsoQ4(number,domain) ; else if (! strcmp(aClass,"MITC4")) newElement = new MITC4(number,domain) ; else if (! strcmp(aClass,"H4U")) newElement = new Tetra4(number,domain) ; else { printf ("%s : unknown element type \n",aClass) ; assert(false) ; } return newElement ; } void Element::treatGeoMeshInteraction() // ************************************ // Check if element interacts with enrichment item or not. If so, insert this element // into the list of each enrichment item // Modified at 2005-09-07 to make it more efficient than before. // 28-12-2005: MATERIAL INTERFACE IMPLEMENTATION, ASSUMING 2 MATERIALS { EnrichmentItem *enrItem; for(size_t i = 0 ; i < domain->giveNumberOfEnrichmentItems() ; i++) { enrItem = domain->giveEnrichmentItem(i+1); enrItem->treatMeshGeoInteraction(this); } } void Element :: isEnrichedWith(EnrichmentItem* enrItem) // ***************************************************** // If element is enriched with enrichment item enrItem, then insert // enrItem into the list of enrichment items { if(enrichmentItemListOfElem == NULL) enrichmentItemListOfElem = new std::list<EnrichmentItem*>; if( find(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),enrItem) == enrichmentItemListOfElem->end()) enrichmentItemListOfElem->push_back(enrItem); } std::list<Element*>* Element :: ComputeNeighboringElements() // ********************************************************** // Loop on Element's nodes and get the nodal support of these nodes // and insert into list<Element*> neighbors // Since there are redundancies, first sort this list and then list.unique() // Criterion for sort is defined by operator < ( compare the element.number) { map<Node*,vector<Element*> > nodeElemMap = this->domain->giveNodalSupports(); neighbors = new std::list<Element*> ; for (size_t i = 0 ; i < numberOfNodes ; i++) { Node *aNode = this->giveNode(i+1); neighbors->insert(neighbors->end(),nodeElemMap[aNode].begin(),nodeElemMap[aNode].end()) ; } // removing the redundancies in neighbors ... neighbors->sort(); neighbors->unique(); neighbors->remove(this); // not contain the receiver !!! return neighbors ; } std::list<Element*>* Element :: giveNeighboringElements() // ******************************************************* // returns the neighboring elements of the receiver, if it does not exist yet, // compute it. { if (neighbors == NULL) neighbors = this->ComputeNeighboringElements(); return neighbors ; } void Element :: printMyNeighbors() // ******************************* // Print neighbors of the receiver. // Useful for debugging { neighbors = this->giveNeighboringElements(); std::cout << " Neighbors of element " << number << " : "; for (list<Element*>::iterator it = neighbors->begin(); it != neighbors->end(); ++it) std::cout << (*it)->giveNumber() << " " ; std::cout << std::endl; } Mu::Point* Element :: giveMyCenter() // ********************************* // compute the gravity center of the receiver { double sumX = 0.0 ; double sumY = 0.0 ; for(size_t i = 0 ; i < numberOfNodes ; i++) { Node *nodeI = this -> giveNode(i+1); double xI = nodeI->giveCoordinate(1); double yI = nodeI->giveCoordinate(2); sumX += xI ; sumY += yI ; } double xc = sumX/numberOfNodes ; double yc = sumY/numberOfNodes ; return new Mu::Point(xc,yc); } bool Element :: in(Mu::Circle *c) // ****************************** // if at least one node of the receiver belong to the circle c, then // this element is considered locate inside c. { size_t count = 0 ; Mu::Point *p; Node *aNode; for(size_t i = 0 ; i < numberOfNodes ; i++) { aNode = this->giveNode(i+1) ; p = aNode->makePoint(); if(c->in(p)) { count += 1 ; delete p; i = numberOfNodes ; } } return (count != 0)? true:false ; } std::list<Element*> Element :: conflicts(Mu::Circle *c) // **************************************************** // With the help of Cyrille Dunant. { checked = true ; std::list<Element*> ret,temp ; ret.push_back(this); std::list<Element*>* myNeighbors = this->giveNeighboringElements(); for (std::list<Element*>::iterator it = myNeighbors->begin(); it != myNeighbors->end(); it++) { if( ((*it)->checked == false) && ((*it)->in(c))) { temp = (*it)->conflicts(c); ret.insert(ret.end(),temp.begin(),temp.end()); } } return ret ; } bool Element :: intersects(Mu::Circle *c) // ************************************** // Check the intersection between element and circle c // used for determining the annular domain for J integral computation. // 2005-08-10. { std::vector<double> distanceVect ; double radius = c->getRadius() ; double centerX = c->getCenter()->x ; double centerY = c->getCenter()->y ; for(size_t i = 0 ; i < numberOfNodes ; i++) { double x = this->giveNode(i+1)->giveCoordinate(1); double y = this->giveNode(i+1)->giveCoordinate(2); double r = sqrt((x-centerX)*(x-centerX)+(y-centerY)*(y-centerY)); distanceVect.push_back(r-radius); } double max = (*std::max_element(distanceVect.begin(),distanceVect.end())); double min = (*std::min_element(distanceVect.begin(),distanceVect.end())); return ( max*min <= 0 ? true : false ) ; } bool Element::intersects(Mu::Segment *seg) // *************************************** { std::vector<Mu::Point> pts ; for(size_t i = 0 ; i < numberOfNodes ; i++) { Mu::Point *p = this->giveNode(i+1)->makePoint() ; pts.push_back(*p); delete p ; } bool ret = false ; for(size_t i = 0 ; i < pts.size() ; i++) { Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ; ret = ret || seg->intersects(&s) ; } return ret ; } bool Element :: IsOnEdge(Mu::Point* testPoint) // ******************************************* // This method allows the tip touch element edge or element node // 2005-09-06 { size_t i; std::vector<Mu::Point> pts ; for(i = 0 ; i < numberOfNodes ; i++) { Mu::Point *p = this->giveNode(i+1)->makePoint() ; pts.push_back(*p); delete p ; } bool found = false ; i = 0 ; while( (i < pts.size()) && (!found) ) { Mu::Segment s(pts[i],pts[(i+1)%pts.size()]) ; if(s.on(testPoint)) { std:: cout << " Ah, I found you ! " << std::endl ; found = true ; } i++ ; } return found ; } bool Element :: isWithinMe(Mu::Point *p) // ************************************* // check if p is within the receiver using orientation test. // Used in method PartitionMyself() to detect kink points // 2005-09-06 { double const EPSILON = 0.00000001; double x0 = p->x ; double y0 = p->y ; double delta,x1,y1,x2,y2 ; size_t count = 0; for (size_t i = 1 ; i <= numberOfNodes ; i++) { // coordinates of first node x1 = this->giveNode(i)->giveCoordinate(1); y1 = this->giveNode(i)->giveCoordinate(2); // coordinates of second node if(i != numberOfNodes) { x2 = this->giveNode(i+1)->giveCoordinate(1); y2 = this->giveNode(i+1)->giveCoordinate(2); } else { x2 = this->giveNode(1)->giveCoordinate(1); y2 = this->giveNode(1)->giveCoordinate(2); } delta = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0) ; if (delta > EPSILON) count += 1 ; } return (count == numberOfNodes); } bool Element :: isCoincidentToMyNode(Mu::Point *p) // *********************************************** { for(size_t i = 0 ; i < numberOfNodes ; i++) { Mu::Point *pp = this->giveNode(i+1)->makePoint() ; if( pp == p ) return true ; delete pp ; } return false ; } void Element :: clearChecked() // *************************** // set checked false for the next time checking { checked = false ; } void Element :: printMyEnrItems() // ****************************** // debug only { if(enrichmentItemListOfElem != NULL) { std::cout << " Element " << number << " interacted with " ; for (list<EnrichmentItem*>::iterator it = enrichmentItemListOfElem->begin(); it != enrichmentItemListOfElem->end(); ++it) { (*it)->printYourSelf(); } std::cout << std::endl ; } } /*! RB-SB-2004-10-29 takes a string and appends it with the values of stress for the receiver. Goes to the next line to allow further information to be stored in the string. */ void Element :: exportStressResultsToMatlab(string& theStringStress) // ***************************************************************** { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0; double val5 = 0.0; double vonMises ; FloatArray* stressveci; for(size_t i = 1 ; i <= this->giveNumberOfGaussPoints(); i++) { stressveci = this->giveGaussPointNumber(i)->giveStressVector(); vonMises = this->giveGaussPointNumber(i)->computeVonMisesStress();//NVP 2005 assert(stressveci->giveSize() == 4); val1 = stressveci->at(1); val2 = stressveci->at(2); val3 = stressveci->at(3); val4 = stressveci->at(4); val5 = vonMises ; //NVP 2005 char val1c[50]; char val2c[50]; char val3c[50]; char val4c[50]; char val5c[50]; //NVP 2005 _gcvt( val1, 17, val1c ); _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); _gcvt( val5, 17, val5c ); //NVP 2005 string space(" "); string newline("\n"); string valString; valString += val1c; valString += space; valString += val2c; valString += space; valString += val3c; valString += space; valString += val4c; valString += space; valString += val5c; valString += newline; theStringStress += valString; } } /*! RB-SB-2004-10-29 takes a string and appends it with the values of strain for all of the receiver's Gauss points. Goes to the next line to allow further information to be stored in the string. Results are written as for GAUSS POINT 1 : on row 1 : sigmaxx sigmayy sigmaxy sigmazz ... for GAUSS POINT N : on row N : sigmaxx sigmayy sigmaxy sigmazz N is the number of Gauss points of the receiver. */ void Element :: exportStrainResultsToMatlab(string& theStringStrain) // ***************************************************************** { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0;//values FloatArray* strainveci;//strain vector int ngp = this->giveNumberOfGaussPoints();//number of Gauss points GaussPoint* gp;//Gauss point TimeStep* stepN = this->domain->giveTimeIntegrationScheme()->giveCurrentStep();//current step for (size_t i = 1 ; i <= ngp ; i++) { gp = this->giveGaussPointNumber(i); //get Gauss point number i this->computeStrainVector(gp,stepN); //compute the strain vector to make sure its value exists strainveci = this->giveGaussPointNumber(i)->giveStrainVector();//get the strain vector assert(strainveci->giveSize() == 4); //make sure it's ok val1 = strainveci->at(1); //get the values of the strains val2 = strainveci->at(2); val3 = strainveci->at(3); val4 = strainveci->at(4); char val1c[50]; //for transformation into chars and strings char val2c[50]; char val3c[50]; char val4c[50]; _gcvt( val1, 17, val1c );//transform the values val1... into chars val1c taking 14 digits _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); string space(" ");//define some useful strings for output string newline("\n"); string valString; valString += val1c;//concatenate the strings together valString +=space; valString += val2c; valString +=space; valString += val3c; valString +=space; valString += val4c; valString +=newline; //final string composed of the four values of the strains at the Gauss point theStringStrain+=valString;//the final, modified, string used for output } } /*! RB-SB-2004-10-29 Returns the global coordinates of the Gauss points of the receiver. */ void Element :: exportGaussPointsToMatlab(string& theString) { GaussPoint* gp; //Gauss point FloatMatrix* N; //array of shape functions FloatArray* XI; //array of nodal coordinates FloatArray* globalCoords; //array of global coords. //double weight = 0. ; // total weight of Gauss points, for debug only. NVP 2005-07-28 char value[30]; string space(" "); string newline("\n"); for (size_t k = 1 ; k <= this->giveNumberOfGaussPoints() ; k++) { gp = this->giveGaussPointNumber(k); //weight += gp->giveWeight(); N = this->ComputeNmatrixAt(gp); XI = this->ComputeGlobalNodalCoordinates(); globalCoords = N->Times(XI); _gcvt(globalCoords->at(1),17,value);//transforms the double param1 in char param3 with 14 digits theString+=value; theString+=space; _gcvt(globalCoords->at(2),17,value); theString+=value; theString+=space; theString+=newline; delete N; delete XI; delete globalCoords; } // _gcvt(weight,3,value); //theString+=value; //theString+=space; //Changed by M. Forton 5/11/11 - Uncomment to fix //theString += newline; } /*! RB-SB-2004-10-29 Returns the array of nodal coordinates for an element. The values are stored as follows: [xNode1 yNode1 xNode2 yNode2 ... xNode_numnode yNode_numnode] */ FloatArray* Element :: ComputeGlobalNodalCoordinates() { size_t n = this->giveNumberOfNodes(); FloatArray* result = new FloatArray(2*n); Node* node; for (int k = 1 ; k <= n ; k++) { node = this->giveNode(k); result->at(2*k-1) = node->giveCoordinate(1); result->at(2*k) = node->giveCoordinate(2); } return result; } GaussPoint* Element :: giveGaussPointNumber(int i) // ************************************************ { if (gaussPointArray) { return gaussPointArray[i-1]; } else { printf("Sorry, cannot give Gauss point number %d of element %d \n",i,number); printf("The Gauss Point Array for element %d was never created \n",number); return NULL; exit(0); } } /* void Element :: exportStressPointsToMatlab(string& theStringStress,TimeStep* stepN) // ******************************************************************************** // NVP - 2005-07-19 { double val1 = 0.0; double val2 = 0.0; double val3 = 0.0; double val4 = 0.0; FloatArray *stressveci; this->computeStressPoints(); for (size_t i = 0 ; i < this->giveNumberOfStressPoints(); i++) { stressveci = this->computeStressAt(gpForStressPlot[i],stepN); double II = stressveci->computeInvariantJ2(); double equiStress = sqrt(3.0 * II) ; // equivalent von Mises stress. val1 = stressveci->at(1); val2 = stressveci->at(2); val3 = stressveci->at(3); val4 = stressveci->at(4); double val5 = equiStress ; char val1c[50]; char val2c[50]; char val3c[50]; char val4c[50]; char val5c[50]; _gcvt( val1, 17, val1c ); _gcvt( val2, 17, val2c ); _gcvt( val3, 17, val3c ); _gcvt( val4, 17, val4c ); _gcvt( val5, 17, val5c ); string space(" "); string valString; valString += val1c; valString += space; valString += val2c; valString += space; valString += val3c; valString += space; valString += val4c; valString += space; valString += val5c; valString += space; theStringStress += valString; } string newline("\n"); theStringStress += newline ; }*/ void Element::reinitializeStiffnessMatrix() { delete stiffnessMatrix; stiffnessMatrix = NULL; } void Element::computeNodalLevelSets(EnrichmentItem* enrItem) { GeometryEntity *geo = enrItem->giveMyGeo(); for(size_t i = 0 ; i < numberOfNodes ; i++) { Node *nodeI = this->giveNode(i+1); Mu::Point *p = nodeI->makePoint(); double ls = geo->computeSignedDistanceOfPoint(p); nodeI->setLevelSets(enrItem,ls); } } void Element::updateMaterialID() { if(material == 0) material = 2; else material += 1 ; } void Element :: resolveConflictsInEnrItems() // **************************************** // check if this list contains both a CrackTip and a CrackInterior // then remove the CrackInterior from the list. // functor IsType<CrackTip,EnrichmentItem>() defined generically in file "functors.h" { list<EnrichmentItem*> ::iterator iter1,iter2; iter1=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<MaterialInterface,EnrichmentItem>()); iter2=find_if(enrichmentItemListOfElem->begin(),enrichmentItemListOfElem->end(),IsType<CrackInterior,EnrichmentItem>()); if (iter1 != enrichmentItemListOfElem->end() && iter2 != enrichmentItemListOfElem->end()) enrichmentItemListOfElem->remove(*iter2); }
28.337997
127
0.612638
orkzking
7507e24f930050d37452586d5f7b9f3c34743c26
3,581
cpp
C++
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
src/TitleScene.cpp
ccabrales/ZoneRush
0ded2f31580b9a369b19d59268000cff939e2bbd
[ "MIT" ]
null
null
null
#include "TitleScene.h" void TitleScene::setup(){ title.load("ZoneRush2.png"); playButton.load("PlaySelected.png"); exitButton.load("Exit.png"); loadingImage.load("Loading.png"); resetPosition(); selectedIndex = 0; loadState = TITLE; imageDx = -20.0; rightEmitter.setPosition(ofVec3f(ofGetWidth()-1,ofGetHeight()/2.0)); rightEmitter.setVelocity(ofVec3f(-310,0.0)); rightEmitter.posSpread = ofVec3f(0,ofGetHeight()); rightEmitter.velSpread = ofVec3f(120,20); rightEmitter.life = 13; rightEmitter.lifeSpread = 0; rightEmitter.numPars = 3; rightEmitter.size = 12; rightEmitter.color = ofColor(100,100,200); rightEmitter.colorSpread = ofColor(70,70,70); logoEmitter.setPosition(ofVec3f(ofGetWidth()-1, titlePos.y + 50)); logoEmitter.posSpread = ofVec3f(0, -60); logoEmitter.setVelocity(ofVec3f(-2810,0.0)); logoEmitter.velSpread = ofVec3f(520,20); logoEmitter.life = 4; logoEmitter.lifeSpread = 3; logoEmitter.numPars = 2; // logoEmitter.size = 12; logoEmitter.color = ofColor(140,140,220); logoEmitter.colorSpread = ofColor(70,70,70); } void TitleScene::resetPosition(){ playPos = ofPoint((ofGetWidth() / 2.0) - (playButton.getWidth() / 2.0), 3 * ofGetHeight() / 5.0); exitPos = ofPoint((ofGetWidth() / 2.0) - (exitButton.getWidth() / 2.0), playPos.y+playButton.getHeight() + 10.0); titlePos = ofPoint((ofGetWidth() / 2.0) - (title.getWidth() / 2.0), ofGetHeight() / 5.0); loadingPos = ofPoint(ofGetWidth(), (ofGetHeight() / 2.0) - loadingImage.getHeight()); } void TitleScene::update(){ selectedIndex = 1 - selectedIndex; //Swap between 0 and 1 for the selected index switch (selectedIndex) { case 0: playButton.load("PlaySelected.png"); exitButton.load("Exit.png"); break; case 1: playButton.load("Play.png"); exitButton.load("ExitSelected.png"); break; default: break; } } void TitleScene::backgroundUpdate(const Track::Data* data, ofxParticleSystem* particleSystem){ if (loadState == TRANSITION) { //update titlePos.x += imageDx; playPos.x += imageDx; exitPos.x += imageDx; loadingPos.x += imageDx; if (loadingPos.x <= ((ofGetWidth() / 2.0) - (loadingImage.getWidth() / 2.0)) ) { loadState = LOAD; //finished transition } } else if (loadState == TOGAME) { loadingPos.x += imageDx; if (loadingPos.x <= (-loadingImage.getWidth())) loadState = END; } rightEmitter.numPars = max((int)(data->intensity*20) + (data->onBeat?12:0), 2); rightEmitter.setVelocity(data->onBeat?ofVec3f(-510,0.0):ofVec3f(-310,0.0)); particleSystem->addParticles(logoEmitter); particleSystem->addParticles(rightEmitter); } void TitleScene::draw(){ ofPushStyle(); if (loadState == TITLE || loadState == TRANSITION) { title.draw(titlePos); playButton.draw(playPos); exitButton.draw(exitPos); } if (loadState != TITLE || loadState != END) loadingImage.draw(loadingPos); ofPopStyle(); } void TitleScene::windowResized(int w, int h) { resetPosition(); } bool TitleScene::isPlaySelected() { return selectedIndex == 0; } //Toggle the variable flag void TitleScene::setLoading(LoadState state) { loadState = state; if (loadState == TITLE) resetPosition(); } TitleScene::LoadState TitleScene::getCurrentState() { return loadState; }
29.352459
117
0.63055
ccabrales
7508f423ff4f2dd47d6703130584e1bc6a1e2d1d
3,347
cpp
C++
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
null
null
null
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
2
2019-03-01T09:25:32.000Z
2019-03-01T09:26:08.000Z
project_booking_qt_gui/ProjectBookingQtUI/ProjectBookingQtUI/reports.cpp
VBota1/project_booking
13337130e1294df43c243cf1df53edfa736c42b7
[ "MIT" ]
null
null
null
#include "reports.h" Reports::Reports(QTreeWidget *month,QListWidget *standard,QListWidget *project,QLabel *current,StatusDisplay *statusWidget) { monthReport=month; standardReport=standard; projectReport=project; currentProject=current; statusDisplay = statusWidget; } void Reports::updateMonthReport(BackendHandler backend, int month){ monthReport->clear(); Result< QList<Data> > report = backend.reportForMonth(month); if (report.hasError) { statusDisplay->update(report.err()); return; } Data day; foreach (day,report.ok()) { QTreeWidgetItem *dayItem = new QTreeWidgetItem(monthReport); monthReport->addTopLevelItem(dayItem); dayItem->setText(0,day.date); TaskDay task; foreach (task,day.tasks) { QTreeWidgetItem *taskItem = new QTreeWidgetItem(dayItem); taskItem->setText(0,task.task); QTreeWidgetItem *timeItem = new QTreeWidgetItem(taskItem); timeItem->setText(0,"time_spent: " + task.time_spent); QTreeWidgetItem *labelCollectionItem = new QTreeWidgetItem(taskItem); labelCollectionItem->setText(0,"labels"); QString label; foreach (label, task.labels) { QTreeWidgetItem *labelItem = new QTreeWidgetItem(labelCollectionItem); labelItem->setText(0, label); } } } } void Reports::updateStandardReport(BackendHandler backend) { standardReport->clear(); Result< QList<TaskReport> > report = backend.standardReport(); if (report.hasError) { statusDisplay->update(report.err()); return; } updateCurrentProject("None"); TaskReport task; foreach (task,report.ok()){ QString taskText = "name: " + task.name.leftJustified(30,' ',true) + "\t time: " + task.time_spent + "\t labels:"; QString label; foreach(label,task.labels) taskText.append(" "+label); if(task.clock_in_timestamp!="None") { taskText.append("\t clockedIn: "+task.clock_in_timestamp); updateCurrentProject(task); } standardReport->addItem(taskText); } } void Reports::updateCurrentProject(TaskReport task) { QString taskText = task.name + "\t labels:"; QString label; foreach(label,task.labels) taskText.append(" "+label); updateCurrentProject(taskText); } void Reports::updateCurrentProject(QString task) { currentProject->setText("Active Project: "+task); currentProject->update(); } void Reports::updateProjectReport(BackendHandler backend) { projectReport->clear(); Result< QList<LabelReport> > report = backend.projectLabelReport(); if (report.hasError) { statusDisplay->update(report.err()); return; } LabelReport project; foreach(project,report.ok()) { QString projectText = "project: " + project.label.leftJustified(30,' ',true) + "\t time: " + project.time_spent; projectReport->addItem(projectText); } } void Reports::refresh(){ BackendHandler backend; updateMonthReport(backend, QDate::currentDate().month()); updateStandardReport(backend); updateProjectReport(backend); }
27.211382
125
0.632805
VBota1
75097d8a49eeac251bc1667c6a93628f398378e3
274
hpp
C++
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
176
2018-06-06T12:20:21.000Z
2022-01-27T02:54:34.000Z
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
11
2018-06-09T21:30:02.000Z
2019-09-14T16:03:12.000Z
modules/spdlog/shiva/spdlog/spdlog.hpp
Milerius/rs_engine
d25b54147f2f9a4710e3015c4eed7d076e3de04b
[ "MIT" ]
19
2018-08-15T11:40:02.000Z
2020-08-31T11:00:44.000Z
// // Created by roman Sztergbaum on 19/06/2018. // #pragma once #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_color_sinks.h> namespace shiva { namespace log = spdlog; } namespace shiva::logging { using logger = std::shared_ptr<shiva::log::logger>; }
14.421053
55
0.70073
Milerius
7509db9a401daf1896cb04c933a014f57817ff92
362
hpp
C++
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/interpolation.hpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
#pragma once #include "dansandu/chocolate/common.hpp" namespace dansandu::chocolate::interpolation { Vector3 interpolate(const Vector3& a, const Vector3& b, const float x, const float y, const float epsilon); Vector3 interpolate(const Vector3& a, const Vector3& b, const Vector3& c, const float x, const float y, const float epsilon); }
25.857143
107
0.720994
dansandu
750c844815ad49209ee37371cb7a5b86dea0d376
4,486
hxx
C++
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
include/opengm/learning/gridsearch-learning.hxx
chaubold/opengm
acc42b98b713db33f2b35aad05a7a1cf9752e862
[ "MIT" ]
null
null
null
#pragma once #ifndef OPENGM_GRIDSEARCH_LEARNER_HXX #define OPENGM_GRIDSEARCH_LEARNER_HXX #include <vector> namespace opengm { namespace learning { template<class DATASET> class GridSearchLearner { public: typedef DATASET DatasetType; typedef typename DATASET::GMType GMType; typedef typename DATASET::LossType LossType; typedef typename GMType::ValueType ValueType; typedef typename GMType::IndexType IndexType; typedef typename GMType::LabelType LabelType; class Parameter{ public: std::vector<double> parameterUpperbound_; std::vector<double> parameterLowerbound_; std::vector<size_t> testingPoints_; Parameter(){;} }; GridSearchLearner(DATASET&, const Parameter& ); template<class INF> void learn(const typename INF::Parameter& para); //template<class INF, class VISITOR> //void learn(typename INF::Parameter para, VITITOR vis); const opengm::learning::Weights<double>& getWeights(){return weights_;} Parameter& getLerningParameters(){return para_;} private: DATASET& dataset_; opengm::learning::Weights<double> weights_; Parameter para_; }; template<class DATASET> GridSearchLearner<DATASET>::GridSearchLearner(DATASET& ds, const Parameter& p ) : dataset_(ds), para_(p) { weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights()); if(para_.parameterUpperbound_.size() != ds.getNumberOfWeights()) para_.parameterUpperbound_.resize(ds.getNumberOfWeights(),10.0); if(para_.parameterLowerbound_.size() != ds.getNumberOfWeights()) para_.parameterLowerbound_.resize(ds.getNumberOfWeights(),0.0); if(para_.testingPoints_.size() != ds.getNumberOfWeights()) para_.testingPoints_.resize(ds.getNumberOfWeights(),10); } template<class DATASET> template<class INF> void GridSearchLearner<DATASET>::learn(const typename INF::Parameter& para){ // generate model Parameters opengm::learning::Weights<double> modelPara( dataset_.getNumberOfWeights() ); opengm::learning::Weights<double> bestModelPara( dataset_.getNumberOfWeights() ); double bestLoss = std::numeric_limits<double>::infinity(); std::vector<size_t> itC(dataset_.getNumberOfWeights(),0); bool search=true; while(search){ // Get Parameter for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ modelPara.setWeight(p, para_.parameterLowerbound_[p] + double(itC[p])/double(para_.testingPoints_[p]-1)*(para_.parameterUpperbound_[p]-para_.parameterLowerbound_[p]) ); } // Evaluate Loss opengm::learning::Weights<double>& mp = dataset_.getWeights(); mp = modelPara; const double loss = dataset_. template getTotalLoss<INF>(para); // ************** if(loss<bestLoss){ // *call visitor* for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ std::cout << modelPara[p] <<" "; } std::cout << " ==> "; std::cout << loss << std::endl; bestLoss=loss; bestModelPara=modelPara; if(loss<=0.000000001){ search = false; } } //Increment Parameter for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ if(itC[p]<para_.testingPoints_[p]-1){ ++itC[p]; break; } else{ itC[p]=0; if (p==dataset_.getNumberOfWeights()-1) search = false; } } } std::cout << "Best"<<std::endl; for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ std::cout << bestModelPara[p] <<" "; } std::cout << " ==> "; std::cout << bestLoss << std::endl; weights_ = bestModelPara; // save best weights in dataset for(size_t p=0; p<dataset_.getNumberOfWeights(); ++p){ dataset_.getWeights().setWeight(p, weights_[p]); } }; } } #endif
35.322835
183
0.56041
chaubold
750cfaefd4746b7cea1bfd20de616b38d29defa8
4,698
cpp
C++
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
4
2018-06-05T14:15:52.000Z
2022-02-08T05:14:23.000Z
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
null
null
null
google/code_jam/2020/r3/pen_testing.cpp
Loks-/competitions
3bb231ba9dd62447048832f45b09141454a51926
[ "MIT" ]
1
2018-10-21T11:01:35.000Z
2018-10-21T11:01:35.000Z
#include "common/hash.h" #include "common/stl/base.h" #include "common/stl/hash/vector.h" #include "common/vector/enumerate.h" #include "common/vector/mask.h" #include <unordered_map> namespace { static const unsigned N = 15; class CompactState { public: unsigned l; uint64_t mask; vector<unsigned> vc; CompactState() { l = N; mask = (1ull << N) - 1; vc.resize(l, 0); } bool operator==(const CompactState& r) const { return (mask == r.mask) && (vc == r.vc); } }; } // namespace namespace std { template <> struct hash<CompactState> { size_t operator()(const CompactState& s) const { hash<vector<unsigned>> h; return HashCombine(h(s.vc), s.mask); } }; } // namespace std namespace { class Solver { public: unordered_map<CompactState, pair<double, unsigned>> m; uint64_t Count(const CompactState& s) { uint64_t r = 1; auto v = nvector::MaskToVector(s.mask); assert(v.size() == s.l); unsigned k = s.l; for (unsigned i = 0; i < s.l; ++i) { for (; (k > 0) && (v[k - 1] >= s.vc[i]);) --k; r *= (s.l - i - k); } return r; } double P2(const CompactState& s) { assert(s.l == 2); unsigned ss = 0; for (unsigned i = 0; i < N; ++i) { if (s.mask & (1ull << i)) ss += i; } for (auto c : s.vc) ss -= c; return (ss >= N) ? 1.0 : 0.; } bool GaveUp(const CompactState& s) const { auto v = nvector::MaskToVector(s.mask); assert(v.size() == s.l); unsigned ss = v[s.l - 1] + v[s.l - 2] - s.vc[s.l - 1] - s.vc[s.l - 2]; return ss < N; } double P(const CompactState& s) { assert(s.l >= 2); auto it = m.find(s); if (it != m.end()) return it->second.first; double p = 0; unsigned r = N; if (s.l == 2) { p = P2(s); } else if (!GaveUp(s)) { CompactState st(s); uint64_t sc = Count(st); for (unsigned i = 0; i < s.l; ++i) { if ((i > 0) && (s.vc[i - 1] == s.vc[i])) continue; unsigned k = 0, j = 0; for (; j < s.vc[i]; ++j) { if (s.mask & (1ull << j)) ++k; } for (;; ++j) { if (s.mask & (1ull << j)) break; } if ((i > 0) && (j >= s.vc[i - 1])) continue; unsigned c = s.vc[i]; st.vc[i] = j + 1; uint64_t scn = Count(st); double q1 = double(scn) / double(sc); double pc = ((q1 > 0) ? q1 * P(st) : 0.); st.vc[i] = c; st.mask &= ~(1ull << j); st.l -= 1; st.vc.erase(st.vc.begin() + i); pc += (1 - q1) * P(st); st.vc.insert(st.vc.begin() + i, c); st.l += 1; st.mask |= (1ull << j); if (p < pc) { p = pc; r = i; } } } m[s] = make_pair(p, r); return p; } public: unsigned Request(const CompactState& s) { // if (s.l > (N + 3) / 2) return 0; // We never output first elements if (s.l > 6) return 0; // Trade off between performance and quality P(s); return m[s].second; } size_t MapSize() const { return m.size(); } }; class FullState : public CompactState { public: vector<unsigned> vp; FullState() { vp = nvector::Enumerate<unsigned>(1, N + 1); } }; class SolverProxy { protected: Solver& s; FullState fs; unsigned last_request; public: SolverProxy(Solver& _s) : s(_s), last_request(N) {} double P() { return s.P(fs); } unsigned Request() { last_request = s.Request(fs); return (last_request == N) ? 0 : fs.vp[last_request]; } void Update(unsigned result) { if (last_request != N) { if (result) { fs.vc[last_request] += 1; } else { unsigned k = fs.vc[last_request]; fs.l -= 1; assert(fs.mask & (1ull << k)); fs.mask &= ~(1ull << k); fs.vc.erase(fs.vc.begin() + last_request); fs.vp.erase(fs.vp.begin() + last_request); } } } unsigned Get1() const { return fs.vp[fs.l - 2]; } unsigned Get2() const { return fs.vp[fs.l - 1]; } }; } // namespace int main_pen_testing() { Solver s; unsigned T, t1, t2; cin >> T >> t1 >> t2; // cerr << s.P(CompactState()) * T << " " << s.MapSize() << endl; std::vector<SolverProxy> vs(T, SolverProxy(s)); bool all_zero = false; for (unsigned it = 1; !all_zero; ++it) { all_zero = true; for (SolverProxy& s : vs) { unsigned u = s.Request(); if (u) all_zero = false; cout << u << " "; } cout << endl; if (all_zero) { for (SolverProxy& s : vs) { cout << s.Get1() << " " << s.Get2() << " "; } cout << endl; } else { for (SolverProxy& s : vs) { cin >> t1; s.Update(t1); } } } return 0; }
23.373134
74
0.504683
Loks-
750e33686e6c97f42691a16b2d3c80c696e33a99
2,984
cpp
C++
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
null
null
null
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
null
null
null
C++/hoffman_encoding.cpp
evidawei/HacktoberFest_2021
3c950c6a6451ac732c4090f374c7dc4b6ef36c50
[ "MIT" ]
1
2021-10-11T14:05:10.000Z
2021-10-11T14:05:10.000Z
#include <bits/stdc++.h> using namespace std; #define EMPTY_STRING "" struct Node { char ch; int freq; Node *left, *right; }; Node* getNode(char ch, int freq, Node* left, Node* right) { Node* node = new Node(); node->ch = ch; node->freq = freq; node->left = left; node->right = right; return node; } struct comp { bool operator()(const Node* l, const Node* r) const { return l->freq > r->freq; } }; bool isLeaf(Node* root) { return root->left == nullptr && root->right == nullptr; } void encode(Node* root, string str, unordered_map<char, string> &huffmanCode) { if (root == nullptr) { return; } if (isLeaf(root)) { huffmanCode[root->ch] = (str != EMPTY_STRING) ? str : "1"; } encode(root->left, str + "0", huffmanCode); encode(root->right, str + "1", huffmanCode); } void decode(Node* root, int &index, string str) { if (root == nullptr) { return; } if (isLeaf(root)) { cout << root->ch; return; } index++; if (str[index] == '0') { decode(root->left, index, str); } else { decode(root->right, index, str); } } void buildHuffmanTree(string text) { if (text == EMPTY_STRING) { return; } unordered_map<char, int> freq; for (char ch: text) { freq[ch]++; } priority_queue<Node*, vector<Node*>, comp> pq; for (auto pair: freq) { pq.push(getNode(pair.first, pair.second, nullptr, nullptr)); } while (pq.size() != 1) { Node* left = pq.top(); pq.pop(); Node* right = pq.top(); pq.pop(); int sum = left->freq + right->freq; pq.push(getNode('\0', sum, left, right)); } Node* root = pq.top(); unordered_map<char, string> huffmanCode; encode(root, EMPTY_STRING, huffmanCode); cout << "Huffman Codes are:\n" << endl; for (auto pair: huffmanCode) { cout << pair.first << " " << pair.second << endl; } cout << "\nThe original string is:\n" << text << endl; string str; for (char ch: text) { str += huffmanCode[ch]; } cout << "\nThe encoded string is:\n" << str << endl; cout << "\nThe decoded string is:\n"; if (isLeaf(root)) { // Special case: For input like a, aa, aaa, etc. while (root->freq--) { cout << root->ch; } } else { // Traverse the Huffman Tree again and this time, // decode the encoded string int index = -1; while (index < (int)str.size() - 1) { decode(root, index, str); } } } // Huffman coding algorithm implementation in C++ int main() { string text = "Huffman coding is a data compression algorithm."; buildHuffmanTree(text); return 0; }
22.778626
78
0.510054
evidawei
7511d416a4978fcd2aa044fd577ad9edd11ae6b8
1,495
hpp
C++
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/step/map.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/detail/type_traits.hpp" #include "caf/fwd.hpp" #include <utility> namespace caf::flow::step { template <class F> class map { public: using trait = detail::get_callable_trait_t<F>; static_assert(!std::is_same_v<typename trait::result_type, void>, "map functions may not return void"); static_assert(trait::num_args == 1, "map functions must take exactly one argument"); using input_type = std::decay_t<detail::tl_head_t<typename trait::arg_types>>; using output_type = std::decay_t<typename trait::result_type>; explicit map(F fn) : fn_(std::move(fn)) { // nop } map(map&&) = default; map(const map&) = default; map& operator=(map&&) = default; map& operator=(const map&) = default; template <class Next, class... Steps> bool on_next(const input_type& item, Next& next, Steps&... steps) { return next.on_next(fn_(item), steps...); } template <class Next, class... Steps> void on_complete(Next& next, Steps&... steps) { next.on_complete(steps...); } template <class Next, class... Steps> void on_error(const error& what, Next& next, Steps&... steps) { next.on_error(what, steps...); } private: F fn_; }; } // namespace caf::flow::step
25.775862
80
0.671572
seewpx
75138d319658400837893d58e2aee8f95eb1f383
1,081
hpp
C++
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/algorithm/include/bksge/fnd/algorithm/reverse.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file reverse.hpp * * @brief reverse の定義 * * @author myoukaku */ #ifndef BKSGE_FND_ALGORITHM_REVERSE_HPP #define BKSGE_FND_ALGORITHM_REVERSE_HPP #include <bksge/fnd/algorithm/config.hpp> #if defined(BKSGE_USE_STD_ALGORITHM) #include <algorithm> namespace bksge { using std::reverse; } // namespace bksge #else #include <bksge/fnd/algorithm/iter_swap.hpp> #include <bksge/fnd/config.hpp> namespace bksge { /** * @brief 要素の並びを逆にする。 * * @tparam BidirectionalIterator * * @param first * @param last * * @require *first は Swappable でなければならない * * @effect 0 以上 (last - first) / 2 未満の整数 i について、 * iter_swap(first + i, (last - i) - 1) を行う * * @complexity 正確に (last - first) / 2 回 swap する */ template <typename BidirectionalIterator> inline void reverse( BidirectionalIterator first, BidirectionalIterator last) { for (; first != last && first != --last; ++first) { bksge::iter_swap(first, last); } } } // namespace bksge #endif #endif // BKSGE_FND_ALGORITHM_REVERSE_HPP
16.630769
51
0.650324
myoukaku
7518a26a3f9a48b498a5a0f719682f3753612846
3,880
cc
C++
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
null
null
null
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
1
2021-12-03T14:37:41.000Z
2021-12-03T14:37:41.000Z
src/tot_compare.cc
Mu2e/TrackerMCTune
6472497f9359b33a236d47f39192a7faffc71dae
[ "Apache-2.0" ]
2
2019-10-31T18:17:00.000Z
2021-11-22T21:43:02.000Z
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <stdlib.h> #include <vector> #include <TFile.h> #include <TTree.h> #include <TH1F.h> #include <TH2F.h> #include <TF1.h> #include <TCanvas.h> #include <TLegend.h> #include <TApplication.h> #include <TLatex.h> #include <TLine.h> #include <TPaveText.h> #include <TMath.h> #include <TProfile.h> int main(int argc, char** argv) { std::string filename[2]; filename[0] = ""; filename[1] = ""; std::string help = "./tot_compare -d <data filename> -s <sim filename>"; std::string inputcommand = std::string(argv[0]); for (int i=1;i<argc;i++) inputcommand += " " + std::string(argv[i]); int c; while ((c = getopt (argc, argv, "hd:s:")) != -1){ switch (c){ case 'h': std::cout << help << std::endl; return 0; case 'd': filename[0] = std::string(optarg); break; case 's': filename[1] = std::string(optarg); break; case '?': if (optopt == 'd' || optopt == 's') std::cout << "Option -" << optopt << " requires an argument." << std::endl; else std::cout << "Unknown option `-" << optopt << "'." << std::endl; return 1; } } if (filename[0].size() == 0 && filename[1].size() == 0 && optind == argc-2){ for (int index = optind; index < argc; index++){ filename[index-optind] = std::string(argv[index]); } } if (filename[0].size() == 0 || filename[1].size() == 0){ std::cout << help << std::endl; return 1; } int argc2 = 0;char **argv2;TApplication theApp("tapp", &argc2, argv2); std::vector<double> times[2]; std::vector<double> docas[2]; std::vector<double> tots[2]; TH2F* h[2]; for (int ifile=0;ifile<2;ifile++){ TFile *f = new TFile(filename[ifile].c_str()); TTree *t = (TTree*) f->Get("tot"); double t_time, t_tot, t_doca; t->SetBranchAddress("tot",&t_tot); t->SetBranchAddress("time",&t_time); t->SetBranchAddress("doca",&t_doca); for (int i=0;i<t->GetEntries();i++){ t->GetEntry(i); tots[ifile].push_back(t_tot); times[ifile].push_back(t_time); docas[ifile].push_back(t_doca); } h[ifile] = new TH2F(TString::Format("tot_%d",ifile),"tot",32,0,64,120,-20,100); for (int j=0;j<tots[ifile].size();j++){ if (docas[ifile][j] < 2.5) h[ifile]->Fill(tots[ifile][j],times[ifile][j]); } } TCanvas *cscatter = new TCanvas("cscatter","scatter",600,600); h[0]->SetStats(0); h[0]->SetTitle(""); h[0]->GetXaxis()->SetTitle("Time over threshold (ns)"); h[0]->GetYaxis()->SetTitle("Drift time (ns)"); h[0]->Draw(); h[1]->SetMarkerColor(kRed); h[1]->Draw("same"); TLegend *l = new TLegend(0.55,0.65,0.85,0.85); l->AddEntry(h[0],"8-Straw Prototype Data","P"); l->AddEntry(h[1],"G4 + Straw Simulation","P"); l->SetBorderSize(0); l->Draw(); TCanvas *chist = new TCanvas("chist","chist",600,600); TProfile *hdata = (TProfile*) h[0]->ProfileX("hdata",1,-1,"S"); TProfile *hsim = (TProfile*) h[1]->ProfileX("hsim",1,-1,"S"); hdata->SetLineColor(kBlue); hdata->SetTitle(""); hdata->SetStats(0); hdata->GetXaxis()->SetTitle("Time over threshold (ns)"); hdata->GetYaxis()->SetTitle("Drift time (ns)"); hdata->SetMarkerStyle(22); // hdata->GetXaxis()->SetRangeUser(4,50); hdata->Draw(); hsim->SetLineColor(kRed); hsim->SetFillColor(kRed); hsim->SetMarkerColor(kRed); hsim->SetFillStyle(3001); hsim->Draw("same E2"); TProfile *hsim2 = (TProfile*) hsim->Clone("hsim2"); hsim2->SetLineColor(kRed); hsim2->SetFillStyle(0); hsim2->Draw("hist same"); TLegend *l2 = new TLegend(0.55,0.65,0.85,0.85); l2->AddEntry(hdata,"8-Straw Prototype Data","PL"); l2->AddEntry(hsim,"G4 + Straw Simulation","FL"); l2->SetBorderSize(0); l2->Draw(); theApp.Run(); return 0; }
26.575342
85
0.584794
Mu2e
75190d8b3eaf38c7736806ffc0e6b19f972a5745
12,435
cpp
C++
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
4
2018-08-27T05:31:58.000Z
2018-09-01T00:02:29.000Z
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
null
null
null
viewer/sokol_imgui.cpp
JCash/dungeonmaker
c64a90bdf1cff79d69f32ea6a8f219bb9daba7d9
[ "MIT" ]
null
null
null
#include "imgui.h" #if defined(__APPLE__) #define SOKOL_METAL #elif defined(WIN32) #define SOKOL_D3D11 #elif defined(__EMSCRIPTEN__) #define SOKOL_GLES2 #else #error "No GFX Backend Specified" #endif #define SOKOL_IMPL #include "sokol_app.h" #include "sokol_gfx.h" #include "sokol_time.h" #include <stdio.h> const int MaxVertices = (1<<16); const int MaxIndices = MaxVertices * 3; extern const char* vs_src_imgui; extern const char* fs_src_imgui; static sg_draw_state draw_state = { }; ImDrawVert vertices[MaxVertices]; uint16_t indices[MaxIndices]; typedef struct { ImVec2 disp_size; } vs_params_t; void imgui_sokol_event(const sapp_event* e) { switch (e->type) { case SAPP_EVENTTYPE_KEY_DOWN: ImGui::GetIO().KeysDown[e->key_code] = true; break; case SAPP_EVENTTYPE_KEY_UP: ImGui::GetIO().KeysDown[e->key_code] = false; break; case SAPP_EVENTTYPE_CHAR: ImGui::GetIO().AddInputCharacter(e->char_code); break; case SAPP_EVENTTYPE_MOUSE_DOWN: ImGui::GetIO().MouseDown[e->mouse_button] = true; break; case SAPP_EVENTTYPE_MOUSE_UP: ImGui::GetIO().MouseDown[e->mouse_button] = false; break; case SAPP_EVENTTYPE_MOUSE_SCROLL: ImGui::GetIO().MouseWheel = 0.25f * e->scroll_y; break; case SAPP_EVENTTYPE_MOUSE_MOVE: ImGui::GetIO().MousePos = ImVec2(e->mouse_x, e->mouse_y); break; default: break; } } static void imgui_draw_cb(ImDrawData* draw_data); void imgui_setup() { // setup the imgui environment ImGui::CreateContext(); ImGui::StyleColorsDark(); ImGuiIO& io = ImGui::GetIO(); io.IniFilename = 0; io.RenderDrawListsFn = imgui_draw_cb; io.Fonts->AddFontDefault(); io.KeyMap[ImGuiKey_Tab] = SAPP_KEYCODE_TAB; io.KeyMap[ImGuiKey_LeftArrow] = SAPP_KEYCODE_LEFT; io.KeyMap[ImGuiKey_RightArrow] = SAPP_KEYCODE_RIGHT; io.KeyMap[ImGuiKey_DownArrow] = SAPP_KEYCODE_DOWN; io.KeyMap[ImGuiKey_UpArrow] = SAPP_KEYCODE_UP; io.KeyMap[ImGuiKey_Home] = SAPP_KEYCODE_HOME; io.KeyMap[ImGuiKey_End] = SAPP_KEYCODE_END; io.KeyMap[ImGuiKey_Delete] = SAPP_KEYCODE_DELETE; io.KeyMap[ImGuiKey_Backspace] = SAPP_KEYCODE_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = SAPP_KEYCODE_ENTER; io.KeyMap[ImGuiKey_Escape] = SAPP_KEYCODE_ESCAPE; // io.KeyMap[ImGuiKey_A] = 0x00; // io.KeyMap[ImGuiKey_C] = 0x08; // io.KeyMap[ImGuiKey_V] = 0x09; // io.KeyMap[ImGuiKey_X] = 0x07; // io.KeyMap[ImGuiKey_Y] = 0x10; // io.KeyMap[ImGuiKey_Z] = 0x06; // // OSX => ImGui input forwarding // osx_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); }); // osx_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; }); // osx_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; }); // osx_mouse_wheel([] (float v) { ImGui::GetIO().MouseWheel = 0.25f * v; }); // osx_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; }); // osx_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; }); // osx_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); }); // dynamic vertex- and index-buffers for ImGui-generated geometry sg_buffer_desc vbuf_desc = { .usage = SG_USAGE_STREAM, .size = sizeof(vertices) }; draw_state.vertex_buffers[0] = sg_make_buffer(&vbuf_desc); sg_buffer_desc ibuf_desc = { .type = SG_BUFFERTYPE_INDEXBUFFER, .usage = SG_USAGE_STREAM, .size = sizeof(indices) }; draw_state.index_buffer = sg_make_buffer(&ibuf_desc); // font texture for ImGui's default font unsigned char* font_pixels; int font_width, font_height; io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height); sg_image_desc img_desc = { .width = font_width, .height = font_height, .pixel_format = SG_PIXELFORMAT_RGBA8, .wrap_u = SG_WRAP_CLAMP_TO_EDGE, .wrap_v = SG_WRAP_CLAMP_TO_EDGE, .min_filter = SG_FILTER_LINEAR, .mag_filter = SG_FILTER_LINEAR, .content.subimage[0][0] = { .ptr = font_pixels, .size = font_width * font_height * 4 } }; draw_state.fs_images[0] = sg_make_image(&img_desc); // shader object for imgui renering sg_shader_desc shd_desc = { .vs.uniform_blocks[0].size = sizeof(vs_params_t), .vs.uniform_blocks[0].uniforms[0].name = "disp_size", .vs.uniform_blocks[0].uniforms[0].type = SG_UNIFORMTYPE_FLOAT2, .vs.source = vs_src_imgui, .fs.images[0].type = SG_IMAGETYPE_2D, .fs.images[0].name = "tex", .fs.source = fs_src_imgui, }; sg_shader shd = sg_make_shader(&shd_desc); // pipeline object for imgui rendering sg_pipeline_desc pip_desc = { .layout = { .buffers[0].stride = sizeof(ImDrawVert), .attrs = { [0] = { .offset=IM_OFFSETOF(ImDrawVert, pos), .format=SG_VERTEXFORMAT_FLOAT2 }, [1] = { .offset=IM_OFFSETOF(ImDrawVert, uv), .format=SG_VERTEXFORMAT_FLOAT2 }, [2] = { .offset=IM_OFFSETOF(ImDrawVert, col), .format=SG_VERTEXFORMAT_UBYTE4N } } }, .shader = shd, .index_type = SG_INDEXTYPE_UINT16, .blend = { .enabled = true, .src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA, .dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA, .color_write_mask = SG_COLORMASK_RGB } }; draw_state.pipeline = sg_make_pipeline(&pip_desc); } static void imgui_draw_cb(ImDrawData* draw_data) { if (draw_data->CmdListsCount == 0) { return; } // copy vertices and indices int num_vertices = 0; int num_indices = 0; int num_cmdlists = 0; for (; num_cmdlists < draw_data->CmdListsCount; num_cmdlists++) { const ImDrawList* cl = draw_data->CmdLists[num_cmdlists]; const int cl_num_vertices = cl->VtxBuffer.size(); const int cl_num_indices = cl->IdxBuffer.size(); // overflow check if ((num_vertices + cl_num_vertices) > MaxVertices) { break; } if ((num_indices + cl_num_indices) > MaxIndices) { break; } // copy vertices memcpy(&vertices[num_vertices], &cl->VtxBuffer.front(), cl_num_vertices*sizeof(ImDrawVert)); // copy indices, need to rebase to start of global vertex buffer const ImDrawIdx* src_index_ptr = &cl->IdxBuffer.front(); const uint16_t base_vertex_index = num_vertices; for (int i = 0; i < cl_num_indices; i++) { indices[num_indices++] = src_index_ptr[i] + base_vertex_index; } num_vertices += cl_num_vertices; } // update vertex and index buffers const int vertex_data_size = num_vertices * sizeof(ImDrawVert); const int index_data_size = num_indices * sizeof(uint16_t); sg_update_buffer(draw_state.vertex_buffers[0], vertices, vertex_data_size); sg_update_buffer(draw_state.index_buffer, indices, index_data_size); // render the command list vs_params_t vs_params; vs_params.disp_size = ImGui::GetIO().DisplaySize; sg_apply_draw_state(&draw_state); sg_apply_uniform_block(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params)); int base_element = 0; for (int cl_index = 0; cl_index < num_cmdlists; cl_index++) { const ImDrawList* cmd_list = draw_data->CmdLists[cl_index]; //for (const ImDrawCmd& cmd : cmd_list->CmdBuffer) { for (size_t i = 0; i < cmd_list->CmdBuffer.size(); ++i) { const ImDrawCmd& cmd = cmd_list->CmdBuffer[i]; if (cmd.UserCallback) { cmd.UserCallback(cmd_list, &cmd); } else { const int sx = (int) cmd.ClipRect.x; const int sy = (int) cmd.ClipRect.y; const int sw = (int) (cmd.ClipRect.z - cmd.ClipRect.x); const int sh = (int) (cmd.ClipRect.w - cmd.ClipRect.y); sg_apply_scissor_rect(sx, sy, sw, sh, true); sg_draw(base_element, cmd.ElemCount, 1); } base_element += cmd.ElemCount; } } } void imgui_teardown() { ImGui::DestroyContext(); } #if defined(SOKOL_GLCORE33) const char* vs_src_imgui = "#version 330\n" "uniform vec2 disp_size;\n" "in vec2 position;\n" "in vec2 texcoord0;\n" "in vec4 color0;\n" "out vec2 uv;\n" "out vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "#version 330\n" "uniform sampler2D tex;\n" "in vec2 uv;\n" "in vec4 color;\n" "out vec4 frag_color;\n" "void main() {\n" " frag_color = texture(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_GLES2) const char* vs_src_imgui = "uniform vec2 disp_size;\n" "attribute vec2 position;\n" "attribute vec2 texcoord0;\n" "attribute vec4 color0;\n" "varying vec2 uv;\n" "varying vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "precision mediump float;\n" "uniform sampler2D tex;\n" "varying vec2 uv;\n" "varying vec4 color;\n" "void main() {\n" " gl_FragColor = texture2D(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_GLES3) const char* vs_src_imgui = "#version 300 es\n" "uniform vec2 disp_size;\n" "in vec2 position;\n" "in vec2 texcoord0;\n" "in vec4 color0;\n" "out vec2 uv;\n" "out vec4 color;\n" "void main() {\n" " gl_Position = vec4(((position/disp_size)-0.5)*vec2(2.0,-2.0), 0.5, 1.0);\n" " uv = texcoord0;\n" " color = color0;\n" "}\n"; const char* fs_src_imgui = "#version 300 es\n" "precision mediump float;" "uniform sampler2D tex;\n" "in vec2 uv;\n" "in vec4 color;\n" "out vec4 frag_color;\n" "void main() {\n" " frag_color = texture(tex, uv) * color;\n" "}\n"; #elif defined(SOKOL_METAL) const char* vs_src_imgui = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct params_t {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos [[attribute(0)]];\n" " float2 uv [[attribute(1)]];\n" " float4 color [[attribute(2)]];\n" "};\n" "struct vs_out {\n" " float4 pos [[position]];\n" " float2 uv;\n" " float4 color;\n" "};\n" "vertex vs_out _main(vs_in in [[stage_in]], constant params_t& params [[buffer(0)]]) {\n" " vs_out out;\n" " out.pos = float4(((in.pos / params.disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " out.uv = in.uv;\n" " out.color = in.color;\n" " return out;\n" "}\n"; const char* fs_src_imgui = "#include <metal_stdlib>\n" "using namespace metal;\n" "struct fs_in {\n" " float2 uv;\n" " float4 color;\n" "};\n" "fragment float4 _main(fs_in in [[stage_in]], texture2d<float> tex [[texture(0)]], sampler smp [[sampler(0)]]) {\n" " return tex.sample(smp, in.uv) * in.color;\n" "}\n"; #elif defined(SOKOL_D3D11) const char* vs_src_imgui = "cbuffer params {\n" " float2 disp_size;\n" "};\n" "struct vs_in {\n" " float2 pos: POSITION;\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" "};\n" "struct vs_out {\n" " float2 uv: TEXCOORD0;\n" " float4 color: COLOR0;\n" " float4 pos: SV_Position;\n" "};\n" "vs_out main(vs_in inp) {\n" " vs_out outp;\n" " outp.pos = float4(((inp.pos/disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n" " outp.uv = inp.uv;\n" " outp.color = inp.color;\n" " return outp;\n" "}\n"; const char* fs_src_imgui = "Texture2D<float4> tex: register(t0);\n" "sampler smp: register(s0);\n" "float4 main(float2 uv: TEXCOORD0, float4 color: COLOR0): SV_Target0 {\n" " return tex.Sample(smp, uv) * color;\n" "}\n"; #endif
33.790761
119
0.604664
JCash
751f699db40b8db0c4cffb7c35b3f5337e15d5f6
1,868
cpp
C++
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
problems/codejam/2016/2/rather-perplexing-showdown/code.cpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // ***** string make(int P, int R, int S) { assert(P >= 0 && R >= 0 && S >= 0); if (P + R + S == 1) { if (P == 1) return "P"; if (R == 1) return "R"; if (S == 1) return "S"; assert(false); } int a = (P + R + S) / 2 - S; // P vs R -> P (write PR) int b = (P + R + S) / 2 - P; // R vs S -> R (write RS) int c = (P + R + S) / 2 - R; // S vs P -> S (write PS) if (a < 0 || b < 0 || c < 0) return ""; auto s = make(a, b, c); if (s.empty()) return ""; string w; for (char p : s) if (p == 'P') w += "RP"; else if (p == 'R') w += "SR"; else w += "SP"; return w; } auto get(int N, int P, int R, int S) { int M = P + R + S; assert(M == (1 << N)); auto s = make(P, R, S); if (s.empty()) return "IMPOSSIBLE"s; for (int n = 1; n < M; n <<= 1) { for (int i = 0; i < M; i += 2 * n) { auto a = s.substr(i, n), b = s.substr(i + n, n); if (a > b) { s.replace(i, n, b); s.replace(i + n, n, a); } } } return s; } void test() { for (int N = 1; N <= 3; N++) { for (int M = 1 << N, P = 0; P <= M; P++) { for (int R = 0, S = M - P - R; P + R <= M; R++, S--) { printf("%d %2d %2d %2d -- %s\n", N, P, R, S, get(N, P, R, S).data()); } } } } auto solve() { int N, P, R, S; cin >> N >> P >> R >> S; return get(N, P, R, S); } // ***** int main() { // test(); unsigned T; cin >> T >> ws; for (unsigned t = 1; t <= T; ++t) { auto solution = solve(); cout << "Case #" << t << ": " << solution << '\n'; } return 0; }
21.72093
85
0.336188
brunodccarvalho
75222869cec69877f7cf1812e300de8d226b149e
3,234
cxx
C++
model_server/obj/src/string_to_int.cxx
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
model_server/obj/src/string_to_int.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
model_server/obj/src/string_to_int.cxx
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ /////////////////////// File string_to_int.C ///////////////////// // // -- Converts ASCII string into integer number using UNIX LEX str_to_int() // // Relations :none. // // Constructors : none // // Methods : none // // History: 08/19/91 S. Spibvakovsky Initial coding //----------------------------------------------------------------------- #include "genError.h" #ifndef ISO_CPP_HEADERS #include <stdio.h> #else /* ISO_CPP_HEADERS */ #include <cstdio> using namespace std; #endif /* ISO_CPP_HEADERS */ extern "C" int str_to_int(char *, int *); // This call just separates c from C and intercepts the error code. int string_to_int(char *str) { int value; int err_stat = 0; Initialize(string_to_int); value = str_to_int(str, &err_stat); if (err_stat) Error(ERR_INPUT); ReturnValue(value); } /* START-LOG------------------------------------------- $Log: string_to_int.cxx $ Revision 1.2 2000/07/10 23:07:30EDT ktrans mainline merge from Visual C++ 6/ISO (extensionless) standard header files Revision 1.2.1.2 1992/10/09 18:55:39 boris Fix comments END-LOG--------------------------------------------- */
40.936709
77
0.527829
kit-transue
752307c05d9b1adb8aa85249d908665b5ecf029f
2,565
hpp
C++
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
src/common/thread.hpp
longlonghands/fps-challenge
020c133a782285364d52b1c98e9661c9aedfd96d
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <memory> #include <stdexcept> #include <thread> namespace common { namespace async { void sleep(int ms); /// This class implements a platform-independent /// wrapper around an operating system thread. class Thread { public: typedef std::shared_ptr<Thread> Ptr; Thread(); virtual ~Thread(); // call the OS to start the thread bool start(std::function<void()> target); bool start(std::function<void(void *)> target, void *arg); // Waits until the thread exits. void join(); // Waits until the thread exits. // The thread should be canceled before calling this method. // This method must be called from outside the current thread // context or deadlock will ensue. bool waitForExit(int timeout = 5000); // Returns the native thread ID. std::thread::id id() const; // Returns the native thread ID of the current thread. static std::thread::id currentID(); bool isStarted() const; bool isRunning() const; protected: // The context which we send to the thread context. // This allows us to gracefully handle late callbacks // and avoid the need for deferred destruction of Runner objects. struct Context { typedef Context *ptr; bool threadIsAlive; bool OwnerIsAlive; // Thread-safe POD members // May be accessed at any time std::string tid; bool started; bool running; // Non thread-safe members // Should not be accessed once the Runner is started std::function<void()> target; std::function<void(void *)> target1; void *arg; // The implementation is responsible for resetting // the context if it is to be reused. void reset() { OwnerIsAlive = true; threadIsAlive = false; tid = ""; arg = nullptr; target = nullptr; target1 = nullptr; started = false; running = false; } Context() { reset(); } ~Context() { // printf("\ncontext deleting ...\n"); } }; bool startAsync(); static void runAsync(Context::ptr context); Thread(const Thread &) = delete; Thread &operator=(const Thread &) = delete; Context::ptr m_context; std::unique_ptr<std::thread> m_handle; }; }} // namespace tidy::async
26.173469
71
0.579337
longlonghands
970891b77c47801c8b11786a89e88ae016939709
10,383
cpp
C++
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
src/particle.cpp
ndevenish/nsl
03dd69ce39258cad0547b968c062074e4b90fdf0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2006-2012 Nicholas Devenish * * 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 <string> #include <sstream> #include <stdexcept> #include <iostream> #include <fstream> #include "nslobject.h" #include "nslobjectfactory.h" #include "particle.h" #include "container.h" #include "physics.h" #include "vector3.h" #include "errors.h" #include "random.h" #include "electromagnetics.h" #include "neutronphysics.h" using std::runtime_error; using std::string; using std::ofstream; using nsl::rand_normal; using nsl::rand_uniform; using std::endl; /* particle::mag_field = 0; particle::elec_field = 0; particle::particlebox = 0; */ // Hack: File global pointers to avoid initialisation static container *g_particlebox = 0; static bfield *g_mag_field = 0; static efield *g_elec_field = 0; particle::particle() { initvals(); objecttype = "particle"; types.push_back(objecttype); } void particle::initvals( void ) { particlebox = 0; fake_edm = 0.; flytime = 0.; gamma = 0.0; position.x = position.y = position.z = 0.0; velocity_vec.x = velocity_vec.y = velocity_vec.z = 0.0; velocity = 0.0; spinEplus.x = spinEplus.y = spinEplus.z = 0.0; spinEminus = spinEplus; E_sum_phase = E_minus_sum_phase = 0.0; vxEeffect *= 0; bounces = 0; } bool particle::prepareobject() { readsettings(); return true; } void particle::readsettings(void) { // Reset all the per-phase run variables here fake_edm = 0.; flytime = 0.; frequencydiff = 0.; E_sum_phase = E_minus_sum_phase = 0.; bounces = 0; vxEeffect *= 0; active = true; sampledBz.reset(); sampledBz2.reset(); sampleBz.reset(); sampleZ.reset(); // Get and validate the positions read_positionsettings(); // Get and validate the velocities (this depends on positions being initialisied) read_velocitysettings(); // Read the spin settings read_spinsettings(); // This section now reads into static variables, as the process was taking inordinate // amounts of time for large particle numbers // Find a container! if (!g_particlebox) { g_particlebox = (container*)findbytype("container"); if (!g_particlebox) throw runtime_error("Unable to find a container for particle"); } particlebox = g_particlebox; // Find a magnetic field to link to if (!g_mag_field) g_mag_field = (bfield*)findbytype("bfield"); mag_field = g_mag_field; // Look for an electric field to link to if (!g_elec_field) g_elec_field = (efield*)findbytype("efield"); elec_field = g_elec_field; } void particle::read_velocitysettings( void ) { // First get the vector if we have one if (isset("vx") || isset("vy") || isset("vz")) { velocity_vec.x = getlongdouble("vx", 0.0); velocity_vec.y = getlongdouble("vy", 0.0); velocity_vec.z = getlongdouble("vz", 0.0); } else { velocity_vec.x = velocity_vec.y = velocity_vec.z = 1.0; } if (isset("velocity")) { velocity = getlongdouble("velocity", 0.0); velocity_vec.scaleto(velocity); } else { velocity = velocity_vec.mod(); } // Warn for zero velocity if (velocity == 0.0) Warning("Velocity in particle is unset (or set to 0.0)"); ///////////////////////////////////////////// // Maxwell-Boltzmann distribution if (get("maxwelldistribution", "off") == "on") generate_maxwellianvelocity(); // Calculate the energy group energygroup = 0.5 * velocity * velocity / g + position.z; // Calculate the relativistic gamma factor vgamma = sqrtl(1. / (1. - (velocity*velocity)/csquared)); } void particle::generate_maxwellianvelocity( void ) { //We want this particle to have a velocity on a maxwell-boltzmann distribution // Don't do it if we have no mass information if (!isset("mass")) throw runtime_error("Cannot set maxwell-boltzmann velocity without mass information."); // Read in the mass information mass = getlongdouble("mass", 0); if (mass <= 0.) throw runtime_error("Zero and negative mass particles unsupported"); // Calculate the effective temperature for the desired maximum velocity long double T = (velocity*velocity * mass ) / (2.*k); //long double T = mass / (velocity * velocity * 2. * k); long double factor = sqrtl((k*T) / mass ); long double mwcutoff = getlongdouble("maxwelliancutoff", position.z + 1.); // Check we are not above the cutoff if (mwcutoff < position.z) throw runtime_error("Particle start position is higher than maxwellian cutoff"); // Do a stupid uniform thing to save time long double egroup = sqrt(rand_uniform() * pow(0.04 + mwcutoff, 2.)) - 0.04; velocity = sqrt(2.*g*(egroup - position.z)); velocity_vec.z = -velocity; velocity_vec.x = velocity_vec.y = 0.; return; /* //ofstream max("maxwellians.txt"); // Loop until we have a valid velocity while(1) { // Generate random maxwellian velocities - http://research.chem.psu.edu/shsgroup/chem647/project14/project14.html velocity_vec.x = rand_normal() * factor; velocity_vec.y = rand_normal() * factor; velocity_vec.z = rand_normal() * factor; // Read back the velocity magnitude velocity = velocity_vec.mod(); // Are we using a cutoff height? If so, see if we are within it if (isset("maxwelliancutoff")) { // Is this above our cutoff? long double cutoff = sqrtl(2*g*(getlongdouble("maxwelliancutoff", 0.79) - position.z)); // If not, it is valid! otherwise recast. if (velocity < cutoff) { long double egroup = (( velocity * velocity ) / ( 2. * g )) + position.z; max << velocity << endl; static long count = 0; logger << ++count << endl; // break; continue; } } else { break; } } // while(1) */ } void particle::read_positionsettings( void ) { position.x = getlongdouble("x", 0.0); position.y = getlongdouble("y", 0.0); position.z = getlongdouble("z", 0.0); // See if we have set a startvolume string startvolume; if (isset("startvolume")) { startvolume = get("startvolume"); string startposition; startposition = get("startposition", "center"); /*if (isset("startposition")) startposition = get("startposition"); else startposition = "center"; */ // Get the base position for this nslobject *startvol; startvol = particlebox->findbyname(startvolume); if (startvol->isoftype("container")) position = ((container*)startvol)->getposition(startposition); else throw runtime_error("Attempting to start particle in non-container volume"); } } void particle::read_spinsettings( void) { // Gamma value gamma = getlongdouble("gamma", 0.0); if (!isset("gamma")) Warning("Gamma in particle is unset (or set to 0.0)"); // Multiply by 2pi Because we will mostly want to use this setting // NOTE: Be careful if changing this in future, as is assumed to be 2*pi*gamma elsewhere gamma *= 2. * pi; // ~~~~~ Spin stuff long double start_spin_polar_angle, start_spin_phase; // Start by getting the spin polar angles start_spin_polar_angle = pi*getlongdouble("start_spin_polar_angle", 0.5); start_spin_phase = pi*getlongdouble("start_spin_phase", 0.0); spinEplus.x = sinl(start_spin_polar_angle)*cosl(start_spin_phase); spinEplus.y = sinl(start_spin_polar_angle)*sinl(start_spin_phase); spinEplus.z = cosl(start_spin_polar_angle); spinEminus = spinEplus; } /** Updates the Exv effect for the particle. */ void particle::updateExv ( efield &elecfield ) { /* vector3 vxE; vector3 E; elecfield.getfield(E, this->position); this->vxEeffect = (crossproduct(E, this->velocity_vec) * this->vgamma)/ csquared; */ // void neutron_physics::Exveffect( const vector3 &position, const vector3 &velocity, const long double gamma, vector3 &vxEeffect ) neutron_physics::Exveffect( this->position, this->velocity_vec, this->vgamma, elecfield, this->vxEeffect ); } /* // Physical Properties values vector3 position; vector3 velocity_vec; vector3 spinEplus; vector3 spinEminus; // A 'cache' for the exB effect that only changes every bounce (in a linear electric field) vector3 vxEeffect; long double velocity; // m s^-1 // Gyromagnetic ratio of the particle long double gamma; // 2*pi*Hz/Tesla // Particles velocity gamma long double vgamma; // Number of bounces! long bounces; long double E_sum_phase, E_minus_sum_phase; // Radians long double flytime; // s // particles mass long double mass; // kg // Our calculated edm parameters long double frequencydiff; //radians long double fake_edm; // e.cm x10(-26) dataset cumulativeedm; // Utility class pointers container *particlebox; bfield *mag_field; efield *elec_field; */ std::ostream& operator<<(std::ostream& os, const particle& p) { using std::scientific; os.precision(3); //os.setscientific(); os << "Particle Property dump:" << endl; os << "Position: " << p.position << endl; os << "Velocity: " << p.velocity << " ( " << p.velocity_vec << " )" << endl; os << "Spin E+: " << p.spinEplus << endl; os << " E-: " << p.spinEminus << endl; os << "VxE Effect: " << p.vxEeffect << endl; os << "Gamma (L): " << p.gamma << endl; os << "Gamme (R): " << p.vgamma << endl; os << "Bounces: " << p.bounces << endl; os << "Sum Phase, E+: " << p.E_sum_phase << endl; os << " E-: " << p.E_minus_sum_phase << endl; os << "Flytime: " << p.flytime << endl; os << "Mass: " << p.mass << endl; os << "Frequency Diff: " << p.frequencydiff << endl; os << "Fake EDM: " << p.fake_edm << endl; return os; }
27.323684
131
0.690456
ndevenish
97090938d893075b49d16b6dd0c8497823d900d3
1,059
cc
C++
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
1
2022-02-04T05:06:03.000Z
2022-02-04T05:06:03.000Z
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
3
2017-07-10T13:18:04.000Z
2018-08-30T19:29:46.000Z
src/main/native/darwin/util.cc
kjlubick/bazel
6f0913e6e75477ec297430102a8213333a12967e
[ "Apache-2.0" ]
1
2022-01-12T18:08:14.000Z
2022-01-12T18:08:14.000Z
// Copyright 2021 The Bazel 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 "src/main/native/darwin/util.h" #include "src/main/cpp/util/logging.h" namespace bazel { namespace darwin { dispatch_queue_t JniDispatchQueue() { static dispatch_once_t once_token; static dispatch_queue_t queue; dispatch_once(&once_token, ^{ queue = dispatch_queue_create("build.bazel.jni", DISPATCH_QUEUE_SERIAL); BAZEL_CHECK_NE(queue, nullptr); }); return queue; } } // namespace darwin } // namespace bazel
31.147059
76
0.745042
kjlubick
97094f6541bda09c47adf1bc12acd753f4e0a99b
1,307
cpp
C++
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
4
2016-09-07T07:02:52.000Z
2019-06-22T08:55:53.000Z
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
null
null
null
test/dataalign/test_dataalign.cpp
fox000002/ulib-win
628c4a0b8193d1ad771aa85598776ff42a45f913
[ "Apache-2.0" ]
3
2019-06-22T16:00:39.000Z
2022-03-09T13:46:27.000Z
#include <stdio.h> #include <windows.h> int mswindows_handle_hardware_exceptions (DWORD code) { printf("Handling exception\n"); if (code == STATUS_DATATYPE_MISALIGNMENT) { printf("misalignment fault!\n"); return EXCEPTION_EXECUTE_HANDLER; } else return EXCEPTION_CONTINUE_SEARCH; } void test() { __try { char temp[10]; memset(temp, 0, 10); double *val; val = (double *)(&temp[3]); printf("%lf\n", *val); } __except(mswindows_handle_hardware_exceptions (GetExceptionCode ())) {} } int main() { char a; char b; class S1 { public: char m_1; // 1-byte element // 3-bytes of padding are placed here int m_2; // 4-byte element double m_3, m_4; // 8-byte elements }; S1 x; long y; S1 z[5]; printf("sizeof S1 : %d\n\n", sizeof(S1)); printf("a = %p\n", &a); printf("b = %p\n", &b); printf("x = %p\n", &x); printf("x.m_1 = %p\n", &x.m_1); printf("x.m_2 = %p\n", &x.m_2); printf("x.m_3 = %p\n", &x.m_3); printf("x.m_4 = %p\n", &x.m_4); printf("y = %p\n", &y); printf("z[0] = %p\n", z); printf("z[1] = %p\n", &z[1]); test(); return 0; }
20.107692
72
0.497322
fox000002
9709fcca401e1a7f071545e31f5dc431f22736ac
7,362
cpp
C++
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/private/rendererandroid.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file rendererandroid.cpp * @brief * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2017-12-09 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/precompiled.h" #include "o3d/engine/renderer.h" // ONLY IF O3D_ANDROID IS SELECTED #ifdef O3D_ANDROID #include "o3d/engine/glextdefines.h" #include "o3d/engine/glextensionmanager.h" #include "o3d/core/gl.h" #include "o3d/engine/context.h" #include "o3d/core/appwindow.h" #include "o3d/core/application.h" #include "o3d/core/debug.h" #ifdef O3D_EGL #include "o3d/core/private/egldefines.h" #include "o3d/core/private/egl.h" #endif using namespace o3d; // Create the OpenGL context. void Renderer::create(AppWindow *appWindow, Bool debug, Renderer *sharing) { if (m_state.getBit(STATE_DEFINED)) { O3D_ERROR(E_InvalidPrecondition("The renderer is already initialized")); } if (!appWindow || (appWindow->getHWND() == NULL_HWND)) { O3D_ERROR(E_InvalidParameter("Invalid application window")); } if ((sharing != nullptr) && m_sharing) { O3D_ERROR(E_InvalidOperation("A shared renderer cannot be sharing")); } O3D_MESSAGE("Creating a new OpenGLES context..."); if (GL::getImplementation() == GL::IMPL_EGL) { // // EGL implementation // #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); EGLSurface eglSurface = reinterpret_cast<EGLSurface>(appWindow->getHDC()); EGLConfig eglConfig = reinterpret_cast<EGLConfig>(appWindow->getPixelFormat()); // EGL_CONTEXT_OPENGL_DEBUG EGLint contextAttributes[] = { /*EGL_CONTEXT_MAJOR_VERSION_KHR*/EGL_CONTEXT_CLIENT_VERSION, 3, /* EGL_CONTEXT_MINOR_VERSION_KHR, 2,*/ debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR : EGL_NONE, // debug ? EGL_CONTEXT_FLAGS_KHR : EGL_NONE, debug ? EGL_CONTEXT_OPENGL_DEBUG : EGL_NONE, EGL_NONE }; EGLContext eglContext = eglCreateContext( eglDisplay, eglConfig, sharing ? reinterpret_cast<EGLContext>(sharing->getHGLRC()) : EGL_NO_CONTEXT, contextAttributes); if (eglContext == EGL_NO_CONTEXT) { O3D_ERROR(E_InvalidResult("Unable to create the OpenGLES context")); } EGL::makeCurrent(eglDisplay, eglSurface, eglSurface, eglContext); m_HDC = appWindow->getHDC(); m_HGLRC = reinterpret_cast<_HGLRC>(eglContext); m_state.enable(STATE_DEFINED); m_state.enable(STATE_EGL); #else O3D_ERROR(E_UnsuportedFeature("Support for EGL is missing")); #endif } else { O3D_ERROR(E_UnsuportedFeature("Support for EGL only")); } GLExtensionManager::init(); O3D_MESSAGE("Video renderer: " + getRendererName()); O3D_MESSAGE("OpenGL version: " + getVersionName()); computeVersion(); m_appWindow = appWindow; m_bpp = appWindow->getBpp(); m_depth = appWindow->getDepth(); m_stencil = appWindow->getStencil(); m_samples = appWindow->getSamples(); if (sharing) { m_sharing = sharing; m_sharing->m_shareCount++; } if (debug) { initDebug(); } m_glContext = new Context(this); doAttachment(m_appWindow); } // delete the renderer void Renderer::destroy() { if (m_state.getBit(STATE_DEFINED)) { if (m_refCount > 0) { O3D_ERROR(E_InvalidPrecondition("Unable to destroy a referenced renderer")); } if (m_shareCount > 0) { O3D_ERROR(E_InvalidPrecondition("All shared renderer must be destroyed before")); } // unshare if (m_sharing) { m_sharing->m_shareCount--; if (m_sharing->m_shareCount < 0) { O3D_ERROR(E_InvalidResult("Share counter reference is negative")); } m_sharing = nullptr; } deletePtr(m_glContext); if (m_HGLRC && m_appWindow) { if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); EGL::makeCurrent(eglDisplay, 0, 0, 0); EGL::destroyContext(eglDisplay, reinterpret_cast<EGLContext>(m_HGLRC)); #endif } m_HGLRC = NULL_HGLRC; } m_HDC = NULL_HDC; m_depth = m_bpp = m_stencil = m_samples = 0; m_state.zero(); m_version = 0; if (m_appWindow) { disconnect(m_appWindow); m_appWindow = nullptr; } m_glErrno = GL_NO_ERROR; } } void *Renderer::getProcAddress(const Char *ext) const { return EGL::getProcAddress(ext); } // Is it the current OpenGL context. Bool Renderer::isCurrent() const { if (!m_state.getBit(STATE_DEFINED)) { return False; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL return EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC); #endif } else { return False; } } // Set as current OpenGL context void Renderer::setCurrent() { if (!m_state.getBit(STATE_DEFINED)) { return; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL if (EGL::getCurrentContext() == reinterpret_cast<EGLContext>(m_HGLRC)) { return; } EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); if (EGL::makeCurrent( eglDisplay, reinterpret_cast<EGLSurface>(m_HDC), reinterpret_cast<EGLSurface>(m_HDC), reinterpret_cast<EGLContext>(m_HGLRC))) { O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); } #else O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); #endif } else { O3D_ERROR(E_InvalidResult("Unable to set the current OpenGL context")); } } Bool Renderer::setVSyncMode(VSyncMode mode) { if (!m_state.getBit(STATE_DEFINED)) { return False; } int value = 0; if (mode == VSYNC_NONE) { value = 0; } else if (mode == VSYNC_YES) { value = 1; } else if (mode == VSYNC_ADAPTIVE) { value = -1; } if (m_state.getBit(STATE_EGL)) { #ifdef O3D_EGL EGLDisplay eglDisplay = EGL::getDisplay(reinterpret_cast<EGLNativeDisplayType>(Application::getDisplay())); if (!EGL::swapInterval(eglDisplay, value)) { return False; } #else return False; #endif } else { return False; } if (mode == VSYNC_NONE) { m_state.setBit(STATE_VSYNC, False); m_state.setBit(STATE_ADAPTIVE_VSYNC, False); } else if (mode == VSYNC_YES) { m_state.setBit(STATE_VSYNC, True); m_state.setBit(STATE_ADAPTIVE_VSYNC, False); } else if (mode == VSYNC_ADAPTIVE) { m_state.setBit(STATE_VSYNC, True); m_state.setBit(STATE_ADAPTIVE_VSYNC, True); } return True; } #endif // O3D_ANDROID
27.470149
123
0.619669
dream-overflow
970a0dc9bef87e899dc9a929f4a47aa138c8dc3b
3,481
cpp
C++
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
1
2021-01-31T22:59:59.000Z
2021-01-31T22:59:59.000Z
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
null
null
null
Codility_CommonPrimerDivisor.cpp
CharlieGearsTech/Codility
b0c4355eb68f05f24390075e3fe2fe555d40b6b9
[ "MIT" ]
null
null
null
#include <iostream> #include <assert.h> #include <math.h> #include <vector> #include <algorithm> #include <numeric> #include <map> #include <deque> #include <stdlib.h> #include <string> #include <set> #include <vector> #include <new> #include <memory> using namespace std; /*Crea un arreglo en la que los indices muestran el numero divisible de la secuencia y el valor es el numero divisor*/ map<int,int> prepareArrayFactor(int n) { map<int,int> f; auto i = 2u; /*Rango para numeros que pueden dividir a N*/ while(i+i <=(size_t)n) { auto k=i*i; while(k <= (size_t)n) { f[k] = i; k+=i; } i++; } return f; } /* Encontrar los numeros que multiplicados nos dan a X, X debe de ser un numero menor al tamaño de A*/ vector<int> factorization(int x, map<int,int>& A) { vector<int> primeFactors; /*Revisar unicamente numeros que son divisibles*/ while(A[x] > 0) { /*Agregar el divisor a la lista de factorizacion*/ primeFactors.push_back(A[x]); /* Dividir para disminuir el numero divisible en un factor menor.*/ x /= A[x]; } /*Agregar el ultimo numero divisor.*/ primeFactors.push_back(x); return primeFactors; } /*Esta solucion se basa en usar la formula de factorizacion que nos devuelve un contenedor con todos los factores de X numero, despues de eso comparamos los arreglos iguales. Uso set para organizar y hacer unicos los factores.*/ int solution(vector<int> &A, vector<int> &B) { auto N=A.size(); set<int> holder; copy(A.begin(),A.end(),inserter(holder,holder.begin())); copy(B.begin(),B.end(),inserter(holder,holder.begin())); int max_element=*holder.rbegin(); //O(logN) auto maxFactorArray=prepareArrayFactor(max_element); int count=0; //O(n*logn*logn) for(auto k=0u; k<N; ++k) { auto Afactor=factorization(A[k],maxFactorArray); auto Bfactor=factorization(B[k],maxFactorArray); set<int> AfactorSet; set<int> BfactorSet; copy(Afactor.begin(),Afactor.end(),inserter(AfactorSet,AfactorSet.begin())); copy(Bfactor.begin(),Bfactor.end(),inserter(BfactorSet,BfactorSet.begin())); if(std::equal(AfactorSet.begin(),AfactorSet.end(),BfactorSet.begin())) ++count; } return count; } /*Imprimir vector<int>s*/ void printV(vector<int>& vRes) { for(auto it= vRes.begin(); it != vRes.end();++it) { cout<<*it<<"\t"; } cout<<endl; } /*Assertion de vectores de ints*/ void assertV( vector<int>& result, vector<int>&& comp) { bool res = std::equal(result.begin(),result.end(),comp.begin()); assert(res); } int main() { int result; vector<int> a; vector<int> b; a={15,10,3}; b={75,30,5}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); a={15}; b={75}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); a={12,12,18}; b={24,25,9}; result=solution(a,b); cout<<result<<endl; assert(result==1); a.clear(); b.clear(); /*This algorithm is unable to execute large number since it allocates all the prime divisor for each element*/ // a={2147483647}; // b={2147483647}; // result=solution(a,b); // cout<<result<<endl; // assert(result==1); // a.clear(); // b.clear(); return 0; }
23.362416
228
0.607871
CharlieGearsTech