row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
8,229
- name: Comparing last updated kernel and running kernel shell: | LAST_KERNEL=$(rpm -q --last kernel |head -1 | awk '{print $1}' | sed 's/kernel-//'); CURRENT_KERNEL=$(uname -r) if [[ $LAST_KERNEL != $CURRENT_KERNEL ]]; then # Set reboot flag touch /tmp/reboot echo "KERNEL_CHANGED" else echo "No KERNEL Change Detected" fi register: kernel_update_status - name: Reboot Requirement debug: msg: "KERNEL_CHANGED" when: kernel_update_status == "KERNEL_CHANGED" - name: Reboot the machine (Wait for 5 min or 300 Sec) reboot: reboot_timeout: 300 test_command: uptime when: kernel_update_status == "KERNEL_CHANGED" register: reboot_status - name : Wait for server to come back online after restart. wait_for_connection: delay : '10' timeout : '500' - meta : end_play
9bc7ba08057c8a86372b35213112d16e
{ "intermediate": 0.3178209662437439, "beginner": 0.4625280797481537, "expert": 0.2196509838104248 }
8,230
Using an understanding understanding of loops, if statements, compound conditions, strings, lists, and binary numbers. "Write a program that prompts the user for a string. Similar to Lab 2 Question 4, the program will print the string back in reverse order, but this time it will only print characters located at index that is divisible by 2 and divisible by 3 (meaning there is no remainder after division of string index by 2 or after division by 3). You must use a “for” loop and only one “if” statement in your solution. Sample run: Enter a string: abcdefghijklmnopqrst smga
4cabf6e997a24944788006a0c1c987c5
{ "intermediate": 0.1268426775932312, "beginner": 0.8168259263038635, "expert": 0.0563313364982605 }
8,231
Using knowledge of loops, if statements, compound conditions, strings, lists, and binary numbers "Question 2. (3 marks correctness, 3 marks demo, 1 mark documentation) Write a program that takes a list of numbers as input from the user, prints the list of numbers that the user entered, and prints the sum of the even and odd numbers in the list. Instructions: 1. Declare an empty list to store the numbers. 2. Prompt the user to enter a series of numbers, one at a time, until the input “done” is given. 3. Append each number to the list. 4. Calculate the sum of the even and odd numbers in the list separately. Note: In this case the program is looking for even and odd numbers given by the user, not odd and even indices. 5. Print the list of numbers to the screen. 6. Print the sum of the even numbers. 7. Print the sum of the odd numbers
5b3a31ca4d17fcdf526896606a93d221
{ "intermediate": 0.17393070459365845, "beginner": 0.7457917928695679, "expert": 0.08027749508619308 }
8,232
how to add this loader.jsx on below code loader.jsx import React from 'react'; const Loader = () => ( <div className="flex justify-center items-center h-screen"> <div className="relative w-12 h-12"> <div className="absolute top-0 left-0 w-full h-full rounded-full bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 animate-pulse"></div> <div className="absolute top-0 left-0 w-full h-full rounded-full bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 opacity-75 animate-pulse"></div> <div className="absolute top-0 left-0 w-full h-full rounded-full bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 opacity-50 animate-pulse"></div> <div className="absolute top-0 left-0 w-full h-full rounded-full bg-gradient-to-r from-purple-400 via-pink-500 to-red-500 opacity-25 animate-pulse"></div> </div> <div className="ml-3 text-xl font-bold text-gray-700 animate-pulse">Loading...</div> </div> ); export default Loader; import Descriptions from "./components/Descriptions"; import { useEffect, useState } from "react"; import { getFormattedWeatherData } from "./weatherService"; function App() { const [isAnimating, setIsAnimating] = useState(false); const handleButtonClick = () => { setIsAnimating(true); setTimeout(() => { setIsAnimating(false); }, 1000); // Animation duration in milliseconds }; const [city, setCity] = useState("Hyderabad"); const [weather, setWeather] = useState(null); const [units, setUnits] = useState("metric"); const hotBg = `https://source.unsplash.com/1920x1080/?summer`; const [bg, setBg] = useState(hotBg); useEffect(() => { const coldBg = "https://source.unsplash.com/1920x1080/?ice"; const fetchWeatherData = async () => { const data = await getFormattedWeatherData(city, units); setWeather(data); // dynamic bg const threshold = units === "metric" ? 20 : 60; if (data.temp <= threshold) setBg(coldBg); else setBg(hotBg); }; fetchWeatherData(); }, [units, city]); const handleUnitsClick = (e) => { const button = e.currentTarget; const currentUnit = button.innerText.slice(1); const isCelsius = currentUnit === "C"; button.innerText = isCelsius ? "°F" : "°C"; setUnits(isCelsius ? "metric" : "imperial"); }; const enterKeyPressed = (e) => { if (e.keyCode === 13) { setCity(e.currentTarget.value); e.currentTarget.blur(); } }; return ( <div className="justify-center bg-cover bg-no-repeat bg-center h-screen" style={{ backgroundImage: `url(${bg})` }} > <div className="h-screen flex justify-center items-center "> <div className="absolute inset-0 bg-black opacity-30"></div> <div className="flex justify-center content-center mx-auto sm:px-6 lg:px-8 relative max-w-[600px] w-full rounded-lg shadow-lg bg-gradient-to-r from-purple-600 to-blue-600 to-pink-600 pb-6"> {weather && ( <div className="space-y-4"> <div className="flex justify-between items-center"> <input onKeyDown={enterKeyPressed} type="text" name="city" placeholder="Enter City..." className="border border-gray-300 px-2 py-1 rounded-lg w-full md:w-3/4 focus:outline-none focus:border-blue-400" /> <button onClick={(e) => handleUnitsClick(e)} className={` px-4 py-2 mr-4 text-white text-[40px] font-bold hover:text-yellow-400 transition duration-500 ease-in-out transform ${ isAnimating ? "animate-bounce" : "" }`} > {units === "metric" ? "°C" : "°F"} </button> </div> <div className="flex flex-col items-center justify-center space-y-6"> <div className="flex items-center space-x-4"> <h3 className="font-medium text-gray-700 text-lg"> {weather.name}, {weather.country} </h3> <img src={weather.iconURL} alt="weatherIcon" className="w-12 h-12" /> <h3 className="font-medium text-gray-700 text-lg"> {weather.description} </h3> </div> <div className="flex items-center space-x-2"> <h1 className="font-bold text-4xl text-gray-700"> {weather.temp.toFixed()}°{units === "metric" ? "C" : "F"} </h1> </div> </div> {/* bottom description */} <Descriptions weather={weather} units={units} /> </div> )} </div> </div> </div> ); } export default App;
6ad1e0ed4f2de1b9d20ab264a4410984
{ "intermediate": 0.3109692633152008, "beginner": 0.48630428314208984, "expert": 0.20272649824619293 }
8,233
Write a query that lists for each book its title and the name of its publisher. Order the listing alphabetically by the books' titles. Rename the columns as shown on the result table below.
d3475f11861995a1ad819a58eb5bceae
{ "intermediate": 0.3048074543476105, "beginner": 0.23173806071281433, "expert": 0.4634544849395752 }
8,234
can you write a pine script codes for Trading view
5429cc051cddb33b69273ba9e0c8cd9a
{ "intermediate": 0.3850594162940979, "beginner": 0.4243708848953247, "expert": 0.1905696541070938 }
8,235
How to run Cypress tests on Slack
fb5224f79853e0636400a1c5798323ae
{ "intermediate": 0.3404037058353424, "beginner": 0.07352545112371445, "expert": 0.5860707759857178 }
8,236
A customer can have any number of bank accounts For future multi-factor authentication and other purposes, we must record the customer’s telephone number The bank ranks its customers into three groups: basic, silver, and gold - the system must keep track of this information Customers ranked silver and gold can loan money from the bank Customers can make payments on their loans Customers can transfer money from their accounts if the account balance is sufficient Customers can view their accounts, accounts movements, and accounts balance Bank employees can view all customers and accounts Bank employees can create new customers and accounts and change customer rank Only allowed JavaScript import is HTMX Use a class-less CSS framework, and avoid unnecessary classes in your HTML Use Python 3.9 or newer, Django 4.0 or newer Customers must be able to transfer money to customers in at least one other bank (run two or more instances of the bank simultaneously) Bank to bank transfers must follow a robust, documented protocol Implement some kind of multi-factor authentication for customers and bank employees Must implement at least one of these: REST project name is bank_project and app name is bank_app for package installation use pipenv for database use sqlite3 use htmx for forms and buttons and links base.html is the base template for all other templates
82bca5172326c6e7d05047e86cb4ac84
{ "intermediate": 0.8184555768966675, "beginner": 0.08778737485408783, "expert": 0.0937570109963417 }
8,237
Modify the code below in such a way that the code returns the addresses of all transactions from the “TRANSACTIONS” tab in the given block import requests bscscan_api_key = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ def get_newly_created_contracts(start_block, end_block): url = f’https://api.bscscan.com/api?module=account&action=contractcreated&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}‘ try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f’Error in API request: {e}’) return [] data = response.json() if data[‘status’] == ‘0’: print(f"Error: {data[‘result’]}“) return [] return data[‘result’] def display_new_contracts(start_block, end_block): contracts = get_newly_created_contracts(start_block, end_block) if not contracts: print(‘No new contracts found.’) else: print(f’Token creators between blocks {start_block} and {end_block}:') for contract in contracts: print(f"Block: {contract[‘blockNumber’]} - Token Creator: {contract[‘creatorAddress’]}”) start_block = 28000476 # Replace with your desired start block end_block = 28503476 # Replace with your desired end block display_new_contracts(start_block, end_block)
0868342dc98974cef7797849fc41c731
{ "intermediate": 0.4839744567871094, "beginner": 0.35246679186820984, "expert": 0.1635587215423584 }
8,238
why is this code public static void ListContactsWithLastName(List<Contact> contacts) { string lastName; Write("Enter the last name to find: "); lastName = Console.ReadLine(); if (contacts.Contains(Contact.lastName)) { } } giving me this error and how to fix: Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'Person.lastName' Parashumti - HW3 - Contact Manager C:\Users\erjon\source\repos\Parashumti - HW3 - Contact Manager\Parashumti - HW3 - Contact Manager\Program.cs 90 Active
84cc3da0b737fedfc0b17f908e93c7eb
{ "intermediate": 0.5398650169372559, "beginner": 0.28600284457206726, "expert": 0.17413215339183807 }
8,239
teach me count SQL
978db8bd40084e27b3a6eee7ca235f2a
{ "intermediate": 0.2320004403591156, "beginner": 0.616944432258606, "expert": 0.15105514228343964 }
8,240
Please write python example code
d063b592504f5ba40f63639ec1caf56b
{ "intermediate": 0.3519745469093323, "beginner": 0.27782154083251953, "expert": 0.3702039122581482 }
8,241
модифицируй код так, чтобы в ответ на слово 'пост' пользователя вылетала подборка, с кнопками 'да' и 'нет', при нажатии на 'да' данная подборка выкладывалась в группу при нажатии на 'нет' составлялась другая подборка."""import random import vk_api import requests from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType from vk_api.utils import get_random_id from bs4 import BeautifulSoup import re import sqlite3 # Авторизуемся как сообщество vk_session = vk_api.VkApi(token='vk1.a.KdAkdaN3v-HPcxH8O63IhIfGl_n4U5wby3BzjOYIWthbOvqrajoHJGhKaDb9w9grxESWO7S6en5YKvWqPimOKNtAPBrM8oonxHQ7fCq-FEPsAY-w4-n9x21zS4-3fIqXYQ67QjTFtQqRL6A48x_MUbt0AOgcyyBfbenQnHH-YQeQBaAbKe96UKSinf3gB6kP06eCA9VUDgP31DL9GOC4FQ') vk = vk_session.get_api() longpoll = VkBotLongPoll(vk_session, '220038884') #all_items def get_random_item(): # Создаем соединение с базой данных conn = sqlite3.connect("kross.db") # Создаем курсор для работы с базой данных cursor = conn.cursor() # Выполняем запрос для получения количества элементов в таблице items cursor.execute("SELECT COUNT(*) FROM items") num_items = cursor.fetchone()[0] # Генерируем случайное число от 1 до num_items random_id = random.randint(1, num_items) # Выполняем запрос для получения элемента с рандомным ID cursor.execute("SELECT name, size, info, price, photo_link FROM items WHERE rowid=?", (random_id,)) item = cursor.fetchone() # Закрываем соединение с базой данных conn.close() return item # Функция для отправки фото в сообщении def send_photo(peer_id, photos, message): # Список для хранения идентификаторов фото attachments = [] # Перебираем ссылки на фото for photo in photos: # Скачиваем фото по ссылке response = requests.get(photo) # Открываем файл в бинарном режиме для загрузки на сервер ВК with open('photo.jpg', 'wb') as file: file.write(response.content) # Получаем адрес сервера для загрузки фото upload_url = vk.photos.getMessagesUploadServer()['upload_url'] # Загружаем фото на сервер и получаем ответ response = requests.post(upload_url, files={'photo': open('photo.jpg', 'rb')}).json() # Сохраняем фото в альбоме сообщества и получаем данные о фото photo_data = vk.photos.saveMessagesPhoto(**response)[0] # Формируем идентификатор фото в нужном формате attachment = f'photo{photo_data["owner_id"]}_{photo_data["id"]}' # Добавляем идентификатор в список attachments.append(attachment) # Отправляем сообщение с фото vk.messages.send( peer_id=peer_id, message=message, attachment=','.join(attachments), random_id=get_random_id() ) # Основной цикл бота for event in longpoll.listen(): # Если пришло новое сообщение if event.type == VkBotEventType.MESSAGE_NEW: # Получаем текст сообщения и id чата text = event.obj.message['text'] peer_id = event.obj.message['peer_id'] # Если текст сообщения равен "пост" if text.lower() == 'пост': message_list = [] my_photos =[] for n in range(1, 6): random_item = get_random_item() name = random_item[0] size = random_item[1] price = random_item[3] urlm = random_item[4] message = f'\nНазвание: {name}\nРазмер: {size}\nЦена: {price}\n' my_photos.append(urlm) message_list.append(message) pho = list(set(my_photos)) mes = list(set(message_list)) # Задаем список ссылок на фото (можно изменить на свои) photos = pho # Задаем текст сообщения (можно изменить на свой) message = mes # Вызываем функцию для отправки фото в сообщении send_photo(peer_id, photos, message)"""
0815540ea78bd764638ce3d1aa097461
{ "intermediate": 0.3684937357902527, "beginner": 0.4709985852241516, "expert": 0.1605076938867569 }
8,242
im getting this error bad argument #1 to 'gsub' (string expected, got table) if (Config.saveOnlyESXOwnedVehicles) then QBCore.Functions.CreateCallback("AP:getVehicleOwnership", function(source, plate, model) local trimmedPlate = string.gsub(plate, "^%s*(.-)%s*$", "%1") local results = SqlExecute('SELECT plate FROM player_vehicles WHERE plate = @plate OR plate = @fakeplate', { ['@plate'] = plate, ['@fakeplate'] = fakeplate }) return #results > 0 end)
d4e734946b09ac074108a149f99195a0
{ "intermediate": 0.4110679626464844, "beginner": 0.3812738358974457, "expert": 0.20765818655490875 }
8,243
docker run container-name
cca0ff02f54af6b9d15e0628e191c0e6
{ "intermediate": 0.3623901903629303, "beginner": 0.27371007204055786, "expert": 0.36389976739883423 }
8,244
java code to remove all but the first instrument track from a midi sound sequence
7b7281aa7fda6864f3666287ce8324a7
{ "intermediate": 0.41340315341949463, "beginner": 0.1874687224626541, "expert": 0.3991280496120453 }
8,245
I need a TextField for currency in Android Compose. The TextField should behave: 1. If it is empty is should show 0 with gray text color; 2. When user types the first number, it should turn black; 3. If the user removes all number, the text should stay black without 0, which is mentioned in the first case; 4. If the TextField loses focus and there is no number, the text should like in the first case(0 with gray color)
be6664113d3c130c0c77f38ad68f7549
{ "intermediate": 0.5771088004112244, "beginner": 0.1516522765159607, "expert": 0.27123895287513733 }
8,246
у меня график строится благодаря коду import pandas as pd import seaborn as sns df_78 = pd.read_excel('target_final_2.xlsx', dtype=str, index_col=None) df_melt = pd.melt(df_78, id_vars=['Time','target'], value_vars=['first', 'second', 'third'], var_name='sort_1', value_name='value') df_melt['Time'] = df_melt['Time'].astype(str).astype(int) df_melt['value'] = df_melt['value'].astype(str).astype(int) # Выводим результат picture= sns.lineplot( x = "Time", y = "value", data = df_melt, errorbar='sd', hue = "target",palette=['red', '#D751C9', 'black', 'orange', '#5170D7', 'green']) handles, labels = picture.get_legend_handles_labels() label_dict = dict(zip(labels, handles)) new_labels = [ '0 nM', '1 nM', '5 nM', '10 nM', '20 nM','prot'] new_handles = [label_dict[label] for label in new_labels] #picture.set_title("Заголовок графика", fontsize=16, pad=20) #, fontweight="bold" picture.legend(bbox_to_anchor=(0, 0.8), loc="center left") # сдвиг легенды ближе к оси y , borderaxespad=10 picture.legend(new_handles, new_labels, title="target \nconcentration") picture.set(xlim=(df_melt['Time'].min(), df_melt['Time'].max())) picture.set(ylim=(0, 80000)) picture.set_xlabel( "Time (min)") picture.set_ylabel( "RFU", fontsize=14) legend = picture.get_legend() legend.get_frame().set_linewidth(0) sns.despine(top=True, right=True) picture.spines['bottom'].set_linewidth(2) # увеличить толщину нижней оси до 2 picture.spines["left"].set_linewidth(2) # увеличить толщину левой оси до 2 legend.get_title().set_fontsize("8") # установка размера шрифта заголовка легенды legend.set_title("target \nconcentration", prop={"size": 10}) # установка размера заголовка легенды for text in legend.texts: text.set_fontsize("8") # установка размера шрифта самого текста в легенде . МНе нужно поменять текст "prot" на "200 nM, no SPARDA/ "
f0546d5b5470f0327c964446f775d56a
{ "intermediate": 0.33436304330825806, "beginner": 0.498931884765625, "expert": 0.16670513153076172 }
8,247
Laravel storage s3. How to get multiple files in one request?
8b867dcd14f0a56761070d4767db8c5a
{ "intermediate": 0.5369833111763, "beginner": 0.23195217549800873, "expert": 0.2310645878314972 }
8,248
Laravel s3 delete all files how?
3a2be6c55fea44af86c875973a18b39a
{ "intermediate": 0.5478072762489319, "beginner": 0.1414858102798462, "expert": 0.31070688366889954 }
8,249
package com.bezkoder.springjwt.security.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.bezkoder.springjwt.models.User; import com.bezkoder.springjwt.repository.UserRepository; @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired UserRepository userRepository; @Autowired private PasswordEncoder encoder; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username)); return UserDetailsImpl.build(user); } @Transactional public void updateMember(User user) { User persistence = userRepository.findById(user.getId()) .orElseThrow(() -> new IllegalArgumentException("Failed to find user")); String rawPassword = user.getPassword(); String encPassword = encoder.encode(rawPassword); persistence.setPassword(encPassword); persistence.setEmail(user.getEmail()); } }
212205e3e891b6bce6719411f98c13f7
{ "intermediate": 0.3840685188770294, "beginner": 0.2989213764667511, "expert": 0.3170100748538971 }
8,250
i'm loading a texture in my imgui menu and it's causing some fps issues, i'm using stb_image.h, and this function bool LoadTextureFromFile(const char* filename, ID3D11ShaderResourceView** out_srv, int* out_width, int* out_height) { // Load from disk into a raw RGBA buffer int image_width = 0; int image_height = 0; unsigned char* image_data = stbi_load(filename, &image_width, &image_height, NULL, 4); if (image_data == NULL) return false; // Create texture D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = image_width; desc.Height = image_height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D11Texture2D* pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = image_data; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, out_srv); pTexture->Release(); *out_width = image_width; *out_height = image_height; stbi_image_free(image_data); return true; }
76434607c69937a05eaddd9a39fe9bd2
{ "intermediate": 0.45546892285346985, "beginner": 0.3390507102012634, "expert": 0.20548035204410553 }
8,251
这个脚本什么意思。 if [[ $SKIP_FE == "true" ]] then echo "skip feProcess" else echo "start feProcess" mkdir -p ~/.ssh cp $PWD/deploy/priv/id_rsa ~/.ssh/id_rsa cp $PWD/deploy/priv/config ~/.ssh/config chmod 600 ~/.ssh/id_rsa chmod 600 ~/.ssh/config fi
fdf3d043e5b4b9925bfa2cae2abe6b7a
{ "intermediate": 0.36496663093566895, "beginner": 0.4067758321762085, "expert": 0.22825755178928375 }
8,252
get [“Miles value”](){ return id => “[dat-test-id=‘detail-${id}’]” увидел это в ts, откуда берется id?
ec6d21fc991a0899d3704c751ca0be0c
{ "intermediate": 0.3895096480846405, "beginner": 0.3296903073787689, "expert": 0.28080007433891296 }
8,253
i Want to make a state isSelected with spread planning and urgent and update this state in react native
86c54834a5d7ec210b6664ffc729299e
{ "intermediate": 0.38453927636146545, "beginner": 0.22981682419776917, "expert": 0.385643869638443 }
8,254
I need a TextField for currency in Android Compose. The TextField should behave: 1. If it is empty is should show 0 with gray text color; 2. When user types the first number, it should turn black; 3. If the user removes all number, the text should stay black without 0, which is mentioned in the first case; 4. If the TextField loses focus and there is no number, the text should like in the first case(0 with gray color)
351a42dcc7568e74d24a081290aa703f
{ "intermediate": 0.5771088004112244, "beginner": 0.1516522765159607, "expert": 0.27123895287513733 }
8,255
How can I use a csv file in psychopy to only download and show specific images for each observer?
a18e21ef277dee8eb02ff26f479561b3
{ "intermediate": 0.5029191374778748, "beginner": 0.1284315139055252, "expert": 0.36864936351776123 }
8,256
how do i make a rpn package from my project builded with make
25c6fa140beaa6955cca19c1f68d873c
{ "intermediate": 0.35848379135131836, "beginner": 0.1754976361989975, "expert": 0.46601855754852295 }
8,257
The code below does not return all transactions in the specified block. import requests bscscan_api_key = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ def get_transactions(start_block, end_block): url = f’https://api.bscscan.com/api?module=account&action=tokentx&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}‘ try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f’Error in API request: {e}’) return [] data = response.json() if data[‘status’] == ‘0’: print(f"Error: {data[‘result’]}“) return [] return data[‘result’] def display_transactions(start_block, end_block): transactions = get_transactions(start_block, end_block) if not transactions: print(‘No transactions found.’) else: print(f’Transactions between blocks {start_block} and {end_block}:') for tx in transactions: print(f"Block: {tx[‘blockNumber’]} - From: {tx[‘from’]} To: {tx[‘to’]}”) start_block = 28000476 # Replace with your desired start block end_block = 28503476 # Replace with your desired end block display_transactions(start_block, end_block) It returns a response like this C:\Users\AshotxXx\PycharmProjects\pythonProject17\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\pythonProject17\main.py Error: Error! Missing address No transactions found. Process finished with exit code 0 Write a code that will return all transactions from the specified block. 'Action' parameter to 'txlist' doesn't work.
680a0ca70cc2fe8a6a6896f5d77152f4
{ "intermediate": 0.46920955181121826, "beginner": 0.3362186849117279, "expert": 0.1945718377828598 }
8,258
You are an AI programming assistant. - Follow the user's requirements carefully and to the letter. - First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail. - Then output the code in a single code block. - Minimize any other prose.
2d240c6be6745c93b8c630a5df14fb95
{ "intermediate": 0.19757366180419922, "beginner": 0.3483876883983612, "expert": 0.4540386199951172 }
8,259
what is the best way to check if the current prediction matches any of the previous predictions without taking too much memory in image detection problem using python?
efe0fea9385853026034ad3bf052cb20
{ "intermediate": 0.31139829754829407, "beginner": 0.09379813075065613, "expert": 0.594803512096405 }
8,260
how to pause 5 secondon python
10be6ac61c2884e18a9ffaafbe33e237
{ "intermediate": 0.2903911769390106, "beginner": 0.18507471680641174, "expert": 0.5245341062545776 }
8,261
how do i create my rpm package for CentOS for my project which is builds with cmake
247d7e1a266c306e871bdba297d65473
{ "intermediate": 0.5237882733345032, "beginner": 0.15219470858573914, "expert": 0.32401707768440247 }
8,262
Based on the context between hashtags, I need you to generate C# example code using the latest version of tensorflow.net library that uses dag-based scheduling algorithm with reinforced learning using DQN to find the lowest possible global execution time maximizing CPU and RAM usage, the example should contain code to train the model if already exists and it should save the trained model. #I have a system with 50 CPUs and 60 GB of RAM, I need to execute a list of jobs which can have dependencies between them, the jobs contain a list of items to be processed and can be configured with the number of CPUs and items to process per CPU, the items to process per CPU impact the amount of RAM used by the job.#
d762d0f236073e2ca29b9a58fcd696b9
{ "intermediate": 0.25823378562927246, "beginner": 0.08711576461791992, "expert": 0.6546505093574524 }
8,263
can you give me a sample code java using kecloak for two microservices that intercat each other
77f8a5da9ad956f8e69cda1a4853713a
{ "intermediate": 0.7548450231552124, "beginner": 0.14717644453048706, "expert": 0.09797859191894531 }
8,264
image car and man and dog logo
59d4a939d08bb85d2487bad77a5fa2ba
{ "intermediate": 0.40704596042633057, "beginner": 0.26856598258018494, "expert": 0.3243880271911621 }
8,265
Измени приведенный ниже код таким образом, чтобы он отображал список всех внешних транзакций в указанном блоке import requests bscscan_api_key = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ def get_transactions(address, start_block, end_block): url = f’https://api.bscscan.com/api?module=account&action=txlist&address={address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}’ try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f’Error in API request: {e}‘) return [] data = response.json() if data[‘status’] == ‘0’: print(f"Error: {data[‘result’]}") return [] return data[‘result’] def display_transactions(address, start_block, end_block): transactions = get_transactions(address, start_block, end_block) if not transactions: print(‘No transactions found.’) else: print(f’Transactions between blocks {start_block} and {end_block} for address {address}:’) for tx in transactions: print(f"Hash: {tx[‘hash’]} - From: {tx[‘from’]} To: {tx[‘to’]}") address = ‘0x742d35Cc6634C0532925a3b844Bc454e4438f44e’ # Replace with your desired address start_block = 28000476 # Replace with your desired start block end_block = 28000478 # Replace with your desired end block (use a smaller range for testing) display_transactions(address, start_block, end_block)
40ae512b41e4c785c3ed6a78ea07c033
{ "intermediate": 0.42011553049087524, "beginner": 0.41257309913635254, "expert": 0.16731137037277222 }
8,266
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" #include <cstring> 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; }; 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); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; 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(); 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); }; Renderer.cpp: #include "Renderer.h" Renderer::Renderer() : currentFrame(0), shutdownInProgress(false) { } Renderer::~Renderer() { Shutdown(); } void Renderer::Initialize(GLFWwindow* window) { this->window = window; CreateInstance(); CreateSurface(); ChoosePhysicalDevice(); CreateDevice(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (shutdownInProgress) { return; } shutdownInProgress = true; if (device != VK_NULL_HANDLE) { vkDeviceWaitIdle(device); } CleanupFramebuffers(); CleanupRenderPass(); CleanupSyncObjects(); CleanupCommandBuffers(); CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); if (device != VK_NULL_HANDLE) { CleanupDevice(); } DestroySurface(); CleanupInstance(); shutdownInProgress = false; } void Renderer::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); std::cout << "vkBeginCommandBuffer called…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { physicalDevice = testDevice; break; } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = 0; if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } void Renderer::CleanupCommandPool() { // Clean up Vulkan command pool CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool vkDestroyCommandPool(device, commandPool, nullptr); } void Renderer::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } void Renderer::CleanupFramebuffers() { for (auto framebuffer : framebuffers) { if (framebuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(device, framebuffer, nullptr); framebuffer = VK_NULL_HANDLE; } } framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer } void Renderer::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } void Renderer::CleanupSyncObjects() { for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (renderFinishedSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); if (imageAvailableSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); if (inFlightFences[i] != VK_NULL_HANDLE) vkDestroyFence(device, inFlightFences[i], nullptr); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) { if (pipeline) { pipeline->Cleanup(); } // Create pipeline object and configure its properties pipeline = std::make_shared<Pipeline>(); pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(), mesh->GetVertexInputAttributeDescriptions(), swapChainExtent, {material->GetvertexShader().get(), material->GetfragmentShader().get()}, renderPass, material->GetPipelineLayout(), device); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } The code seems to hang at this line of code in the Renderer::BeginFrame method: vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); The validation output looks like this: Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 0 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 1 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 1 Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 2 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 0 Calling vkBeginCommandBufferà It does this after renderering several frames, but then just stops progressing past this line. The application completely stops at this point. Any ideas of what the issue could be?
9d842242eaa5ce905c54dd2c9a755de9
{ "intermediate": 0.367301881313324, "beginner": 0.36825671792030334, "expert": 0.2644413709640503 }
8,267
what is constr in pydantic
8596e0f69f450881330b878165a178ed
{ "intermediate": 0.4127753674983978, "beginner": 0.3370327353477478, "expert": 0.250191867351532 }
8,268
Make for me a game pong on scratch
df5238a3fbc21fba131059a0bf224cfe
{ "intermediate": 0.3283328711986542, "beginner": 0.34960460662841797, "expert": 0.32206249237060547 }
8,269
Based on the context between hashtags, I need you to generate python example code that uses dag-based scheduling algorithm with reinforced learning using DQN to find the lowest possible global execution time maximizing CPU and RAM usage, the example should contain code to train the model if already exists and it should save the trained model. #I have a system with 50 CPUs and 60 GB of RAM, I need to execute a list of jobs which can have dependencies between them, the jobs contain a list of items to be processed and can be configured with the number of CPUs and items to process per CPU, the items to process per CPU impact the amount of RAM used by the job.#
d69abb998301a32946828b9034052f83
{ "intermediate": 0.14930474758148193, "beginner": 0.05345303192734718, "expert": 0.7972422242164612 }
8,270
const handleSelection = (type) => { setIsSelected({ …isSelected, [type]: !isSelected[type], }); }; // usage <Button title={isSelected.planning ? ‘Planning selected’ : ‘Select planning’} onPress={() => handleSelection(‘planning’)} /> <Button title={isSelected.urgent ? ‘Urgent selected’ : ‘Select urgent’} onPress={() => handleSelection(‘urgent’)} /> update this code to disabled button when other enabled
34cfd99914b14bb559b432b9a94a4c29
{ "intermediate": 0.34556034207344055, "beginner": 0.30483901500701904, "expert": 0.349600613117218 }
8,271
write code ball game c++ use glut open gl
877eacbb86216cb56307d574f3b4be52
{ "intermediate": 0.37907761335372925, "beginner": 0.44479572772979736, "expert": 0.1761266440153122 }
8,272
привет, я написал код на c++/cli с помощью chat Gtp 3.5, но получил много ошибок, помоги мне их исправить private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { // Задаем строки для поиска String^ searchStr1 = "строка1"; String^ searchStr2 = "строка2"; String^ searchStr3 = "строка3"; // Запускаем поиск и удаление строк в параллельных потоках Thread^ thread1 = gcnew Thread(gcnew ThreadStart(this, &HUNTMMR2::MyForm::Thread1Method)); Thread^ thread2 = gcnew Thread(gcnew ThreadStart(this, &HUNTMMR2::MyForm::Thread2Method)); Thread^ thread3 = gcnew Thread(gcnew ThreadStart(this, &HUNTMMR2::MyForm::Thread3Method)); // Запускаем потоки thread1->Start(); thread2->Start(); thread3->Start(); // Дожидаемся завершения всех потоков thread1->Join(); thread2->Join(); thread3->Join(); } void Thread1Method() { String^ searchStr1 = "строка1"; SearchAndDeleteString(searchStr1, listBox1); } void Thread2Method() { String^ searchStr2 = "строка2"; SearchAndDeleteString(searchStr2, listBox2); } void Thread3Method() { String^ searchStr3 = "строка3"; SearchAndDeleteString(searchStr3, nullptr); } void SearchAndDeleteString(String^ searchString, ListBox^ listBox) { // Поиск и удаление строки // Используем openFileDialog1 для выбора файла OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog(); openFileDialog1->Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*"; // Проверяем, был ли выбран файл if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) { String^ filePath = openFileDialog1->FileName; // Открываем выбранный файл для чтения StreamReader^ reader = gcnew StreamReader(filePath); // Открываем временный файл для записи String^ tempFilePath = Path::GetTempFileName(); StreamWriter^ writer = gcnew StreamWriter(tempFilePath); String^ line; StringBuilder^ updatedContents = gcnew StringBuilder(); while ((line = reader->ReadLine()) != nullptr) { updatedContents->AppendLine(line); } // Закрываем файлы reader->Close(); writer->Close(); const int maxCommands = 50; const int maxPlayers = 3; StringBuilder^ sb1 = gcnew StringBuilder(); StringBuilder^ sb2 = gcnew StringBuilder(); for (int i = 0; i <= maxCommands; i++) { for (int j = 0; j <= maxPlayers; j++) { String^ searchStr1 = String::Format("<Attr name=\"MissionBagPlayer_{0}_{1}_blood_line_name\" value=\"", i, j); String^ searchStr2 = String::Format("<Attr name=\"MissionBagPlayer_{0}_{1}_mmr\" value=\"", i, j); String^ searchStr3 = String::Format("<Attr name=\"MissionBagPlayer_{0}_{1}_profileid\" value=\"", i, j); int startIndex = 0; while ((startIndex = updatedContents->IndexOf(searchStr1, startIndex)) != -1) { int valueIndex = updatedContents->IndexOf("value=\"", startIndex); if (valueIndex != -1) { int valueEndIndex = updatedContents->IndexOf("\"", valueIndex + 7); String^ value = updatedContents->Substring(valueIndex + 7, valueEndIndex - valueIndex - 7); if (listBox != nullptr) { listBox->Invoke(gcnew Action<String^>([listBox, value]() { listBox->Items->Add(value); })); } sb1->Append(value)->AppendLine(); updatedContents = updatedContents->Remove(valueIndex + 7, valueEndIndex - valueIndex - 7); startIndex = valueEndIndex + 1; } } startIndex = 0; while ((startIndex = updatedContents->IndexOf(searchStr2, startIndex)) != -1) { int valueIndex = updatedContents->IndexOf("value=\"", startIndex); if (valueIndex != -1) { int valueEndIndex = updatedContents->IndexOf("\"", valueIndex + 7); String^ value = updatedContents->Substring(valueIndex + 7, valueEndIndex - valueIndex - 7); if (listBox != nullptr) { listBox->Invoke(gcnew Action<String^>([listBox, value]() { listBox->Items->Add(value); })); } sb2->Append(value)->AppendLine(); updatedContents = updatedContents->Remove(valueIndex + 7, valueEndIndex - valueIndex - 7); startIndex = valueEndIndex + 1; } } startIndex = 0; while ((startIndex = updatedContents->IndexOf(searchStr3, startIndex)) != -1) { updatedContents = updatedContents->Remove(startIndex + 7, 1); startIndex = startIndex + 8; } } } // Записываем обновленное содержимое во временный файл StreamWriter^ updatedWriter = gcnew StreamWriter(tempFilePath); updatedWriter->Write(updatedContents); updatedWriter->Close(); // Удаляем исходный файл File::Delete(filePath); // Переименовываем временный файл в исходное имя файла File::Move(tempFilePath, filePath); } }
13eb1073f41626d00e8e41d2179f0d80
{ "intermediate": 0.36741209030151367, "beginner": 0.3838859498500824, "expert": 0.2487020194530487 }
8,273
hi
dcc7178cb4f8fce359adccfecae23923
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
8,274
we have a string and list . we need to compare the string with the items of list if the string and item.name have a match more than 50% return the item from list in reatc native
a7a74417e832c56eaa2ead54f4cfbf2d
{ "intermediate": 0.46981188654899597, "beginner": 0.15459851920604706, "expert": 0.3755895495414734 }
8,275
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" #include <cstring> 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; }; 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); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; 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(); 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); }; Renderer.cpp: #include "Renderer.h" Renderer::Renderer() : currentFrame(0), shutdownInProgress(false) { } Renderer::~Renderer() { Shutdown(); } void Renderer::Initialize(GLFWwindow* window) { this->window = window; CreateInstance(); CreateSurface(); ChoosePhysicalDevice(); CreateDevice(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (shutdownInProgress) { return; } shutdownInProgress = true; if (device != VK_NULL_HANDLE) { vkDeviceWaitIdle(device); } CleanupFramebuffers(); CleanupRenderPass(); CleanupSyncObjects(); CleanupCommandBuffers(); CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); if (device != VK_NULL_HANDLE) { CleanupDevice(); } DestroySurface(); CleanupInstance(); shutdownInProgress = false; } void Renderer::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); std::cout << "vkBeginCommandBuffer called…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { physicalDevice = testDevice; break; } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = 0; if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } void Renderer::CleanupCommandPool() { // Clean up Vulkan command pool CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool vkDestroyCommandPool(device, commandPool, nullptr); } void Renderer::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } void Renderer::CleanupFramebuffers() { for (auto framebuffer : framebuffers) { if (framebuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(device, framebuffer, nullptr); framebuffer = VK_NULL_HANDLE; } } framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer } void Renderer::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } void Renderer::CleanupSyncObjects() { for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (renderFinishedSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); if (imageAvailableSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); if (inFlightFences[i] != VK_NULL_HANDLE) vkDestroyFence(device, inFlightFences[i], nullptr); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) { if (pipeline) { pipeline->Cleanup(); } // Create pipeline object and configure its properties pipeline = std::make_shared<Pipeline>(); pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(), mesh->GetVertexInputAttributeDescriptions(), swapChainExtent, {material->GetvertexShader().get(), material->GetfragmentShader().get()}, renderPass, material->GetPipelineLayout(), device); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } The code seems to hang at this line of code in the Renderer::BeginFrame method: vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); The validation output looks like this: Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 0 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 1 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 1 Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 2 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 0 Calling vkBeginCommandBufferà It does this after renderering several frames, but then just stops progressing past this line. The application completely stops at this point. Any ideas of what the issue could be?
b1ba7907f279f11619176241b9360a20
{ "intermediate": 0.367301881313324, "beginner": 0.36825671792030334, "expert": 0.2644413709640503 }
8,276
Преобразуй десятеричное значение блока в приведенном коде в шестнадцатеричное import requests bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' def get_external_transactions(block_number): url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f'Error in API request: {e}') return [] data = response.json() if data['result'] is None: print(f"Error: Cannot find the block") return [] return data['result']['transactions'] def display_transactions(block_number): transactions = get_external_transactions(block_number) if not transactions: print('No transactions found.') else: print(f'Transactions in block {block_number}:') for tx in transactions: print(f"Hash: {tx['hash']} - From: {tx['from']} To: {tx['to']} Value: {tx['value']}") block_number = '0x1AB4C4' # Replace with your desired block number (hexadecimal value) abc = hex(0x1AB4C4) print(abc) display_transactions(block_number)
8efcaab710c7ee4a2db8b358f753f6c6
{ "intermediate": 0.4482796788215637, "beginner": 0.3297829329967499, "expert": 0.2219374030828476 }
8,277
const TelegramBot = require('node-telegram-bot-api'); const sourceChannelId = 813511483; const targetChannelId = 813511483; const bot = new TelegramBot('6298783679:AAHu7hJus-qu_QLal7PDaIalUBRBNACjBzY', { polling: true }); let chat = await bot.getChat("813511483") console.log(chat) bot.on('message', (message) => { if (message.chat.id === sourceChannelId) { const notification = `Renvois Message => : ${message.text}`; console.log(notification) bot.sendMessage(targetChannelId, notification); } });
7ec678a896d638b34e5ad764a9412744
{ "intermediate": 0.46943235397338867, "beginner": 0.3045729398727417, "expert": 0.2259947657585144 }
8,278
How do I recognize malicious/suspicious C# code? Give me a good example of a malicious code hidden as a regular code.
07a9da082187f27a6e3aeb71e543bff5
{ "intermediate": 0.2934969365596771, "beginner": 0.4679517149925232, "expert": 0.23855136334896088 }
8,279
You are a senior developper. You have to develop a virtual tour application using three.js. List all the steps you need to realize the tour.
6e1857afe58a94b564b9f88c5ac28e25
{ "intermediate": 0.48152878880500793, "beginner": 0.259722501039505, "expert": 0.25874871015548706 }
8,280
"while ~isempty(idx) % Check if idx is empty or has only one element if numel(idx) > 1 temp_idx = idx(yp(idx) <= YPredict(:, idx(1:end-1))); else temp_idx = []; end if ~isempty(temp_idx) temp_idx = temp_idx(temp_idx >= 1 & temp_idx <= nTimeStep-1); if ~isempty(temp_idx) [LstmNet, yp(temp_idx)] = predictAndUpdateState(LstmNet, YPredict(:, temp_idx)); YPredict(:, temp_idx+1) = yp(:, temp_idx); end end idx = find(YPredict(:, 2:nTimeStep) <= YPredict(:, 1:nTimeStep-1)); end" this code give me this error "Index exceeds the number of array elements. Index must not exceed 1. Error in MainStockForecating2 (line 70) temp_idx = idx(yp(idx) <= YPredict(:, idx(1:end-1)));"
48d89e6fa2b8df099c546183e1e24f6f
{ "intermediate": 0.4044823944568634, "beginner": 0.3113812506198883, "expert": 0.2841363847255707 }
8,281
使用java编程实现PING的服务器端和客户端,实现操作系统提供的ping命令的类似功能
a338831467c3b2bfa5d0f0c404f25625
{ "intermediate": 0.33683663606643677, "beginner": 0.4013708531856537, "expert": 0.26179245114326477 }
8,282
we have a string and list . we need to compare the string with the items of list if the string and item.name have a match more than 50% return the item from list . exemple str='pediatree' and list =[{id:1,name:"pediatre"},{id:1,name:"medecin physique"},{id:1,name:"medecin esthetique"},{id:1,name:"medecin generaliste"}]
18e999b34412c23d925b717f719e8b9f
{ "intermediate": 0.43821656703948975, "beginner": 0.18986362218856812, "expert": 0.37191978096961975 }
8,283
hi
7adda3a664d123950fbbdd553ca1a4d8
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
8,284
can you explain me a concept of target entity and source entity (wish side of a relation) in JPA Relationship
2f0d96e0ef92430d309999872e924f7d
{ "intermediate": 0.5859021544456482, "beginner": 0.18393167853355408, "expert": 0.23016619682312012 }
8,285
Hello
28b80b1fee1abd118f9cef4ea1352d7d
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
8,286
how can I make this show nice WriteLine("Name {0,-10}", contact.name + contact.lastName); WriteLine("Phone {0,-10}", contact.phoneNum); WriteLine("Email {0,-10}", contact.email); WriteLine("State {0,-10}", contact.state); WriteLine("Age {0, -10}", contact.age);
e93ed9d53fdcbb58fd0e2e68eab60465
{ "intermediate": 0.3343488276004791, "beginner": 0.2192312777042389, "expert": 0.446419894695282 }
8,287
how can I save a created cdf file using pycdf from spacepy
95c5bf761f41e706b164c027f9d6df5f
{ "intermediate": 0.5962343215942383, "beginner": 0.14811758697032928, "expert": 0.25564810633659363 }
8,288
org.freedesktop.DBus - возвращает только три интерфейса, result = g_dbus_proxy_call_sync(proxy, “Introspect”, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); при таком вызове, можно ли расширить возможности вывода?
227a8c12ed36f2bfe813c08f1f4d8f11
{ "intermediate": 0.5844565033912659, "beginner": 0.24127115309238434, "expert": 0.17427240312099457 }
8,289
The following code does pretty much what I want it to doa. My only requirement is that it pastes only the last 20 values found in column 10: Sub LastTenJobs() Dim wscf As Worksheet Dim wsjr As Worksheet Dim lastRow As Long Dim copyRange As Range Dim cell As Range Set wscf = Sheets(Range("G3").Value) Set wsjr = Sheets("Start Page") Application.ScreenUpdating = True Application.EnableEvents = True Range("F25:F28").Calculate ActiveSheet.Range("F5:F24").ClearContents Application.Wait (Now + TimeValue("0:00:01")) ActiveSheet.Range("G3").Formula = ActiveSheet.Range("G3").Formula Application.Wait (Now + TimeValue("0:00:01")) ActiveSheet.Range("H3").Formula = ActiveSheet.Range("H3").Formula If ActiveSheet.Range("G3") = "" Or 0 Then Application.ScreenUpdating = True Application.EnableEvents = True Exit Sub End If Dim lastRowJ As Long Dim lastRowF As Long Dim i As Long 'Set variables Set wscf = Sheets(Range("G3").Value) Set wsjr = Sheets("Start Page") 'Find the last row of column J in wscf lastRowJ = wscf.Cells(wscf.Rows.count, 10).End(xlUp).Row 'If the last row of column J is less than 5, then there is no data to copy If lastRowJ < 5 Then Exit Sub End If 'Copy data from the last row of column J to column F in wsjr lastRowF = 5 'For i = lastRowJ To lastRowJ - 20 + 1 Step -1 For i = lastRowJ To 1 Step -1 'If wscf.Cells(i, 10).Value <> 0 Then If wscf.Cells(i, 10).Value <> vbNullString Then wsjr.Cells(lastRowF, 6).Value = wscf.Cells(i, 10).Value lastRowF = lastRowF + 1 End If Next i Application.ScreenUpdating = True Application.EnableEvents = True Call IncompleteJobs End Sub
99f4633dedf193d60e07f7d6c9dbd178
{ "intermediate": 0.4361696243286133, "beginner": 0.34633567929267883, "expert": 0.2174946814775467 }
8,290
Generate java spark code for SCD type 2 without udf and with parametrizable fields
6f87af3b72ad51c0f0f433fd6b31e170
{ "intermediate": 0.5054598450660706, "beginner": 0.19739432632923126, "expert": 0.297145813703537 }
8,291
can you explain me a concept of target entity and source entity (wish side of a relation) in JPA Relationship? and give me a cocrete example using those concept source and target for @ManyToOne, @OneToMany, @OneToOne, and @ManyToMany
14e324436caad13d217bcb7b723c9175
{ "intermediate": 0.6760783195495605, "beginner": 0.10842693597078323, "expert": 0.215494766831398 }
8,292
explian me the use of MapStruct librairie in spring boot application, with the full sample code java?
31025e45c4ab879fc3b926156ba04540
{ "intermediate": 0.7393226027488708, "beginner": 0.06667675822973251, "expert": 0.19400061666965485 }
8,293
Show me an ASCII art of a crocodile.
dbd3f6acfec83afca6c1549665adfbe0
{ "intermediate": 0.38056525588035583, "beginner": 0.3549731969833374, "expert": 0.2644614577293396 }
8,294
explian me the use of MapStruct librairie in spring boot application, with the full sample code java?
0c7ef03c6edae5dea94ccab5a7877825
{ "intermediate": 0.7393226027488708, "beginner": 0.06667675822973251, "expert": 0.19400061666965485 }
8,295
explian me the use of MapStruct librairie in spring boot application, with the full sample code java?
5b3ccd887b1df76924ff0bd9cabe98b3
{ "intermediate": 0.7393226027488708, "beginner": 0.06667675822973251, "expert": 0.19400061666965485 }
8,296
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" #include <cstring> 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; }; 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); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; 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(); 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); }; Renderer.cpp: #include "Renderer.h" Renderer::Renderer() : currentFrame(0), shutdownInProgress(false) { } Renderer::~Renderer() { Shutdown(); } void Renderer::Initialize(GLFWwindow* window) { this->window = window; CreateInstance(); CreateSurface(); ChoosePhysicalDevice(); CreateDevice(); CreateSwapchain(); CreateRenderPass(); CreateCommandPool(); CreateFramebuffers(); CreateSyncObjects(); } void Renderer::Shutdown() { if (shutdownInProgress) { return; } shutdownInProgress = true; if (device != VK_NULL_HANDLE) { vkDeviceWaitIdle(device); } CleanupFramebuffers(); CleanupRenderPass(); CleanupSyncObjects(); CleanupCommandBuffers(); CleanupCommandPool(); CleanupImageViews(); CleanupSwapchain(); if (device != VK_NULL_HANDLE) { CleanupDevice(); } DestroySurface(); CleanupInstance(); shutdownInProgress = false; } void Renderer::BeginFrame() { // Wait for any previous work on this swapchain image to complete vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); vkResetFences(device, 1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex); if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; //currentCommandBuffer = commandBuffers[currentFrame]; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; // Add debug message before vkBeginCommandBuffer std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n"; std::cout << "Calling vkBeginCommandBuffer…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); std::cout << "vkBeginCommandBuffer called…\n"; vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); VkRenderPassBeginInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); } void Renderer::EndFrame() { vkCmdEndRenderPass(currentCommandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame]; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &currentCommandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame]; vkEndCommandBuffer(currentCommandBuffer); vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]); VkPresentInfoKHR presentInfo{}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame]; VkSwapchainKHR swapChains[] = { swapchain }; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = swapChains; presentInfo.pImageIndices = &imageIndex; VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo); std::cout << "Frame rendered: " << currentFrame << "\n"; if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) { // Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes } else if (queuePresentResult != VK_SUCCESS) { throw std::runtime_error("Failed to present the swapchain image."); } currentFrame = (currentFrame + 1) % kMaxFramesInFlight; } void Renderer::CreateSurface() { if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) { throw std::runtime_error("Failed to create a window surface."); } } void Renderer::DestroySurface() { vkDestroySurfaceKHR(instance, surface, nullptr); } void Renderer::CreateInstance() { // Set up the application info VkApplicationInfo appInfo{}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Game Engine"; appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.pEngineName = "Game Engine"; appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); appInfo.apiVersion = VK_API_VERSION_1_2; // Set up the instance create info VkInstanceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount = glfwExtensionCount; createInfo.ppEnabledExtensionNames = glfwExtensions; createInfo.enabledLayerCount = 0; // Create the Vulkan instance if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) { throw std::runtime_error("Failed to create the Vulkan instance."); } std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> availableLayers(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size()); createInfo.ppEnabledLayerNames = validationLayers.data(); } else { createInfo.enabledLayerCount = 0; } } void Renderer::CleanupInstance() { // Destroy the Vulkan instance vkDestroyInstance(instance, nullptr); } void Renderer::ChoosePhysicalDevice() { // Enumerate the available physical devices and choose one that supports required features uint32_t deviceCount = 0; vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr); if (deviceCount == 0) { throw std::runtime_error("Failed to find a GPU with Vulkan support."); } std::vector<VkPhysicalDevice> allDevices(deviceCount); vkEnumeratePhysicalDevices(instance, &deviceCount, allDevices.data()); for (const auto& testDevice : allDevices) { if (glfwGetPhysicalDevicePresentationSupport(instance, testDevice, 0) && CheckPhysicalDeviceExtensionSupport(testDevice).empty() && GetQueueFamilyIndices(testDevice).IsComplete()) { physicalDevice = testDevice; break; } } if (physicalDevice == VK_NULL_HANDLE) { throw std::runtime_error("Failed to find a suitable GPU."); } } void Renderer::CreateDevice() { // Get the GPU’s queue family indices const QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); // Set up the device queue create info std::vector<VkDeviceQueueCreateInfo> queueCreateInfos; std::set<uint32_t> uniqueQueueFamilyIndices = { indices.graphicsFamily.value(),indices.presentFamily.value() }; float queuePriority = 1.0f; for (uint32_t queueFamilyIndex : uniqueQueueFamilyIndices) { VkDeviceQueueCreateInfo queueCreateInfo{}; queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueCreateInfo.queueFamilyIndex = queueFamilyIndex; queueCreateInfo.queueCount = 1; queueCreateInfo.pQueuePriorities = &queuePriority; queueCreateInfos.push_back(queueCreateInfo); } // Set up the physical device features VkPhysicalDeviceFeatures deviceFeatures{}; // Set up the device create info VkDeviceCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size()); createInfo.pQueueCreateInfos = queueCreateInfos.data(); createInfo.pEnabledFeatures = &deviceFeatures; createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size()); createInfo.ppEnabledExtensionNames = deviceExtensions.data(); // Create the logical device if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) { throw std::runtime_error("Failed to create a logical device."); } // Retrieve the graphics queue and the present queue vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue); vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue); } void Renderer::CleanupDevice() { // Destroy the logical device vkDestroyDevice(device, nullptr); } void Renderer::CreateSwapchain() { // Get swapchain support details SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice,surface); VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats); swapChainImageFormat = surfaceFormat.format; // Initialize the swapChainImageFormat VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes); VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities,window); uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } // Create the swapchain // … VkSwapchainCreateInfoKHR createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; createInfo.surface = surface; createInfo.minImageCount = imageCount; createInfo.imageFormat = surfaceFormat.format; createInfo.imageColorSpace = surfaceFormat.colorSpace; createInfo.imageExtent = extent; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; QueueFamilyIndices indices = GetQueueFamilyIndices(physicalDevice); uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() }; if (indices.graphicsFamily != indices.presentFamily) { createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT; createInfo.queueFamilyIndexCount = 2; createInfo.pQueueFamilyIndices = queueFamilyIndices; } else { createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; } createInfo.preTransform = swapChainSupport.capabilities.currentTransform; createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR; createInfo.presentMode = presentMode; createInfo.clipped = VK_TRUE; if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapchain) != VK_SUCCESS) { throw std::runtime_error("failed to create swap chain!"); } // Retrieve swapchain images (color buffers) // … // Retrieve swapchain images vkGetSwapchainImagesKHR(device, swapchain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(device, swapchain, &imageCount, swapChainImages.data()); // Create image views for swapchain images CreateImageViews(); } void Renderer::CleanupSwapchain() { // Clean up Vulkan swapchain if (swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, swapchain, nullptr); swapchain = VK_NULL_HANDLE; } } void Renderer::CreateImageViews() { swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); ++i) { VkImageViewCreateInfo createInfo{}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = swapChainImageFormat; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; createInfo.flags = 0; if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create an image view."); } } } void Renderer::CleanupImageViews() { for (auto imageView : swapChainImageViews) { vkDestroyImageView(device, imageView, nullptr); } swapChainImageViews.clear(); } void Renderer::CreateRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference colorAttachmentRef{}; colorAttachmentRef.attachment = 0; colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; VkSubpassDescription subpass{}; subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpass.colorAttachmentCount = 1; subpass.pColorAttachments = &colorAttachmentRef; VkRenderPassCreateInfo renderPassInfo{}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; renderPassInfo.attachmentCount = 1; renderPassInfo.pAttachments = &colorAttachment; renderPassInfo.subpassCount = 1; renderPassInfo.pSubpasses = &subpass; VkSubpassDependency dependency{}; dependency.srcSubpass = VK_SUBPASS_EXTERNAL; dependency.dstSubpass = 0; dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.srcAccessMask = 0; dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; renderPassInfo.dependencyCount = 1; renderPassInfo.pDependencies = &dependency; if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) { throw std::runtime_error("Failed to create render pass."); } } void Renderer::CleanupRenderPass() { vkDestroyRenderPass(device, renderPass, nullptr); } void Renderer::CreateCommandPool() { // Find a queue family index that supports graphics operations QueueFamilyIndices queueFamilyIndices = GetQueueFamilyIndices(physicalDevice); // Create a command pool for the queue family VkCommandPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value(); poolInfo.flags = 0; if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create command pool."); } CreateCommandBuffers(); // Create command buffers after creating the command pool } void Renderer::CleanupCommandPool() { // Clean up Vulkan command pool CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool vkDestroyCommandPool(device, commandPool, nullptr); } void Renderer::CreateCommandBuffers() { //commandBuffers.resize(kMaxFramesInFlight); commandBuffers.resize(kMaxFramesInFlight * 2); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = static_cast<uint32_t>(commandBuffers.size()); if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate command buffers."); } // Set the initial value of the currentCommandBuffer currentCommandBuffer = commandBuffers[currentFrame]; } void Renderer::CleanupCommandBuffers() { vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data()); } void Renderer::CreateFramebuffers() { // Check if the framebuffers vector is not empty, and call CleanupFramebuffers() if (!framebuffers.empty()) { CleanupFramebuffers(); } // Create Vulkan framebuffers for swapchain images framebuffers.resize(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); ++i) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = renderPass; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = swapChainExtent.width; framebufferInfo.height = swapChainExtent.height; framebufferInfo.layers = 1; if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &framebuffers[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create framebuffer."); } } } void Renderer::CleanupFramebuffers() { for (auto framebuffer : framebuffers) { if (framebuffer != VK_NULL_HANDLE) { vkDestroyFramebuffer(device, framebuffer, nullptr); framebuffer = VK_NULL_HANDLE; } } framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer } void Renderer::CreateSyncObjects() { imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE); inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE); VkSemaphoreCreateInfo semaphoreInfo{}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkFenceCreateInfo fenceInfo{}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS || vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS || vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) { throw std::runtime_error("Failed to create synchronization objects for a frame."); } } } void Renderer::CleanupSyncObjects() { for (size_t i = 0; i < kMaxFramesInFlight; ++i) { if (renderFinishedSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr); if (imageAvailableSemaphores[i] != VK_NULL_HANDLE) vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr); if (inFlightFences[i] != VK_NULL_HANDLE) vkDestroyFence(device, inFlightFences[i], nullptr); } } SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface) { SwapChainSupportDetails details; // Query the capabilities vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities); // Query the supported formats uint32_t formatCount; vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr); if (formatCount != 0) { details.formats.resize(formatCount); vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data()); } // Query the supported present modes uint32_t presentModeCount; vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr); if (presentModeCount != 0) { details.presentModes.resize(presentModeCount); vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data()); } return details; } VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) { for (const auto& availableFormat : availableFormats) { if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) { return availableFormat; } } return availableFormats[0]; } VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) { for (const auto& availablePresentMode : availablePresentModes) { if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) { return availablePresentMode; } } return VK_PRESENT_MODE_FIFO_KHR; } VkExtent2D Renderer::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window) { if (capabilities.currentExtent.width != UINT32_MAX) { return capabilities.currentExtent; } else { int width, height; glfwGetFramebufferSize(window, &width, &height); VkExtent2D actualExtent = { static_cast<uint32_t>(width), static_cast<uint32_t>(height) }; actualExtent.width = std::max(capabilities.minImageExtent.width, std::min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = std::max(capabilities.minImageExtent.height, std::min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } std::vector<const char*> Renderer::CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice) { uint32_t extensionCount; vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> availableExtensions(extensionCount); vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data()); std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end()); for (const auto& extension : availableExtensions) { requiredExtensions.erase(extension.extensionName); } std::vector<const char*> remainingExtensions; for (const auto& extension : requiredExtensions) { remainingExtensions.push_back(extension.c_str()); } return remainingExtensions; } QueueFamilyIndices Renderer::GetQueueFamilyIndices(VkPhysicalDevice physicalDevice) { QueueFamilyIndices indices; uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilies.data()); int i = 0; for (const auto& queueFamily : queueFamilies) { if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { indices.graphicsFamily = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { indices.presentFamily = i; } if (indices.IsComplete()) { break; } i++; } return indices; } VkDevice* Renderer::GetDevice() { return &device; }; VkPhysicalDevice* Renderer::GetPhysicalDevice() { return &physicalDevice; }; VkCommandPool* Renderer::GetCommandPool() { return &commandPool; }; VkQueue* Renderer::GetGraphicsQueue() { return &graphicsQueue; }; VkCommandBuffer* Renderer::GetCurrentCommandBuffer() { return &currentCommandBuffer; } 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; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &uboLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) { if (pipeline) { pipeline->Cleanup(); } // Create pipeline object and configure its properties pipeline = std::make_shared<Pipeline>(); pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(), mesh->GetVertexInputAttributeDescriptions(), swapChainExtent, {material->GetvertexShader().get(), material->GetfragmentShader().get()}, renderPass, material->GetPipelineLayout(), device); } std::shared_ptr<Pipeline> Renderer::GetPipeline() { return pipeline; } The code seems to hang at this line of code in the Renderer::BeginFrame method: vkBeginCommandBuffer(currentCommandBuffer, &beginInfo); The validation output looks like this: Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 0 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 1 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 1 Current Frame: 0 | Cmd Buffer Index: 1 | Image Index: 2 Calling vkBeginCommandBufferà vkBeginCommandBuffer calledà Frame rendered: 0 Current Frame: 1 | Cmd Buffer Index: 0 | Image Index: 0 Calling vkBeginCommandBufferà It does this after renderering several frames, but then just stops progressing past this line. The application completely stops at this point. Any ideas of what the issue could be?
36aadb18104eafbd13f5ec9abf962d82
{ "intermediate": 0.367301881313324, "beginner": 0.36825671792030334, "expert": 0.2644413709640503 }
8,297
Why does my github actions keep changing to the repo with the latest commit push, how can i set it to only deploy when main has recent pushes?
da7c3119c65f1041a94c9973b023fb45
{ "intermediate": 0.503757894039154, "beginner": 0.24060887098312378, "expert": 0.25563326478004456 }
8,298
repeat this:
7f773c5a73f38b93e37f4415c33c0cdb
{ "intermediate": 0.3278663754463196, "beginner": 0.3366943299770355, "expert": 0.3354393541812897 }
8,299
Generate java spark code for SCD type 2 without udf and with parametrizable fields and hashing
c88cdb226b93e70ddd7ee13dbc29de72
{ "intermediate": 0.5402789115905762, "beginner": 0.17016877233982086, "expert": 0.2895522713661194 }
8,300
Generate java spark code for SCD type 2 without udf and with parametrized fields and hashing and 5 primary keys and 10 value fields and schema check
4da2fc49e7b94e7714e52efe1013fb15
{ "intermediate": 0.5596026182174683, "beginner": 0.14715349674224854, "expert": 0.2932438850402832 }
8,301
Измени ниже приведенный код таким образом, чтобы возвращались не все транзакции заданного блока, а только транзакции, у которых в {tx[‘to’] есть метод Create (New contract source code verified) import requests bscscan_api_key = ‘CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS’ def get_external_transactions(block_number): url = f’https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}‘ try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f’Error in API request: {e}’) return [] data = response.json() if data[‘result’] is None: print(f"Error: Cannot find the block") return [] return data[‘result’][‘transactions’] def display_transactions(block_number): transactions = get_external_transactions(block_number) if not transactions: print(‘No transactions found.’) else: print(f’Transactions in block {block_number}:') for tx in transactions: print(f"Hash: {tx[‘hash’]} - From: {tx[‘from’]} To: {tx[‘to’]} Value: {tx[‘value’]}") block_number = ‘1B330D0’ # Replace with your desired block number (hexadecimal value) decimal_block_number = int(‘1B330D0’, 16) print(decimal_block_number) display_transactions(block_number)
af99b84849e3e3d1219c18a4e037242d
{ "intermediate": 0.47168660163879395, "beginner": 0.37975871562957764, "expert": 0.1485546976327896 }
8,302
java code to display a 88 key piano keyboard as swing gui with pressable white and black keys
14215593b5815c2b0ebd1590575a6319
{ "intermediate": 0.48298192024230957, "beginner": 0.16698680818080902, "expert": 0.3500312864780426 }
8,303
what are openmpi-dev openmpi-common and build-essential packages for arch linux
7ab8761e4e206fdf226b57d0e711a153
{ "intermediate": 0.5670361518859863, "beginner": 0.22555026412010193, "expert": 0.20741359889507294 }
8,304
Generate java spark code for SCD type 2 without udf and with parametrizable fields, hashing, partitionning and schema check
4615e99c79ad476e16c320f297d626de
{ "intermediate": 0.5915141105651855, "beginner": 0.1617279201745987, "expert": 0.24675799906253815 }
8,305
Based on the following prisma schemas model Quote { id Int @id @default(autoincrement()) price Decimal @db.Decimal(10, 2) quantity Float // UoMCode String // measurment ItemMeasurement @relation(fields: [UoMCode], references: [UoMCode]) measurementUnit String measurement UnitOfMeasurement @relation(fields: [measurementUnit], references: [code]) shopContactName String? shopContactPhone String? shopLocation String? shopLatitude String? shopLongitude String? quotationId Int quotation Quotation @relation(fields: [quotationId], references: [id]) quoteComments QuotationComment[] cleanedQuote CleanedQuote? interpolatedQuote InterpolatedQuote? updateNotes Json[] deleteNotes Json[] updatedAt DateTime @updatedAt createdAt DateTime @default(now()) } model Quotation { id Int @id @default(autoincrement()) status QuotationStatus @default(PENDING) creationStatus QuotationCreationStatus @default(COLLECTED) approverId Int? approver User? @relation("approver", fields: [approverId], references: [id]) marketplaceCode Int marketplace Marketplace @relation(fields: [marketplaceCode], references: [code]) collectorId Int collector User @relation("collector", fields: [collectorId], references: [id]) questionnaireId Int itemCode Int questionnaireItem QuestionnaireItem @relation(fields: [questionnaireId, itemCode], references: [questionnaireId, itemCode]) branchApproverId Int? branchApprover User? @relation("branchApprover", fields: [branchApproverId], references: [id]) quotes Quote[] unfoundQuotes UnfoundQuote[] cleanedQuotes CleanedQuote[] interpolatedQuotes InterpolatedQuote[] // quoteMean QuotesMean? updatedAt DateTime @updatedAt createdAt DateTime @default(now()) @@unique([questionnaireId, itemCode, marketplaceCode]) } model UnfoundQuote { id Int @id @default(autoincrement()) reason String quotationId Int quotation Quotation @relation(fields: [quotationId], references: [id]) quoteComments QuotationComment[] updatedAt DateTime @updatedAt createdAt DateTime @default(now()) } update the following function //---------- Edit Quote reason ---------- async editQuoteReason(req: Request, res: Response, next: NextFunction) { try { const updatedQuote: UnfoundQuote = req.body; const quotationId = parseInt(req.params.quotaionId); const quotation = await prisma.quotation.findFirst({ where: { id: quotationId, status: QuotationStatus.PENDING, }, include: { quotes: true, questionnaireItem: true, unfoundQuotes: true, }, }); const questionnaire = await prisma.questionnaire.findUnique({ where: { id: quotation?.questionnaireId }, }); if ( !quotation || quotation.collectorId !== req.user?.id || !questionnaire ) { console.log('User is: ', req.user, ' Quotation is: ', quotation); return res .status(httpStatusCodes.NOT_FOUND) .json( new ResponseJSON('Quote not found', true, httpStatusCodes.NOT_FOUND) ); } if ( questionnaire.endDate.getTime() <= addDays(new Date(), -10).getTime() || ([ QuotationStatus.BRANCH_APPROVED, QuotationStatus.STATISTICIAN_APPROVED, QuotationStatus.SUPERVISOR_APPROVED, ].includes(quotation.status as any) && req.user.role === rolesNum['DATA COLLECTOR']) ) { return res .status(httpStatusCodes.UNAUTHORIZED) .json( new ResponseJSON( 'Quote is Already Approved', true, httpStatusCodes.UNAUTHORIZED ) ); } if (quotation.collectorId != req.user.id) { return res .status(httpStatusCodes.UNAUTHORIZED) .json( new ResponseJSON( errorMessages.UNAUTHORIZED, true, httpStatusCodes.UNAUTHORIZED ) ); } updatedQuote.updatedAt = new Date(); const result = await prisma.$transaction([ prisma.quote.update({ where: { id: quotationId, }, data: updatedQuote, }), prisma.quotation.update({ where: { id: quotationId }, data: { status: QuotationStatus.PENDING, }, }), // prisma.quotationComment.deleteMany({ // where: { // commenterId: req.user.id, // quotationId: quotationId, // }, // }), ]); return res .status(httpStatusCodes.OK) .json( new ResponseJSON( 'Quote reason edited', false, httpStatusCodes.OK, result[0] ) ); } catch (error) { console.error('Error--- ', error); next( apiErrorHandler( error, req, errorMessages.INTERNAL_SERVER, httpStatusCodes.INTERNAL_SERVER ) ); } } so to do an update on a quotation only with status QuoatiionStatus.REJECTED and update the field reason. And change the status to QuotationStatus.PENDING on update. Show the changes in steps
c452f3d1bc7fca8cb08a2ba4472980aa
{ "intermediate": 0.5177257061004639, "beginner": 0.30947545170783997, "expert": 0.17279884219169617 }
8,306
For the single angle pulse data of the strain gauge test, how to do it with matlab is the signal recognition and smoothing processing, giving the treatment method in matlab
90d167693b39d1fef39eb86f577c25d7
{ "intermediate": 0.2784879505634308, "beginner": 0.13822981715202332, "expert": 0.5832822322845459 }
8,307
Review and employee strength about revgurus company
391d7f1acab0641a578a48b222822afb
{ "intermediate": 0.3803046643733978, "beginner": 0.27542105317115784, "expert": 0.34427428245544434 }
8,308
Create for me a website for my University, Badr University in Cairo, Include drop down lists with html
190199b9ed5ae376b038778be5265993
{ "intermediate": 0.34278345108032227, "beginner": 0.23349237442016602, "expert": 0.4237242043018341 }
8,309
Please fill up the missing code for this package com.ipsummusic.challenge.controllers; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.stripe.exception.StripeException; import com.stripe.model.Charge; import com.stripe.model.ChargeCollection; import com.stripe.model.Customer; import com.stripe.model.CustomerCollection; import com.stripe.model.PaymentIntent; import com.stripe.model.PaymentIntentCollection; import com.stripe.model.PaymentMethod; import com.stripe.model.PaymentMethodCollection; import com.stripe.model.Refund; import com.stripe.model.SetupIntent; import com.stripe.model.SetupIntentCollection; import com.stripe.param.ChargeListParams; import com.stripe.param.CustomerCreateParams; import com.stripe.param.CustomerUpdateParams; import com.stripe.param.PaymentIntentCaptureParams; import com.stripe.param.PaymentIntentCreateParams; import com.stripe.param.PaymentIntentCreateParams.CaptureMethod; import com.stripe.param.PaymentIntentListParams; import com.stripe.param.SetupIntentListParams; import io.github.cdimascio.dotenv.Dotenv; import spark.Request; import spark.Response; import spark.Route; public class ChallengeController { private static Gson gson = new Gson(); /** * Get Config * Fetch the Stripe publishable key * Example call: * curl -X GET http://localhost:4242/config \ * Returns: a JSON response of the pubblishable key * { * key: <STRIPE_PUBLISHABLE_KEY> * } */ public static Route getConfig = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route setupIntentLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); String customerId = null; String clientSecret = null; // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route successfulLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 2: '/schedule-lesson' // Authorize a payment for a lesson // // Parameters: // customer_id: id of the customer // amount: amount of the lesson in cents // description: a description of this lesson // // Example call: // curl -X POST http://localhost:4242/schdeule-lesson \ // -d customer_id=cus_GlY8vzEaWTFmps \ // -d amount=4500 \ // -d description='Lesson on Feb 25th' // // Returns: a JSON response of one of the following forms: // For a successful payment, return the Payment Intent: // { // payment: <payment_intent> // } // // For errors: // { // error: // code: the code returned from the Stripe error if there was one // message: the message returned from the Stripe error. if no payment method was // found for that customer return an msg 'no payment methods found for // <customer_id>' // payment_intent_id: if a payment intent was created but not successfully // authorized // } public static Route scheduleLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 2: '/complete-lesson-payment' // Capture a payment for a lesson. // // Parameters: // amount: (optional) amount to capture if different than the original amount // authorized // // Example call: // curl -X POST http://localhost:4242/complete_lesson_payment \ // -d payment_intent_id=pi_XXX \ // -d amount=4500 // // Returns: a JSON response of one of the following forms: // // For a successful payment, return the payment intent: // { // payment: <payment_intent> // } // // for errors: // { // error: // code: the code returned from the error // message: the message returned from the error from Stripe // } // public static Route completeLessonPayment = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 2: '/refund-lesson' // Refunds a lesson payment. Refund the payment from the customer (or cancel the // auth // if a payment hasn't occurred). // Sets the refund reason to 'requested_by_customer' // // Parameters: // payment_intent_id: the payment intent to refund // amount: (optional) amount to refund if different than the original payment // // Example call: // curl -X POST http://localhost:4242/refund-lesson \ // -d payment_intent_id=pi_XXX \ // -d amount=2500 // // Returns // If the refund is successfully created returns a JSON response of the format: // // { // refund: refund.id // } // // If there was an error: // { // error: { // code: e.error.code, // message: e.error.message // } // } public static Route refundLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 3: Managing account info // Displays the account update page for a given customer public static Route accountUpdate = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 3: '/delete-account' // Deletes a customer object if there are no uncaptured payment intents for // them. // // Parameters: // customer_id: the id of the customer to delete // // Example request // curl -X POST http://localhost:4242/delete-account/:customer_id \ // // Returns 1 of 3 responses: // If the customer had no uncaptured charges and was successfully deleted // returns the response: // { // deleted: true // } // // If the customer had uncaptured payment intents, return a list of the payment // intent ids: // { // uncaptured_payments: ids of any uncaptured payment intents // } // // If there was an error: // { // error: { // code: e.error.code, // message: e.error.message // } // } // public static Route deleteAccount = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route paymentMethod = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route updatePaymentDetails = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; // Milestone 4: '/calculate-lesson-total' // Returns the total amounts for payments for lessons, ignoring payments // for videos and concert tickets, ranging over the last 36 hours. // // Example call: curl -X GET http://localhost:4242/calculate-lesson-total // // Returns a JSON response of the format: // { // payment_total: Total before fees and refunds (including disputes), and excluding payments // that haven't yet been captured. // fee_total: Total amount in fees that the store has paid to Stripe // net_total: Total amount the store has collected from payments, minus their fees. // } public static Route calculateLessonTotal = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route findCustomersWithFailedPayments = (Request request, Response response) -> { List<Object> responseList = new ArrayList<Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseList); }; }
bfb450232caa34213a48b5f5f459dd16
{ "intermediate": 0.3488830029964447, "beginner": 0.34631356596946716, "expert": 0.30480343103408813 }
8,310
Unhandled rejection Error: ETELEGRAM: 409 Conflict: terminated by other getUpdates request; make sure that only one bot instance is running const TelegramBot = require('node-telegram-bot-api');
9263356866412ba49161512eb577f9eb
{ "intermediate": 0.5364882946014404, "beginner": 0.2042073756456375, "expert": 0.25930431485176086 }
8,311
how to read : spring.datasource.password=${JDBC_DATABASE_PASSWORD:<<YOUR_PASSWORD>>} using java code
dba2f2d782bd99b4e213d853f8c2134d
{ "intermediate": 0.31238171458244324, "beginner": 0.5671206116676331, "expert": 0.12049766629934311 }
8,312
Generate code to create neural network ensembling model to generate the top 10 most probable set of items ranged from 1 to 52 based on previous classified combination set of items ranged from 1 to 52
72ad62bce96db51be0c1c2c8718d7b5d
{ "intermediate": 0.08944320678710938, "beginner": 0.04205654561519623, "expert": 0.868500292301178 }
8,313
Please write java code for this '# Milestone 3: Managing account info Now that we're storing our students' account and payment information, we need to help them update and delete it: - People sometimes change their credit cards, email addresses, and names; they need to be able to reflect that in our records. - Letting people delete their account information is sometimes a legal requirement and always a best practice. However, first we need to make sure our students have paid for all of their lessons. ## Requirements ### Updating account and payment information Complete the Account Update page and implement a `POST /account-update/:customer_id` endpoint so that learners can update their name, email, and saved payment method. We aren't collecting any payment, so use Setup Intents on this page just like the Lessons sign-up. <br /> Update the Customer object using the Payment Method generated by the Setup Intent. This update replaces the Payment Method currently associated with the Customer. Display the student's card details inside the `id="account-information"` element, both when the page is loaded and after a student saves a new Payment Method object. If the student changes their name or email address, update those values on their Customer object. If they try to use an email address already associated with another Customer, reveal the `id=customer-exists-error` element and display an error message saying "Customer email already exists". ### Checking for uncaptured payments, then delete the account We don't need any user interface for account deletion, students can email us with their request. Complete the `POST /delete-account/:customer_id` endpoint so that it deletes the Stripe Customer object, but only if they have no uncaptured payments. It doesn't require any body parameters. It can return three different responses: - If the student has any uncaptured payments, then it returns a list of Payment Intent IDs. - If the student has completed all of their payments, delete their Customer and return `deleted: true`. - If there's an error, return details. _Test locally by [setting up Playwright](../test/README.md), starting your application's client and server, and then running `npx playwright test ./specs/milestone3.spec.ts` in the repo's `./test` directory._
c62fc88bb49409f1f1b343077e70eebd
{ "intermediate": 0.5723682045936584, "beginner": 0.1972232609987259, "expert": 0.23040851950645447 }
8,314
Write a Python application that detects white stickers in an image
a03e473692644cf7028ff98ff6a17404
{ "intermediate": 0.33925706148147583, "beginner": 0.13199736177921295, "expert": 0.5287455916404724 }
8,315
explain me @ControllerAdvice and how to use is with a sample code java with springboot MVC Controller
cf91787a6237fed50ec26e5b394b4c51
{ "intermediate": 0.7025320529937744, "beginner": 0.22045738995075226, "expert": 0.0770106166601181 }
8,316
Hi
12108313862cb11ef1d37502504b8056
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
8,318
How to ssh into ubuntu server from wsl if i have pem private key
47b06794d57fb0dccf42f5c3397aa24d
{ "intermediate": 0.3895489573478699, "beginner": 0.2816506028175354, "expert": 0.3288004696369171 }
8,319
How do i set my github actions to only deploy from main branch and only listen for commit pushes to main and ignore pushes to other branches
d39c99f446cf6c4273c4a5b81c70d69a
{ "intermediate": 0.54539555311203, "beginner": 0.18779727816581726, "expert": 0.2668071985244751 }
8,320
"clc clear all close all % Stock Morket/Exchange Forecasing Using LSTM % A sequence-to-sequence regression LSTM Network. % This Example uses the data set of Tehran Stock in 2022. %% Step1: load and Prepare Data [Xtrain,YTrain,Params] = LoadPrepareData2(); %% Step2: Create a LSTM network NumHiddenUnits = 100; Layers = [ sequenceInputLayer(1) lstmLayer(NumHiddenUnits,... "InputWeightsInitializer",'zeros',... 'RecurrentWeightsInitializer','he') fullyConnectedLayer(1) regressionLayer]; %% Step3: Training Options maxEpochs = 1000; InitialLearnRate = 0.04; Options = trainingOptions("adam",... "Plots","training-progress",... 'MaxEpochs',maxEpochs,... 'InitialLearnRate',InitialLearnRate,... 'LearnRateSchedule','piecewise',... 'LearnRateDropPeriod',100,... 'LearnRateDropFactor',0.9,... 'ExecutionEnvironment','gpu',... 'Shuffle','never'); %% Step4: Train the Network LstmNet = trainNetwork(Xtrain,YTrain,Layers,Options); %% Step5: Forecasting the Test Data % nTimeStep = 38; % YPredict = ForecastingWithPredictedValues(... % LstmNet,Xtrain,nTimeStep,Params); %% Step5: Forecasting the Test Data nTimeStep = 38; YPredict = zeros(size(Xtrain,1), nTimeStep); % Predict future values bigger than previous values LstmNet = resetState(LstmNet); LstmNet = predictAndUpdateState(LstmNet,Xtrain); [LstmNet,YPredict(:,1)] = predictAndUpdateState(LstmNet,Xtrain(end)); for i = 2:nTimeStep [LstmNet,YPredict(:,i)] = predictAndUpdateState(LstmNet,YPredict(:,i-1)); end %% Unstandadize the predictions Xtrain = Xtrain*Params.s + Params.m; YPredict = YPredict*Params.s + Params.m; %% Plot figure,plot(Xtrain,'LineWidth',2); hold on idx = numel(Xtrain):(numel(Xtrain) + nTimeStep); plot(idx,[Xtrain(end) YPredict],"LineWidth",2,'LineStyle','-') xlabel('Time [Day]') ylabel('Close Values') title('LSTM Forecasting') legend('Observed','Forecasted') " Rewrite the code and make sure the all Ypredicted value are greater than pervious value.
2a041b13386d1de7437449d90ccc2a28
{ "intermediate": 0.2718467712402344, "beginner": 0.3161354064941406, "expert": 0.4120177924633026 }
8,321
name: Deploy to Production on: push: branches: - main jobs: build-and-deploy: runs-on: ubuntu-latest steps: - name: Checkout main branch uses: actions/checkout@v2 with: ref: main what does the above github action yaml do
3f2822a0bbea9143a261b835a5ade0aa
{ "intermediate": 0.4707479178905487, "beginner": 0.34440433979034424, "expert": 0.18484778702259064 }
8,322
Modify the code below to also display the following details of the created contract (token): 1. Capitalization amount (FDV) of the created contract (token) 2. Date and time of listing of the created contract (token) 3. Date and time of adding liquidity to the created contract (token) 4. Date and time of creation of the created contract (token) 5. The amount of liquidity of the created contract (token) at the time of the request 6. Sum of trading volume for 5 minutes, 30 minutes, 1 hour, 6 hours, 12 hours and 24 hours # Возращает адреса созданных токенов в одном блоке import requests bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' def get_external_transactions(block_number): url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f'Error in API request: {e}') return [] data = response.json() if data['result'] is None: print(f"Error: Cannot find the block") return [] return data['result']['transactions'] def get_contract_address(tx_hash): url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f'Error in API request: {e}') return None data = response.json() if data['result'] is None: return None return data['result']['contractAddress'] def get_contract_name(contract_address): method_signature = '0x06fdde03' # Keccak256 hash of the “name()” function signature url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}' try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f'Error in API request: {e}') return None data = response.json() if data['result'] is None or data['result'][:2] == '0x': return None return bytes.fromhex(data['result'][2:]).decode('utf-8') def display_transactions(block_number): transactions = get_external_transactions(block_number) if not transactions: print('No transactions found.') else: print(f'Transactions in block {block_number}:') for tx in transactions: if tx['to'] is None: contract_address = get_contract_address(tx['hash']) contract_name = get_contract_name(contract_address) print(f"New contract creation: Contract Address: {contract_address} - Contract Name: {contract_name}") block_number = '1B33D5F' # Replace with your desired block number (hexadecimal value) decimal_block_number = int(block_number, 16) print(decimal_block_number) display_transactions(block_number)
5c5c771edea28dcd4ef9cfb8ff0e630a
{ "intermediate": 0.38949209451675415, "beginner": 0.44722869992256165, "expert": 0.1632792353630066 }
8,323
i want to make server sided xml mod for 7 days to die in wich i use 1 of armor mod named Banded Armor Plating Mod and 4 of Military Fiber and 4 of Steel Armor parts and 6 of Military Armor Parts and 300 of Lead, in result of this recipe i want to get armor attachment named Scavenger's Fortification wich has Armor Rating +6, Explosion Resistance +3, Heat resistance -6, cold resistance +3, and i want so it can only be craftedin workbench and it takes 8 hours to craft
378900b9dff039af5eefce4aa294787f
{ "intermediate": 0.3680087924003601, "beginner": 0.2723926901817322, "expert": 0.3595985770225525 }
8,324
Use a pretrained deep learning model for object detection (ex: Yolo or MobileNet SSD) to detect moving object in a video
2aae91db87586cb5eff99ad5c0f9e599
{ "intermediate": 0.07109657675027847, "beginner": 0.044526584446430206, "expert": 0.8843768239021301 }
8,325
Generate optimized code for better classifier performance based on the following code : “import numpy as np import pandas as pd from keras.models import Sequential, Model from keras.layers import Dense, Dropout, Input, Concatenate from keras.optimizers import Adam, RMSprop from keras.utils import to_categorical from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler Next, let’s define a function to create a single neural network model: def create_model(input_dim, output_dim): model = Sequential() model.add(Dense(128, input_dim=input_dim, activation=‘relu’)) model.add(Dropout(0.2)) model.add(Dense(256, activation=‘relu’)) model.add(Dropout(0.2)) model.add(Dense(128, activation=‘relu’)) model.add(Dense(output_dim, activation=‘softmax’)) return model Now let’s create a function to build the ensembling model with multiple neural network models: def build_ensemble_model(n_models, input_dim, output_dim): model_inputs = [Input(shape=(input_dim,)) for _ in range(n_models)] model_outputs = [create_model(input_dim, output_dim)(model_input) for model_input in model_inputs] ensemble_output = Concatenate(axis=-1)(model_outputs) top_10_output = Dense(10, activation=‘softmax’)(ensemble_output) ensemble_model = Model(model_inputs, top_10_output) ensemble_model.compile(optimizer=‘adam’, loss=‘categorical_crossentropy’, metrics=[‘accuracy’]) return ensemble_model Let’s assume we have the dataset with input features in X and the corresponding target labels in y. # Load the dataset and preprocess # X, y = load_data() # Scale input features between 0 and 1 scaler = MinMaxScaler() X = scaler.fit_transform(X) # One-hot-encode the target labels y = to_categorical(y, num_classes=53) # Split the dataset into training and testing set X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) After loading and preprocessing the dataset, let’s create an ensembling model for generating the top 10 most probable items. In this case, we’ll use 3 individual models in the ensemble. # Create ensemble model with specified number of models ensemble_model = build_ensemble_model(n_models=3, input_dim=52, output_dim=53) # Train the ensemble model ensemble_model.fit([X_train]*3, y_train, epochs=100, batch_size=64, validation_split=0.1) Finally, we can predict the top 10 most probable items using the trained ensemble model. # Predict probabilities using the ensemble model y_pred = ensemble_model.predict([X_test]*3) # Get top 10 most probable items top_10 = np.argsort(y_pred, axis=1)[:,-10:]”
f0131120f2afad45c5eb1ab038a0274f
{ "intermediate": 0.39816489815711975, "beginner": 0.3525998592376709, "expert": 0.24923527240753174 }
8,326
Optimize the following code to run on billions of data with broadcast joins and repartition : “import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.functions; import static org.apache.spark.sql.functions.*; public class SCDType2Example { public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName(“SCD Type 2 Example”) .master(“local”) .getOrCreate(); Dataset oldData = spark.read().parquet(“path/to/oldData”); Dataset newData = spark.read().parquet(“path/to/newData”); String primaryKey = “id”; String[] nonKeyColumns = {“name”, “age”, “city”}; // Parametrizable columns String hashColumn = “hash”; // Calculate hash value for both old and new data oldData = createHash(oldData, nonKeyColumns, hashColumn); newData = createHash(newData, nonKeyColumns, hashColumn); // Identify unchanged rows Dataset unchangedData = oldData.join(newData, oldData.col(primaryKey) .equalTo(newData.col(primaryKey))) .where(oldData.col(hashColumn).equalTo(newData.col(hashColumn))) .select(oldData.columns()); // Identify changed rows from old data to close Dataset changedOldData = oldData.join(newData, oldData.col(primaryKey) .equalTo(newData.col(primaryKey))) .where(oldData.col(hashColumn).notEqual(newData.col(hashColumn))) .select(oldData.columns()) .withColumn(“end_date”, current_date()) .withColumn(“current_flag”, lit(false)); // Identify changed rows from new data to insert Dataset changedNewData = newData.join(oldData, newData.col(primaryKey) .equalTo(oldData.col(primaryKey))) .where(newData.col(hashColumn).notEqual(oldData.col(hashColumn))) .select(newData.columns()) .withColumn(“start_date”, current_date()) .withColumn(“end_date”, lit(null).cast(“date”)) .withColumn(“current_flag”, lit(true)); // Identify new rows to insert Dataset newRows = newData.join(oldData, newData.col(primaryKey) .equalTo(oldData.col(primaryKey)), “leftanti”) .withColumn(“start_date”, current_date()) .withColumn(“end_date”, lit(null).cast(“date”)) .withColumn(“current_flag”, lit(true)); // Combine unchanged, changed old, changed new, and new rows Dataset result = unchangedData .union(changedOldData) .union(changedNewData) .union(newRows); result.write().parquet(“path/to/output”); } private static Dataset createHash(Dataset data, String[] nonKeyColumns, String hashColumn) { Dataset result = data; StringBuilder concatString = new StringBuilder(); for (String column : nonKeyColumns) { concatString.append(“cast(”).append(column).append(” as string),“); } String concatColumns = concatString.toString(); if (concatColumns.endsWith(”,“)) { concatColumns = concatColumns.substring(0, concatColumns.length() - 1); } return result.withColumn(hashColumn, sha2(functions.concat_ws(”", functions.expr(concatColumns)), 256)); } } "
3f8df3686e649a214c646be3eb53a6ef
{ "intermediate": 0.37033548951148987, "beginner": 0.41876915097236633, "expert": 0.210895374417305 }
8,327
Can I find information of small molecule inhibitors for PMS2 from the PDB (https://www.rcsb.org/)? If so, how?
bfcd67dab186a037d04e320baef4ef25
{ "intermediate": 0.4013444781303406, "beginner": 0.23232172429561615, "expert": 0.3663337826728821 }
8,328
Есть такие данные ввиде pandas. Time target sort_1 value 25 25 200 nM,\nno SPARDA first 518 151 25 0 nM first 3884 277 25 1 nM first 4038 403 25 5 nM first 5641 529 25 10 nM first 11383 655 25 20 nM first 27107 781 25 200 nM,\nno SPARDA second 526 907 25 0 nM second 2808 1033 25 1 nM second 4026 1159 25 5 nM second 5135 1285 25 10 nM second 11821 1411 25 20 nM second 26546 1537 25 200 nM,\nno SPARDA third 603 1663 25 0 nM third 2962 1789 25 1 nM third 2015 1915 25 5 nM third 4908 2041 25 10 nM third 9214 2167 25 20 nM third 27629. Как взять среднее по target?
5ad367caea9df51816a769ae230f4b8d
{ "intermediate": 0.4873813986778259, "beginner": 0.27248328924179077, "expert": 0.2401352971792221 }
8,329
Optimize the following code by reducing the number of joins : "import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.functions; import static org.apache.spark.sql.functions.*; public class SCDType2Example { public static void main(String[] args) { SparkSession spark = SparkSession .builder() .appName(“SCDDevice2Example”) .master(“local”) .getOrCreate(); Dataset oldData = spark.read().parquet(“path/to/oldData”); Dataset newData = spark.read().parquet(“path/to/newData”); // Repartition the data oldData = oldData.repartition(“id”); newData = newData.repartition(“id”); String primaryKey = “id”; String[] nonKeyColumns = {“name”, “age”, “city”}; // Parametrizable columns String hashColumn = “hash”; oldData = createHash(oldData, nonKeyColumns, hashColumn); newData = createHash(newData, nonKeyColumns, hashColumn); Dataset unchangedData = oldData.join( broadcast(newData), oldData.col(primaryKey).equalTo(newData.col(primaryKey)) ) .where(oldData.col(hashColumn).equalTo(newData.col(hashColumn))) .select(oldData.columns()); Dataset changedOldData = oldData.join( broadcast(newData), oldData.col(primaryKey).equalTo(newData.col(primaryKey)) ) .where(oldData.col(hashColumn).notEqual(newData.col(hashColumn))) .select(oldData.columns()) .withColumn(“end_date”, current_date()) .withColumn(“current_flag”, lit(false)); Dataset changedNewData = newData.join( broadcast(oldData), newData.col(primaryKey).equalTo(oldData.col(primaryKey)) ) .where(newData.col(hashColumn).notEqual(oldData.col(hashColumn))) .select(newData.columns()) .withColumn(“start_date”, current_date()) .withColumn(“end_date”, lit(null).cast(“date”)) .withColumn(“current_flag”, lit(true)); Dataset newRows = newData.join( broadcast(oldData), newData.col(primaryKey).equalTo(oldData.col(primaryKey)), “leftanti” ) .withColumn(“start_date”, current_date()) .withColumn(“end_date”, lit(null).cast(“date”)) .withColumn(“current_flag”, lit(true)); Dataset result = unchangedData .union(changedOldData) .union(changedNewData) .union(newRows); result.write().parquet(“path/to/output”); } private static Dataset createHash(Dataset data, String[] nonKeyColumns, String hashColumn) { Dataset result = data; StringBuilder concatString = new StringBuilder(); for (String column : nonKeyColumns) { concatString.append(“cast(”).append(column).append(" as string),“); } String concatColumns = concatString.toString(); if (concatColumns.endsWith(”,“)) { concatColumns = concatColumns.substring(0, concatColumns.length() - 1); } return result.withColumn(hashColumn, sha2(functions.concat_ws(”", functions.expr(concatColumns)), 256)); } }"
8e1204566488d2794b4dd9f10bdc74aa
{ "intermediate": 0.30239659547805786, "beginner": 0.3581012487411499, "expert": 0.33950212597846985 }