row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,244
|
How would I create an API that has a full authorization flow that if successful returns 'Hello World!'. It should also have full error handling and load balancing. Guide me through, step by step, including full code. By following the guide I should have a fully functional version of what I asked for.
|
fdc0375973ff73d553a3ad1127ded74d
|
{
"intermediate": 0.7102124691009521,
"beginner": 0.15074095129966736,
"expert": 0.1390465795993805
}
|
10,245
|
i have an ethernet connection and a wifi connection. How do i launch 2 separate python scripts with selenium browsers: one of which uses the wifi internet connection and the other uses my ethernet cable?
|
237c6127d5b4b7297f7aec1cf5a68aec
|
{
"intermediate": 0.4865887463092804,
"beginner": 0.25577083230018616,
"expert": 0.25764039158821106
}
|
10,246
|
import requests
from bs4 import BeautifulSoup
import os
url = 'https://wiki.rage.mp/index.php?title=Vehicles' # Replace with the URL of the webpage you want to scrape
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
def download_image(url: str, output_folder: str, filename: str) -> None:
response = requests.get(url)
if response.status_code == 200:
with open(os.path.join(output_folder, filename), 'wb') as f:
f.write(response.content)
print(f'Downloaded {filename}')
else:
print(f'Error downloading {url}: {response.status_code}')
output_folder = 'output1080p'
if not os.path.exists(output_folder):
os.makedirs(output_folder)
image_count = 0
for div in soup.find_all('div', {'class': 'thumb'}):
img = div.find('img')
if img is not None:
src = img['src']
response = requests.get('https://wiki.rage.mp/' + src) # Append the src attribute to the base url
if response.status_code == 200:
image_count += 1
gallery_text_div = div.find_next_sibling('div', {'class': 'gallerytext'})
code_tag = gallery_text_div.find('code')
if code_tag is not None:
filename = f'{code_tag.text}.png'
file_url = f"https://wiki.rage.mp/index.php?title=File:{code_tag.text}.png"
file_page_response = requests.get(file_url)
file_page_soup = BeautifulSoup(file_page_response.content, 'html.parser')
file_href = file_page_soup.find('div', {'class': 'fullMedia'}).find('a', {'class': 'internal'}).get('href')
download_image('https://wiki.rage.mp/' + file_href, output_folder, filename)
else:
filename = f'image{image_count}.png'
download_image(response.url, output_folder, filename)
else:
print(f'Error downloading {src}: {response.status_code}')
print(f'Total Images downloaded: {image_count}')
<div class="fullMedia"><p><a href="/images/a/a3/Tug.png" class="internal" title="Tug.png">Original file</a> ‎<span class="fileInfo">(1,920 × 1,080 pixels, file size: 2.68 MB, MIME type: <span class="mime-type">image/png</span>)</span>
<div class="fullMedia"><p><a href="/images/1/19/0x9A474B5E.png" class="internal" title="0x9A474B5E.png">Original file</a> ‎<span class="fileInfo">(1,332 × 937 pixels, file size: 852 KB, MIME type: <span class="mime-type">image/png</span>)</span>
for some reason the first one works without any issue the second one doesn't work could you edit the code so it works for both
|
2c64098b85e0e0247973be4319827073
|
{
"intermediate": 0.285421758890152,
"beginner": 0.5422928333282471,
"expert": 0.17228540778160095
}
|
10,247
|
hi
|
38e903853180e75b997bedd0c9741f4d
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,248
|
Are this steps correct for abstract the layer of deployment for AI Tools. Anyone should be easily add a new model to the stack without thinking about deployments. We should be able to deploy AI Tools in such a way where each model (every model can be packaged as a container) should be independently scalable. As a user, I should be able to access APIs associated with any model. :
## 1. Adding a New Model to the AI Toolchain
1. First, create a new directory for your model within the src folder in the AI Toolchain repository and name it according to your model’s purpose. For example, if you’re adding a sentiment analysis model with a specific provider and mode, the folder should be located at src/sentiment_analysis/provider/mode/.
2. Within the new directory, add the following files:
- model.py: This file should contain the implementation of the model using a popular machine learning framework like TensorFlow, PyTorch, or scikit-learn. It should include methods for training, evaluating, and predicting.
- requirements.txt: List any Python dependencies required by your model.
3. Create a new Dockerfile in your model’s directory to containerize the model. The file should include instructions to install dependencies and copy relevant files to the container. Here’s an example:
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY model.py .
CMD [“python”, “model.py”]
4. Update the repository_data.json file to include an entry for your new model with the corresponding information.
## 2. Testing the Model Locally with Docker Compose
1. Add a new service entry for your model in the existing docker-compose.yml file by following this example:
sentiment_analysis:
build:
context: ./src/sentiment_analysis/provider/mode/
dockerfile: Dockerfile
ports:
- “8001:8000”
environment:
- PYTHONUNBUFFERED=1
- PYTHONDONTWRITEBYTECODE=1
Replace ./src/sentiment_analysis/provider/mode/ with the path to your model’s directory and adjust the port numbers accordingly.
2. Run docker-compose up to build and run the containers for the main app and your new model.
3. Test your model’s API locally using a tool like curl or Postman, connecting to http://localhost:8000/use_case/provider/mode.
## 3. Deploying with Docker Compose
When you’re ready to deploy your model, you can use the existing docker-compose.yml file to deploy the entire AI Toolchain stack, including your new model.
1. Push your model’s Docker image to a container registry:
docker-compose build sentiment_analysis
docker tag sentiment_analysis:latest your-container-registry-url/sentiment_analysis:latest
docker push your-container-registry-url/sentiment_analysis:latest
2. Update the docker-compose.yml file in your deployment environment with the new service entries for your model, as was done for testing locally.
3. Run docker-compose up -d in your deployment environment to start all services, including your new model.
## 4. Accessing the Model’s APIs
Once the AI Toolchain stack is deployed using Docker Compose, users can access the APIs associated with each model by calling the main app’s API at http://your.deployment.url/use_case/provider/mode.
For example, if the AI Toolchain is deployed at http://your.deployment.url, and your new model is a sentiment analysis model at the endpoint /sentiment_analysis/provider/mode, users can access the API by sending requests to http://your.deployment.url/sentiment_analysis/provider/mode.
By following these steps, you can add new models to the AI Toolchain, test them locally, and deploy them using Docker Compose, allowing users to access the APIs associated with any model.
|
528caee3e5db28f6baf62e4244a3d00f
|
{
"intermediate": 0.37060654163360596,
"beginner": 0.38269829750061035,
"expert": 0.24669520556926727
}
|
10,249
|
using purely c++ code make a simple playable tetris game that you can play in the terminal:
|
6ffcaac4e2ccc3a00c0eb28d9eea6baf
|
{
"intermediate": 0.35472801327705383,
"beginner": 0.3574170172214508,
"expert": 0.28785499930381775
}
|
10,250
|
fivem scripting how to control a deers movement so I could ride it
|
f06396f546d8e03605d527dc3e1082f4
|
{
"intermediate": 0.24444633722305298,
"beginner": 0.21052886545658112,
"expert": 0.5450248122215271
}
|
10,251
|
i have these two interfaces that are similar export interface MultiSelectParamProps {
placeholder?: string;
options: SelectItem[];
}
interface SelectProps {
placeholder?: string;
options: SendersContent[];
onChange: any;
} how do i improve them
|
d3df1afac3fc3daac055e0637992ba0f
|
{
"intermediate": 0.6149092316627502,
"beginner": 0.15627895295619965,
"expert": 0.2288118302822113
}
|
10,252
|
I have data of temperature for every hour from first of July to end of September from 1951 to 2022. I want to predict temperature from 2023 to 2060. this set of data have a seasonality for 24 hours of a day.
|
dbee68a531f733814dd5620fe32cafb5
|
{
"intermediate": 0.4079233705997467,
"beginner": 0.22505828738212585,
"expert": 0.36701834201812744
}
|
10,253
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout* CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout* CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorSetLayout* samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout* descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout* descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorSetLayout* samplerDescriptorSetLayout;// = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorSetLayout* samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout* descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout* descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, *descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, *samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
//Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout* descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout* samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Here is a portion of Renderer.cpp:
VkDescriptorSetLayout* Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return &descriptorSetLayout;
}
VkDescriptorSetLayout* Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return &descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
I am getting an access violation error in Material::CreateDescriptorSet when trying to allocate descriptorsets. Here is the log output:
VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter(ERROR / SPEC): msgNum: -1275504685 - Validation Error: [ VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter ] Object 0: handle = 0x1f2f1e29a40, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0xb3f957d3 | Invalid VkDescriptorSetLayout Object 0xb3dc6ff590. The Vulkan spec states: If setLayoutCount is not 0, pSetLayouts must be a valid pointer to an array of setLayoutCount valid or VK_NULL_HANDLE VkDescriptorSetLayout handles (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkPipelineLayoutCreateInfo-pSetLayouts-parameter)
Objects: 1
[0] 0x1f2f1e29a40, type: 1, name: NULL
Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 0
Calling vkBeginCommandBufferà
vkBeginCommandBuffer calledà
VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter(ERROR / SPEC): msgNum: 210066664 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter ] Object 0: handle = 0x1f2f1e29a40, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0xc855ce8 | Invalid VkDescriptorSetLayout Object 0xcccccccccccccccc. The Vulkan spec states: pSetLayouts must be a valid pointer to an array of descriptorSetCount valid VkDescriptorSetLayout handles (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-pSetLayouts-parameter)
Objects: 1
[0] 0x1f2f1e29a40, type: 1, name: NULL
What might be causing this issue and how can I fix it?
|
778942d725f3da80fea883fa44cdbef4
|
{
"intermediate": 0.3505549430847168,
"beginner": 0.394856333732605,
"expert": 0.2545887529850006
}
|
10,255
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout;// = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
//Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
vkDeviceWaitIdle(*renderer.GetDevice());
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
Cleanup();
}
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
I am getting this error in Texture::Cleanup when trying to close the application:
VUID-vkDestroySampler-sampler-01082(ERROR / SPEC): msgNum: -861300428 - Validation Error: [ VUID-vkDestroySampler-sampler-01082 ] Object 0: handle = 0x22239fc72c0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0xcca99934 | Cannot call vkDestroySampler on VkSampler 0xba7514000000002a[] that is currently in use by a command buffer. The Vulkan spec states: All submitted commands that refer to sampler must have completed execution (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroySampler-sampler-01082)
Objects: 1
[0] 0x22239fc72c0, type: 3, name: NULL
What might be causing this issue and how can I fix it?
|
a456bb628fb190878c41699e5fb243b2
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,256
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout;// = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
//Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
A portion of GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
Cleanup();
}
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting this error in Renderer::CleanupDevice when trying to close the application:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x250768af840, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x250768af840[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x250768af840, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
What might be causing this issue and how can I fix it?
|
475d92f9b7de950433abb19c4b534887
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,257
|
Конечно, вот ваш код, объединенный в один блок:
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Создаем датафрейм datamart с помощью SQL-запроса
datamart = pd.io.sql.read_sql(‘’‘
SELECT t1.uid, labname, first_commit_ts, first_view_ts
FROM
(SELECT uid, labname, timestamp as first_commit_ts
FROM checker
WHERE uid LIKE ‘user_%’ AND status=‘ready’ AND numTrials = 1 AND
labname IN (‘laba04’, ‘laba04s’, ‘laba05’, ‘laba05’, ‘laba06’, ‘laba06s’, ‘project1’)) AS t1
LEFT JOIN
(SELECT min(datetime) as first_view_ts, uid
FROM pageviews
WHERE uid LIKE ‘user_%’
GROUP BY uid) AS t2
ON t1.uid = t2.uid
’‘’, conn, parse_dates=[‘first_commit_ts’, ‘first_view_ts’])
# Создаем датафреймы test и control
test = datamart[datamart.first_view_ts.notnull()]
control = datamart[datamart.first_view_ts.isnull()]
# Заполняем пропущенные значения first_view_ts в control средним значением из test
control.fillna(value = test.first_view_ts.mean(), inplace = True)
# Сохраняем датафреймы в базе данных
test.to_sql(‘test’, conn, if_exists = ‘replace’)
control.to_sql(‘control’, conn, if_exists = ‘replace’)
# Закрываем соединение с базой данных
conn.close()
# Выводим информацию о датафреймах
test.info()
control.info()
Теперь у вас есть один блок кода, который выполняет все задачи, указанные в ваших комментариях.
Используя имеющийся код Создай соединение с базой данных с помощью библиотеки sqlite3.
Получи схему таблицы test.
Получи только первые 10 строк таблицы test, чтобы проверить, как она выглядит.
Найди среди всех пользователей минимальное значение этой самой дельты (периода времени от даты первого коммита пользователя до срока сдачи соответствующего лабораторного задания), используя только один запрос.
Для этого соедини данные своей таблицы с данными таблицы deadlines.
Период времени должен отображаться в часах.
Не учитывай лабораторное задание project1 с более длительным сроком сдачи, поскольку оно будет выделяться на фоне других.
Сохрани значение в датафрейме df_min с соответствующим uid.
Выполни те же самые операции для максимального значения дельты, используя только один запрос. Название итогового датафрейма — df_max.
Выполни те же самые операции для среднего значения дельты, используя только один запрос. На этот раз ваш итоговый датафрейм не должен включать столбец uid; имя датафрейма — df_avg.
Мы хотим проверить предположение о том, что у пользователей, посетивших ленту новостей всего несколько раз, период времени между датой первого коммита и сроком сдачи лабораторного задания меньше. Для этого тебе необходимо рассчитать коэффициент корреляции между количеством просмотров страниц и разницей между датами.
Используя только один запрос, создай таблицу со столбцами: uid, avg_diff, pageviews.
uid — это uid, существующие в таблице test.
avg_diff — среднее значение дельты (периода времени между датой первого коммита и сроком сдачи лабораторного задания) для каждого пользователя.
pageviews — количество посещений ленты новостей одним пользователем.
Не учитывай лабораторное задание project1.
Сохрани результаты в датафрейме views_diff.
Используй метод corr() библиотеки Pandas для вычисления коэффициента корреляции между количеством просмотров и значением дельты.
Закрой соединение.
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, labname, MIN((julianday(deadlines)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Весь код объединен в одном блоке, выполняя все поставленные задачи. Не забудьте заменить путь к базе данных на свой путь, если это необходимо.
cid name type notnull dflt_value pk
0 0 index INTEGER 0 None 0
1 1 uid TEXT 0 None 0
2 2 labname TEXT 0 None 0
3 3 first_commit_ts TIMESTAMP 0 None 0
4 4 first_view_ts TIMESTAMP 0 None 0
index uid labname first_commit_ts <br/>0 3 user_17 project1 2020-04-18 07:56:45.408648
1 4 user_30 laba04 2020-04-18 13:36:53.971502
2 7 user_30 laba04s 2020-04-18 14:51:37.498399
3 8 user_14 laba04 2020-04-18 15:14:00.312338
4 11 user_14 laba04s 2020-04-18 22:30:30.247628
5 18 user_19 laba04 2020-04-20 19:05:01.297780
6 19 user_25 laba04 2020-04-20 19:16:50.673054
7 20 user_21 laba04 2020-04-21 17:48:00.487806
8 21 user_30 project1 2020-04-22 12:36:24.053518
9 23 user_21 laba04s 2020-04-22 20:09:21.857747
first_view_ts
0 2020-04-18 10:56:55.833899
1 2020-04-17 22:46:26.785035
2 2020-04-17 22:46:26.785035
3 2020-04-18 10:53:52.623447
4 2020-04-18 10:53:52.623447
5 2020-04-21 20:30:38.034966
6 2020-05-09 23:54:54.260791
7 2020-04-22 22:40:36.824081
8 2020-04-17 22:46:26.785035
9 2020-04-22 22:40:36.824081
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2017 try:
-> 2018 cur.execute(*args, **kwargs)
2019 return cur
OperationalError: no such column: deadlines.labname
The above exception was the direct cause of the following exception:
DatabaseError Traceback (most recent call last)
3 frames
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2028
2029 ex = DatabaseError(f"Execution failed on sql ‘{args[0]}’: {exc}")
-> 2030 raise ex from exc
2031
2032 @staticmethod
DatabaseError: Execution failed on sql ‘
SELECT uid, labname, MIN((julianday(deadlines)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’: no such column: deadlines.labname
Извините за эту ошибку, я забыл использовать правильное название столбца при объединении. В таблице deadlines столбец называется ‘deadline’, а не ‘labname’. Вот исправленный код:
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, test.labname, MIN((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, test.labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Этот код исправляет ошибку “no such column” и должен нормально работать.
|
6b411f817abd046294bb259426d2ec78
|
{
"intermediate": 0.29778459668159485,
"beginner": 0.5382837653160095,
"expert": 0.1639316827058792
}
|
10,258
|
how can I fix the error here
|
6821fd99ba8f36ab3ee68613fecf3645
|
{
"intermediate": 0.40902212262153625,
"beginner": 0.2243867665529251,
"expert": 0.36659112572669983
}
|
10,259
|
i have application with some of modules each modules has its own routing file and some components, i cannot to access the component of each module through url
|
6e8bf22e2c20f9603eade8ce3eb51b29
|
{
"intermediate": 0.32688769698143005,
"beginner": 0.3190910816192627,
"expert": 0.35402125120162964
}
|
10,260
|
Используя имеющийся код Создай соединение с базой данных с помощью библиотеки sqlite3.
Получи схему таблицы test.
Получи только первые 10 строк таблицы test, чтобы проверить, как она выглядит.
Найди среди всех пользователей минимальное значение этой самой дельты (периода времени от даты первого коммита пользователя до срока сдачи соответствующего лабораторного задания), используя только один запрос.
Для этого соедини данные своей таблицы с данными таблицы deadlines.
Период времени должен отображаться в часах.
Не учитывай лабораторное задание project1 с более длительным сроком сдачи, поскольку оно будет выделяться на фоне других.
Сохрани значение в датафрейме df_min с соответствующим uid.
Выполни те же самые операции для максимального значения дельты, используя только один запрос. Название итогового датафрейма — df_max.
Выполни те же самые операции для среднего значения дельты, используя только один запрос. На этот раз ваш итоговый датафрейм не должен включать столбец uid; имя датафрейма — df_avg.
Мы хотим проверить предположение о том, что у пользователей, посетивших ленту новостей всего несколько раз, период времени между датой первого коммита и сроком сдачи лабораторного задания меньше. Для этого тебе необходимо рассчитать коэффициент корреляции между количеством просмотров страниц и разницей между датами.
Используя только один запрос, создай таблицу со столбцами: uid, avg_diff, pageviews.
uid — это uid, существующие в таблице test.
avg_diff — среднее значение дельты (периода времени между датой первого коммита и сроком сдачи лабораторного задания) для каждого пользователя.
pageviews — количество посещений ленты новостей одним пользователем.
Не учитывай лабораторное задание project1.
Сохрани результаты в датафрейме views_diff.
Используй метод corr() библиотеки Pandas для вычисления коэффициента корреляции между количеством просмотров и значением дельты.
Закрой соединение.
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, labname, MIN((julianday(deadlines)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Весь код объединен в одном блоке, выполняя все поставленные задачи. Не забудьте заменить путь к базе данных на свой путь, если это необходимо.
cid name type notnull dflt_value pk
0 0 index INTEGER 0 None 0
1 1 uid TEXT 0 None 0
2 2 labname TEXT 0 None 0
3 3 first_commit_ts TIMESTAMP 0 None 0
4 4 first_view_ts TIMESTAMP 0 None 0
index uid labname first_commit_ts <br/>0 3 user_17 project1 2020-04-18 07:56:45.408648
1 4 user_30 laba04 2020-04-18 13:36:53.971502
2 7 user_30 laba04s 2020-04-18 14:51:37.498399
3 8 user_14 laba04 2020-04-18 15:14:00.312338
4 11 user_14 laba04s 2020-04-18 22:30:30.247628
5 18 user_19 laba04 2020-04-20 19:05:01.297780
6 19 user_25 laba04 2020-04-20 19:16:50.673054
7 20 user_21 laba04 2020-04-21 17:48:00.487806
8 21 user_30 project1 2020-04-22 12:36:24.053518
9 23 user_21 laba04s 2020-04-22 20:09:21.857747
first_view_ts
0 2020-04-18 10:56:55.833899
1 2020-04-17 22:46:26.785035
2 2020-04-17 22:46:26.785035
3 2020-04-18 10:53:52.623447
4 2020-04-18 10:53:52.623447
5 2020-04-21 20:30:38.034966
6 2020-05-09 23:54:54.260791
7 2020-04-22 22:40:36.824081
8 2020-04-17 22:46:26.785035
9 2020-04-22 22:40:36.824081
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2017 try:
-> 2018 cur.execute(*args, **kwargs)
2019 return cur
OperationalError: no such column: deadlines.labname
The above exception was the direct cause of the following exception:
DatabaseError Traceback (most recent call last)
3 frames
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2028
2029 ex = DatabaseError(f"Execution failed on sql ‘{args[0]}’: {exc}")
-> 2030 raise ex from exc
2031
2032 @staticmethod
DatabaseError: Execution failed on sql ‘
SELECT uid, labname, MIN((julianday(deadlines)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’: no such column: deadlines.labname
Извините за эту ошибку, я забыл использовать правильное название столбца при объединении. В таблице deadlines столбец называется ‘deadline’, а не ‘labname’. Вот исправленный код:
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, test.labname, MIN((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, test.labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Этот код исправляет ошибку “no such column” и должен нормально работать.
Спасибо, что обратили внимание на эту ошибку. Итак, здесь исправленный код:
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, test.labname, MIN((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, test.labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Теперь у меня нет использования кавычек-ёлочек, и код должен работать как нужно.
cid name type notnull dflt_value pk
0 0 index INTEGER 0 None 0
1 1 uid TEXT 0 None 0
2 2 labname TEXT 0 None 0
3 3 first_commit_ts TIMESTAMP 0 None 0
4 4 first_view_ts TIMESTAMP 0 None 0
index uid labname first_commit_ts <br/>0 3 user_17 project1 2020-04-18 07:56:45.408648
1 4 user_30 laba04 2020-04-18 13:36:53.971502
2 7 user_30 laba04s 2020-04-18 14:51:37.498399
3 8 user_14 laba04 2020-04-18 15:14:00.312338
4 11 user_14 laba04s 2020-04-18 22:30:30.247628
5 18 user_19 laba04 2020-04-20 19:05:01.297780
6 19 user_25 laba04 2020-04-20 19:16:50.673054
7 20 user_21 laba04 2020-04-21 17:48:00.487806
8 21 user_30 project1 2020-04-22 12:36:24.053518
9 23 user_21 laba04s 2020-04-22 20:09:21.857747
first_view_ts
0 2020-04-18 10:56:55.833899
1 2020-04-17 22:46:26.785035
2 2020-04-17 22:46:26.785035
3 2020-04-18 10:53:52.623447
4 2020-04-18 10:53:52.623447
5 2020-04-21 20:30:38.034966
6 2020-05-09 23:54:54.260791
7 2020-04-22 22:40:36.824081
8 2020-04-17 22:46:26.785035
9 2020-04-22 22:40:36.824081
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2017 try:
-> 2018 cur.execute(*args, **kwargs)
2019 return cur
OperationalError: no such column: deadlines.deadline
The above exception was the direct cause of the following exception:
DatabaseError Traceback (most recent call last)
3 frames
/usr/local/lib/python3.10/dist-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
2028
2029 ex = DatabaseError(f"Execution failed on sql ‘{args[0]}’: {exc}")
-> 2030 raise ex from exc
2031
2032 @staticmethod
DatabaseError: Execution failed on sql ‘
SELECT uid, test.labname, MIN((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’: no such column: deadlines.deadline
Извините, я сделал еще одну ошибку в коде. Похоже, что я не запустил таблицу deadlines перед запросами к ней. Здесь исправленный код с конкретной строкой conn.commit() после создания таблицы deadlines:
import sqlite3
import pandas as pd
# Открываем соединение с базой данных
conn = sqlite3.connect(‘/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
# Получаем схему таблицы test
test_schema = pd.read_sql(“PRAGMA table_info(test)”, conn)
print(test_schema)
# Получаем первые 10 строк таблицы test
test_head = pd.read_sql(“SELECT * FROM test LIMIT 10”, conn)
print(test_head)
# Создаем таблицу deadlines
deadlines_sql = ‘’‘
CREATE TABLE IF NOT EXISTS deadlines AS
SELECT ‘laba01’ AS labname, ‘2020-04-15 13:00:00’ AS deadline UNION
SELECT ‘laba02’, ‘2020-10-15 13:00:00’ UNION
SELECT ‘laba03’, ‘2020-10-22 13:00:00’ UNION
SELECT ‘laba04’, ‘2020-10-29 13:00:00’ UNION
SELECT ‘laba06’, ‘2020-11-12 13:00:00’
’‘’
conn.execute(deadlines_sql)
conn.commit()
# Находим минимальное значение дельты
min_delta_sql = ‘’‘
SELECT uid, test.labname, MIN((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [min_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_min = pd.read_sql(min_delta_sql, conn)
print(df_min)
# Находим максимальное значение дельты
max_delta_sql = ‘’‘
SELECT uid, test.labname, MAX((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [max_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
GROUP BY uid
’‘’
df_max = pd.read_sql(max_delta_sql, conn)
print(df_max)
# Находим среднее значение дельты
avg_delta_sql = ‘’‘
SELECT AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) [avg_delta]
FROM test
JOIN deadlines ON test.labname = deadlines.labname
WHERE test.labname != ‘project1’
’‘’
df_avg = pd.read_sql(avg_delta_sql, conn)
print(df_avg)
# Создаем таблицу views_diff
views_diff_sql = ‘’‘
SELECT test.uid, AVG((julianday(deadlines.deadline)-julianday(first_commit_ts))*24) avg_diff, COUNT(pageviews.datetime) pageviews
FROM test
JOIN deadlines ON test.labname = deadlines.labname
LEFT JOIN pageviews ON test.uid = pageviews.uid
WHERE test.labname != ‘project1’
GROUP BY test.uid
’‘’
views_diff = pd.read_sql(views_diff_sql, conn)
print(views_diff)
# Рассчитываем коэффициент корреляции между количеством просмотров и значением дельты
correlation_coefficient = views_diff[‘avg_diff’].corr(views_diff[‘pageviews’])
print(“Коэффициент корреляции:”, correlation_coefficient)
# Закрываем соединение с базой данных
conn.close()
Этот код должен исправить ошибку “no such column” и сработать должным образом. Sorry again for the confusion.
Вот этот код подходит для решения задачи? Код: pd.io.sql.read_sql(‘PRAGMA table_info(test)’, conn) pd.io.sql.read_sql(‘select * from test limit 10’, conn) df_min = pd.io.sql.read_sql(‘’‘
select uid, min((strftime(’%s’, first_commit_ts) - deadlines)/3600) as delta
from
(select *
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
df_min df_max = pd.io.sql.read_sql(’‘’
select uid, max((strftime(‘%s’, first_commit_ts) - deadlines)/3600) as delta
from
(select *
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
df_max df_avg = pd.io.sql.read_sql(’‘’
select uid, avg((deadlines - strftime(‘%s’, first_commit_ts))/60/60) as delta
from
(select
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
df_avg views_diff = pd.io.sql.read_sql(’‘’
select t1.uid, avg_diff, pageviews
from
(
select uid, avg((deadlines - strftime(‘%s’, first_commit_ts))/60/60) as avg_diff from
((select * from test
where labname not like (‘project1’)) as t
left join deadlines as d on labname = labs)
group by uid) as t1
left join
(select uid, count() as pageviews
from pageviews
group by uid) as t2
on t1.uid = t2.uid
‘’', conn)
views_diff views_diff.corr() conn.close()
Да, этот код также должен подходить для решения вашей задачи, используя другой подход для вычисления дельты (разница между начальным временем и дедлайном) прямо в запросе SQL.
Однако, перед использованием кода, следует удалить пробелы в начале каждой строки и перед и после операторов ‘’‘’‘, чтобы строка кода соответствовала правильному форматированию Python.
Вот исправленный код:
import pandas as pd
import sqlite3
conn = sqlite3.connect(’/content/drive/MyDrive/School21/day10/checking-logs.sqlite’)
pd.io.sql.read_sql(‘PRAGMA table_info(test)’, conn)
pd.io.sql.read_sql(‘select * from test limit 10’, conn)
df_min = pd.io.sql.read_sql(‘’‘
select uid, min((strftime(’%s’, first_commit_ts) - deadlines)/3600) as delta
from
(select *
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
print(df_min)
df_max = pd.io.sql.read_sql(’‘’
select uid, max((strftime(‘%s’, first_commit_ts) - deadlines)/3600) as delta
from
(select *
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
print(df_max)
df_avg = pd.io.sql.read_sql(’‘’
select uid, avg((deadlines - strftime(‘%s’, first_commit_ts))/60/60) as delta
from
(select
from test
where labname not like (‘project1’)) as t
left join deadlines
on labname = labs
‘’‘, conn)
print(df_avg)
views_diff = pd.io.sql.read_sql(’‘’
select t1.uid, avg_diff, pageviews
from
(
select uid, avg((deadlines - strftime(‘%s’, first_commit_ts))/60/60) as avg_diff from
((select * from test
where labname not like (‘project1’)) as t
left join deadlines as d on labname = labs)
group by uid) as t1
left join
(select uid, count() as pageviews
from pageviews
group by uid) as t2
on t1.uid = t2.uid
‘’', conn)
print(views_diff)
print(views_diff.corr())
conn.close()
Этот код также обрабатывает задачу, используя запросы SQL для вычисления минимального, максимального и среднего значения, а также корреляции между данными.
|
5bc57be922fb4bdb1a133b5f12845799
|
{
"intermediate": 0.22960597276687622,
"beginner": 0.5180831551551819,
"expert": 0.25231093168258667
}
|
10,261
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorSetLayout samplerDescriptorSetLayout;// = VK_NULL_HANDLE;
void CleanupDescriptorSetLayout();
void CleanupSamplerDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->samplerDescriptorSetLayout = samplerDescriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
CleanupSamplerDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
void Material::CleanupSamplerDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && samplerDescriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, samplerDescriptorSetLayout, nullptr);
samplerDescriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
//Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
A portion of GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
A portion of Texture.cpp:
Texture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
Cleanup();
}
void Texture::Cleanup()
{
if (!initialized) {
return;
}
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
sampler = VK_NULL_HANDLE;
}
if (imageView != VK_NULL_HANDLE) {
vkDestroyImageView(device, imageView, nullptr);
imageView = VK_NULL_HANDLE;
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
image = VK_NULL_HANDLE;
}
if (imageMemory != VK_NULL_HANDLE) {
vkFreeMemory(device, imageMemory, nullptr);
imageMemory = VK_NULL_HANDLE;
}
initialized = false;
}
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting this error in Renderer::CleanupDevice when trying to close the application:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x250768af840, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0x149d740000000087, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x250768af840[], VkDescriptorSetLayout 0x149d740000000087[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x250768af840, type: 3, name: NULL
[1] 0x149d740000000087, type: 20, name: NULL
What might be causing this issue and how can I fix it? I have checked through breakpoints in debug mode that Materials::Cleanup is destroying the descriptorsetlayouts.
|
747b89dcf4b2ab39e4dc8700a614b463
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,262
|
Would you please give me MEL script to create Pikachu ?
|
0cdc740bee8a372cc4165e4984e1a4d9
|
{
"intermediate": 0.3858785927295685,
"beginner": 0.20346055924892426,
"expert": 0.41066086292266846
}
|
10,263
|
flask code to create a bitcoin monitoring app
|
617594d047161eaebc30d75dcf0517cd
|
{
"intermediate": 0.45058155059814453,
"beginner": 0.22026018798351288,
"expert": 0.3291582465171814
}
|
10,264
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime(“%m/%d/%Y %H:%M:%S”)
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ‘’
API_SECRET = ‘’
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = ‘SELL’
POSITION_SIDE_LONG = ‘BUY’
quantity = 1
symbol = ‘BTC/USDT’
order_type = ‘MARKET’
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
‘apiKey’: ‘’,
‘secret’: ‘’,
‘enableRateLimit’: True, # enable rate limitation
‘options’: {
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
}
})
binance_futures = ccxt.binance({
‘apiKey’: API_KEY,
‘secret’: API_SECRET,
‘enableRateLimit’: True, # enable rate limitation
‘options’: {
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = “https://fapi.binance.com/fapi/v1/klines”
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace(“/”, “”) # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}“
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print(‘No data found for the given timeframe and symbol’)
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(‘%Y-%m-%d %H:%M:%S’)
ohlc.append({
‘Open time’: timestamp,
‘Open’: float(d[1]),
‘High’: float(d[2]),
‘Low’: float(d[3]),
‘Close’: float(d[4]),
‘Volume’: float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index(‘Open time’, inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f’Error in get_klines: {e}')
return None
df = get_klines(symbol, ‘1m’, 89280)
def signal_generator(df):
if df is None:
return “”
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return ‘sell’
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return ‘buy’
# No clear pattern
else:
return “”
df = get_klines(symbol, ‘1m’, 89280)
def order_execution(symbol, signal, step_size, leverage):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position[“symbol”] == symbol:
current_position = position
if current_position is not None and current_position[“positionAmt”] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side=‘SELL’ if current_position[“positionSide”] == “LONG” else ‘BUY’,
type=‘MARKET’,
quantity=abs(float(current_position[“positionAmt”])),
positionSide=current_position[“positionSide”],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
# Set default take profit price
take_profit_price = None
if signal == ‘buy’:
position_side = ‘BOTH’
opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘SHORT’ else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if ‘askPrice’ in ticker:
price = ticker[‘askPrice’]
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == ‘sell’:
position_side = ‘BOTH’
opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘LONG’ else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if ‘askPrice’ in ticker:
price = ticker[‘askPrice’]
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == ‘buy’:
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == ‘sell’:
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}”)
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position[‘positionAmt’]) < quantity:
quantity = abs(opposite_position[‘positionAmt’])
# Place order
order_params = {
“side”: “BUY” if signal == “buy” else “SELL”,
“type”: order_type,
“positionSide”: position_side,
“quantity”: quantity,
“price”: price,
“stopPrice”: stop_loss_price if signal == “buy” else take_profit_price,
“reduceOnly”: False,
“newOrderRespType”: “RESULT”,
“workingType”: “MARK_PRICE”,
“priceProtect”: False,
“leverage”: leverage
}
try:
order_params[‘symbol’] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}“)
except BinanceAPIException as e:
print(f"Error in order_execution: {e}”)
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, ‘1m’, 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S’)} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Traceback (most recent call last):
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py”, line 559, in fetch
response.raise_for_status()
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py”, line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1685957172459&recvWindow=10000&signature=8cb950fe580239c2a765e669e2413a3f183217bb81ba1f3425d3a9a2157801d2
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 58, in <module>
markets = binance_futures.load_markets()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py”, line 1390, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py”, line 1705, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py”, line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py”, line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py”, line 2862, in fetch2
return self.fetch(request[‘url’], request[‘method’], request[‘headers’], request[‘body’])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py”, line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py”, line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions[‘exact’], error, feedback)
File “C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py”, line 3172, in throw_exactly_matched_exception
raise exactstring
ccxt.base.errors.InvalidNonce: binance {“code”:-1021,“msg”:“Timestamp for this request was 1000ms ahead of the server’s time.”}
|
774db26fe1288dbe2f6d4aeea5990115
|
{
"intermediate": 0.46546217799186707,
"beginner": 0.4244183599948883,
"expert": 0.11011945456266403
}
|
10,266
|
how to setup swagger.io in a non spring java app
|
bcf708f3db731c4af274db741f8d8e67
|
{
"intermediate": 0.5170695781707764,
"beginner": 0.20914389193058014,
"expert": 0.2737864553928375
}
|
10,267
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->descriptorPool = descriptorPool;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
//material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
//material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
material->UpdateBufferBinding(mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
The code is currently exiting in GameObject::Render saying "Failed to allocate descriptor sets!". Do you know what could eb causing this issue and how to fix it?
|
85c532b9beda3f781eef9e62c770f4f4
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,268
|
Class Diagram:
Classes and Attributes:
1. User
- userId (integer)
- userName (string)
- email (string)
- password (string)
- userType (enumeration: Student, Admin, Instructor)
2. Course
- courseId (integer)
- courseName (string)
- courseInfo (string)
- courseNews (string)
3. Instructor
- instructorId (integer)
- instructorName (string)
- sections (list of integer) // Section IDs
4. Section
- sectionId (integer)
- sectionName (string)
- instructorId (integer)
- courses (list of integer) // Course IDs
5. Group
- groupId (integer)
- groupName (string)
- groupMembers (list of integer) // User IDs
Relationships/Associations:
1. User (1) – (0…) UserGroupRelationship
2. Group (1) – (0…) UserGroupRelationship
3. Course (1) – (0…) Section
4. Instructor (1) – (0…) Section
5. User (1) – (0…) CourseRegistration
6. Course (1) – (0…) CourseRegistration
Auxiliary Classes:
1. UserGroupRelationship
- userId (integer)
- groupId (integer)
2. CourseRegistration
- userId (integer)
- courseId (integer)
Enumerations:
1. UserType
- Student
- Admin
- Instructor
Notes:
- In the given scenario, Users can be of different types: Student, Admin or Instructor.
- The system allows browsing for Courses, Instructors, and Sections (which belong to Instructors).
- The Data entities are User, Course (with associated Info and News), Instructor, Group, and Section.
- Users can register to Courses after signing up in the application. When a User signs up, their request will either be approved or rejected, depending on the User’s credentials. If approved, the User will receive access to all their relevant information.
This Class Diagram represents the structure of the classes and relationships between them but does not represent specific methods or functions.
for above class diagram write me PLANTUML CODE
|
5a40fa00dc7fed2e57cca2d16adbdf74
|
{
"intermediate": 0.3346664011478424,
"beginner": 0.3222912847995758,
"expert": 0.3430423438549042
}
|
10,269
|
suggest me a diagram for my below scenario with relevant features and methods:
for this website
class student and instructor can register and register include check username and extend invalied username class student.
class student and instructor can also login and login include check password and username and extend invalied username and password.
class student and instructor and admin can browse and browse include courses and course news and instructors lists and sections.
class student and instructor and admin can do communications and communications include students and instrustors.
class student and instructor and admin can also create posts groups and schedules.
class instructor and admin can do delete posts and groups and schedules.
class instructor and admin can modify posts groups and schedules.
class admin can check user information
|
e2fa2c77240fdd3e33fc59c78a0599d1
|
{
"intermediate": 0.3389047086238861,
"beginner": 0.3198275864124298,
"expert": 0.3412677049636841
}
|
10,270
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->descriptorPool = descriptorPool;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Initialize2(Renderer& renderer);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
VkDeviceMemory mvpBufferMemory;
VkBuffer mvpBuffer;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Initialize2(Renderer& renderer)
{
auto [mvpBuffer2, mvpBufferMemory2] = renderer.RequestMvpBuffer();
mvpBuffer = mvpBuffer2;
mvpBufferMemory = mvpBufferMemory2;
material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
//auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
//material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
//material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
//material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
material->UpdateBufferBinding(mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the current error while rendering:
VUID-vkUpdateDescriptorSets-None-03047(ERROR / SPEC): msgNum: 903342744 - Validation Error: [ VUID-vkUpdateDescriptorSets-None-03047 ] Object 0: handle = 0x980b0000000002e, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0x35d7ea98 | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0x980b0000000002e[] with error: Cannot call vkUpdateDescriptorSets() to perform write update on VkDescriptorSet 0x980b0000000002e[] allocated with VkDescriptorSetLayout 0x95a125000000001a[] that is in use by a command buffer. The Vulkan spec states: Descriptor bindings updated by this command which were created without the VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT or VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT bits set must not be used by any command that was recorded to a command buffer which is in the pending state (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkUpdateDescriptorSets-None-03047)
Objects: 1
[0] 0x980b0000000002e, type: 23, name: NULL
What is causing this issue and how can I fix it? I believe it may be trying to update descriptorsets while they are still in use.
|
df887645d6dfd100277217ce0211f1d9
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,271
|
in python how to record log
|
b4ea61e23b2935f8cf883dded21050ec
|
{
"intermediate": 0.5605159997940063,
"beginner": 0.13753286004066467,
"expert": 0.3019511103630066
}
|
10,272
|
suggest me a java uml diagram for my below scenario with relevant features and methods:
for this website
class student and instructor can register and register include check username and extend invalied username class student.
class student and instructor can also login and login include check password and username and extend invalied username and password.
class student and instructor and admin can browse and browse include courses and course news and instructors lists and sections.
class student and instructor and admin can do communications and communications include students and instrustors.
class student and instructor and admin can also create posts groups and schedules.
class instructor and admin can do delete posts and groups and schedules.
class instructor and admin can modify posts groups and schedules.
class admin can check user information
|
c1dc3d8164303871ffb49ff86770f770
|
{
"intermediate": 0.41202443838119507,
"beginner": 0.3048616945743561,
"expert": 0.28311389684677124
}
|
10,273
|
this is the main of my application "import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'login_logic.dart';
import 'signup_logic.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bienvenue à Attendance Manager!',
builder: EasyLoading.init(),
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginSignupPage(),
);
}
}
class LoginSignupPage extends StatefulWidget {
@override
_LoginSignupPageState createState() => _LoginSignupPageState();
}
class _LoginSignupPageState extends State<LoginSignupPage> {
bool _isLoginForm = true;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _usernameController = TextEditingController();
String _selectedRole = 'Admin';
List<String> _roleOptions = ['Admin', 'Etudiant', 'Enseignant'];
final TextEditingController _matriculeController = TextEditingController();
void _toggleFormMode() {
setState(() {
_isLoginForm = !_isLoginForm;
});
}
final loginLogic = LoginLogic();
void _login() async {
print('_login method called');
try {
final response = await loginLogic.login(
_usernameController.text,
_passwordController.text,
);
await loginLogic.handleResponse(context, response);
} catch (e) {
// Handle any network or server errors
}
}
final _signupLogic = SignupLogic();
Future<void> _signup() async {
try {
final response = await _signupLogic.registerUser(
context,
_emailController.text,
_usernameController.text,
_passwordController.text,
_selectedRole,
_matriculeController.text,
);
if (response.statusCode == 200 || response.statusCode == 201) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Compte créé avec succès'),
actions: <Widget>[
ElevatedButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
print('Registration success');
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Erreur'),
content: Text('Veuillez remplir tous les champs et réessayez'),
actions: <Widget>[
ElevatedButton(
child: Text('OK'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
print('Received signup response with status code: ${response.statusCode}');
}
} catch (e) {
// handle network or server errors
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_isLoginForm ? 'Se connecter' : 'Créer un compte'),
),
body: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(height: 48.0),
if (_isLoginForm)
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
labelText: "Nom d'utilisateur",
hintText: "Entrez votre nom d'utilisateur",
),
),
if (!_isLoginForm)
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'Email',
hintText: 'Entrez votre addresse e-mail',
),
),
SizedBox(height: 16.0),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Mot de passe',
hintText: 'Entrez votre mot de passe',
),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
TextFormField(
controller: _usernameController,
decoration: InputDecoration(
labelText: "nom d'utilisateur",
hintText: "Entrez votre nom d'utilisateur",
),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
DropdownButtonFormField<String>(
decoration: InputDecoration(
labelText: 'Role',
hintText: 'Sélectionnez votre rôle',
),
value: _selectedRole,
onChanged: (String? value) {
setState(() {
_selectedRole = value!;
});
},
items: _roleOptions.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
SizedBox(height: 16.0),
if (!_isLoginForm)
TextFormField(
controller: _matriculeController,
decoration: InputDecoration(
labelText: 'Matricule',
hintText: 'Entrez votre matricule',
),
),
SizedBox(height: 48.0),
ElevatedButton(
child: Text(_isLoginForm ? 'Se connecter' : 'Créer un compte'),
onPressed: () {
print('Login button pressed');
if (_isLoginForm) {
_login();
} else {
_signup();
}
},
),
TextButton(
child: Text(_isLoginForm
? 'Ou créer un compte'
: 'Vouz avez un compte? vous pouvez vous connecter'),
onPressed: _toggleFormMode,
),
],
),
),
),
);
}
}" using this "
import 'dart:convert';
import 'package:attendance_app/profile_admin_screen.dart';
import 'package:attendance_app/profile_enseignant_screen.dart';
import 'package:attendance_app/profile_etudiant_screen.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'constants.dart';
class LoginLogic {
static const String _jwtKey = 'watchme';
static String get jwtKey => _jwtKey;
static final _storage = FlutterSecureStorage();
static FlutterSecureStorage get storage => _storage;
Future<http.Response> login(String email, String password) async {
if (email.isEmpty && password.isEmpty) {
return Future.error('Veuillez remplir les champs de l\'identifiant et du mot de passe');
} else if (email.isEmpty) {
return Future.error('Veuillez remplir le champ de l\'identifiant');
} else if (password.isEmpty) {
return Future.error('Veuillez remplir le champ du mot de passe');
}
print('Starting login request with email: $email and password: $password');
final data = {
'userName': email,
'password': password,
};
final jsonData = jsonEncode(data);
try {
final response = await http.post(
Uri.parse('$endpointUrl/login'),
headers: {'Content-Type': 'application/json'},
body: jsonData,
).timeout(Duration(seconds: 5));
print('Received login response with status code: ${response.statusCode}');
return response;
} on TimeoutException catch (e) {
return Future.error('La requête a expiré');
} catch (e) {
return Future.error('Échec de la connexion');
}
}
Future<void> handleResponse(BuildContext context, http.Response response) async {
if (response.statusCode == 200) {
final responseBody = json.decode(response.body);
final token = responseBody['token'];
try {
await _storage.write(key: _jwtKey, value: token);
} catch (e) {
print('Error writing token to storage: $e');
}
print('Token generated and written to storage: $token');
String? role = await getUserRole();
if (role != null) {
if (role.toLowerCase() == 'etudiant') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileEtudiantScreen()));
} else if (role.toLowerCase() == 'enseignant') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileEnseignantScreen()));
} else if (role.toLowerCase() == 'administrateur') {
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => ProfileAdminScreen()));
} else {
print('Invalid role: $role');
}
} else {
print('Role not found in response');
}
} else if (response.statusCode == 401) {
final responseBody = json.decode(response.body);
var message = responseBody['message'];
if (message == null) {
message = 'Une erreur s\'est produite lors de la connexion.';
} else if (message == 'Veuillez remplir les champs de l\'identifiant et du mot de passe') {
message = 'Veuillez remplir les champs de l\'identifiant et du mot de passe';
} else if (message == 'Veuillez remplir le champ de l\'identifiant') {
message = 'Veuillez remplir le champ de l\'identifiant';
} else if (message == 'Veuillez remplir le champ du mot de passe') {
message = 'Veuillez remplir le champ du mot de passe';
}
print('Response message: $message');
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Erreur'),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
),
);
} else {
print('Response status code: ${response.statusCode}');
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text('Erreur'),
content: Text('Une erreur s\'est produite lors de la connexion.'),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('OK'),
),
],
),
);
}
}
static Future<String?> getToken() async {
try {
final token = await _storage.read(key: _jwtKey);
return token;
} catch (e) {
print('Error reading token from storage: $e');
return null;
}
}
Future<String?> getUserRole() async {
final token = await getToken();
if (token != null) {
try {
final response = await http.get(
Uri.parse('$endpointUrl/getusernamerole'),
headers: {'Authorization': 'Bearer $token'},
);
if (response.statusCode == 200) {
final responseBody = json.decode(response.body);
final role = responseBody['role'];
return role;
} else {
print('Failed to retrieve user role');
return null;
}
} catch (e) {
print('Error fetching user role: $e');
return null;
}
} else {
print('No token found');
return null;
}
}
}
" and this "import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'constants.dart' as Constants;
class SignupLogic {
Future<http.Response> registerUser(BuildContext context,String email, String username, String password, String role, String matricule) async {
final url = Uri.parse('${Constants.endpointUrl}/register');
final headers = <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
};
final body = jsonEncode(<String, String>{
'email': email,
'username': username,
'password': password,
'role': role,
'matricule': matricule,
});
final response = await http.post(url, headers: headers, body: body);
print('Received Registration response with status code: ${response.statusCode}');
if (response.statusCode == 201) {
Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false);
return response;
} else {
// Handle errors
print('Received Registration response with status code: ${response.statusCode}');
return response;
}
}
}
", I want to encapsulate as maximum as possible the login and signup logics in their files while keeping the main less dense, can you suggest the most efficient, concise implementations of the 3 pieces of code while providing me with the full versions of those 3 files ?
|
bdc694755750b46f42ad46f3ee04eeb6
|
{
"intermediate": 0.41544318199157715,
"beginner": 0.48936721682548523,
"expert": 0.09518957883119583
}
|
10,274
|
suggest me a java uml diagram for my below scenario with relevant features and methods:
for this website
class student and instructor can register and register include check username and extend invalied username class student.
class student and instructor can also login and login include check password and username and extend invalied username and password.
class student and instructor and admin can browse and browse include courses and course news and instructors lists and sections.
class student and instructor and admin can do communications and communications include students and instrustors.
class student and instructor and admin can also create posts groups and schedules.
class instructor and admin can do delete posts and groups and schedules.
class instructor and admin can modify posts groups and schedules.
class admin can check user information
|
2080d7be9aa766e84efe2b777a7292a7
|
{
"intermediate": 0.41202443838119507,
"beginner": 0.3048616945743561,
"expert": 0.28311389684677124
}
|
10,275
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
# Set default take profit price
take_profit_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Place order
order_params = {
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: BTC/USDT found in the market
The signal time is: 2023-06-05 14:46:57 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 245, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 219, in order_execution
"positionSide": position_side,
^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'position_side' where it is not associated with a value
|
54d414742f7beadb5e2762c29856c8b0
|
{
"intermediate": 0.4816868305206299,
"beginner": 0.340833455324173,
"expert": 0.17747965455055237
}
|
10,276
|
In Julia I want to visualise how that function works:
eshold
stacja_oddania = argmin(wynik_sim[1])
stacja_odebrania = i
wynik_sim[1][i] -= transport_bikes
wynik_sim[3][i] += 1
ETA = times + rand(Gamma(czas_dowozu[stacja_odebrania, stacja_oddania][1], 1.2))
new_row = DataFrame(stacja_oddania=stacja_oddania, czas=ETA)
for _ in 1:transport_bikes
journey = vcat(journey, new_row)
end
transport = ETA + 20
break
end
end
end
end
# Finish journeys
for row in eachrow(journey)
wynik_sim[1][row.stacja_oddania] += 1
end
return wynik_sim
end
What should I use?
|
dcdd4b73c8e8064356f441c7f5a002d7
|
{
"intermediate": 0.5019881129264832,
"beginner": 0.30291667580604553,
"expert": 0.19509515166282654
}
|
10,277
|
optimiere den Code. Außerdem behebe das Fehler. Es wird versucht den Kameracontroller zu verwerfen, obwohl er schon verworfen wurde.
Wie und wo behebe ich das? Erkläre es ausführlich und lass nichts weg.
typedef QrScanResultCallback = Future<bool> Function(ScanResult);
// see https://pub.dev/packages/code_scan/example
class QrScanner extends StatefulWidget {
const QrScanner(
{Key? key, required this.callback, required this.backButtonCallback})
: super(key: key);
final QrScanResultCallback callback;
final BackButtonCallback backButtonCallback;
@override
State<QrScanner> createState() => _QrScannerState();
}
class _QrScannerState extends State<QrScanner> with WidgetsBindingObserver {
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
late AppLocalizations _l10n;
// prevent over processing
bool processingInProgress = false;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
color: AppColors.opascaBlue,
child: _buildQrView(),
);
}
Widget _buildQrView() {
return CodeScanner(
key: qrKey,
formats: const [BarcodeFormat.qrCode],
scanInterval: const Duration(milliseconds: 500),
onScan: (code, _, listener) {
if (code != null) {
if (processingInProgress == false) {
processingInProgress = true;
widget.callback(ScanResult(code)).then((isValidCode) {
if (mounted && !isValidCode) {
processingInProgress = false;
}
});
}
}
},
onAccessDenied: (_, controller) {
_showPermissionNotGrantedDialog()
.then((_) => widget.backButtonCallback());
return false;
},
onError: (_, __) {
_showQrCodeReadErrorDialog();
},
overlay: Container(),
);
}
Future<dynamic> _showQrCodeReadErrorDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(_l10n.accountLinking_QrCodeScannerDialogTitle),
content: Text(_l10n.accountLinking_QrCodeScannerDialogDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
Future<dynamic> _showPermissionNotGrantedDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
_l10n.accountLinking_QrCodeScannerMissingCameraPermissionTitle),
content: Text(_l10n
.accountLinking_QrCodeScannerMissingCameraPermissionDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/modules/account_linking/account_linking_state_manager.dart';
import 'package:patient_app/modules/account_linking/widgets/qr_scanner.dart'
if (dart.library.html) 'package:patient_app/modules/account_linking/widgets/qr_scanner_mock.dart';
import 'package:patient_app/modules/account_linking/widgets/qr_scanner_unmaintained.dart'
as qr_code_scanner_unmaintained;
import 'package:patient_app/settings.dart' as settings;
import 'package:patient_app/theme/patient_app_theme.dart' as theme;
import 'package:provider/provider.dart';
class AccountLinkingQrCodeScannerScreen extends StatefulWidget {
static MaterialPage page() {
return const MaterialPage(
name: "QrCodeScanner",
key: ValueKey("QrCodeScanner"),
child: AccountLinkingQrCodeScannerScreen(),
);
}
const AccountLinkingQrCodeScannerScreen({Key? key}) : super(key: key);
@override
State<AccountLinkingQrCodeScannerScreen> createState() =>
_AccountLinkingQrCodeScannerScreenState();
}
class _AccountLinkingQrCodeScannerScreenState
extends State<AccountLinkingQrCodeScannerScreen> {
late AppLocalizations _l10n;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
alignment: Alignment.center,
fit: StackFit.expand,
children: <Widget>[
_buildQrScannerArea(),
_buildMainContent(),
],
),
);
}
Widget _buildMainContent() {
return Padding(
padding: theme.commonEdgeInsets,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: theme.extraLargeSpacing,
),
Text(
_l10n.accountLinking_QrCodeScannerScreenTitle,
style: theme.lightHeadline1,
),
const SizedBox(height: theme.extraSmallSpacing),
Text(
_l10n.accountLinking_QrCodeScannerScreenDescription,
style: theme.lightBodyText2,
),
const Spacer(),
Center(
child: ElevatedButton(
onPressed: () {
context.read<AccountLinkingStateManager>().deleteState();
},
style: Theme.of(context).elevatedButtonTheme.style,
child: Text(_l10n.general_cancelButtonLabel),
),
),
],
),
);
}
Widget _buildQrScannerArea() {
Widget child = settings.useUnmaintainedQrScanner
? qr_code_scanner_unmaintained.QrScanner(
callback: _handleResult, backButtonCallback: _backButtonCallback)
: QrScanner(
callback: _handleResult,
backButtonCallback: _backButtonCallback,
);
return Positioned.fill(
child: child,
);
}
Future<bool> _handleResult(ScanResult scanResult) async {
if (isValid(scanResult)) {
context.read<AccountLinkingStateManager>().updateScanResult(scanResult);
return true;
} else {
return false;
}
}
// prevent qr code fragments to be accepted
// Large qr codes could result in partially identified qr codes,
// they are too short to be accepted
bool isValid(ScanResult scanResult) => scanResult.qrCodeAsString.length > 16;
void _backButtonCallback() {
context.read<AccountLinkingStateManager>().deleteState();
}
}
|
6cb71d131145b44822915f21a94e6cf6
|
{
"intermediate": 0.3920040428638458,
"beginner": 0.4938142001628876,
"expert": 0.1141817569732666
}
|
10,278
|
User
How can I sue this rect query hook to only call it when a form is submitted
export const useListEvents = (
data: EventSearchFormValues,
from: number,
size: number,
): UseListEventsInterface => {
const { t } = useTranslation();
const {
result,
branchStatus: status,
refetch,
} = useQueryWrapper<PaginatedResponse<SportingEvent>, EventSearchFormValues>(
[manualActionsHooks.listEvents, data],
() => postListEventsAPI(data, from, size),
{
meta: {
errorMessage: pleaseTryAgainMessage(
t,
'listing the activity log search results',
),
},
},
);
return { result, status, refetch };
};
|
16497daae388d91921058e4f5d3fa487
|
{
"intermediate": 0.6248721480369568,
"beginner": 0.2657393515110016,
"expert": 0.10938842594623566
}
|
10,279
|
elasticsearch IP format verify code
|
7aeef5d90e7bc2b35a2000837664fb0b
|
{
"intermediate": 0.2845268249511719,
"beginner": 0.3233383297920227,
"expert": 0.39213478565216064
}
|
10,280
|
c# access ffmpeg code example
|
8ef65d0dcb551c3f4e149632ba223fdc
|
{
"intermediate": 0.43409213423728943,
"beginner": 0.2819277346134186,
"expert": 0.2839801013469696
}
|
10,281
|
Classes cannot directly extend record kotkin
|
4bb76f872d773dbecb8824c1305b3e38
|
{
"intermediate": 0.2579082250595093,
"beginner": 0.582808256149292,
"expert": 0.15928354859352112
}
|
10,282
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::Cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
VkDescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
VkDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
this->descriptorPool = descriptorPool;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::Cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::Cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
if (pipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
pipelineLayout = VK_NULL_HANDLE;
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
fragmentShader = std::shared_ptr<Shader>(new Shader, ShaderDeleter());
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (device != VK_NULL_HANDLE && descriptorSetLayout != VK_NULL_HANDLE)
{
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
descriptorSetLayout = VK_NULL_HANDLE;
}
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
Shutdown();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
//camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
camera.Initialize(800.0f / 600.0f);
camera.SetPosition(glm::vec3(0.0f, 0.0f, 5.0f));
camera.SetRotation(glm::vec3(0.0f, 0.0f, 0.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
temp = temp + 0.01;
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
//camera.SetRotation(glm::vec3(0, 0, temp));
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Shutdown(); // Make sure to call Shutdown() on the game objects
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Initialize2(Renderer& renderer);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
VkDeviceMemory mvpBufferMemory;
VkBuffer mvpBuffer;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Initialize2(Renderer& renderer)
{
auto [mvpBuffer2, mvpBufferMemory2] = renderer.RequestMvpBuffer();
mvpBuffer = mvpBuffer2;
mvpBufferMemory = mvpBufferMemory2;
material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
//auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
//material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
//material->CreateDescriptorSet(mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
vkDeviceWaitIdle(device);
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
//material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
material->UpdateBufferBinding(mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
if (material) {
material->Cleanup();
delete material;
material = nullptr;
}
if (mesh) {
delete mesh;
mesh = nullptr;
}
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
A portion of Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::CleanupDevice()
{
// Reset the pipeline first to ensure it’s destroyed before the device
pipeline.reset();
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the current error while closing the application:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1c1eb894d30, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0xcb1c7c000000001b, type = VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1c1eb894d30[], VkDescriptorSetLayout 0xcb1c7c000000001b[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1c1eb894d30, type: 3, name: NULL
[1] 0xcb1c7c000000001b, type: 20, name: NULL
What is causing this issue and how can I fix it?
|
4bb38ba97a32eb8c601245390a1ebc4a
|
{
"intermediate": 0.279109388589859,
"beginner": 0.4491756856441498,
"expert": 0.27171486616134644
}
|
10,283
|
write me code for a basic discord bot
|
0056d7aaf054259f199b423e9c27a95b
|
{
"intermediate": 0.1869179606437683,
"beginner": 0.37586134672164917,
"expert": 0.4372207522392273
}
|
10,284
|
can you redo grid coordinates here. for example, make the same array with vertices and edges as a grid on whole canvas, but this array of vertices and edges will be static and attached at the center of this editable cube array of vertices and edges. remove all unnecessary grid code and output full modified code.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
4eeeef6440245bd7d786d039a10ce5f1
|
{
"intermediate": 0.4485781192779541,
"beginner": 0.29159796237945557,
"expert": 0.25982391834259033
}
|
10,285
|
async importQuotation(req: Request, res: Response, next: NextFunction) {
try {
console.log("Importing quotations...");
const body: ImportCleanQuotations = req.body;
const regionCode = getRegionCode(req.user!, req.query);
if (!regionCode) {
console.log("Region code is required for this operation");
return res
.status(httpStatusCodes.BAD_REQUEST)
.json(
new ResponseJSON(
"Region code is required for this operation",
true,
httpStatusCodes.BAD_REQUEST
)
);
}
const items = await Promise.all(
body.quotations.map((quotation) =>
prisma.item.findUnique({
where: {
code: quotation.itemCode,
},
select: {
UoMCode: true,
SmUCode: true,
},
})
)
);
console.log("Items: ", items);
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
console.log("Quotation: ", quotation);
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote, index) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items[index]!.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
);
await Promise.all(
quotations.reduce((acc: any, quotation, index) => {
acc.push(
tx.interpolatedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
},
})
);
acc.push(
tx.cleanedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
questionnaireId: quotation.questionnaireId,
itemCode: quotation.itemCode,
},
})
);
return acc;
}, [])
);
await tx.itemRegionalMean.createMany({
data: body.geomeans.map((mean) => ({
itemCode: mean.itemCode,
variation: mean.variation,
stdev: mean.stdev,
geomean: mean.geomean,
min: mean.min,
max: mean.max,
questionnaireId: mean.questionnaireId,
regionCode,
})),
});
return quotations;
});
console.log("Quotations created: ", createMany);
return res
.status(httpStatusCodes.OK)
.json(
new ResponseJSON(
"Quotations Created",
false,
httpStatusCodes.OK,
createMany
)
);
} catch (error) {
console.log("Error --- ", error);
next(
apiErrorHandler(
error,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
}
this function keeps throwing internal server error on the following input {
"quotations" : [
{
"itemCode": 101010101,
"questionnaireId": 17,
"marketplaceCode": 2010101,
"quotes": [
{
"price": 13,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
},
{
"price": 13.41,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
}
]
}
],
"geomeans": [
{
"itemCode": 101010101,
"variation": 0.14,
"stdev": 1.93,
"geomean": 13.99,
"min": 11.47,
"max": 16.53,
"questionnaireId": 17
}
]
} Importing quotations...
User {
id: 4,
fullName: 'new stat',
userName: 'newstat',
email: 'newstat@gmail.com',
emailVerified: false,
phoneNumber: '251978563412',
role: 4362,
accountLockedOut: false,
accessFailedCount: 0,
disabled: false,
registrantId: 2,
tokenExpireAfter: 5184000,
createdAt: 2023-05-17T11:07:23.908Z,
updatedAt: 2023-05-17T11:07:23.908Z,
marketplaceCode: null,
tempRole: null,
language: 'en',
tempRoleEndDate: null,
supervisorId: null,
branchCode: null,
regionCode: 14
}
RegionCode: 14
Items: [ { UoMCode: 'g', SmUCode: 'g' } ]
Quotation: {
itemCode: 101010101,
questionnaireId: 17,
marketplaceCode: 2010101,
quotes: [
{
price: 13,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
},
{
price: 13.41,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
}
],
status: 'BRANCH_APPROVED',
creationStatus: 'IMPORTED',
collectorId: 4
}
Error --- TypeError: Cannot read property 'UoMCode' of undefined
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1188:54
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1182:45
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1168:27
at Generator.next (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:4:12)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1166:65 {
clientVersion: '4.3.1'
} the above function throws this error how can i fix it ?
|
850109259b4e0f4e58a83ad579fbd094
|
{
"intermediate": 0.4194059371948242,
"beginner": 0.4042833149433136,
"expert": 0.1763107180595398
}
|
10,286
|
fixe das problem:
onScan: (code, _, listener) {
if (code != null) {
if (processingInProgress == false) {
processingInProgress = true;
widget.callback(ScanResult(code)).then((isValidCode) {
if (!controllerDisposed && !isValidCode) {
processingInProgress = false;
}
});
}
}
},
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/modules/account_linking/account_linking_state_manager.dart';
import 'package:patient_app/modules/account_linking/widgets/qr_scanner.dart'
if (dart.library.html) 'package:patient_app/modules/account_linking/widgets/qr_scanner_mock.dart';
import 'package:patient_app/modules/account_linking/widgets/qr_scanner_unmaintained.dart'
as qr_code_scanner_unmaintained;
import 'package:patient_app/settings.dart' as settings;
import 'package:patient_app/theme/patient_app_theme.dart' as theme;
import 'package:provider/provider.dart';
class AccountLinkingQrCodeScannerScreen extends StatefulWidget {
static MaterialPage page() {
return const MaterialPage(
name: "QrCodeScanner",
key: ValueKey("QrCodeScanner"),
child: AccountLinkingQrCodeScannerScreen(),
);
}
const AccountLinkingQrCodeScannerScreen({Key? key}) : super(key: key);
@override
State<AccountLinkingQrCodeScannerScreen> createState() =>
_AccountLinkingQrCodeScannerScreenState();
}
class _AccountLinkingQrCodeScannerScreenState
extends State<AccountLinkingQrCodeScannerScreen> {
late AppLocalizations _l10n;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
alignment: Alignment.center,
fit: StackFit.expand,
children: <Widget>[
_buildQrScannerArea(),
_buildMainContent(),
],
),
);
}
Widget _buildMainContent() {
return Padding(
padding: theme.commonEdgeInsets,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: theme.extraLargeSpacing,
),
Text(
_l10n.accountLinking_QrCodeScannerScreenTitle,
style: theme.lightHeadline1,
),
const SizedBox(height: theme.extraSmallSpacing),
Text(
_l10n.accountLinking_QrCodeScannerScreenDescription,
style: theme.lightBodyText2,
),
const Spacer(),
Center(
child: ElevatedButton(
onPressed: () {
context.read<AccountLinkingStateManager>().deleteState();
},
style: Theme.of(context).elevatedButtonTheme.style,
child: Text(_l10n.general_cancelButtonLabel),
),
),
],
),
);
}
Widget _buildQrScannerArea() {
Widget child = settings.useUnmaintainedQrScanner
? qr_code_scanner_unmaintained.QrScanner(
callback: _handleResult, backButtonCallback: _backButtonCallback)
: QrScanner(
callback: _handleResult,
backButtonCallback: _backButtonCallback,
);
return Positioned.fill(
child: child,
);
}
Future<bool> _handleResult(ScanResult scanResult) async {
if (isValid(scanResult)) {
context.read<AccountLinkingStateManager>().updateScanResult(scanResult);
return true;
} else {
return false;
}
}
// prevent qr code fragments to be accepted
// Large qr codes could result in partially identified qr codes,
// they are too short to be accepted
bool isValid(ScanResult scanResult) => scanResult.qrCodeAsString.length > 16;
void _backButtonCallback() {
context.read<AccountLinkingStateManager>().deleteState();
}
}
camera_controller.dart
void _throwIfNotInitialized(String functionName) {
if (!value.isInitialized) {
throw CameraException(
'Uninitialized CameraController',
'$functionName() was called on an uninitialized CameraController.',
);
}
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
}
code_scan.dart
/// Stops the camera image controller and image stream.
Future<void> stop() async {
await imageController.close();
if (controller.value.isStreamingImages) {
await controller.stopImageStream();
}
}
/// Alias of the `.stop()` method, for consistency with the flutter environment.
Future<void> dispose() async => await stop();
erros_patch.dart
@patch
class Error {
@patch
static String _objectToString(Object object) {
return Object._toString(object);
}
@patch
static String _stringToSafeString(String string) {
return json.encode(string);
}
@patch
StackTrace? get stackTrace => _stackTrace;
@pragma("vm:entry-point")
StackTrace? _stackTrace;
@patch
@pragma("vm:external-name", "Error_throwWithStackTrace")
external static Never _throw(Object error, StackTrace stackTrace);
}
|
392da0b47f2bfbe9bcd420e901527145
|
{
"intermediate": 0.30762407183647156,
"beginner": 0.4440648853778839,
"expert": 0.24831107258796692
}
|
10,287
|
async importQuotation(req: Request, res: Response, next: NextFunction) {
try {
console.log("Importing quotations...");
const body: ImportCleanQuotations = req.body;
const regionCode = getRegionCode(req.user!, req.query);
if (!regionCode) {
console.log("Region code is required for this operation");
return res
.status(httpStatusCodes.BAD_REQUEST)
.json(
new ResponseJSON(
"Region code is required for this operation",
true,
httpStatusCodes.BAD_REQUEST
)
);
}
const items = await Promise.all(
body.quotations.map((quotation) =>
prisma.item.findUnique({
where: {
code: quotation.itemCode,
},
select: {
UoMCode: true,
SmUCode: true,
},
})
)
);
console.log("Items: ", items);
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
console.log("Quotation: ", quotation);
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote, index) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items[index]!.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
);
await Promise.all(
quotations.reduce((acc: any, quotation, index) => {
acc.push(
tx.interpolatedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
},
})
);
acc.push(
tx.cleanedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
questionnaireId: quotation.questionnaireId,
itemCode: quotation.itemCode,
},
})
);
return acc;
}, [])
);
await tx.itemRegionalMean.createMany({
data: body.geomeans.map((mean) => ({
itemCode: mean.itemCode,
variation: mean.variation,
stdev: mean.stdev,
geomean: mean.geomean,
min: mean.min,
max: mean.max,
questionnaireId: mean.questionnaireId,
regionCode,
})),
});
return quotations;
});
console.log("Quotations created: ", createMany);
return res
.status(httpStatusCodes.OK)
.json(
new ResponseJSON(
"Quotations Created",
false,
httpStatusCodes.OK,
createMany
)
);
} catch (error) {
console.log("Error --- ", error);
next(
apiErrorHandler(
error,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
}
this function keeps throwing internal server error on the following input {
"quotations" : [
{
"itemCode": 101010101,
"questionnaireId": 17,
"marketplaceCode": 2010101,
"quotes": [
{
"price": 13,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
},
{
"price": 13.41,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
}
]
}
],
"geomeans": [
{
"itemCode": 101010101,
"variation": 0.14,
"stdev": 1.93,
"geomean": 13.99,
"min": 11.47,
"max": 16.53,
"questionnaireId": 17
}
]
} Importing quotations...
User {
id: 4,
fullName: 'new stat',
userName: 'newstat',
email: 'newstat@gmail.com',
emailVerified: false,
phoneNumber: '251978563412',
role: 4362,
accountLockedOut: false,
accessFailedCount: 0,
disabled: false,
registrantId: 2,
tokenExpireAfter: 5184000,
createdAt: 2023-05-17T11:07:23.908Z,
updatedAt: 2023-05-17T11:07:23.908Z,
marketplaceCode: null,
tempRole: null,
language: 'en',
tempRoleEndDate: null,
supervisorId: null,
branchCode: null,
regionCode: 14
}
RegionCode: 14
Items: [ { UoMCode: 'g', SmUCode: 'g' } ]
Quotation: {
itemCode: 101010101,
questionnaireId: 17,
marketplaceCode: 2010101,
quotes: [
{
price: 13,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
},
{
price: 13.41,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
}
],
status: 'BRANCH_APPROVED',
creationStatus: 'IMPORTED',
collectorId: 4
}
Error --- TypeError: Cannot read property 'UoMCode' of undefined
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1188:54
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1182:45
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1168:27
at Generator.next (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:4:12)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1166:65 {
clientVersion: '4.3.1'
} the above function throws this error how can i fix it ? update the above code so that it filters items which my not have a corresponding code and checks for null or undefined and skip those items so that the function doesnt break
|
aeed1a0ffcfda1464adb39937d9eae27
|
{
"intermediate": 0.4194059371948242,
"beginner": 0.4042833149433136,
"expert": 0.1763107180595398
}
|
10,288
|
can you do second static 2d array of vertices and edges snapable grid? for example, add the same array with vertices and edges as a grid on whole canvas, but this array of vertices and edges will be static and attached at the center of this editable cube array of vertices and edges. remove all unnecessary grid code and output full modified code with vmc menu to add new wireframe lines.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
9025d3b82157e234debd9e08e91cdd8d
|
{
"intermediate": 0.4043979048728943,
"beginner": 0.36806467175483704,
"expert": 0.22753743827342987
}
|
10,289
|
html radio buttons in angular
|
2d82cb9fe09a757966c598332e6aa4bf
|
{
"intermediate": 0.4372834265232086,
"beginner": 0.28522804379463196,
"expert": 0.2774885296821594
}
|
10,290
|
can you do second static 2d array of vertices and edges snapable grid? for example, add the same array with vertices and edges as a grid on whole canvas, but this array of vertices and edges will be static and attached at the center of this editable cube array of vertices and edges. remove all unnecessary grid code and output full modified code with vmc menu to add new wireframe lines.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
3560c08bea9d1841b690751f86839067
|
{
"intermediate": 0.4043979048728943,
"beginner": 0.36806467175483704,
"expert": 0.22753743827342987
}
|
10,291
|
can you do second static 2d array of vertices and edges snapable grid? for example, add the same array with vertices and edges as a grid on whole canvas, but this array of vertices and edges will be static and attached at the center of this editable cube array of vertices and edges. remove all unnecessary grid code and output full modified code with vmc menu to add new wireframe lines.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
c9c8c0e99aa3cff94cc584204004ee91
|
{
"intermediate": 0.4043979048728943,
"beginner": 0.36806467175483704,
"expert": 0.22753743827342987
}
|
10,292
|
suggest me class diagram from my below scenario with relevant features
Actor
Students, Admin
Description
This use case allows Students to Browse the website for multiple things to get course info and course news and Instructor list and their sections
Data
Student Name, his courses, Instructor, and groups as well as news
stimulus
command to enter his information and course info
Response
Send confirmation and give him the ability to browse for course news/info/sections
Comment
The student must sign up for the application before If it got rejected, a notice will appear on the
website. If the request is approved, the student and instructor will receive all his info about courses and instructors and news for the website
website. If the request is approved, the student/instructor will receive all his info about courses/instructors/news for the website
|
61a70b023e5bc4d521f788ba4b5547ba
|
{
"intermediate": 0.2551424205303192,
"beginner": 0.4552449882030487,
"expert": 0.28961262106895447
}
|
10,293
|
how to draw polygon by point in Unity Unlit shader HLSL
|
b580b20f4f47297dd24b2026bdad4a6b
|
{
"intermediate": 0.4054565131664276,
"beginner": 0.33011293411254883,
"expert": 0.2644304931163788
}
|
10,294
|
now i have html radio buttons disgined vertically , and also have one div i want this div appear directly under the one radio button i select not in fixed place
|
4a01ae5ec61cbce39084f64cbcfd104c
|
{
"intermediate": 0.45757773518562317,
"beginner": 0.2027592957019806,
"expert": 0.3396630585193634
}
|
10,295
|
有一个用来注册输入法的函数如下:
public static void Register()
{
var regservice = new RegistrationServices();
regservice.RegisterAssembly(Assembly.LoadFrom("YIME.Core.dll"),
AssemblyRegistrationFlags.SetCodeBase);
var iconname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
"YIME.Core.dll");
Console.WriteLine(iconname);
Console.WriteLine(CultureInfo.GetCultureInfo("zh-cn").LCID);
//Insert code here.
var p = new ITfInputProcessorProfiles();
var result = p.Register(CLSID_TEXTSERVICE);
Console.WriteLine(result.ToString());
//添加到输入法清单
result = p.AddLanguageProfile(CLSID_TEXTSERVICE, new LangID((ushort)CultureInfo.GetCultureInfo("zh-cn").LCID), GUID_PROFILE,
name.ToCharArray(), (uint)name.ToCharArray().Length, iconname.ToCharArray(), (uint)iconname.Length, 0);
Console.WriteLine(result.ToString());
var c = new ITfCategoryMgr();
foreach (var supportCategory in SupportCategories)
{
var r = c.RegisterCategory(CLSID_TEXTSERVICE, supportCategory, CLSID_TEXTSERVICE);
Console.WriteLine(r.ToString());
}
Console.ReadLine();
}
但是在.net6中,System.Runtime.InteropServices空间下没有RegistrationServices了,这个函数应该怎么改?
|
9f85e566cd56384011b3a87418fea5a5
|
{
"intermediate": 0.38639453053474426,
"beginner": 0.30378299951553345,
"expert": 0.3098224699497223
}
|
10,296
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime(“%m/%d/%Y %H:%M:%S”)
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ‘’
API_SECRET = ‘’
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = ‘SELL’
POSITION_SIDE_LONG = ‘BUY’
quantity = 1
symbol = ‘BTC/USDT’
order_type = ‘MARKET’
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
‘apiKey’: ‘’,
‘secret’: ‘’,
‘enableRateLimit’: True, # enable rate limitation
‘options’: {
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
}
})
binance_futures = ccxt.binance({
‘apiKey’: API_KEY,
‘secret’: API_SECRET,
‘enableRateLimit’: True, # enable rate limitation
‘options’: {
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = “https://fapi.binance.com/fapi/v1/klines”
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace(“/”, “”) # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}“
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print(‘No data found for the given timeframe and symbol’)
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(‘%Y-%m-%d %H:%M:%S’)
ohlc.append({
‘Open time’: timestamp,
‘Open’: float(d[1]),
‘High’: float(d[2]),
‘Low’: float(d[3]),
‘Close’: float(d[4]),
‘Volume’: float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index(‘Open time’, inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f’Error in get_klines: {e}')
return None
df = get_klines(symbol, ‘1m’, 89280)
def signal_generator(df):
if df is None:
return “”
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return ‘sell’
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return ‘buy’
# No clear pattern
else:
return “”
df = get_klines(symbol, ‘1m’, 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position[“symbol”] == symbol:
current_position = position
if current_position is not None and current_position[“positionAmt”] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side=‘SELL’ if current_position[“positionSide”] == “LONG” else ‘BUY’,
type=‘MARKET’,
quantity=abs(float(current_position[“positionAmt”])),
positionSide=current_position[“positionSide”],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
# Set default take profit price
take_profit_price = None
if signal == ‘buy’:
position_side = ‘BOTH’
opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘SHORT’ else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if ‘askPrice’ in ticker:
price = ticker[‘askPrice’]
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == ‘sell’:
position_side = ‘BOTH’
opposite_position = current_position if current_position and current_position[‘positionSide’] == ‘LONG’ else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if ‘askPrice’ in ticker:
price = ticker[‘askPrice’]
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == ‘buy’:
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == ‘sell’:
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}”)
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position[‘positionAmt’]) < quantity:
quantity = abs(opposite_position[‘positionAmt’])
# Place order
order_params = {
“side”: “BUY” if signal == “buy” else “SELL”,
“type”: order_type,
“positionSide”: position_side,
“quantity”: quantity,
“price”: price,
“stopPrice”: stop_loss_price if signal == “buy” else take_profit_price,
“reduceOnly”: False,
“newOrderRespType”: “RESULT”,
“workingType”: “MARK_PRICE”,
“priceProtect”: False,
“leverage”: leverage
}
try:
order_params[‘symbol’] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}“)
except BinanceAPIException as e:
print(f"Error in order_execution: {e}”)
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, ‘1m’, 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime(‘%Y-%m-%d %H:%M:%S’)} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: BTC/USDT found in the market
The signal time is: 2023-06-05 14:46:57 :
Traceback (most recent call last):
File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 245, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 219, in order_execution
“positionSide”: position_side,
^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable ‘position_side’ where it is not associated with a value
|
c1074bbf20f1663833a0307b6fc018cc
|
{
"intermediate": 0.4520643949508667,
"beginner": 0.3942992687225342,
"expert": 0.15363627672195435
}
|
10,297
|
what does this code do:
Sub padYear0000()
Dim inputDate As String
inputDate = ActiveCell.Value
If Len(inputDate) > 0 Then
'Copy the formatted date to clipboard
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.SetText inputDate & "0000"
.PutInClipboard
End With
MsgBox "The formatted date has been copied to the clipboard."
Else
MsgBox "Invalid date format. Please select a cell containing a valid date value."
End If
End Sub
|
1cfaaab5501d3c83bac3e2517749f423
|
{
"intermediate": 0.39239075779914856,
"beginner": 0.4483259618282318,
"expert": 0.15928329527378082
}
|
10,298
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: BTC/USDT found in the market
The signal time is: 2023-06-05 17:21:45 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 254, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 241, in order_execution
response = binance_futures.fapiPrivatePostOrder(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'side'
|
0d31f90359c5bb5a9cc637850a450a8e
|
{
"intermediate": 0.5044465065002441,
"beginner": 0.3187195956707001,
"expert": 0.17683392763137817
}
|
10,299
|
can you pls remove all unnecessary grid related code from original code and apply this static snapable grid to it. also, try to use that “toggle grid” button to turn that satic grid array on and off from canvas. can you do second static 2d array of vertices and edges snapable grid? for example, add the same array with vertices and edges as a grid on whole canvas, but this array of vertices and edges will be static and attached at the center of this editable cube array of vertices and edges. remove all unnecessary grid code and output full modified code with vmc menu to add new wireframe lines.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
9615a9ceccea18a26df351d341442e33
|
{
"intermediate": 0.38140109181404114,
"beginner": 0.45874086022377014,
"expert": 0.15985804796218872
}
|
10,300
|
I want to create a C program that I input 2 intergers then the program change it to bits and show us how to multiply them and then convert to decimal
|
6d7d6cbc166d5beb29bf09c71769c6e0
|
{
"intermediate": 0.37722089886665344,
"beginner": 0.19295744597911835,
"expert": 0.429821640253067
}
|
10,301
|
i have radio buttons all of them show the same div when select any of them, please make the first one default active
|
dabccb2b6ad7534c3bbcd464e81cdb30
|
{
"intermediate": 0.37803351879119873,
"beginner": 0.22028203308582306,
"expert": 0.4016844630241394
}
|
10,302
|
do some template array of vertices and edges for grid. multiply that static grid array, so it can fit on whole canvas as a grid, independent of resizing and else. attach that static grid array (SGA) to the center, so it always stay at the center and only be affected by snapping or attacment functions to do new wireframe lines in that 3d matrix array, without being affected by any transformations. remove all unnecessary grid code and also, output full modified code with vmc menu to add new wireframe lines and turn that grid on/off button. also, new created lines should be counted as actual wireframe model part, not grid related, so they should always be visible.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
d2024ed1304baa013a57cd688edb5415
|
{
"intermediate": 0.24187274277210236,
"beginner": 0.4446031153202057,
"expert": 0.31352415680885315
}
|
10,303
|
cretae radio button in angular using native html, and select the first one by default
|
1b4ea2ed2f6dc283f841106f845d18fb
|
{
"intermediate": 0.35804805159568787,
"beginner": 0.29678210616111755,
"expert": 0.3451698422431946
}
|
10,304
|
do some template array of vertices and edges for grid. multiply that static grid array, so it can fit on whole canvas as a grid, independent of resizing and else. attach that static grid array (SGA) to the center, so it always stay at the center and only be affected by snapping or attacment functions to do new wireframe lines in that 3d matrix array, without being affected by any transformations. output fully modified code with vmc menu to add new wireframe lines and turn that grid on/off button. also, new created lines should be counted as actual wireframe model part, not grid related, so they should always be visible.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
ad031c731fd18019b5839891a2f060f9
|
{
"intermediate": 0.3226148784160614,
"beginner": 0.3979717195034027,
"expert": 0.2794133424758911
}
|
10,305
|
do some template array of vertices and edges for grid. multiply that static grid array, so it can fit on whole canvas as a grid, independent of resizing and else. attach that static grid array (SGA) to the center, so it always stay at the center and only be affected by snapping or attacment functions to do new wireframe lines in that 3d matrix array, without being affected by any transformations. remove all unnecessary grid code and also, output full modified code with vmc menu to add new wireframe lines and turn that grid on/off button. also, new created lines should be counted as actual wireframe model part, not grid related, so they should always be visible.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
5d3a05e107268d184769211cc6b1c703
|
{
"intermediate": 0.27347737550735474,
"beginner": 0.46947064995765686,
"expert": 0.2570520043373108
}
|
10,306
|
SecurityFilterChain spring 6
|
4c6979547cab473186053d690f7968fd
|
{
"intermediate": 0.33377739787101746,
"beginner": 0.285421758890152,
"expert": 0.38080087304115295
}
|
10,307
|
do some template array of vertices and edges for grid. multiply that static grid array, so it can fit on whole canvas as a grid, independent of resizing and else. attach that static grid array (SGA) to the center, so it always stay at the center and only be affected by snapping or attacment functions to do new wireframe lines in that 3d matrix array, without being affected by any transformations. output fully modified code with vmc menu to add new wireframe lines and turn that grid on/off button. also, new created lines should be counted as actual wireframe model part, not grid related, so they should always be visible.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
40bdc88a7b92c96e42b2a4667bfd0261
|
{
"intermediate": 0.3226148784160614,
"beginner": 0.3979717195034027,
"expert": 0.2794133424758911
}
|
10,308
|
do some template array of vertices and edges for grid. multiply that static grid array, so it can fit on whole canvas as a grid, independent of resizing and else. attach that static grid array (SGA) to the center, so it always stay at the center and only be affected by snapping or attacment functions to do new wireframe lines in that 3d matrix array, without being affected by any transformations. output fully modified code with vmc menu to add new wireframe lines and turn that grid on/off button. also, new created lines should be counted as actual wireframe model part, not grid related, so they should always be visible.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
cc349129cd2f730f641c217c6bcbdf25
|
{
"intermediate": 0.3226148784160614,
"beginner": 0.3979717195034027,
"expert": 0.2794133424758911
}
|
10,309
|
function extractFPValue(fpDeclaration) {
const regex = /\w+\(([^()]+)\)/g;
const matches = fpDeclaration.match(regex);
if (matches) {
return matches.map(match => {
const args = match.match(/\(([^()]+)\)/);
if (args) {
return args[1];
}
return '';
});
}
return [];
}
const _0x17ff2c = function() {
const _0x59ce2b = _0x5acc53;
_0x4dd6a8(_0x26dff1(_0x59ce2b(0x1df, 'N(7U') + _0x499657(_0x2ae151) + GET_FP['fp']), GET_FP['fp']), _0x1ec59f();
}
const extractedValues = extractFPValue(_0x17ff2c.toString());
console.log(extractedValues);
Popraw tego kod tak by wynik był taki:
0x1df, 'N(7U'
a nie taki:
[ "7U'", '_0x2ae151' ]
|
fef4876dbe6306116d03f8c521a3e443
|
{
"intermediate": 0.39264780282974243,
"beginner": 0.42281103134155273,
"expert": 0.1845412254333496
}
|
10,310
|
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class=“vmc-menu” id=“vmc-menu”>
<label>Vertex X: <input type=“number” id=“vmc-vertex-x” step=“0.1”></label>
<label>Vertex Y: <input type=“number” id=“vmc-vertex-y” step=“0.1”></label>
<label>Vertex Z: <input type=“number” id=“vmc-vertex-z” step=“0.1”></label>
<button id=“add-edge”>Add Edge</button>
<button id=“remove-edge”>Remove Edge</button>
</div>
<div class=“red-dot” id=“red-dot”></div>
<script>
const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
I’m sorry, but I cannot provide a solution to this task as it involves creating a new wireframe model and modifying the code significantly. It would require a more detailed understanding of the project and its specific requirements. However, I can suggest breaking down the task into smaller steps and tackling them one by one. It may also be helpful to consult relevant documentation and resources on 3D graphics and WebGL programming.
wtf you alk about? you thing it will be feasible to make a template to then multiply it to do a grid that way?
I apologize if my previous response was unclear. Yes, it is possible to create a template array of vertices and edges as a grid, and then multiply or replicate that grid to fill the canvas as needed. However, this would require modifying the code provided and implementing the necessary functions to accomplish this. Additionally, there would need to be a way to differentiate between the grid and the wireframe lines added by the user, so that only the wireframe lines are counted as actual parts of the 3D model.
what about performance?
There are a number of factors that can affect performance when working with 3D graphics and WebGL, such as the complexity of the model, the number of vertices and edges, the speed of the user’s computer, and the implementation of the JavaScript code. In general, using a static grid array as a template and then replicating it to fill the canvas can be a viable approach for simple models. However, for more complex models, it may be necessary to use more advanced data structures (e.g. octrees) or optimizations (e.g. culling) to improve performance. Additionally, it’s important to optimize the JavaScript code itself and use Web Workers or other techniques to offload processing to separate threads when possible. Ultimately, the best approach will depend on the specific requirements of the project and will require careful testing and evaluation to ensure optimal performance.
there’s 2 arrays of vertices and edges throughout you can add a new edge, but in case with grid array it should play a role as nomal grid as in any other edior software…
If the goal is to create a grid array that functions as a normal grid in an editor software, then the mesh should be generated in a way that allows for easy snapping and visibility. In addition to the existing vertices and edges arrays, an additional grid array can be created to represent the lines of the grid. This grid array can then be used to determine if a new wireframe line should snap to the closest point on the grid. Additionally, you can set a flag on the wireframe lines to differentiate them from the grid lines and to ensure that they are always visible.
To ensure that the grid array remains static and is not affected by transformations, you can construct it in a separate function that generates coordinates for a flat grid plane in the XZ plane, and evenly spaces the vertices along the X and Z axes. These vertices can then be connected with horizontal and vertical lines to form the grid. The grid array should be separate from the vertices and edges array, and should not be transformed or rotated along with the wireframe model.
yes, it will be cool. but need to preserve this snapabiliy to grid but at the same time don’t count grid as part of actual wireframe model you construct…
Yes, that’s correct. To preserve snapability to the grid while not counting it as part of the actual wireframe model, you can create a separate gridLines array that contains the lines of the grid, and use it to check if a new wireframe line should snap to the closest point on the grid. You can also use a separate flag in the wireframeLines array to differentiate them from the gridLines array, so they are treated differently when it comes to rendering and counting the parts of the actual 3D model.
When a new wireframe line is created, you can iterate through the gridLines array and find the two nearest lines that the new line should snap to. You can then calculate the intersection point between the new line and the closest grid lines, and set the start and end points of the new line to the snapped position. This will allow the user to easily snap the wireframe line to the grid for precision purposes, while keeping the grid lines separate from the actual wireframe model.
so, when you creaing a line from one point to anoher, this line will transform into “construct array” and this construct array will be responsible for actual wireframe model you are building righ now, without affecting anything else.
Yes, that’s right. When a new wireframe line is created, it should be added to an additional wireframeLines array that is separate from the vertices and edges arrays. This wireframeLines array should contain all of the wireframe lines that are added by the user, and should be used to render the distinct parts of the actual 3D model.
The vertices and edges arrays should contain the static geometry of the model, which doesn’t change dynamically as the user adds new lines. The wireframeLines array, on the other hand, should change dynamically based on the user’s inputs and selections.
By keeping the grid lines, static geometry, and wireframe lines in separate arrays, you can make sure that they are treated differently when it comes to rendering and counting the parts of the actual 3D model. This will allow you to create a more dynamic and flexible wireframe model, while still preserving the snapability to the grid and keeping the static parts of the model separate from the dynamic parts.
what else to count here? can you output some pseudo-code schematics with details to give it to gpt-4 AI, so it can understand what to do with original code? try deeply and extremely careful analyze the situation here, and output properre pseudo-code for gpt-4 AI, so it understand how to do grid properre.
|
eca2e1f34d62ae73f3240ba1c54f7fd5
|
{
"intermediate": 0.2215682715177536,
"beginner": 0.4752333462238312,
"expert": 0.3031984269618988
}
|
10,311
|
Please write a step by step, detailed and specific guide on how I would host a well designed, modern and slick Coming Soon page for completely free in the cloud, given that I want to host it on my domain kritica.xyz, specifically on the subdomain 'leo.kritica.xyz'. Note that I use Cloudflare for DNS, performance optimization and anti DDoS. Include full code. By following the guide you produce I should have a fully functional product with everything I asked for and some more included.
|
38e64d36071a1b9428da10b64f0ce0d4
|
{
"intermediate": 0.32167741656303406,
"beginner": 0.3585302233695984,
"expert": 0.31979241967201233
}
|
10,312
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
cf41d4b0375724d87e42695bfea95344
|
{
"intermediate": 0.28507527709007263,
"beginner": 0.39201095700263977,
"expert": 0.3229137361049652
}
|
10,313
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>go. full code time, baby!
|
086b5e65e827e8e895f21dcf047530a6
|
{
"intermediate": 0.28507527709007263,
"beginner": 0.39201095700263977,
"expert": 0.3229137361049652
}
|
10,314
|
checked attribute not work in html radio button in angular when using ngModel
|
aa51a074eb4316a76a161ac646d9be71
|
{
"intermediate": 0.6293574571609497,
"beginner": 0.21495868265628815,
"expert": 0.15568384528160095
}
|
10,315
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
55c27bbb8b1cc740bd5079ac3e00ed8e
|
{
"intermediate": 0.28507527709007263,
"beginner": 0.39201095700263977,
"expert": 0.3229137361049652
}
|
10,316
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
b234f65fc4a646cfba879013ead5744f
|
{
"intermediate": 0.28507527709007263,
"beginner": 0.39201095700263977,
"expert": 0.3229137361049652
}
|
10,317
|
async importQuotation(req: Request, res: Response, next: NextFunction) {
try {
console.log("Importing quotations...");
const body: ImportCleanQuotations = req.body;
const regionCode = getRegionCode(req.user!, req.query);
if (!regionCode) {
console.log("Region code is required for this operation");
return res
.status(httpStatusCodes.BAD_REQUEST)
.json(
new ResponseJSON(
"Region code is required for this operation",
true,
httpStatusCodes.BAD_REQUEST
)
);
}
const items = await Promise.all(
body.quotations.map((quotation) =>
prisma.item.findUnique({
where: {
code: quotation.itemCode,
},
select: {
UoMCode: true,
SmUCode: true,
},
})
)
);
console.log("Items: ", items);
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
console.log("Quotation: ", quotation);
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote, index) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items[index]!.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
);
await Promise.all(
quotations.reduce((acc: any, quotation, index) => {
acc.push(
tx.interpolatedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
},
})
);
acc.push(
tx.cleanedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
questionnaireId: quotation.questionnaireId,
itemCode: quotation.itemCode,
},
})
);
return acc;
}, [])
);
await tx.itemRegionalMean.createMany({
data: body.geomeans.map((mean) => ({
itemCode: mean.itemCode,
variation: mean.variation,
stdev: mean.stdev,
geomean: mean.geomean,
min: mean.min,
max: mean.max,
questionnaireId: mean.questionnaireId,
regionCode,
})),
});
return quotations;
});
console.log("Quotations created: ", createMany);
return res
.status(httpStatusCodes.OK)
.json(
new ResponseJSON(
"Quotations Created",
false,
httpStatusCodes.OK,
createMany
)
);
} catch (error) {
console.log("Error --- ", error);
next(
apiErrorHandler(
error,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
}
this function keeps throwing internal server error on the following input {
"quotations" : [
{
"itemCode": 101010101,
"questionnaireId": 17,
"marketplaceCode": 2010101,
"quotes": [
{
"price": 13,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
},
{
"price": 13.41,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
}
]
}
],
"geomeans": [
{
"itemCode": 101010101,
"variation": 0.14,
"stdev": 1.93,
"geomean": 13.99,
"min": 11.47,
"max": 16.53,
"questionnaireId": 17
}
]
} Importing quotations...
User {
id: 4,
fullName: 'new stat',
userName: 'newstat',
email: 'newstat@gmail.com',
emailVerified: false,
phoneNumber: '251978563412',
role: 4362,
accountLockedOut: false,
accessFailedCount: 0,
disabled: false,
registrantId: 2,
tokenExpireAfter: 5184000,
createdAt: 2023-05-17T11:07:23.908Z,
updatedAt: 2023-05-17T11:07:23.908Z,
marketplaceCode: null,
tempRole: null,
language: 'en',
tempRoleEndDate: null,
supervisorId: null,
branchCode: null,
regionCode: 14
}
RegionCode: 14
Items: [ { UoMCode: 'g', SmUCode: 'g' } ]
Quotation: {
itemCode: 101010101,
questionnaireId: 17,
marketplaceCode: 2010101,
quotes: [
{
price: 13,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
},
{
price: 13.41,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
}
],
status: 'BRANCH_APPROVED',
creationStatus: 'IMPORTED',
collectorId: 4
}
Error --- TypeError: Cannot read property 'UoMCode' of undefined
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1188:54
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1182:45
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1168:27
at Generator.next (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:4:12)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1166:65 {
clientVersion: '4.3.1'
} the above function throws this error how can i fix it ?
|
e8586a8a60159339bac70922874e49c0
|
{
"intermediate": 0.4194059371948242,
"beginner": 0.4042833149433136,
"expert": 0.1763107180595398
}
|
10,318
|
a js code to grab contents from 2 text areas and separate encode to base64 with encodin function
|
c17a44d2f68a4ca04c5fb589cb315e0f
|
{
"intermediate": 0.45371508598327637,
"beginner": 0.20897257328033447,
"expert": 0.33731234073638916
}
|
10,319
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
...
];
const edges = [
[0, 1],
...
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
ae8c7f1a63815330f113bdc9ada665f7
|
{
"intermediate": 0.30932942032814026,
"beginner": 0.33234161138534546,
"expert": 0.3583289682865143
}
|
10,320
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
...
];
const edges = [
[0, 1],
...
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
d4c5f12ca030b02a429fadea3f533813
|
{
"intermediate": 0.30932942032814026,
"beginner": 0.33234161138534546,
"expert": 0.3583289682865143
}
|
10,321
|
Please write a step by step, detailed and specific guide on how I would host a well designed, modern and slick 'Browse' page for an online digital book sales platform called Kritica, for completely free in the cloud, given that I want to host it on my domain kritica.xyz. Account for APIs, the storage of content, and everything else that is needed. Note that I use Cloudflare for DNS, performance optimization and anti DDoS. Include FULL code; by following the guide you produce I should have a fully functional product with everything I asked for and some more included.
|
98da0c7bababd5974a18050432571481
|
{
"intermediate": 0.5546852946281433,
"beginner": 0.26776573061943054,
"expert": 0.17754900455474854
}
|
10,322
|
here’s a high-level pseudocode outline to help guide the implementation for adding a snapable grid to the project:
1. Define the grid size and spacing as constants.
const GRID_SIZE = 10;
const GRID_SPACING = 1;
2. Create an additional array gridLines for storing the grid’s line segments.
const gridLines = [];
3. Generate the grid using a function, which populates the gridLines array.
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
}
4. In the render function, modify the code so that it renders gridLines separately from the vertices and edges arrays, using a different color or style to distinguish them from the main wireframe lines.
5. When the user tries to create a wireframe line, find the closest grid points for snapping purposes. You can implement this using a function.
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
}
6. Create a separate wireframeLines array to store the lines created by the user.
const wfLines = [];
7. When a new wireframe line is created, add it to the wireframeLines array and snap its start and end points to the closest grid points.
8. In the render function, draw the wireframeLines separately from the vertices, edges, and gridLines arrays. (also, try improve event listeners, because of performance degradation with time for an unknown reason.): const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
...
];
const edges = [
[0, 1],
...
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
5c73940fc5763040a2da3e3dd22b9ae4
|
{
"intermediate": 0.30932942032814026,
"beginner": 0.33234161138534546,
"expert": 0.3583289682865143
}
|
10,323
|
divide my code on files main.cpp, board.cpp, board.h, ship.cpp, ship.h and in answer provide me a whole code
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <limits>
#include <vector>
#include <ostream>
using namespace std;
class Ship {
public:
virtual ~Ship() {}
virtual char getSymbol() const = 0;
virtual int getLength() const = 0;
};
class AircraftCarrier : public Ship {
public:
char getSymbol() const override { return 'A'; }
int getLength() const override { return 5; }
};
class Battleship : public Ship {
public:
char getSymbol() const override { return 'B'; }
int getLength() const override { return 4; }
};
class Cruiser : public Ship {
public:
char getSymbol() const override { return 'C'; }
int getLength() const override { return 3; }
};
class Destroyer : public Ship {
public:
char getSymbol() const override { return 'D'; }
int getLength() const override { return 2; }
};
class Submarine : public Ship {
public:
char getSymbol() const override { return 'S'; }
int getLength() const override { return 1; }
};
class Board {
public:
static const int SIZE = 10;
Board() {
// Initialize the grid and hits matrices
grid.resize(SIZE, vector<Ship *>(SIZE, nullptr));
hits.resize(SIZE, vector<bool>(SIZE, false));
}
friend ostream& operator<<(ostream& os, const Board& board) {
os << " \033[1;31m0 1 2 3 4 5 6 7 8 9\033[0m" << endl;
for (int y = 0; y < SIZE; ++y) {
os << "\033[1;31m" << y << " \033[0m";
for (int x = 0; x < SIZE; ++x) {
if (board.hits[y][x]) {
if (board.grid[y][x] != nullptr) {
os << "\033[1;31m" << board.grid[y][x]->getSymbol() << "\033[0m";
} else {
os << "\033[1;34mX\033[0m";
}
} else {
if (board.grid[y][x] != nullptr) {
os << "\033[1;37m.\033[0m";
} else {
os << "~";
}
}
os << " ";
}
os << endl;
}
return os;
}
void clear() {
// Cleanup the grid and hits matrices
for (int y = 0; y < SIZE; ++y) {
for (int x = 0; x < SIZE; ++x) {
grid[y][x] = nullptr;
hits[y][x] = false;
}
}
}
bool placeShip(int x, int y, Ship *ship, char direction) {
int length = ship->getLength();
if (canPlaceShip(x, y, length, direction)) {
for (int i = 0; i < length; ++i) {
int newX = x;
int newY = y;
if (direction == 'H') {
newX += i;
} else if (direction == 'V') {
newY += i;
}
grid[newY][newX] = ship;
}
return true;
}
return false;
}
void print(bool showShips) const {
cout << " \033[1;31m0 1 2 3 4 5 6 7 8 9\033[0m" << endl;
for (int y = 0; y < SIZE; ++y) {
cout << "\033[1;31m" << y << " \033[0m";
for (int x = 0; x < SIZE; ++x) {
if (hits[y][x]) {
if (grid[y][x] != nullptr) {
cout << "\033[1;31m" << grid[y][x]->getSymbol() << " ";
} else {
cout << "\033[1;31mX ";
}
} else if (showShips && grid[y][x] != nullptr) {
cout << "\033[1;31m" << grid[y][x]->getSymbol() << " ";
} else {
cout << "\033[1;32m~ ";
}
}
cout << endl;
}
}
void saveToFile(string filename, bool showShips) const {
ofstream file(filename);
if (file.is_open()) {
file << " 0 1 2 3 4 5 6 7 8 9" << endl;
for (int y = 0; y < SIZE; ++y) {
file << y << " ";
for (int x = 0; x < SIZE; ++x) {
if (hits[y][x]) {
if (grid[y][x] != nullptr) {
file << grid[y][x]->getSymbol() << " ";
} else {
file << "X ";
}
} else if (showShips && grid[y][x] != nullptr) {
file << grid[y][x]->getSymbol() << " ";
} else {
file << "~ ";
}
}
file << endl;
}
file.close();
cout << "Board saved to " << filename << endl;
} else {
cout << "Unable to open file " << filename << endl;
}
}
bool receiveAttack(int x, int y) {
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
return false;
}
if (hits[y][x]) {
return false;
}
hits[y][x] = true;
if (grid[y][x] != nullptr) {
return true;
}
return false;
}
bool isGameOver() const {
for (int y = 0; y < SIZE; ++y) {
for (int x = 0; x < SIZE; ++x) {
if (grid[y][x] != nullptr && !hits[y][x]) {
return false;
}
}
}
return true;
}
private:
vector<vector<Ship *>> grid;
vector<vector<bool>> hits;
bool canPlaceShip(int x, int y, int length, char direction) const {
if (x < 0 || x + length > SIZE || y < 0 || y + length > SIZE) {
return false;
}
if (direction == 'H') {
if (x + length > SIZE) {
return false;
}
for (int i = 0; i < length; ++i) {
if (grid[y][x + i] != nullptr) {
return false;
}
if (x + i > 0 && grid[y][x + i - 1] != nullptr) {
return false;
}
if (x + i < SIZE - 1 && grid[y][x + i + 1] != nullptr) {
return false;
}
if (y > 0 && grid[y - 1][x + i] != nullptr) {
return false;
}
if (y < SIZE - 1 && grid[y + 1][x + i] != nullptr) {
return false;
}
}
} else if (direction == 'V') {
if (y + length > SIZE) {
return false;
}
for (int i = 0; i < length; ++i) {
if (grid[y + i][x] != nullptr) {
return false;
}
if (y + i > 0 && grid[y + i - 1][x] != nullptr) {
return false;
}
if (y + i < SIZE - 1 && grid[y + i + 1][x] != nullptr) {
return false;
}
if (x > 0 && grid[y + i][x - 1] != nullptr) {
return false;
}
if (x < SIZE - 1 && grid[y + i][x + 1] != nullptr) {
return false;
}
}
}
return true;
}
};
void placeShips(Board &board, const vector<Ship *> &ships, bool isPlayer) {
for (Ship *ship : ships) {
bool placed = false;
while (!placed) {
int x, y;
char direction;
auto isValidCoordinate = [](int x, int y) {
return x >= 0 && x < Board::SIZE && y >= 0 && y < Board::SIZE;
};
// Використання лямбда-функції для валідації координат гравця
if (isPlayer) {
cout << "Enter the starting coordinates (x y) for the ship "
<< ship->getSymbol() << " (" << ship->getLength() << "): ";
cin >> x >> y;
cout << "Enter the direction (H for horizontal, V for vertical): ";
cin >> direction;
} else {
x = rand() % Board::SIZE;
y = rand() % Board::SIZE;
direction = (rand() % 2 == 0) ? 'H' : 'V';
}
placed = board.placeShip(x, y, ship, direction);
if (!placed && isPlayer) {
cout << "Invalid ship placement. Please try again." << endl;
}
}
if (isPlayer) {
board.print(true);
}
}
}
int main() {
srand(time(0));
Board playerBoard;
Board computerBoard;
playerBoard.saveToFile("player_board.txt", true);
computerBoard.saveToFile("computer_board.txt", false);
AircraftCarrier playerAircraftCarrier, computerAircraftCarrier;
Battleship playerBattleship, computerBattleship;
Cruiser playerCruiser, computerCruiser;
Destroyer playerDestroyer, computerDestroyer;
Submarine playerSubmarine, computerSubmarine;
vector<Ship *> playerShips = {&playerAircraftCarrier, &playerBattleship,
&playerCruiser, &playerDestroyer,
&playerSubmarine};
vector<Ship *> computerShips = {&computerAircraftCarrier, &computerBattleship,
&computerCruiser, &computerDestroyer,
&computerSubmarine};
placeShips(playerBoard, playerShips, true);
placeShips(computerBoard, computerShips, false);
while (true) {
cout << "Player Board:" << endl;
playerBoard.print(true);
cout << endl;
cout << "Computer Board:" << endl;
computerBoard.print(false);
cout << endl;
int x, y;
char direction;
cout << "Enter the coordinates to attack (x y): ";
cin >> x >> y;
// Validate the input
while (cin.fail() || x < 0 || x >= Board::SIZE || y < 0 ||
y >= Board::SIZE) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid coordinates. Please try again." << endl;
cout << "Enter the coordinates to attack (x y): ";
cin >> x >> y;
}
bool playerHit = computerBoard.receiveAttack(x, y);
if (playerHit) {
cout << "Player hit the computer's ship!" << endl;
if (computerBoard.isGameOver()) {
cout << "Player wins!" << endl;
break;
}
} else {
cout << "Player missed!" << endl;
}
// Check if the game is over before the computer attacks
if (playerBoard.isGameOver()) {
cout << "Computer wins!" << endl;
break;
}
// Computer's turn
x = rand() % Board::SIZE;
y = rand() % Board::SIZE;
bool computerHit = playerBoard.receiveAttack(x, y);
if (computerHit) {
cout << "Computer hit your ship!" << endl;
if (playerBoard.isGameOver()) {
cout << "Computer wins!" << endl;
break;
}
} else {
cout << "Computer missed!" << endl;
}
cout << endl;
}
playerBoard.saveToFile("player_board.txt", true);
computerBoard.saveToFile("computer_board.txt", false)
return 0;
}
|
57b3cef80339301ffe3f448f8d0175ad
|
{
"intermediate": 0.2717452347278595,
"beginner": 0.4325077533721924,
"expert": 0.2957470118999481
}
|
10,324
|
async importQuotation(req: Request, res: Response, next: NextFunction) {
try {
console.log("Importing quotations...");
const body: ImportCleanQuotations = req.body;
const regionCode = getRegionCode(req.user!, req.query);
if (!regionCode) {
console.log("Region code is required for this operation");
return res
.status(httpStatusCodes.BAD_REQUEST)
.json(
new ResponseJSON(
"Region code is required for this operation",
true,
httpStatusCodes.BAD_REQUEST
)
);
}
const items = await Promise.all(
body.quotations.map((quotation) =>
prisma.item.findUnique({
where: {
code: quotation.itemCode,
},
select: {
UoMCode: true,
SmUCode: true,
},
})
)
);
console.log("Items: ", items);
const createMany = await prisma.$transaction(async (tx) => {
const quotations = await Promise.all(
body.quotations.map((quotation, index) => {
(quotation as any).status = QuotationStatus.BRANCH_APPROVED;
(quotation as any).creationStatus =
QuotationCreationStatus.IMPORTED;
if (!quotation.collectorId) quotation.collectorId = req.user!.id;
console.log("Quotation: ", quotation);
return tx.quotation.create({
data: {
questionnaireId: quotation.questionnaireId,
collectorId: req.user!.id,
itemCode: quotation.itemCode,
marketplaceCode: quotation.marketplaceCode!,
quotes: {
createMany: {
data: quotation.quotes!.map((quote, index) => ({
...quote,
shopContactName: "Imported",
shopContactPhone: "Imported",
shopLatitude: "Imputated",
shopLongitude: "Imputated",
measurementUnit: items[index]!.UoMCode,
})),
},
// quotation.quotes?.map((quote) => { return {...quote,quantity: items[index]?.measurementQuantity,
// measurmentId: items[index]?.measurement,};}),
},
},
select: {
id: true,
questionnaireId: true,
itemCode: true,
quotes: true,
},
});
})
);
await Promise.all(
quotations.reduce((acc: any, quotation, index) => {
acc.push(
tx.interpolatedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
},
})
);
acc.push(
tx.cleanedQuote.create({
data: {
quoteId: quotation.quotes[index].id,
quotationId: quotation.id,
price: quotation.quotes[index].price,
measurementUnit: items[index]!.SmUCode,
quantity: quotation.quotes[index].quantity,
questionnaireId: quotation.questionnaireId,
itemCode: quotation.itemCode,
},
})
);
return acc;
}, [])
);
await tx.itemRegionalMean.createMany({
data: body.geomeans.map((mean) => ({
itemCode: mean.itemCode,
variation: mean.variation,
stdev: mean.stdev,
geomean: mean.geomean,
min: mean.min,
max: mean.max,
questionnaireId: mean.questionnaireId,
regionCode,
})),
});
return quotations;
});
console.log("Quotations created: ", createMany);
return res
.status(httpStatusCodes.OK)
.json(
new ResponseJSON(
"Quotations Created",
false,
httpStatusCodes.OK,
createMany
)
);
} catch (error) {
console.log("Error --- ", error);
next(
apiErrorHandler(
error,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
}
this function keeps throwing internal server error on the following input {
"quotations" : [
{
"itemCode": 101010101,
"questionnaireId": 17,
"marketplaceCode": 2010101,
"quotes": [
{
"price": 13,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
},
{
"price": 13.41,
"quantity": 325,
"shopContactName": "imported",
"shopContactPhone": "imported"
}
]
}
],
"geomeans": [
{
"itemCode": 101010101,
"variation": 0.14,
"stdev": 1.93,
"geomean": 13.99,
"min": 11.47,
"max": 16.53,
"questionnaireId": 17
}
]
} Importing quotations...
User {
id: 4,
fullName: 'new stat',
userName: 'newstat',
email: 'newstat@gmail.com',
emailVerified: false,
phoneNumber: '251978563412',
role: 4362,
accountLockedOut: false,
accessFailedCount: 0,
disabled: false,
registrantId: 2,
tokenExpireAfter: 5184000,
createdAt: 2023-05-17T11:07:23.908Z,
updatedAt: 2023-05-17T11:07:23.908Z,
marketplaceCode: null,
tempRole: null,
language: 'en',
tempRoleEndDate: null,
supervisorId: null,
branchCode: null,
regionCode: 14
}
RegionCode: 14
Items: [ { UoMCode: 'g', SmUCode: 'g' } ]
Quotation: {
itemCode: 101010101,
questionnaireId: 17,
marketplaceCode: 2010101,
quotes: [
{
price: 13,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
},
{
price: 13.41,
quantity: 325,
shopContactName: 'imported',
shopContactPhone: 'imported'
}
],
status: 'BRANCH_APPROVED',
creationStatus: 'IMPORTED',
collectorId: 4
}
Error --- TypeError: Cannot read property 'UoMCode' of undefined
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1188:54
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1182:45
at Array.map (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1168:27
at Generator.next (<anonymous>)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:8:71
at new Promise (<anonymous>)
at __awaiter (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:4:12)
at /home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1166:65 {
clientVersion: '4.3.1'
} the above function throws this error how can i fix it so that it skips null or undefined items and returns those items so they can be checked
|
40d244c21ff4093060be70255e89c481
|
{
"intermediate": 0.4194059371948242,
"beginner": 0.4042833149433136,
"expert": 0.1763107180595398
}
|
10,325
|
Please write a step by step, detailed and specific guide on how I would self host an API that returns a random funny cat image. You should include the use of tools like Nginx for load balancing and other tools for other purposes. Include FULL code; by following the guide you produce I should have a fully functional product with everything I asked for and some more included.
|
24a423b2824b4001f214690168d7c7fe
|
{
"intermediate": 0.6252277493476868,
"beginner": 0.23419056832790375,
"expert": 0.14058175683021545
}
|
10,326
|
You was generated HTML example. Please, create AI web chat page using this example:
stylesheet.css
body {
background-color: black;
color: red;
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
text-align: center;
margin: 0;
padding: 0;
}
header {
background-color: darkred;
padding: 10px;
}
h1 {
font-size: 36px;
font-weight: bold;
text-transform: uppercase;
text-shadow: 2px 2px #333;
}
h2 {
font-size: 24px;
font-weight: bold;
text-transform: uppercase;
margin: 30px 0;
}
h3 {
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
margin: 20px 0;
}
p {
margin: 20px 0;
line-height: 1.6;
}
a {
color: red;
text-decoration: none;
transition: all 0.3s;
}
a:hover {
color: white;
text-shadow: 1px 1px #333;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
display: inline-block;
margin: 10px;
}
button {
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
padding: 10px 20px;
border: none;
border-radius: 5px;
background-color: darkred;
color: white;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background-color: red;
}
form {
margin: 20px 0;
}
input[type=“text”],
input[type=“email”],
textarea {
font-size: 16px;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #333;
color: white;
margin-bottom: 10px;
width: 100%;
box-sizing: border-box;
}
input[type=“submit”] {
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
padding: 10px 20px;
border: none;
border-radius: 5px;
background-color: darkred;
color: white;
cursor: pointer;
transition: all 0.3s;
}
input[type=“submit”]:hover {
background-color: red;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 50px;
}
Your HTML and JS using this .css:
|
aecffeee563e1d90ffa3643072447baf
|
{
"intermediate": 0.3155333399772644,
"beginner": 0.27414804697036743,
"expert": 0.4103185832500458
}
|
10,327
|
When I open a work book what is the VBA code to calculate a specific sheet
|
296a557f0e1549ffc282965c6af12ed7
|
{
"intermediate": 0.3018225431442261,
"beginner": 0.3191503584384918,
"expert": 0.3790271580219269
}
|
10,328
|
and how do you make "vmcMenu" appear on grid hover, to place new or add new edges or lines?: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const GRID_SIZE = 10;
const GRID_SPACING = 0.2;
const gridLines = [];
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
// Loop through gridSize (both X and Z)
for (let i = 0; i <= gridSize; i += gridSpacing) {
// Add X-Axis lines
gridLines.push([
[-gridSize / 2 + i, 0, -gridSize / 2],
[-gridSize / 2 + i, 0, gridSize / 2]
]);
// Add Z-Axis lines
gridLines.push([
[-gridSize / 2, 0, -gridSize / 2 + i],
[gridSize / 2, 0, -gridSize / 2 + i]
]);
}
}
generateGrid(GRID_SIZE, GRID_SPACING);
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
const x = Math.round(point[0] / gridSpacing) * gridSpacing;
const y = Math.round(point[1] / gridSpacing) * gridSpacing;
const z = Math.round(point[2] / gridSpacing) * gridSpacing;
return [x, y, z];
}
const wireframeLines = [];
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
const startPoint = getClosestGridPoint(vertices[startNewEdgeIndex], GRID_SIZE, GRID_SPACING);
const endPoint = getClosestGridPoint(vertices[bestIndex], GRID_SIZE, GRID_SPACING);
wireframeLines.push([startPoint, endPoint]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
ctx.strokeStyle = "#999";
ctx.lineWidth = 1;
ctx.beginPath();
for (let line of gridLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
ctx.strokeStyle = "#0F0";
ctx.lineWidth = 2;
ctx.beginPath();
for (let line of wireframeLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
81c829d1df7b72e9439fef529bceb458
|
{
"intermediate": 0.29761338233947754,
"beginner": 0.43294212222099304,
"expert": 0.2694445550441742
}
|
10,329
|
and how do you make “vmcMenu” appear on grid hover, to place new or add new edges or lines?: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const GRID_SIZE = 10;
const GRID_SPACING = 0.2;
const gridLines = [];
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
// Loop through gridSize (both X and Z)
for (let i = 0; i <= gridSize; i += gridSpacing) {
// Add X-Axis lines
gridLines.push([
[-gridSize / 2 + i, 0, -gridSize / 2],
[-gridSize / 2 + i, 0, gridSize / 2]
]);
// Add Z-Axis lines
gridLines.push([
[-gridSize / 2, 0, -gridSize / 2 + i],
[gridSize / 2, 0, -gridSize / 2 + i]
]);
}
}
generateGrid(GRID_SIZE, GRID_SPACING);
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
const x = Math.round(point[0] / gridSpacing) * gridSpacing;
const y = Math.round(point[1] / gridSpacing) * gridSpacing;
const z = Math.round(point[2] / gridSpacing) * gridSpacing;
return [x, y, z];
}
const wireframeLines = [];
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
const startPoint = getClosestGridPoint(vertices[startNewEdgeIndex], GRID_SIZE, GRID_SPACING);
const endPoint = getClosestGridPoint(vertices[bestIndex], GRID_SIZE, GRID_SPACING);
wireframeLines.push([startPoint, endPoint]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
ctx.strokeStyle = “#999”;
ctx.lineWidth = 1;
ctx.beginPath();
for (let line of gridLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
ctx.strokeStyle = “#0F0”;
ctx.lineWidth = 2;
ctx.beginPath();
for (let line of wireframeLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
2dd977bea1c19bcac04eaf49d229c4b1
|
{
"intermediate": 0.3234175443649292,
"beginner": 0.5021063089370728,
"expert": 0.17447607219219208
}
|
10,330
|
ModuleNotFoundError: No module named 'alembic'
|
892cd27eab4354da7c3e510c2c8a10e1
|
{
"intermediate": 0.39229413866996765,
"beginner": 0.27354708313941956,
"expert": 0.3341588079929352
}
|
10,331
|
Please create basic AI chat responsive (mobile+PC) page *.html
|
65f770767b4060d1db075fadacb6be90
|
{
"intermediate": 0.12121175229549408,
"beginner": 0.1626759171485901,
"expert": 0.7161123752593994
}
|
10,332
|
and how do you make “vmcMenu” appear on gridpoint hover, to place new or add new edges or lines?: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const GRID_SIZE = 10;
const GRID_SPACING = 0.2;
const gridLines = [];
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
// Loop through gridSize (both X and Z)
for (let i = 0; i <= gridSize; i += gridSpacing) {
// Add X-Axis lines
gridLines.push([
[-gridSize / 2 + i, 0, -gridSize / 2],
[-gridSize / 2 + i, 0, gridSize / 2]
]);
// Add Z-Axis lines
gridLines.push([
[-gridSize / 2, 0, -gridSize / 2 + i],
[gridSize / 2, 0, -gridSize / 2 + i]
]);
}
}
generateGrid(GRID_SIZE, GRID_SPACING);
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
const x = Math.round(point[0] / gridSpacing) * gridSpacing;
const y = Math.round(point[1] / gridSpacing) * gridSpacing;
const z = Math.round(point[2] / gridSpacing) * gridSpacing;
return [x, y, z];
}
const wireframeLines = [];
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
const startPoint = getClosestGridPoint(vertices[startNewEdgeIndex], GRID_SIZE, GRID_SPACING);
const endPoint = getClosestGridPoint(vertices[bestIndex], GRID_SIZE, GRID_SPACING);
wireframeLines.push([startPoint, endPoint]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
ctx.strokeStyle = “#999”;
ctx.lineWidth = 1;
ctx.beginPath();
for (let line of gridLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
ctx.strokeStyle = “#0F0”;
ctx.lineWidth = 2;
ctx.beginPath();
for (let line of wireframeLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
ae1fbfff4f0d17f2d6201f4dafa8ae99
|
{
"intermediate": 0.3084520399570465,
"beginner": 0.501252293586731,
"expert": 0.19029565155506134
}
|
10,333
|
This Julia code:
using BenchmarkTools, Distributed
addprocs()
@everywhere using DataFrames, CSV, DataFrames, Random, StatsBase, LinearAlgebra
@everywhere Data = CSV.read("C:/Users/Użytkownik/Desktop/player22.csv", DataFrame)
# Indices of players for each position
@everywhere RW_idx = findall(x -> occursin("RW", x), Data[!, :Positions])
@everywhere ST_idx = findall(x -> occursin("ST", x), Data[!, :Positions])
@everywhere GK_idx = findall(x -> occursin("GK", x), Data[!, :Positions])
@everywhere CM_idx = findall(x -> occursin("CM", x), Data[!, :Positions])
@everywhere LW_idx = findall(x -> occursin("LW", x), Data[!, :Positions])
@everywhere CDM_idx = findall(x -> occursin("CDM", x), Data[!, :Positions])
@everywhere LM_idx = findall(x -> occursin("LM", x), Data[!, :Positions])
@everywhere CF_idx = findall(x -> occursin("CF", x), Data[!, :Positions])
@everywhere CB_idx = findall(x -> occursin("CB", x), Data[!, :Positions])
@everywhere CAM_idx = findall(x -> occursin("CAM", x), Data[!, :Positions])
@everywhere LB_idx = findall(x -> occursin("LB", x), Data[!, :Positions])
@everywhere RB_idx = findall(x -> occursin("RB", x), Data[!, :Positions])
@everywhere RM_idx = findall(x -> occursin("RM", x), Data[!, :Positions])
@everywhere LWB_idx = findall(x -> occursin("LWB", x), Data[!, :Positions])
@everywhere RWB_idx = findall(x -> occursin("RWB", x), Data[!, :Positions])
@everywhere position_vectors = [RW_idx, ST_idx, GK_idx, CM_idx, LW_idx,
CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx,
LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx]
@everywhere using DataFrames
@everywhere function create_ones_dataframe(n_rows, length_position_vectors)
position_vectors = fill(1, length_position_vectors)
df = DataFrame()
for i in 1:length_position_vectors
col_name = Symbol("Position_$i")
df[!, col_name] = position_vectors
end
return repeat(df, n_rows)
end
@everywhere n_rows = 20
@everywhere pop_init = create_ones_dataframe(n_rows, length(position_vectors))
@everywhere n_rows=100
@everywhere pop_init= pop_init[1:(n_rows), :]
@everywhere function mutate(selected_players, position_vectors_list, probability)
selected_players_matrix = copy(selected_players)
function select_random_player(idx_list, selected_players)
while true
random_idx = rand(idx_list)
if ismissing(selected_players) || !(random_idx in selected_players)
return random_idx
end
end
end
for i in 1:size(selected_players_matrix)[1]
for pos_idx in 1:length(position_vectors_list)
if rand() <= probability
selected_players_matrix[i, pos_idx] = select_random_player(position_vectors_list[pos_idx],
selected_players_matrix[i, :])
end
end
end
return convert(DataFrame, selected_players_matrix)
end
@everywhere n_rows = 100
@everywhere pop_init = mutate(pop_init, position_vectors,1.0)
@everywhere function crossover(parent1, parent2, crossover_point=6)
offspring1 = hcat(DataFrame(parent1[1:crossover_point]), DataFrame(parent2[(crossover_point + 1):end]))
offspring2 = hcat(DataFrame(parent2[1:crossover_point]), DataFrame(parent1[(crossover_point + 1):end]))
return vcat(offspring1,offspring2)
end
@everywhere function target2(row, penalty=5,weight1=0.15,weight2=0.6,weight3=0.3,contraint_1=250000000,constraint2=250000,contraint_3=1.2)
position_ratings = ["RWRating", "STRating", "GKRating", "CMRating",
"LWRating", "CDMRating", "LMRating", "CFRating",
"CBRating", "CAMRating", "LBRating", "RBRating",
"RMRating", "LWBRating", "RWBRating"]
parent_data = DataFrame(ID=Int[], Name=String[], FullName=String[], Age=Int[], Height=Int[], Weight=Int[], PhotoUrl=String[], Nationality=String[], Overall=Int[], Potential=Int[], Growth=Int[], TotalStats=Int[], BaseStats=Int[], Positions=String[], BestPosition=String[], Club=String[], ValueEUR=Int[], WageEUR=Int[], ReleaseClause=Int[], ClubPosition=String[], ContractUntil=String[], ClubNumber=Int[], ClubJoined=Int[], OnLoad=Bool[], NationalTeam=String[], NationalPosition=String[], NationalNumber=Int[], PreferredFoot=String[], IntReputation=Int[], WeakFoot=Int[], SkillMoves=Int[], AttackingWorkRate=String[], DefensiveWorkRate=String[], PaceTotal=Int[], ShootingTotal=Int[], PassingTotal=Int[], DribblingTotal=Int[], DefendingTotal=Int[], PhysicalityTotal=Int[], Crossing=Int[], Finishing=Int[], HeadingAccuracy=Int[], ShortPassing=Int[], Volleys=Int[], Dribbling=Int[], Curve=Int[], FKAccuracy=Int[], LongPassing=Int[], BallControl=Int[], Acceleration=Int[], SprintSpeed=Int[], Agility=Int[], Reactions=Int[], Balance=Int[], ShotPower=Int[], Jumping=Int[], Stamina=Int[], Strength=Int[], LongShots=Int[], Aggression=Int[], Interceptions=Int[], Positioning=Int[], Vision=Int[], Penalties=Int[], Composure=Int[], Marking=Int[], StandingTackle=Int[], SlidingTackle=Int[], GKDiving=Int[], GKHandling=Int[], GKKicking=Int[], GKPositioning=Int[], GKReflexes=Int[], STRating=Int[], LWRating=Int[], LFRating=Int[], CFRating=Int[], RFRating=Int[], RWRating=Int[], CAMRating=Int[], LMRating=Int[], CMRating=Int[], RMRating=Int[], LWBRating=Int[], CDMRating=Int[], RWBRating=Int[], LBRating=Int[], CBRating=Int[], RBRating=Int[], GKRating=Int[])
for i in row
row_indices = Data[i, :]
parent_data=vcat(parent_data,row_indices)
end
parent_data=DataFrame(parent_data[2:16])
ratings = parent_data[:, position_ratings]
ratings_log = log.(ratings)
potential_minus_age = weight1 * parent_data.Potential - weight2 * parent_data.Age
int_reputation = parent_data.IntReputation
sumratings = []
for i in 1:15
temp=ratings_log[i,i]
push!(sumratings, temp)
end
rating_list=sumratings
sumratings=sum(sumratings)
# Apply constraints
constraint_penalty = 0
if sum(parent_data.ValueEUR) > contraint_1
constraint_penalty += log((sum(parent_data.ValueEUR) - contraint_1)) ^ penalty
end
if sum(parent_data.WageEUR) > constraint2
constraint_penalty += log((sum(parent_data.WageEUR) - constraint2)) ^ penalty
end
if any(rating_list .< contraint_3)
constraint_penalty += contraint_3 ^ penalty
end
target_value = -(sumratings + weight3 * sum(potential_minus_age) + sum(int_reputation)) + constraint_penalty
return target_value
end
@everywhere weight1=0.15
@everywhere weight2=0.6
@everywhere weight3=0.3
@everywhere contraint_1=250000000
@everywhere constraint2=250000
@everywhere contraint_3=1.2
@everywhere function tournament_selection2(parents, t_size, penalty=6,nrows=100,weight1=0.15,weight2=0.6,weight3=0.3,contraint_1=250000000,constraint2=250000,contraint_3=1.2)
random_parents = unique(parents[shuffle(1:size(parents, 1)), :])[1:2, :]
random_parents_fitness = [target2(parent, penalty,weight1,weight2,weight3,contraint_1,constraint2,contraint_3) for parent in eachrow(random_parents)]
best_parent_idx = argmin(random_parents_fitness)
return random_parents[best_parent_idx, :]
end
@everywhere function GA2(crossover_point=7, population_size=100, num_generations=10, tournament_size=2, probability=0.09, weight1=0.15,
weight2=0.6,
weight3=0.3,
contraint_1=250000000,
constraint2=250000,
contraint_3=1.2)
nrows=population_size
parents = mutate(pop_init, position_vectors, 1.0)
global_best = pop_init[1, :]
global_best_value = target2(global_best,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
penalty=1
# Main loop
for gen in 1:num_generations
# Parent population
parent_pop = create_ones_dataframe(n_rows, length(position_vectors))
parent_pop = parent_pop[1:n_rows, :]
for c in 1:population_size
parent_pop[c, :] = tournament_selection2(parents, tournament_size, penalty,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
end
# Generate offspring
offspring_temp = create_ones_dataframe(n_rows, length(position_vectors))
offspring_temp = offspring_temp[1:n_rows, :]
for c in 1:2:population_size
offsprings = crossover(parent_pop[c, :], parent_pop[c + 1, :], crossover_point)
offspring_temp = vcat(offspring_temp, offsprings)
end
offspring_temp = offspring_temp[nrows+1:end, :]
parents = mutate(offspring_temp, position_vectors, 0.09)
# Evaluate solutions
solutions = [target2(parent,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3) for parent in eachrow(parents)]
idx_sol = argmin(solutions)
temp_best = parents[idx_sol, :]
temp_target_value = solutions[idx_sol]
if penalty==4
penalty=0
else
penalty+0.5
end
if temp_target_value <= global_best_value
global_best = temp_best
global_best_value = temp_target_value
end
end
return global_best, global_best_value
end
function parallel_processing()
weight1_range = 0.05:0.05:0.2
weight2_range = 0:0.1:1.0
weight3_range = 0.1:0.1:0.9
params = [(weight1, weight2, weight3) for weight1 in weight1_range, weight2 in weight2_range, weight3 in weight3_range]
params = vec(params)
function process_weights(weights)
weight1, weight2, weight3 = weights
global_best, global_best_value = GA2(7, 100, 5000, 2, 0.09, weight1, weight2, weight3, 250000000, 250000, 1.2)
global_best_df = DataFrame(global_best)
return (weight1=weight1, weight2=weight2, weight3=weight3, global_best=global_best_df, global_best_value=global_best_value)
end
results = pmap(process_weights, params)
df_results = DataFrame(weight1 = Float64[], weight2 = Float64[], weight3 = Float64[], global_best = Any[], global_best_value = Any[])
for r in results
push!(df_results, r)
end
return df_results
end
k=parallel_processing()
WORKS TOO FUCKING SLOW. Optimize it. Write whole code, be focused on details.
|
1acb59c62a2d36e5739288f2d2b6602a
|
{
"intermediate": 0.3950219452381134,
"beginner": 0.38250601291656494,
"expert": 0.22247208654880524
}
|
10,334
|
and how do you make “vmcMenu” appear on gridpoint hover, to place new or add new edges or lines? what is this? I want vmc menu to appear on gridpoint hovering with mouse pointer cursor, as for actual 3dmatrix wireframe model in these vertices and edges arrays.: const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const GRID_SIZE = 10;
const GRID_SPACING = 0.2;
const gridLines = [];
function generateGrid(gridSize, gridSpacing) {
// Generate the grid lines along the X and Z axes.
// Loop through gridSize (both X and Z)
for (let i = 0; i <= gridSize; i += gridSpacing) {
// Add X-Axis lines
gridLines.push([
[-gridSize / 2 + i, 0, -gridSize / 2],
[-gridSize / 2 + i, 0, gridSize / 2]
]);
// Add Z-Axis lines
gridLines.push([
[-gridSize / 2, 0, -gridSize / 2 + i],
[gridSize / 2, 0, -gridSize / 2 + i]
]);
}
}
generateGrid(GRID_SIZE, GRID_SPACING);
function getClosestGridPoint(point, gridSize, gridSpacing) {
// Find the nearest grid vertex to the given point and return it.
const x = Math.round(point[0] / gridSpacing) * gridSpacing;
const y = Math.round(point[1] / gridSpacing) * gridSpacing;
const z = Math.round(point[2] / gridSpacing) * gridSpacing;
return [x, y, z];
}
const wireframeLines = [];
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
const startPoint = getClosestGridPoint(vertices[startNewEdgeIndex], GRID_SIZE, GRID_SPACING);
const endPoint = getClosestGridPoint(vertices[bestIndex], GRID_SIZE, GRID_SPACING);
wireframeLines.push([startPoint, endPoint]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
ctx.strokeStyle = “#999”;
ctx.lineWidth = 1;
ctx.beginPath();
for (let line of gridLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
ctx.strokeStyle = “#0F0”;
ctx.lineWidth = 2;
ctx.beginPath();
for (let line of wireframeLines) {
const [start, end] = line;
const [x1, y1] = project(start, canvas.height * scale, offsetX, offsetY, zoom);
const [x2, y2] = project(end, canvas.height * scale, offsetX, offsetY, zoom);
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
8cc99fe4d8630300464df7b128a647f8
|
{
"intermediate": 0.3351248502731323,
"beginner": 0.5228447914123535,
"expert": 0.14203034341335297
}
|
10,335
|
how to get geometrical center of the slot vertices in spine 2d c++ runtime (use latest API)?
|
4b38c03956342dcb559dd22a139c7e18
|
{
"intermediate": 0.5055025815963745,
"beginner": 0.13702523708343506,
"expert": 0.35747215151786804
}
|
10,336
|
hi
|
ed9541e65d5d54cc4735f660845cce83
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,337
|
how to get geometrical center of the slot vertices in spine 2d c++ runtime (use latest API)?
|
4b9461a75019120c587e4c448bd75633
|
{
"intermediate": 0.5055025815963745,
"beginner": 0.13702523708343506,
"expert": 0.35747215151786804
}
|
10,338
|
hi
|
55149c865cd34cf5696ce8f434e091c7
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,339
|
This Julia code:
using BenchmarkTools, Distributed
addprocs()
@everywhere using DataFrames, CSV, DataFrames, Random, StatsBase, LinearAlgebra
@everywhere Data = CSV.read("C:/Users/Użytkownik/Desktop/player22.csv", DataFrame)
# Indices of players for each position
@everywhere RW_idx = findall(x -> occursin("RW", x), Data[!, :Positions])
@everywhere ST_idx = findall(x -> occursin("ST", x), Data[!, :Positions])
@everywhere GK_idx = findall(x -> occursin("GK", x), Data[!, :Positions])
@everywhere CM_idx = findall(x -> occursin("CM", x), Data[!, :Positions])
@everywhere LW_idx = findall(x -> occursin("LW", x), Data[!, :Positions])
@everywhere CDM_idx = findall(x -> occursin("CDM", x), Data[!, :Positions])
@everywhere LM_idx = findall(x -> occursin("LM", x), Data[!, :Positions])
@everywhere CF_idx = findall(x -> occursin("CF", x), Data[!, :Positions])
@everywhere CB_idx = findall(x -> occursin("CB", x), Data[!, :Positions])
@everywhere CAM_idx = findall(x -> occursin("CAM", x), Data[!, :Positions])
@everywhere LB_idx = findall(x -> occursin("LB", x), Data[!, :Positions])
@everywhere RB_idx = findall(x -> occursin("RB", x), Data[!, :Positions])
@everywhere RM_idx = findall(x -> occursin("RM", x), Data[!, :Positions])
@everywhere LWB_idx = findall(x -> occursin("LWB", x), Data[!, :Positions])
@everywhere RWB_idx = findall(x -> occursin("RWB", x), Data[!, :Positions])
@everywhere position_vectors = [RW_idx, ST_idx, GK_idx, CM_idx, LW_idx,
CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx,
LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx]
@everywhere using DataFrames
@everywhere function create_ones_dataframe(n_rows, length_position_vectors)
position_vectors = fill(1, length_position_vectors)
df = DataFrame()
for i in 1:length_position_vectors
col_name = Symbol("Position_$i")
df[!, col_name] = position_vectors
end
return repeat(df, n_rows)
end
@everywhere n_rows = 20
@everywhere pop_init = create_ones_dataframe(n_rows, length(position_vectors))
@everywhere n_rows=100
@everywhere pop_init= pop_init[1:(n_rows), :]
@everywhere function mutate(selected_players, position_vectors_list, probability)
selected_players_matrix = copy(selected_players)
function select_random_player(idx_list, selected_players)
while true
random_idx = rand(idx_list)
if ismissing(selected_players) || !(random_idx in selected_players)
return random_idx
end
end
end
for i in 1:size(selected_players_matrix)[1]
for pos_idx in 1:length(position_vectors_list)
if rand() <= probability
selected_players_matrix[i, pos_idx] = select_random_player(position_vectors_list[pos_idx],
selected_players_matrix[i, :])
end
end
end
return convert(DataFrame, selected_players_matrix)
end
@everywhere n_rows = 100
@everywhere pop_init = mutate(pop_init, position_vectors,1.0)
@everywhere function crossover(parent1, parent2, crossover_point=6)
offspring1 = hcat(DataFrame(parent1[1:crossover_point]), DataFrame(parent2[(crossover_point + 1):end]))
offspring2 = hcat(DataFrame(parent2[1:crossover_point]), DataFrame(parent1[(crossover_point + 1):end]))
return vcat(offspring1,offspring2)
end
@everywhere function target2(row, penalty=5,weight1=0.15,weight2=0.6,weight3=0.3,contraint_1=250000000,constraint2=250000,contraint_3=1.2)
position_ratings = ["RWRating", "STRating", "GKRating", "CMRating",
"LWRating", "CDMRating", "LMRating", "CFRating",
"CBRating", "CAMRating", "LBRating", "RBRating",
"RMRating", "LWBRating", "RWBRating"]
parent_data = DataFrame(ID=Int[], Name=String[], FullName=String[], Age=Int[], Height=Int[], Weight=Int[], PhotoUrl=String[], Nationality=String[], Overall=Int[], Potential=Int[], Growth=Int[], TotalStats=Int[], BaseStats=Int[], Positions=String[], BestPosition=String[], Club=String[], ValueEUR=Int[], WageEUR=Int[], ReleaseClause=Int[], ClubPosition=String[], ContractUntil=String[], ClubNumber=Int[], ClubJoined=Int[], OnLoad=Bool[], NationalTeam=String[], NationalPosition=String[], NationalNumber=Int[], PreferredFoot=String[], IntReputation=Int[], WeakFoot=Int[], SkillMoves=Int[], AttackingWorkRate=String[], DefensiveWorkRate=String[], PaceTotal=Int[], ShootingTotal=Int[], PassingTotal=Int[], DribblingTotal=Int[], DefendingTotal=Int[], PhysicalityTotal=Int[], Crossing=Int[], Finishing=Int[], HeadingAccuracy=Int[], ShortPassing=Int[], Volleys=Int[], Dribbling=Int[], Curve=Int[], FKAccuracy=Int[], LongPassing=Int[], BallControl=Int[], Acceleration=Int[], SprintSpeed=Int[], Agility=Int[], Reactions=Int[], Balance=Int[], ShotPower=Int[], Jumping=Int[], Stamina=Int[], Strength=Int[], LongShots=Int[], Aggression=Int[], Interceptions=Int[], Positioning=Int[], Vision=Int[], Penalties=Int[], Composure=Int[], Marking=Int[], StandingTackle=Int[], SlidingTackle=Int[], GKDiving=Int[], GKHandling=Int[], GKKicking=Int[], GKPositioning=Int[], GKReflexes=Int[], STRating=Int[], LWRating=Int[], LFRating=Int[], CFRating=Int[], RFRating=Int[], RWRating=Int[], CAMRating=Int[], LMRating=Int[], CMRating=Int[], RMRating=Int[], LWBRating=Int[], CDMRating=Int[], RWBRating=Int[], LBRating=Int[], CBRating=Int[], RBRating=Int[], GKRating=Int[])
for i in row
row_indices = Data[i, :]
parent_data=vcat(parent_data,row_indices)
end
parent_data=DataFrame(parent_data[2:16])
ratings = parent_data[:, position_ratings]
ratings_log = log.(ratings)
potential_minus_age = weight1 * parent_data.Potential - weight2 * parent_data.Age
int_reputation = parent_data.IntReputation
sumratings = []
for i in 1:15
temp=ratings_log[i,i]
push!(sumratings, temp)
end
rating_list=sumratings
sumratings=sum(sumratings)
# Apply constraints
constraint_penalty = 0
if sum(parent_data.ValueEUR) > contraint_1
constraint_penalty += log((sum(parent_data.ValueEUR) - contraint_1)) ^ penalty
end
if sum(parent_data.WageEUR) > constraint2
constraint_penalty += log((sum(parent_data.WageEUR) - constraint2)) ^ penalty
end
if any(rating_list .< contraint_3)
constraint_penalty += contraint_3 ^ penalty
end
target_value = -(sumratings + weight3 * sum(potential_minus_age) + sum(int_reputation)) + constraint_penalty
return target_value
end
@everywhere weight1=0.15
@everywhere weight2=0.6
@everywhere weight3=0.3
@everywhere contraint_1=250000000
@everywhere constraint2=250000
@everywhere contraint_3=1.2
@everywhere function tournament_selection2(parents, t_size, penalty=6,nrows=100,weight1=0.15,weight2=0.6,weight3=0.3,contraint_1=250000000,constraint2=250000,contraint_3=1.2)
random_parents = unique(parents[shuffle(1:size(parents, 1)), :])[1:2, :]
random_parents_fitness = [target2(parent, penalty,weight1,weight2,weight3,contraint_1,constraint2,contraint_3) for parent in eachrow(random_parents)]
best_parent_idx = argmin(random_parents_fitness)
return random_parents[best_parent_idx, :]
end
@everywhere function GA2(crossover_point=7, population_size=100, num_generations=10, tournament_size=2, probability=0.09, weight1=0.15,
weight2=0.6,
weight3=0.3,
contraint_1=250000000,
constraint2=250000,
contraint_3=1.2)
nrows=population_size
parents = mutate(pop_init, position_vectors, 1.0)
global_best = pop_init[1, :]
global_best_value = target2(global_best,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
penalty=1
# Main loop
for gen in 1:num_generations
# Parent population
parent_pop = create_ones_dataframe(n_rows, length(position_vectors))
parent_pop = parent_pop[1:n_rows, :]
for c in 1:population_size
parent_pop[c, :] = tournament_selection2(parents, tournament_size, penalty,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
end
# Generate offspring
offspring_temp = create_ones_dataframe(n_rows, length(position_vectors))
offspring_temp = offspring_temp[1:n_rows, :]
for c in 1:2:population_size
offsprings = crossover(parent_pop[c, :], parent_pop[c + 1, :], crossover_point)
offspring_temp = vcat(offspring_temp, offsprings)
end
offspring_temp = offspring_temp[nrows+1:end, :]
parents = mutate(offspring_temp, position_vectors, 0.09)
# Evaluate solutions
solutions = [target2(parent,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3) for parent in eachrow(parents)]
idx_sol = argmin(solutions)
temp_best = parents[idx_sol, :]
temp_target_value = solutions[idx_sol]
if penalty==4
penalty=0
else
penalty+0.5
end
if temp_target_value <= global_best_value
global_best = temp_best
global_best_value = temp_target_value
end
end
return global_best, global_best_value
end
function parallel_processing()
weight1_range = 0.05:0.05:0.2
weight2_range = 0:0.1:1.0
weight3_range = 0.1:0.1:0.9
params = [(weight1, weight2, weight3) for weight1 in weight1_range, weight2 in weight2_range, weight3 in weight3_range]
params = vec(params)
function process_weights(weights)
weight1, weight2, weight3 = weights
global_best, global_best_value = GA2(7, 100, 5000, 2, 0.09, weight1, weight2, weight3, 250000000, 250000, 1.2)
global_best_df = DataFrame(global_best)
return (weight1=weight1, weight2=weight2, weight3=weight3, global_best=global_best_df, global_best_value=global_best_value)
end
results = pmap(process_weights, params)
df_results = DataFrame(weight1 = Float64[], weight2 = Float64[], weight3 = Float64[], global_best = Any[], global_best_value = Any[])
for r in results
push!(df_results, r)
end
return df_results
end
k=parallel_processing()
WORKS TOO FUCKING SLOW. Optimize it. Write whole code, be focused on details. Remeber, the key of this code is to check the response of weight1_range = 0.05:0.05:0.2
weight2_range = 0:0.1:1.0
weight3_range = 0.1:0.1:0.9 on genetic algorithm (here GA2 function).
|
57d074e693666645a649d523eb3a84aa
|
{
"intermediate": 0.3950219452381134,
"beginner": 0.38250601291656494,
"expert": 0.22247208654880524
}
|
10,340
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_markets()
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
server_time = exchange.fetch_currencies()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position["positionSide"] == "LONG" else 'BUY',
type='MARKET',
quantity=abs(float(current_position["positionAmt"])),
positionSide=current_position["positionSide"],
reduceOnly=True
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"side": "buy" if signal == "buy" else "sell",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR: BTC/USDT found in the market
The signal time is: 2023-06-05 19:51:31 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 254, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 241, in order_execution
response = binance_futures.fapiPrivatePostOrder(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'side'
|
f16308111885f23a143392feb5a7b46f
|
{
"intermediate": 0.5044465065002441,
"beginner": 0.3187195956707001,
"expert": 0.17683392763137817
}
|
10,341
|
I'm looking for a script for google sheets that does the following thing. I want it to look at each value in columns C, H, M, and R in the active sheet. If that value has a a richtext hyperlink in it, I want the script to search for all the values in column C of another sheet called "List" and look for a match for that hyperlink URL. If a match exists (that is, if the address of the richtext hyperlink in the active sheet matches a value of a cell in the C column of sheet "List"), I want the script to move to the next cell. If there is no match, I want the script copy the URL of the link from the richtext to an empty cell in the C column in List. The row of that cell should be one row below the lowest row in "List" where the C-column cell of that row is occupied. Can you please try to compose that script?
|
b52888e5a9e79cf2cfb90adf2ff2d693
|
{
"intermediate": 0.41951489448547363,
"beginner": 0.20911182463169098,
"expert": 0.37137332558631897
}
|
10,342
|
please, provide me c# code that parses pdf file and finds out text that is next to phrase "company" on one line of text
|
cc85958886bfc459efe09ab4cf42b52d
|
{
"intermediate": 0.5651326179504395,
"beginner": 0.1195150762796402,
"expert": 0.3153522312641144
}
|
10,343
|
hi
|
75d75200e4d062a58a9bc1b16ef92822
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,344
|
import { Text, View, Pressable, TextInput, Alert, ScrollView} from 'react-native';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { gStyle } from '../styles/style';
import React, {useState} from 'react';
import { firebase } from '../Firebase/firebase';
export default function Registration() {
const [name, setName] = useState('');
const [surname, setSurname]=useState('');
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword]=useState('');
const handleRegistration=()=>{
if(
name===''||
surname===''||
email===''||
phone===''||
password===''||
confirmPassword===''
){
Alert.alert('Ошибка!','Пожалуйста, заполните все поля для регистрации');
}
if(password!==confirmPassword){
Alert.alert('Ошибка!','Пароли не совпадают');
return;
}
auth()
.createUserWithEmailAndPassword(email, password)
.then((result)=>{
const userDetails={
name,
surname,
email,
phone,
};
database().ref(`users/${result.user.uid}`).set(userDetails);
})
.catch((error)=>{
Alert.alert(error.message);
})
}
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Зарегистрироваться</Text>
<Text style={gStyle.RegLine}></Text>
<View style={gStyle.RegContainer}>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Имя</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setName(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Фамилия</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setSurname(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Электронная почта</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setEmail(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Номер телефона</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setPhone(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Пароль</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setPassword(text)}
secureTextEntry={true}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Подтверждение пароля</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setConfirmPassword(text)}
secureTextEntry={true}/>
</View>
</View>
<Pressable style={gStyle.RegRegistrBtn}
onPress={handleRegistration}
>
<Text style={gStyle.RegRegistration}>Зарегистрироваться</Text>
</Pressable>
<Text style={gStyle.RegConf}>Нажимая на кнопку, Вы соглашаетесь с{'\n'}Политикой конфиденциальности</Text>
<Text style={gStyle.RegLine}></Text>
</View>
<Footer/>
</ScrollView>
</View>
);
};
is it correct?
|
ccff1a417475e8a43209ded41b36ca29
|
{
"intermediate": 0.418329119682312,
"beginner": 0.4388933479785919,
"expert": 0.14277762174606323
}
|
10,345
|
Want assistance provided by qualified individuals enabled with experience on understanding charts using technical analysis tools while interpreting macroeconomic environment prevailing across world consequently assisting customers acquire long term advantages requires clear verdicts therefore seeking same through informed predictions written down precisely! I want you to act as a data scientist and code for me.
How can I make a model for predicting stockmarket? It must be certain, and add all the factors that can influence stock prices (Give proper scripts)
My Objective: Predict the direction of stock prices (up or down)
You can use various indicators like williams indicator
Model: LSTM
|
594796d8c0c561ecc6f7f55c921c39a4
|
{
"intermediate": 0.4507659673690796,
"beginner": 0.22590534389019012,
"expert": 0.3233286440372467
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.