row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
7,628
|
python code csv import
|
25204d7e7fd8ce13298885aa2b177a05
|
{
"intermediate": 0.35052070021629333,
"beginner": 0.32184138894081116,
"expert": 0.3276378810405731
}
|
7,629
|
i have some products each one has some images i want to switch between each one images using radio buttons in angular without the radio buttons of one product effect the radio buttons of another products
|
2d810ae0624d8ffb8a30ad2fd5b698c0
|
{
"intermediate": 0.46980828046798706,
"beginner": 0.20983175933361053,
"expert": 0.32035988569259644
}
|
7,630
|
create php script allow only fr visiteur can show my page
|
f4885ed5fcc9e3df0b31976900d3571e
|
{
"intermediate": 0.342752069234848,
"beginner": 0.3269917368888855,
"expert": 0.3302561640739441
}
|
7,631
|
Ubah kode python model analisis sentimen CNN-LSTM berikut dengan diganti menjadi CNN-BiLSTM!
# Membangun model CNN-LSTM dengan pre-trained Word2Vec
num_filters = 64
lstm_units = 64
# Membuat model CNN-LSTM
model = Sequential([
Embedding(input_dim=10000,
output_dim=300,
input_length=500,
weights=[embedding_matrix],
trainable=False),
Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.001)),
MaxPooling1D(pool_size=4),
Dropout(0.25),
LSTM(200, return_sequences=False, kernel_regularizer=l2(0.001), recurrent_regularizer=l2(0.001), dropout=0.25),
Dense(32, activation='relu', kernel_regularizer=l2(0.001)),
Dropout(0.5),
Dense(3, activation='softmax')
])
# Menyusun Model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Melatih Model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)
|
457d18c065cf81a76d77648e15b9d512
|
{
"intermediate": 0.26352083683013916,
"beginner": 0.14946214854717255,
"expert": 0.5870169997215271
}
|
7,632
|
hi
|
f57fd77f640a420e3063b896577bfd6c
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,633
|
python code os.path get owner
|
d843b14ed7f4bc54bb9ae6a910bbe2fb
|
{
"intermediate": 0.3697873651981354,
"beginner": 0.3184885084629059,
"expert": 0.31172415614128113
}
|
7,634
|
using the livecode language how would i format a number so tat it contains a comma after the thousands
|
d4f020470b3c5a89d234e5dfc72eca20
|
{
"intermediate": 0.5008255839347839,
"beginner": 0.21378858387470245,
"expert": 0.2853858172893524
}
|
7,635
|
When writing a query in Grafana, is there a way to specify what the legend should be directly in the query string?
|
c5321a14c4c78dacfc87007597d5a734
|
{
"intermediate": 0.672962486743927,
"beginner": 0.08719639480113983,
"expert": 0.23984110355377197
}
|
7,636
|
могу ли я использовать только then из cucumber для описания методов из класса? playwright + ts
вот пример класса
const { expect } = require('@playwright/test');
const constants = require('../constants');
const { scrollIfNeed } = require('../testUtils/navigatorPanelUtils')
module.exports = class Navigator {
constructor(page) {
this.page = page;
}
// locators
// Получить кнопку-переключатель "Навигатор"
getTreeToggleButton() {
return this.page.locator('[data-test="navigator-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Символы"
getSymbolToggleButton() {
return this.page.locator('[data-test="symbol-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Свойства"
getPropertyToggleButton() {
return this.page.locator('[data-test="properties-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Мини-карта"
getMapToggleButton() {
return this.page.locator('[data-test="map-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Комментарии"
getCommentToggleButton() {
return this.page.locator('[data-test="comment-panel_toggle-button"]');
}
// methods
// Открыть панель "Навигатор"
async openTreePanel() {
await this.getTreeToggleButton().click();
await expect(this.getTreeToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Навигатор"
async closeTreePanel() {
await this.getTreeToggleButton().click();
await expect(this.getTreeToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Символы"
async openSymbolPanel() {
await this.getSymbolToggleButton().click();
await expect(this.getSymbolToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Символы"
async closeSymbolPanel() {
await this.getSymbolToggleButton().click();
await expect(this.getSymbolToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Свойства"
async openPropertyPanel() {
await this.getPropertyToggleButton().click();
await expect(this.getPropertyToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Свойства"
async closePropertyPanel() {
await this.getPropertyToggleButton().click();
await expect(this.getPropertyToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Мини-карта"
async openMapPanel() {
await this.getMapToggleButton().click();
await expect(this.getMapToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Мини-карта"
async closeMapPanel() {
await this.getMapToggleButton().click();
await expect(this.getMapToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Комментарии"
async openCommentPanel() {
await this.getCommentToggleButton().click();
await expect(this.getCommentToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Комментарии"
async closeCommentPanel() {
await this.getCommentToggleButton().click();
await expect(this.getCommentToggleButton()).not.toHaveClass(/navItemSelected/);
}
};
|
a7b6963129eb92b8e4a7b0583ef0ab0e
|
{
"intermediate": 0.3107636570930481,
"beginner": 0.49076783657073975,
"expert": 0.19846847653388977
}
|
7,637
|
I have 540 reference images consisting of 3 categories (180 images each). The images can have 3 distortions (1,2,3) each at 3 levels (a,b,c) or they can be original.
I want each observer to see the same number of images from each category.
Moreover, I want all image conditions (distortions and orginals) to be equally present on each category.
To ensure this, I need to have a total number of trials that is divisible by 30 (3 image categories and 10 image configurations)
Here is an example for 360 trials (12*30):
Set seed so they can be prepoduced
From each category, sample 120 images
shuffle and add to list of all permutations (original & A-C * 1-3)
Combine categories and shuffle.
Generate a few hundred of these lists and save them as indivual csv files each of which will be used to select images for one observer to rate.
My question is what can be done to keep similar amount of images overall between observers while obeying the above structure that is established above?
This procedure could make a certain image ref1_dist1_levA being shown more times than ref1_dist1_levB when when the experiment is completed.
Is there any way to balance this (at least partially)? It is a must that each observer follow the given logic.
Please give a solution in python code.
|
9969f505238564db7277bd53a14d8d3c
|
{
"intermediate": 0.4387393295764923,
"beginner": 0.158526211977005,
"expert": 0.4027344584465027
}
|
7,638
|
This is my ide program for a highsum gui game.
"import GUIExample.GameTableFrame;
import Model.*;
import GUIExample.LoginDialog;
public class GUIExample {
private Dealer dealer;
private Player player;
private GameTableFrame app;
public GUIExample() {
}
public void run() {
dealer.shuffleCards();
app = new GameTableFrame(dealer, player);
app.setVisible(true); // Replace app.run(); with this line
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
GUIExample example = new GUIExample();
example.dealer = new Dealer();
example.player = new Player(login, password, 10000);
example.run();
}
}
}
import javax.swing.*;
import java.awt.event.*;
import Model.HighSum;
import GUIExample.GameTableFrame;
import GUIExample.LoginDialog;
public class HighSumGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum() {
// Override ‘run’ method to display and update the GameTableFrame
@Override
public void run() {
GameTableFrame gameTableFrame = new GameTableFrame(getDealer(), getPlayer());
gameTableFrame.setVisible(true);
// Use a loop to continuously update and start new games as desired by the user
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!carryOn) {
break;
}
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
if (response == JOptionPane.NO_OPTION) {
carryOn = false;
}
}
gameTableFrame.dispose();
}
};
highSum.init(login, password);
highSum.run();
}
}
});
}
}
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
private boolean playerQuit;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public boolean getPlayerQuitStatus() {
return playerQuit;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if (round == 1) { //round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
} else {
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel("Shuffling");
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), "some_default_password");
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString("Dealer", dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString("Player", playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 18));
g.drawString("Chips on the table: ", playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon("images/back.png").paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
package Model;
import javax.swing.*;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super("images/" + suit + name + ".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return "<HIDDEN CARD>";
} else {
return "<" + this.suit + " " + this.name + ">";
}
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super("Dealer", "", 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.*;
import View.*;
import GUIExample.LoginDialog;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
if (!gc.getPlayerQuitStatus()) {
char r = this.view.getPlayerNextGame();
if (r == 'n') {
carryOn = false;
}
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}
}
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.Keyboard;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print("<HIDDEN CARD> ");
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " ");
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}"
These are the requirements:
"On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API "Swing" and "AWT" packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too."
Edit the code so that when highsum gui is run,
The gui pop up is similar to GUIExample where there is a green background and cards are dealt as shown while keeping the highsum game logic into the highsum gui
|
68786fc01d45fbd9d961afdea3bc74f5
|
{
"intermediate": 0.3266892433166504,
"beginner": 0.5791943073272705,
"expert": 0.0941164493560791
}
|
7,639
|
function controlNirr(h, d, b) {
var e = h.value;
var c = $("connexioncompte_2connexion_code");
console.log("Data => "+ h)
var g = new RegExp("^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=\D*\d)[A-Za-z\d!$%@#£€*?&]{8,}$", "g");
if (g.test(e)) {
console.log("Mz1n => ")
}else{
console.log("00000 => ")
}
}
|
8db1522f7c5a137c9245ff7412ec58a7
|
{
"intermediate": 0.29257482290267944,
"beginner": 0.5450081825256348,
"expert": 0.16241693496704102
}
|
7,640
|
можно ли использовать только then из cucumber для описания методов в классе? playwright + ts
вот пример класса
const { expect } = require('@playwright/test');
const constants = require('../constants');
const { scrollIfNeed } = require('../testUtils/navigatorPanelUtils')
module.exports = class Navigator {
constructor(page) {
this.page = page;
}
// locators
// Получить кнопку-переключатель "Навигатор"
getTreeToggleButton() {
return this.page.locator('[data-test="navigator-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Символы"
getSymbolToggleButton() {
return this.page.locator('[data-test="symbol-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Свойства"
getPropertyToggleButton() {
return this.page.locator('[data-test="properties-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Мини-карта"
getMapToggleButton() {
return this.page.locator('[data-test="map-panel_toggle-button"]');
}
// Получить кнопку-переключатель "Комментарии"
getCommentToggleButton() {
return this.page.locator('[data-test="comment-panel_toggle-button"]');
}
// methods
// Открыть панель "Навигатор"
async openTreePanel() {
await this.getTreeToggleButton().click();
await expect(this.getTreeToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Навигатор"
async closeTreePanel() {
await this.getTreeToggleButton().click();
await expect(this.getTreeToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Символы"
async openSymbolPanel() {
await this.getSymbolToggleButton().click();
await expect(this.getSymbolToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Символы"
async closeSymbolPanel() {
await this.getSymbolToggleButton().click();
await expect(this.getSymbolToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Свойства"
async openPropertyPanel() {
await this.getPropertyToggleButton().click();
await expect(this.getPropertyToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Свойства"
async closePropertyPanel() {
await this.getPropertyToggleButton().click();
await expect(this.getPropertyToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Мини-карта"
async openMapPanel() {
await this.getMapToggleButton().click();
await expect(this.getMapToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Мини-карта"
async closeMapPanel() {
await this.getMapToggleButton().click();
await expect(this.getMapToggleButton()).not.toHaveClass(/navItemSelected/);
}
// Открыть панель "Комментарии"
async openCommentPanel() {
await this.getCommentToggleButton().click();
await expect(this.getCommentToggleButton()).toHaveClass(/navItemSelected/);
}
// Закрыть панель "Комментарии"
async closeCommentPanel() {
await this.getCommentToggleButton().click();
await expect(this.getCommentToggleButton()).not.toHaveClass(/navItemSelected/);
}
};
|
642541ea88a99d169edb4a86fb541bf2
|
{
"intermediate": 0.25735193490982056,
"beginner": 0.6170824766159058,
"expert": 0.12556560337543488
}
|
7,641
|
Select distinct r.ExternalReferenceId__c,r.Gateway,r.Id,r.IsProcessed__c,r.ReasonCode,
r.ReasonCode__c,r.ReasonDescription__c,r.RefundDate,r.RefundNumber,r.Status,r.Type,
p.Gateway,p.PaymentNumber,p.RefundAmount,p.GatewayResponse,p.GatewayResponseCode,
p.Id AS PaymentId,
p.Status AS PaymentStatus,p.Type AS PaymentType,p.UnappliedAmount,
i.InvoiceNumber,i.InvoiceDate,i.PaymentAmount,i.AutoPay,i.Balance AS InvoiceBalance,
i.CreatedDate,i.Id As InvoiceId,i.RetryStatus__c,i.Status AS InvoiceStatus,i.DueDate,
i.LastEmailSentDate,
a.AccountNumber,a.Batch,a.AutoPay,a.BcdSettingOption,a.BillCycleDay,
a.CollectionExemptionStartDate__c,a.CollectionExemptionEndDate__c,a.CollectionExemptionStatus__c,
a.CollectionExemptionReason__c,a.LastInvoiceDate,a.Name AS AccountName,
a.PaymentGateway,a.PaymentTerm,a.RetryStatus__c AS AccountRetryStatus__c,
a.Status AS AccountStatus,a.DefaultPaymentMethodId,pm.Type AS PaymentMehodType
From refundpart rp
JOIN Refund r ON rp.RefundId = r.Id
JOIN Paymentapplication pa ON rp.PaymentId = pa.PaymentId
JOIN Payment p ON pa.PaymentId = p.Id
JOIN Invoice i ON pa.InvoiceId = i.Id
JOIN Account a ON i.AccountId = a.Id
JOIN paymentmethod pm ON a.DefaultPaymentMethodId = pm.Id
Where r.accountId = '8ac68bf5879e064801879ecfdc567a13' AND
(((((((a.AutoPay = 'false' and
a.CustomerGroup__c = 'United States Member' or a.CustomerGroup__c = 'Canadian Member')
and (r.ReasonCode__c IN ( 'R901', 'R01', 'R09','R908') or (r.ReasonCode__c like '%R901%' or
r.ReasonCode__c like '%R01%' or r.ReasonCode__c like '%R09%' or r.ReasonCode__c like '%R908%') )) and pm.Type = 'ACH'))
and Refund.ReasonCode = 'Chargeback')
and Invoice.Balance > 0-- and Invoice.InvoiceNumber = '{{Data.Workflow.InvoiceNumber}}'
)
and Refund.Type = 'External')
|
992c09e3b1dfcc80bb98d5db0e0bf73e
|
{
"intermediate": 0.4865148663520813,
"beginner": 0.26295387744903564,
"expert": 0.25053128600120544
}
|
7,642
|
i have some of products each one have radio buttons to switch between images but when i select on radio button of one product why reflects on another products in angular
|
a17416fcc02649a85b9be58e524d1cb1
|
{
"intermediate": 0.48401978611946106,
"beginner": 0.2180316001176834,
"expert": 0.2979486584663391
}
|
7,643
|
write a python code that will output a hmac authentication header
|
11e7218bd25958cff5b65a647c010475
|
{
"intermediate": 0.407176673412323,
"beginner": 0.21914324164390564,
"expert": 0.37368008494377136
}
|
7,644
|
Write me Python code to price an American Put Option using a Genetic Algorithm
|
9beea170efdf4a714b8fcaa3449da1e5
|
{
"intermediate": 0.24205197393894196,
"beginner": 0.09470131993293762,
"expert": 0.663246750831604
}
|
7,645
|
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.
The basic class structure is as follows:
1. Core:
- class Engine
- This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.)
2. Window:
- class Window
- This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events.
3. Renderer:
- class Renderer
- This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines.
- class Shader
- To handle shader modules creation and destruction.
- class Texture
- To handle texture loading and destruction.
- class Pipeline
- To encapsulate the description and creation of a Vulkan graphics or compute pipeline.
4. Scene:
- class Scene
- This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering.
- class GameObject
- To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices.
- class Camera
- To store and manage camera properties such as position, rotation, view, and projection matrices.
- class Mesh
- To handle mesh data (e.g., vertices, indices, etc.) for individual objects.
- class Material
- To store and manage material properties such as colors, shaders, and textures.
5. Math:
- Utilize GLM library to handle vector and matrix math operations.
Here is some of the relevant header and source file code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, descriptorPool);
scene.AddGameObject(terrain.GetTerrainObject());
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Scene.cpp:
#include "Scene.h"
Scene::Scene()
{
}
Scene::~Scene()
{
Shutdown();
}
void Scene::Initialize()
{
// Initialize camera and game objects
camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f));
// Add initial game objects
}
void Scene::Update(float deltaTime)
{
// Update game objects and camera
for (GameObject* gameObject : gameObjects)
{
gameObject->Update(deltaTime);
}
}
void Scene::Render(Renderer& renderer)
{
// Render game objects
for (GameObject* gameObject : gameObjects)
{
gameObject->Render(renderer, camera);
}
// Submit rendering-related commands to Vulkan queues
}
void Scene::Shutdown()
{
// Clean up game objects
for (GameObject* gameObject : gameObjects)
{
delete gameObject;
gameObject = nullptr;
}
gameObjects.clear();
camera.Shutdown();
}
void Scene::AddGameObject(GameObject* gameObject)
{
gameObjects.push_back(gameObject);
}
Camera& Scene::GetCamera()
{
return camera;
}
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize(const Mesh& mesh, const Material& material);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh mesh;
Material material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize(const Mesh& mesh, const Material& material)
{
this->mesh = mesh; // copy or share mesh data
this->material = material; // copy or share material data
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh.GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh.GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material.GetDescriptorSet();
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material.GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh.GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Terrain.h:
#pragma once
#include "Simplex.h"
#include "Mesh.h"
#include "Material.h"
#include "GameObject.h"
class Terrain {
public:
Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue);
~Terrain();
void GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
GameObject* GetTerrainObject();
private:
void GenerateHeightMap();
void ConvertHeightMapToMeshData();
int seed;
int worldSize;
float scale;
VkDevice* device;
VkPhysicalDevice* physicalDevice;
VkCommandPool* commandPool;
VkQueue* graphicsQueue;
SimplexNoise noise;
std::vector<std::vector<float>> heightMap;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
Mesh terrainMesh;
Material terrainMaterial;
GameObject terrainObject;
};
Terrain.cpp:
#include "Terrain.h"
Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue)
: seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) {
}
Terrain::~Terrain() {
// Cleanup any resources associated with the Terrain class
//terrainMesh.Cleanup();
//terrainMaterial.Cleanup();
}
void Terrain::GenerateHeightMap() {
heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f));
for (int x = 0; x < worldSize; ++x) {
for (int z = 0; z < worldSize; ++z) {
float noiseValue = noise.noise(x * scale, z * scale);
heightMap[x][z] = noiseValue;
}
}
}
void Terrain::ConvertHeightMapToMeshData()
{
vertices.clear();
indices.clear();
// Generate vertices
for (int x = 0; x < worldSize; ++x)
{
for (int z = 0; z < worldSize; ++z)
{
Vertex vertex;
vertex.position = glm::vec3(static_cast<float>(x), heightMap[x][z], static_cast<float>(z));
// Set color based on height, feel free to customize this as desired
float color = heightMap[x][z] * 0.5f + 0.5f; // Normalize the height value between 0 and 1
vertex.color = glm::vec3(color, color, color);
vertices.push_back(vertex);
}
}
// Generate indices for rendering using triangle strips
for (int x = 0; x < worldSize - 1; ++x)
{
for (int z = 0; z < worldSize - 1; ++z)
{
int topLeft = x * worldSize + z;
int topRight = topLeft + 1;
int bottomLeft = (x + 1) * worldSize + z;
int bottomRight = bottomLeft + 1;
// First triangle
indices.push_back(topLeft);
indices.push_back(bottomRight);
indices.push_back(bottomLeft);
// Second triangle
indices.push_back(topLeft);
indices.push_back(topRight);
indices.push_back(bottomRight);
}
}
}
void Terrain::GenerateTerrain(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
GenerateHeightMap();
ConvertHeightMapToMeshData();
terrainMesh.Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue);
// Initialize terrainMaterial with the loaded shaders and texture
// Assume descriptorSetLayout and descriptorPool are created before this call
terrainMaterial.Initialize("C:/shaders/vert.spv", "C:/shaders/frag.spv", "C:/textures/texture.jpg", *device, descriptorSetLayout, descriptorPool, *physicalDevice, *commandPool, *graphicsQueue);
terrainObject.Initialize(terrainMesh, terrainMaterial);
}
GameObject* Terrain::GetTerrainObject() {
return &terrainObject;
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(descriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader{}, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Mesh.h:
#pragma once
#include <vector>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
#include "BufferUtils.h"
struct Vertex
{
glm::vec3 position;
glm::vec3 color;
};
class Mesh
{
public:
Mesh();
~Mesh();
void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
const std::vector<Vertex>& GetVertices() const;
const std::vector<uint32_t>& GetIndices() const;
VkBuffer GetVertexBuffer() const;
VkBuffer GetIndexBuffer() const;
void SetVertices(const std::vector<Vertex>& vertices);
void SetIndices(const std::vector<uint32_t>& indices);
private:
VkDevice device;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
};
Mesh.cpp:
#include "Mesh.h"
Mesh::Mesh()
: device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE)
{
}
Mesh::~Mesh()
{
Cleanup();
}
void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->vertices = vertices;
this->indices = indices;
this->device = device;
Initialize(device, physicalDevice, commandPool, graphicsQueue);
// Create vertex buffer and index buffer
// (assuming you have helper functions CreateBuffer and CopyBuffer)
// …
}
void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Create vertex buffer and index buffer
// (assuming you have helper functions CreateBuffer and CopyBuffer)
// …
// Declare and initialize stagingBuffer and bufferSize here
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size();
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingBuffer, stagingBufferMemory);
void* data;
vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, vertices.data(), (size_t)bufferSize);
vkUnmapMemory(device, stagingBufferMemory);
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
vertexBuffer, vertexBufferMemory);
BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize);
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
bufferSize = sizeof(indices[0]) * indices.size();
VkBuffer stagingIndexBuffer;
VkDeviceMemory stagingIndexBufferMemory;
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
stagingIndexBuffer, stagingIndexBufferMemory);
vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data);
memcpy(data, indices.data(), (size_t)bufferSize);
vkUnmapMemory(device, stagingIndexBufferMemory);
BufferUtils::CreateBuffer(device, physicalDevice, bufferSize,
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
indexBuffer, indexBufferMemory);
BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize);
vkDestroyBuffer(device, stagingIndexBuffer, nullptr);
vkFreeMemory(device, stagingIndexBufferMemory, nullptr);
}
void Mesh::Cleanup()
{
if (device != VK_NULL_HANDLE)
{
if (vertexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, vertexBuffer, nullptr);
vkFreeMemory(device, vertexBufferMemory, nullptr);
vertexBuffer = VK_NULL_HANDLE;
vertexBufferMemory = VK_NULL_HANDLE;
}
if (indexBuffer != VK_NULL_HANDLE)
{
vkDestroyBuffer(device, indexBuffer, nullptr);
vkFreeMemory(device, indexBufferMemory, nullptr);
indexBuffer = VK_NULL_HANDLE;
indexBufferMemory = VK_NULL_HANDLE;
}
}
}
const std::vector<Vertex>& Mesh::GetVertices() const
{
return vertices;
}
const std::vector<uint32_t>& Mesh::GetIndices() const
{
return indices;
}
VkBuffer Mesh::GetVertexBuffer() const
{
return vertexBuffer;
}
VkBuffer Mesh::GetIndexBuffer() const
{
return indexBuffer;
}
void Mesh::SetVertices(const std::vector<Vertex>& vertices)
{
this->vertices = vertices;
}
void Mesh::SetIndices(const std::vector<uint32_t>& indices)
{
this->indices = indices;
}
I want to modify the code to make use Mesh objects as pointers instead of instances where possible. I'm hoping this will improve resource management. How can I modify the code to achieve this?
|
6854e1236e2cac66649dd6a6c6100844
|
{
"intermediate": 0.41963455080986023,
"beginner": 0.41251125931739807,
"expert": 0.16785423457622528
}
|
7,646
|
how to update python in ubuntu 20.04. Now I have 3.10.6
|
4568a6ba53d1e6313f168de9db29cbec
|
{
"intermediate": 0.3926037549972534,
"beginner": 0.2539374530315399,
"expert": 0.35345879197120667
}
|
7,647
|
Write me Python code to price an American Put Option using a Genetic Algorithm from scratch
|
a94ca95844dd5e91ba008334cf712e04
|
{
"intermediate": 0.2312134951353073,
"beginner": 0.07539624720811844,
"expert": 0.6933902502059937
}
|
7,648
|
in Google sheets, is there any way for a cell (for example cell B1) to display certain text when cell A1 contains certain word that matches pre-defined text?
|
7aedf9699773621e46f969631ca4b3b2
|
{
"intermediate": 0.32863593101501465,
"beginner": 0.15222175419330597,
"expert": 0.5191423892974854
}
|
7,649
|
set the color of radio button in angular html template which is send from ts
|
064542d3ee945d8da88c827f377f88e2
|
{
"intermediate": 0.4742884635925293,
"beginner": 0.25767800211906433,
"expert": 0.2680334746837616
}
|
7,650
|
how to change from sqlalchemy import MetaData, Table, Column, Integer, SmallInteger, String, TIMESTAMP, Text, Uuid
from sqlalchemy.dialects.postgresql import INTERVAL
metadata = MetaData()
logs = Table(
"logs",
metadata,
Column("id", Integer, primary_key=True),
Column("request_datetime", TIMESTAMP(timezone=True), nullable=False),
Column("request_url", Text, nullable=False),
Column("request_method", String(8), nullable=False),
Column("response_datetime", TIMESTAMP(timezone=True), nullable=False),
Column("response_status_code", SmallInteger, nullable=False),
Column("response_error_code", String(10), nullable=True),
Column("phone_number", String(10), nullable=True),
Column("duration", INTERVAL, nullable=False),
) to this format from typing import Optional
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "user"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))
fullname: Mapped[Optional[str]]
nickname: Mapped[Optional[str]] = mapped_column(String(30))
and what is better
|
b5de4bd7f951a124568c1a53ad2abd1d
|
{
"intermediate": 0.5285770893096924,
"beginner": 0.2849625051021576,
"expert": 0.186460480093956
}
|
7,651
|
function myFunction(e) {
var sheet = e.range.getSheet();
var column = e.range.getColumn();
var row = e.range.getRow();
var numRows = sheet.getLastRow();
// Check if the edited cell is in column E and within the max number of rows in the sheet
if (column === 5 && row <= numRows) {
var value = sheet.getRange(row, column).getValue();
var output = "";
// Check if the word “Apple” is present in the value and set output to “Fruit” if it is
if (/paypayfleamarket/i.test(value)) {
output = "ppフリマ";
}
// Check if the word “mercari” is present in the value and set output to “メルカリ” if it is
if (/mercari/i.test(value)) {
output = "メルカリ";
}
// Check if the word “auctions” is present in the value and set output to “ヤフオク” if it is
if (/auctions/i.test(value)) {
output = "ヤフオク";
}
// Update corresponding cell in column L
sheet.getRange(row, 12).setValue(output);
}
}
I typed the above script in GAS, but it gives me an error that says "TypeError: Cannot read properties of undefined (reading 'range')". How do i correct this?
|
e98bf7d3601777df3e9ee8e13a737861
|
{
"intermediate": 0.4401217997074127,
"beginner": 0.3402460813522339,
"expert": 0.2196321338415146
}
|
7,652
|
Write me Julia simulation for traffic in city. As complex as possible.
|
9d7631b491dec21576f0d366599be78b
|
{
"intermediate": 0.22093553841114044,
"beginner": 0.1722785085439682,
"expert": 0.6067859530448914
}
|
7,653
|
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 some of the relevant header and source file code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize(const Mesh& mesh, const Material& material);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh mesh;
Material material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize(const Mesh& mesh, const Material& material)
{
this->mesh = mesh; // copy or share mesh data
this->material = material; // copy or share material data
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh.GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh.GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material.GetDescriptorSet();
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material.GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh.GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Mesh.h:
#pragma once
#include <vector>
#include <vulkan/vulkan.h>
#include <glm/glm.hpp>
#include "BufferUtils.h"
struct Vertex
{
glm::vec3 position;
glm::vec3 color;
};
class Mesh
{
public:
Mesh();
~Mesh();
void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
const std::vector<Vertex>& GetVertices() const;
const std::vector<uint32_t>& GetIndices() const;
VkBuffer GetVertexBuffer() const;
VkBuffer GetIndexBuffer() const;
void SetVertices(const std::vector<Vertex>& vertices);
void SetIndices(const std::vector<uint32_t>& indices);
private:
VkDevice device;
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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 (device == VK_NULL_HANDLE || shutdownInProgress) {
// If the device is already VK_NULL_HANDLE, it means the cleanup has run before
return;
}
shutdownInProgress = true; // Indicate that the cleanup is in progress
std::cout << "Waiting for device idle…" << std::endl;
vkDeviceWaitIdle(device); // Wait for rendering to complete
std::cout << "Cleaning up framebuffers…" << std::endl;
CleanupFramebuffers();
std::cout << "Cleaning up renderpass…" << std::endl;
CleanupRenderPass();
std::cout << "Cleaning up syncobject…" << std::endl;
CleanupSyncObjects();
std::cout << "Cleaning up commandbuffers…" << std::endl;
CleanupCommandBuffers(); // Free command buffers before destroying the command pool
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface
DestroySurface(); // Move this line after CleanupDevice
CleanupInstance();
}
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];
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 = ¤tCommandBuffer;
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);
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.");
}
}
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);
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 ¤tCommandBuffer;
}
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;
}
I am running into errors while trying to render. Please check the code and tell me if you find any errors.
|
3350314228ccc07b3d7791f176ad71ff
|
{
"intermediate": 0.37031203508377075,
"beginner": 0.28982001543045044,
"expert": 0.3398679792881012
}
|
7,654
|
I have this file which is a job called officeChatArchiver.ts and this will eventually be called as a cron job using aws lambda, so that it will be called everyday. However I want to be able to execute this on command, so that I can test that it functions properly:
import {
deleteOfficeChatByName,
getOfficeChatsToArchive
} from '@/services/officeChat';
import { WebClient } from '@slack/web-api';
import { Callback, Context, Handler } from 'aws-lambda';
const webClient = new WebClient(process.env.SLACK_BOT_TOKEN);
export const handler: Handler = async (
event: any,
context: Context,
callback: Callback
) => {
try {
// Query the database for all channel names to archive
const channels = await getOfficeChatsToArchive();
if (!channels) {
callback(null, {
statusCode: 200,
body: 'No channels to archive'
});
console.log('No channels to archive');
return;
}
// Archive each channel using the Slack Web API
for (const channel of channels) {
await webClient.conversations
.info({
channel: channel.channel
})
.then(async (info) => {
if (!info.channel?.is_archived) {
await webClient.conversations.archive({ channel: channel.channel });
}
await deleteOfficeChatByName(channel.name);
});
}
callback(null, {
statusCode: 200,
body: 'Channels archived successfully.'
});
} catch (error) {
console.error(error);
callback(error as string | Error | null | undefined, {
statusCode: 500,
body: 'Error archiving channels.'
});
}
};
|
6c303af8f1a51f143ad75eb15e473848
|
{
"intermediate": 0.6233975887298584,
"beginner": 0.20922736823558807,
"expert": 0.16737505793571472
}
|
7,655
|
Что делает этот JS?
window.gradio_config = {"version":"3.21.0\n","mode":"blocks","dev_mode":false,"analytics_enabled":true,"components":[{"id":1,"type":"html","props":{"value":"\u003ch1 align=\"center\"\u003eGPT-3.5 Chatbot\u003c/h1\u003e","show_label":true,"name":"html","visible":true,"style":{}}},{"id":2,"type":"html","props":{"value":"\u003ch3 align=\"center\"\u003eThis app provides you full access to GPT-3.5 (4096 token limit). You don\u0027t need any OPENAI API key.\u003c/h1\u003e","show_label":true,"name":"html","visible":true,"style":{}}},{"id":3,"type":"column","props":{"type":"column","variant":"default","scale":1,"min_width":320,"visible":false,"elem_id":"col_container","style":{}}},{"id":4,"type":"chatbot","props":{"value":[],"selectable":false,"show_label":true,"name":"chatbot","visible":true,"elem_id":"chatbot","style":{}}},{"id":5,"type":"textbox","props":{"lines":1,"max_lines":20,"placeholder":"Hi there!","value":"","type":"text","label":"Type an input and press Enter","show_label":true,"name":"textbox","visible":true,"style":{}}},{"id":6,"type":"state","props":{"show_label":true,"name":"state","visible":true,"style":{}}},{"id":7,"type":"row","props":{"type":"row","variant":"default","visible":true,"style":{}}},{"id":8,"type":"column","props":{"type":"column","variant":"default","scale":7,"min_width":320,"visible":true,"style":{}}},{"id":9,"type":"button","props":{"value":"Run","variant":"secondary","interactive":true,"name":"button","visible":true,"style":{"full_width":true}}},{"id":10,"type":"column","props":{"type":"column","variant":"default","scale":3,"min_width":320,"visible":true,"style":{}}},{"id":11,"type":"textbox","props":{"lines":1,"max_lines":20,"value":"","type":"text","label":"Status code from OpenAI server","show_label":true,"name":"textbox","visible":true,"style":{}}},{"id":12,"type":"form","props":{"type":"form","visible":true,"style":{}}},{"id":13,"type":"accordion","props":{"type":"accordion","open":false,"label":"Parameters","visible":true,"style":{}}},{"id":14,"type":"slider","props":{"minimum":0,"maximum":1.0,"step":0.05,"value":1.0,"label":"Top-p (nucleus sampling)","show_label":true,"interactive":true,"name":"slider","visible":true,"style":{}}},{"id":15,"type":"slider","props":{"minimum":0,"maximum":5.0,"step":0.1,"value":1.0,"label":"Temperature","show_label":true,"interactive":true,"name":"slider","visible":true,"style":{}}},{"id":16,"type":"number","props":{"value":0,"show_label":true,"name":"number","visible":false,"style":{}}},{"id":17,"type":"form","props":{"type":"form","visible":true,"style":{}}},{"id":18,"type":"form","props":{"type":"form","visible":true,"style":{}}},{"id":19,"type":"column","props":{"type":"column","variant":"default","scale":1,"min_width":320,"visible":true,"elem_id":"user_consent_container","style":{}}},{"id":20,"type":"checkbox","props":{"value":false,"show_label":true,"name":"checkbox","visible":false,"style":{}}},{"id":21,"type":"accordion","props":{"type":"accordion","open":true,"label":"User Consent for Data Collection, Use, and Sharing","visible":true,"style":{}}},{"id":22,"type":"html","props":{"value":"\n \u003cdiv\u003e\n \u003cp\u003eBy using our app, which is powered by OpenAI\u0027s API, you acknowledge and agree to the following terms regarding the data you provide:\u003c/p\u003e\n \u003col\u003e\n \u003cli\u003e\u003cstrong\u003eCollection:\u003c/strong\u003e We may collect information, including the inputs you type into our app, the outputs generated by OpenAI\u0027s API, and certain technical details about your device and connection (such as browser type, operating system, and IP address) provided by your device\u0027s request headers.\u003c/li\u003e\n \u003cli\u003e\u003cstrong\u003eUse:\u003c/strong\u003e We may use the collected data for research purposes, to improve our services, and to develop new products or services, including commercial applications, and for security purposes, such as protecting against unauthorized access and attacks.\u003c/li\u003e\n \u003cli\u003e\u003cstrong\u003eSharing and Publication:\u003c/strong\u003e Your data, including the technical details collected from your device\u0027s request headers, may be published, shared with third parties, or used for analysis and reporting purposes.\u003c/li\u003e\n \u003cli\u003e\u003cstrong\u003eData Retention:\u003c/strong\u003e We may retain your data, including the technical details collected from your device\u0027s request headers, for as long as necessary.\u003c/li\u003e\n \u003c/ol\u003e\n \u003cp\u003eBy continuing to use our app, you provide your explicit consent to the collection, use, and potential sharing of your data as described above. If you do not agree with our data collection, use, and sharing practices, please do not use our app.\u003c/p\u003e\n \u003c/div\u003e\n ","show_label":true,"name":"html","visible":true,"style":{}}},{"id":23,"type":"button","props":{"value":"I Agree","variant":"secondary","interactive":true,"name":"button","visible":true,"style":{}}},{"id":24,"type":"form","props":{"type":"form","visible":true,"style":{}}}],"css":"#col_container { margin-left: auto; margin-right: auto;}\n #chatbot {height: 520px; overflow: auto;}","title":"Gradio","is_space":true,"enable_queue":true,"show_error":false,"show_api":false,"is_colab":false,"layout":{"id":0,"children":[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":18,"children":[{"id":5}]},{"id":6},{"id":7,"children":[{"id":8,"children":[{"id":9}]},{"id":10,"children":[{"id":12,"children":[{"id":11}]}]}]},{"id":13,"children":[{"id":17,"children":[{"id":14},{"id":15},{"id":16}]}]}]},{"id":19,"children":[{"id":24,"children":[{"id":20}]},{"id":21,"children":[{"id":22},{"id":23}]}]}]},"dependencies":[{"targets":[23],"trigger":"click","inputs":[],"outputs":[20],"backend_fn":false,"js":"(x) =\u003e confirm(\u0027By clicking \"OK\", I agree that my data may be published or shared.\u0027)","queue":false,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":false},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false},{"targets":[20],"trigger":"change","inputs":[],"outputs":[19,3],"backend_fn":true,"js":null,"queue":false,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":false},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false},{"targets":[5],"trigger":"submit","inputs":[],"outputs":[5,9],"backend_fn":true,"js":null,"queue":false,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":false},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false},{"targets":[5],"trigger":"submit","inputs":[5,14,15,16,4,6],"outputs":[4,6,16,11,5,9],"backend_fn":true,"js":null,"queue":null,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":true},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false},{"targets":[9],"trigger":"click","inputs":[],"outputs":[5,9],"backend_fn":true,"js":null,"queue":false,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":false},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false},{"targets":[9],"trigger":"click","inputs":[5,14,15,16,4,6],"outputs":[4,6,16,11,5,9],"backend_fn":true,"js":null,"queue":null,"api_name":null,"scroll_to_output":false,"show_progress":true,"every":null,"batch":false,"max_batch_size":4,"cancels":[],"types":{"continuous":false,"generator":true},"collects_event_data":false,"trigger_after":null,"trigger_only_on_success":false}]};
|
ec7fedd8d331431ddb9407054f3b4305
|
{
"intermediate": 0.30520305037498474,
"beginner": 0.41759347915649414,
"expert": 0.2772034704685211
}
|
7,656
|
Tolong ubah vektor representasi kata pada kode Python Analisis Sentimen LSTM-CNN berikut yang awalnya menggunakan FastText menjadi menggunakan IndoBERT (indobert-base-uncased)!
"import pickle
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense, Dropout, Conv1D, MaxPooling1D
from keras.layers import Flatten
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import gensim
from gensim.models import KeyedVectors
from keras.regularizers import l2
# Membaca dataset
data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb'))
data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic'])
data['Isi Berita'] = data['pre_processed']
# Tokenisasi dan Padding
max_words = 10000 # mengurangi jumlah kata maksimum
max_len = 500 # mengurangi panjang input
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(data['Isi Berita'])
sequences = tokenizer.texts_to_sequences(data['Isi Berita'])
X = pad_sequences(sequences, maxlen=max_len)
y = to_categorical(data['Label'].astype('category').cat.codes)
# Membagi data menjadi data latih dan data uji
X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42)
# Menggunakan pre-trained Fasttext Bahasa Indonesia
model_path = 'fasttext.4B.id.300.epoch5.uncased'
vector_file = 'fasttext.4B.id.300.epoch5.uncased.vec'
id_ft = KeyedVectors.load_word2vec_format(vector_file)
# Membuat matriks embedding
embedding_dim = 300
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in tokenizer.word_index.items():
if i < max_words:
try:
embedding_vector = id_ft[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
# Membuat model LSTM-CNN
model = Sequential()
model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_len, trainable=False))
model.add(LSTM(200, return_sequences=True, dropout=0.25, kernel_regularizer=l2(0.001), recurrent_regularizer=l2(0.001)))
model.add(Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.001)))
model.add(MaxPooling1D(pool_size=4))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation='relu', kernel_regularizer=l2(0.001)))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))
# Menyusun model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Melatih model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)"
|
ec4ae83e60ac7579da04d86c0b0fe27b
|
{
"intermediate": 0.39263084530830383,
"beginner": 0.3503395915031433,
"expert": 0.25702959299087524
}
|
7,657
|
pada kode ini:
"# Mengevaluasi model
y_pred = model.predict(X_test)
y_pred = np.argmax(y_pred, axis=1)
y_true = np.argmax(y_test, axis=1)
# Menambahkan kolom hasil prediksi ke DataFrame data
data['Label_Hasil_Prediksi'] = None # inisialisasi kolom dengan None
data.loc[idx_test, 'Label_Hasil_Prediksi'] = y_pred
# Export ke file CSV
data.to_csv('CNN-LSTM_FastText_128CNN_100LSTM_epoch50.csv', columns=['judul', 'isi', 'Label', 'Label_Hasil_Prediksi', 'Partai_Politik_Heuristic'], index=False, sep=';')
# Menghitung akurasi
accuracy = accuracy_score(y_true, y_pred)
print(f"Akurasi: {accuracy}")
# Menampilkan classification report
report = classification_report(y_true, y_pred, target_names=['Negatif', 'Netral', 'Positif'])
print("Classification Report:")
print(report)"
menghasilkan ini dan ada error pada label positif:
160/160 [==============================] - 8s 50ms/step
Akurasi: 0.6446442533229085
Classification Report:
precision recall f1-score support
Negatif 0.60 0.80 0.69 1567
Netral 0.68 0.75 0.71 2743
positif 0.00 0.00 0.00 806
accuracy 0.64 5116
macro avg 0.43 0.52 0.46 5116
weighted avg 0.55 0.64 0.59 5116
C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\metrics\_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))
C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\metrics\_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))
C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\sklearn\metrics\_classification.py:1344: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples. Use `zero_division` parameter to control this behavior.
_warn_prf(average, modifier, msg_start, len(result))
kenapa bisa terjadi seperti itu dan bagaimana solusinya ?
|
f020d887af0b75cfb2b067bdbe35b804
|
{
"intermediate": 0.2891180217266083,
"beginner": 0.456938773393631,
"expert": 0.25394314527511597
}
|
7,658
|
Please complete task 3 using Scala 3, replacing your solution with the symbol ???. package words
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
@main def main(): Unit =
/*
* Let us start by setting up a Spark context which runs locally
* using two worker threads.
*
* Here we go:
*
*/
val sc = new SparkContext("local[2]", "words")
/*
* The following setting controls how ``verbose'' Spark is.
* Comment this out to see all debug messages.
* Warning: doing so may generate massive amount of debug info,
* and normal program output can be overwhelmed!
*/
sc.setLogLevel("WARN")
/*
* Next, let us set up our input.
*/
val path = "a01-words/data/"
/*
* After the path is configured, we need to decide which input
* file to look at. There are two choices -- you should test your
* code with "War and Peace" (default below), and then use the code with
* "Wealth of Nations" to compute the correct solutions
* (which you will submit to A+ for grading).
*
*/
// Tolstoy -- War and Peace (test input)
val filename = path ++ "pg2600.txt"
// Smith -- Wealth of Nations (uncomment line below to use as input)
// val filename = path ++ "pg3300.txt"
/*
* Now you may want to open up in a web browser
* the Scala programming guide for
* Spark version 3.3.1:
*
* http://spark.apache.org/docs/3.3.1/programming-guide.html
*
*/
/*
* Let us now set up an RDD from the lines of text in the file:
*
*/
val lines: RDD[String] = sc.textFile(filename)
/* The following requirement sanity-checks the number of lines in the file
* -- if this requirement fails you are in trouble.
*/
require((filename.contains("pg2600.txt") && lines.count() == 65007) ||
(filename.contains("pg3300.txt") && lines.count() == 35600))
/*
* Let us make one further sanity check. That is, we want to
* count the number of lines in the file that contain the
* substring "rent".
*
*/
val lines_with_rent: RDD[String] =
lines.filter(line => line.contains("rent"))
val rent_count = lines_with_rent.count()
println("OUTPUT: \"rent\" occurs on %d lines in \"%s\""
.format(rent_count, filename))
require((filename.contains("pg2600.txt") && rent_count == 360) ||
(filename.contains("pg3300.txt") && rent_count == 1443))
/*
* All right, if the execution continues this far without
* failing a requirement, we should be pretty sure that we have
* the correct file. Now we are ready for the work that you need
* to put in.
*
*/
/*
* Spark operates by __transforming__ RDDs. For example, above we
* took the RDD 'lines', and transformed it into the RDD 'lines_with_rent'
* using the __filter__ transformation.
*
* Important:
* While the code that manipulates RDDs may __look like__ we are
* manipulating just another Scala collection, this is in fact
* __not__ the case. An RDD is an abstraction that enables us
* to easily manipulate terabytes of data in a cluster computing
* environment. In this case the dataset is __distributed__ across
* the cluster. In fact, it is most likely that the entire dataset
* cannot be stored in a single cluster node.
*
* Let us practice our skills with simple RDD transformations.
*
*/
/*
* Task 1:
* This task asks you to transform the RDD
* 'lines' into an RDD 'depunctuated_lines' so that __on each line__,
* all occurrences of any of the punctuation characters
* ',', '.', ':', ';', '\"', '(', ')', '{', '}' have been deleted.
*
* Hint: it may be a good idea to consult
* http://www.scala-lang.org/api/3.2.1/scala/collection/StringOps.html
*
*/
val depunctuated_lines: RDD[String] =
lines.map(line => line.replaceAll("[,.:;\"(){}]", ""))
/*
* Let us now check and print out data that you want to
* record (__when the input file is "pg3300.txt"__) into
* the file "wordsSolutions.scala" that you need to submit for grading
* together with this file.
*/
val depunctuated_length = depunctuated_lines.map(_.length).reduce(_ + _)
println("OUTPUT: total depunctuated length is %d".format(depunctuated_length))
require(!filename.contains("pg2600.txt") || depunctuated_length == 3069444)
/*
* Task 2:
* Next, let us now transform the RDD of depunctuated lines to
* an RDD of consecutive __tokens__. That is, we want to split each
* line into zero or more __tokens__ where a __token__ is a
* maximal nonempty sequence of non-space (non-' ') characters on a line.
* Blank lines or lines with only space (' ') in them should produce
* no tokens at all.
*
* Hint: Use either a map or a flatMap to transform the RDD
* line by line. Again you may want to take a look at StringOps
* for appropriate methods to operate on each line. Use filter
* to get rid of blanks as necessary.
*
*/
val tokens: RDD[String] = depunctuated_lines.flatMap(line => line.split("\\s+")).filter(token => token.nonEmpty)
// transform 'depunctuated_lines' to tokens
/* ... and here comes the check and the printout. */
val token_count = tokens.count()
println("OUTPUT: %d tokens".format(token_count))
require(!filename.contains("pg2600.txt") || token_count == 566315)
/*
* Task 3:
* Transform the RDD of tokens into a new RDD where all upper case
* characters in each token get converted into lower case. Here you may
* restrict the conversion to characters in the Roman alphabet
* 'A', 'B', ..., 'Z'.
*
*/
val tokens_lc: RDD[String] = ???
// map each token in 'tokens' to lower case
/* ... and here comes the check and the printout. */
val tokens_a_count = tokens.flatMap(t => t.filter(_ == 'a')).count()
println("OUTPUT: 'a' occurs %d times in tokens".format(tokens_a_count))
require(!filename.contains("pg2600.txt") || tokens_a_count == 199232)
|
359e261563ad9e2278e58cebd9dad521
|
{
"intermediate": 0.4123949706554413,
"beginner": 0.3664155900478363,
"expert": 0.2211894392967224
}
|
7,659
|
act as a flutter developer im getting a error saying this
Usually, this means that the Positioned widget has the wrong ancestor RenderObjectWidget. Typically, Positioned widgets are placed directly inside Stack widgets.
The offending Positioned is currently placed inside a Row widget.
in this code
class NewsScreen extends StatelessWidget {
NewsScreen({Key? key}) : super(key: key);
final NewsController _con = Get.put(NewsController());
Future _pullRefresh() async {
return _con.getNewsList(true);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
if (_con.fromHome.isTrue) {
Get.offAllNamed(AppRoutes.bottomBarScreen, arguments: [0]);
} else {
Get.back();
}
return true;
},
child: Scaffold(
backgroundColor: AppColors.appBackGroundColor,
key: _con.scaffoldkey,
appBar: appBar(),
drawer: DrawerScreen(),
body: Obx(
() => _con.isLoading.value || _con.isEmojiLoading.value
? ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: 10,
itemBuilder: (BuildContext context, int index) => AppShimmer(
height: Get.height * 0.36,
width: Get.width,
color: AppColors.appColor.withOpacity(0.2),
),
)
: _con.newsList.isEmpty
? Center(
child: Text(
"No stories to share yet",
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w500,
),
),
)
: RefreshIndicator(
backgroundColor: AppColors.appColor,
color: Colors.white,
onRefresh: () {
return _pullRefresh();
},
child: Column(
children: [
Expanded(
child: ListView.builder(
physics: BouncingScrollPhysics(),
controller: _con.scrollController,
itemCount: _con.newsList.length,
itemBuilder: (BuildContext context, int index) =>
newsTile(index),
),
),
Obx(
() => _con.paginationLoading.value
? AppLoader(color: AppColors.appColor)
: SizedBox(),
),
],
),
),
),
),
);
}
Widget newsTile(int index) => Container(
decoration: BoxDecoration(color: Colors.white),
padding: EdgeInsets.symmetric(vertical: 15),
margin: EdgeInsets.only(bottom: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: Get.width * 0.03),
child: Text(
_con.newsList[index].title ?? '',
maxLines: 2,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
),
SizedBox(height: 5),
Padding(
padding: EdgeInsets.symmetric(horizontal: Get.width * 0.03),
child: Text(
_con.formatter.format(
DateTime.parse(_con.newsList[index].createdAt.toString())),
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
SizedBox(height: 14),
Padding(
padding: EdgeInsets.symmetric(horizontal: Get.width * 0.03),
child: ReadMoreText(
_con.newsList[index].description ?? '',
moreStyle:
TextStyle(color: Colors.black, fontWeight: FontWeight.w700),
style: TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w400,
),
trimLines: 2,
colorClickableText: Colors.pink,
trimMode: TrimMode.Line,
trimCollapsedText: 'More',
trimExpandedText: ' Show Less ',
lessStyle:
TextStyle(color: Colors.black, fontWeight: FontWeight.w700),
),
),
SizedBox(height: 10),
GestureDetector(
onTap: () {
if (_con.newsList[index].newsFeedAttachments?[0].thumbnail !=
null)
Get.toNamed(AppRoutes.videoScreen,
arguments: _con
.newsList[index].newsFeedAttachments![0].attachment);
},
child: _con.newsList[index].newsFeedAttachments!.isEmpty
? SizedBox()
: _con.newsList[index].newsFeedAttachments?[0].thumbnail ==
null
? CarouselSlider(
items: List.generate(
_con.newsList[index].newsFeedAttachments?.length ??
0,
(i) => imageTile(
_con.newsList[index].newsFeedAttachments![i],
index: index,
),
),
options: CarouselOptions(
viewportFraction: 1,
initialPage: _con.imageIndex.value,
height: Get.height * 0.25,
onPageChanged: (i, _) {
_con.imageIndex.value = i;
},
),
)
: imageTile(_con.newsList[index].newsFeedAttachments![0]),
),
Row(
mainAxisSize: MainAxisSize.max,
children: [
Container(
height: 60,
width: Get.width,
child: Expanded(
child: Stack(
children: [
Positioned(
child: Container(
color: AppColors.appColor,
height: 30,
width: Get.width,
),
bottom: 0,
),
Positioned(
bottom: 6,
child: InkWell(
onTap: () {
Get.toNamed(AppRoutes.likeListController,
arguments: [
_con.newsList[index].newsLikesCount?.value,
_con.newsList[index].id.toString(),
]);
},
child: Row(
children: [
SizedBox(width: 10,),
Obx(
() => Text(
"${_con.newsList[index].newsLikesCount?.value}",
style: TextStyle(
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
),
Text(
" Reacted",
style: TextStyle(
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
SizedBox(width: 10,),
Obx(
() => Text(
"${_con.newsList[index].newsCommentsCount?.value}",
style: TextStyle(
fontWeight: FontWeight.w700,
color: Colors.white,
),
),
),
Text(
" Comments",
style: TextStyle(
fontWeight: FontWeight.w500,
// height: 8,
color: Colors.white,
),
),
],
),
),
),
Positioned(
right: 3,
child: Row(
children: [
commentButton(index),
SizedBox(
width: 10,
),
likesButton(_con.emojiList.elementAt(index).id, index),
SizedBox(
width: 10,
),
],
),
),
],
),
),
),
],
),
d(),
SizedBox(height: 5),
// commentBox(index),
],
),
);
Widget imageTile(NewsFeedAttachment image, {int? index}) => Stack(
alignment:
image.thumbnail != null ? Alignment.center : Alignment.bottomCenter,
children: [
Container(
height: Get.height * 0.25,
width: Get.width,
margin: EdgeInsets.symmetric(horizontal: Get.width * 0.03),
child: imageNetwork(
image.thumbnail == null ? image.attachment! : image.thumbnail!,
boxFit: BoxFit.contain,
),
),
if (image.thumbnail != null) playIcon(),
if (index != null &&
_con.newsList[index].newsFeedAttachments!.length > 1)
ClipRRect(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Container(
padding: EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.2),
borderRadius: BorderRadius.circular(50),
),
margin: EdgeInsets.only(bottom: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: List.generate(
_con.newsList[index].newsFeedAttachments!.length,
(i) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 3),
child: Obx(
() => Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 2),
shape: BoxShape.circle,
),
child: CircleAvatar(
radius: 3,
backgroundColor: i == _con.imageIndex.value
? Colors.white
: Colors.transparent,
),
),
),
),
),
),
),
),
)
],
);
reactionIcon({
required String icon,
required String value,
}) =>
Reaction(
icon: Obx(
() => Image.network(icon,
height: 35,
width: 35,
opacity: _con.selectedEmoji.value == value
? AlwaysStoppedAnimation<double>(1)
: AlwaysStoppedAnimation<double>(0.5),
errorBuilder: (context, url, error) => new Icon(Icons.error),
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
color: AppColors.appColor,
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
int.parse(
loadingProgress.expectedTotalBytes.toString())
: null,
),
);
}),
),
value: value,
);
ClipRRect playIcon() {
return ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: Colors.white.withOpacity(0.5), width: 5),
),
height: 60,
width: 60,
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Icon(
Icons.play_arrow,
color: Colors.white,
size: 25,
),
),
),
),
),
);
}
Container d() {
return Container(
width: Get.width,
height: 1,
color: Color(0xffB3B3B3).withOpacity(0.2),
);
}
Widget commentBox(index) => Container(
padding: EdgeInsets.symmetric(horizontal: Get.width * 0.03),
child: GestureDetector(
onTap: () {
Get.toNamed(
AppRoutes.newscommentsScreen,
arguments: _con.newsList[index].id,
);
},
child: Row(
children: [
ImageIcon(
AssetImage(AppImages.comment),
size: 20,
color: AppColors.appColor,
),
SizedBox(width: 10),
Text(
"Type comment here...",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: AppColors.appColor,
),
),
Spacer(),
IconButton(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
constraints: BoxConstraints(),
padding: EdgeInsets.zero,
icon: ImageIcon(
AssetImage(AppImages.share),
),
onPressed: () {
Share.share(
"${_con.newsList[index].title}\n${_con.newsList[index].description}");
},
)
],
),
),
);
PreferredSizeWidget appBar() {
return AppBar(
shadowColor: Color(0xfff2f2f2),
backgroundColor: Colors.white,
centerTitle: false,
toolbarHeight: 60,
elevation: 1,
leading: _con.fromHome.value
? IconButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
constraints: BoxConstraints(),
padding: const EdgeInsets.only(left: 5, bottom: 5),
icon: Icon(
Icons.keyboard_arrow_left,
color: Colors.black,
size: 40,
),
onPressed: () {
Get.offAllNamed(AppRoutes.bottomBarScreen, arguments: [0]);
})
: GestureDetector(
onTap: () {
_con.scaffoldkey.currentState?.openDrawer();
},
child: Container(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 6),
padding: EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(11),
color: Color(0xffE3FAFA),
),
width: 40,
child: ImageIcon(
AssetImage(
AppImages.menuOpen,
),
color: AppColors.appColor,
),
),
),
title: Text(
'News',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w700,
fontSize: 24,
),
),
actions: [
InkWell(
onTap: () => Get.toNamed(AppRoutes.notificationListScreen),
child: Container(
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 6),
padding: EdgeInsets.symmetric(vertical: 8),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(11),
color: AppColors.appColor,
),
width: 40,
child: ImageIcon(AssetImage(AppImages.notification)),
),
),
GestureDetector(
onTap: () async {
Get.toNamed(AppRoutes.profileScreen);
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 6),
child: ClipRRect(
borderRadius: BorderRadius.circular(100),
child: Obx(
() => LocalStorage.userProfile.isNotEmpty
? Image.network(LocalStorage.userProfile.value,
width: 40,
height: 40,
fit: BoxFit.contain,
errorBuilder: (context, url, error) =>
new Icon(Icons.error),
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
color: AppColors.appColor,
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
int.parse(loadingProgress
.expectedTotalBytes
.toString())
: null,
),
);
},
)
: Image.asset(
AppImages.userProfile,
width: 40,
height: 40,
fit: BoxFit.contain,
),
),
),
),
)
],
systemOverlayStyle: SystemUiOverlayStyle.dark,
);
}
Widget likesButton(var value, var index) {
return Positioned(
bottom: 0,
right: 0,
child: Obx(() {
return GestureDetector(
onTap: () {
print('valueeee $value ');
if (_con.newsList[index].newsLikes!.isNotEmpty) {
_con.deleteFavouriteApi(
_con.newsList[index].newsLikes![0].id,
index,
);
} else {
_con.addToFavouriteApi(
_con.newsList[index].id, _con.emojiList[0].id, index);
}
},
child: Container(
margin: EdgeInsets.only(bottom: 2, right: 0),
padding: EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: !_con.newsList[index].newsLikes!.isEmpty
? AppColors.appColor
: Colors.white,
border: Border.all(
color: AppColors.appColor,
width: 4.0,
),
),
width: 60,
height: 60,
child: ImageIcon(
AssetImage(AppImages.gheart),
color: !_con.newsList[index].newsLikes!.isEmpty
? Colors.white
: AppColors.appColor,
),
),
);
}),
);
}
///comment button
Widget commentButton(index) {
return GestureDetector(
onTap: () => Get.toNamed(
AppRoutes.newscommentsScreen,
arguments: _con.newsList[index].id,
), // add route
child: Container(
margin: EdgeInsets.only(bottom: 2, right: 0),
padding: EdgeInsets.symmetric(vertical: 6),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
border: Border.all(
color: AppColors.appColor,
width: 4.0,
),
),
width: 60,
height: 60,
child: ImageIcon(AssetImage(AppImages.ncomment),
color: AppColors.appColor),
),
);
}
Widget imageNetwork(String url, {Color? color, BoxFit? boxFit}) {
return Image.network(url,
fit: boxFit ?? BoxFit.contain,
errorBuilder: (context, url, error) => new Icon(Icons.error),
loadingBuilder: (BuildContext context, Widget child,
ImageChunkEvent? loadingProgress) {
if (loadingProgress == null) return child;
return Center(
child: CircularProgressIndicator(
color: color ?? AppColors.appColor,
value: loadingProgress.expectedTotalBytes != null
? loadingProgress.cumulativeBytesLoaded /
int.parse(loadingProgress.expectedTotalBytes.toString())
: null,
),
);
});
}
}
|
d236751480b1dcb1d46b795571c66c60
|
{
"intermediate": 0.33237046003341675,
"beginner": 0.48784729838371277,
"expert": 0.17978227138519287
}
|
7,660
|
Tolong ubah vektor representasi kata pada kode python analisis sentimen CNN-LSTM berikut yang awalnya menggunakan FastText menjadi menggunakan IndoBERT (indobert-base-uncased)!
"import pickle
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense, Dropout, Conv1D, MaxPooling1D
from keras.layers import Flatten
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import gensim
from gensim.models import KeyedVectors
from keras.regularizers import l2
# Parameter untuk regularisasi L2
l2_coeff = 0.01
# Membaca dataset
data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb'))
data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic'])
data['Isi Berita'] = data['pre_processed']
# Tokenisasi dan Padding
max_words = 10000 # mengurangi jumlah kata maksimum
max_len = 500 # mengurangi panjang input
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(data['Isi Berita'])
sequences = tokenizer.texts_to_sequences(data['Isi Berita'])
X = pad_sequences(sequences, maxlen=max_len)
y = to_categorical(data['Label'].astype('category').cat.codes)
# Membagi data menjadi data latih dan data uji
X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42)
# Menggunakan pre-trained Fasttext Bahasa Indonesia
model_path = 'fasttext.4B.id.300.epoch5.uncased'
vector_file = 'fasttext.4B.id.300.epoch5.uncased.vec'
id_ft = KeyedVectors.load_word2vec_format(vector_file)
# Membuat matriks embedding
embedding_dim = 300
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in tokenizer.word_index.items():
if i < max_words:
try:
embedding_vector = id_ft[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
# Membangun model CNN-LSTM dengan pre-trained Word2Vec
num_filters = 64
lstm_units = 64
# Membuat model CNN-LSTM
model = Sequential([
Embedding(input_dim=10000,
output_dim=300,
input_length=500,
weights=[embedding_matrix],
trainable=False),
Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.005)),
MaxPooling1D(pool_size=4),
Dropout(0.25),
LSTM(200, return_sequences=False, kernel_regularizer=l2(0.005), recurrent_regularizer=l2(0.005), dropout=0.25),
Dense(32, activation='relu', kernel_regularizer=l2(0.005)),
Dropout(0.5),
Dense(3, activation='softmax')
])
# Menyusun Model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Melatih Model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)"
|
c41d2aedc595c4eab5487e8df5e94c3f
|
{
"intermediate": 0.3944588899612427,
"beginner": 0.3370046019554138,
"expert": 0.2685364782810211
}
|
7,661
|
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 some of the relevant header and source file code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize(const Mesh& mesh, const Material& material);
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh mesh;
Material material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize(const Mesh& mesh, const Material& material)
{
this->mesh = mesh; // copy or share mesh data
this->material = material; // copy or share material data
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh.GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh.GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material.GetDescriptorSet();
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material.GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh.GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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 (device == VK_NULL_HANDLE || shutdownInProgress) {
// If the device is already VK_NULL_HANDLE, it means the cleanup has run before
return;
}
shutdownInProgress = true; // Indicate that the cleanup is in progress
std::cout << "Waiting for device idle…" << std::endl;
vkDeviceWaitIdle(device); // Wait for rendering to complete
std::cout << "Cleaning up framebuffers…" << std::endl;
CleanupFramebuffers();
std::cout << "Cleaning up renderpass…" << std::endl;
CleanupRenderPass();
std::cout << "Cleaning up syncobject…" << std::endl;
CleanupSyncObjects();
std::cout << "Cleaning up commandbuffers…" << std::endl;
CleanupCommandBuffers(); // Free command buffers before destroying the command pool
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface
DestroySurface(); // Move this line after CleanupDevice
CleanupInstance();
}
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];
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 = ¤tCommandBuffer;
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);
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.");
}
}
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);
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 ¤tCommandBuffer;
}
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;
}
I am running into errors while trying to render. It seems to be related to a renderer.GetCurrentCommandBuffer call. Please check the code and tell me if you find any errors with how commandbuffers are being managed that might result in an access violation error.
|
538e8aa2fbd76808c00cf66d88dc2ff6
|
{
"intermediate": 0.37031203508377075,
"beginner": 0.28982001543045044,
"expert": 0.3398679792881012
}
|
7,662
|
write email for appraisal and salary hike
|
3ec316d354286e4f22203de6fa97e114
|
{
"intermediate": 0.381095290184021,
"beginner": 0.28046268224716187,
"expert": 0.3384420573711395
}
|
7,663
|
Create a presentation about the advantages of Rust compared to Python and Java. The target audience is professional Python and Java developers. It should take 1 hour to present.
|
d98f675422b29f4e244579aa5b1617b7
|
{
"intermediate": 0.34156161546707153,
"beginner": 0.28260350227355957,
"expert": 0.3758348822593689
}
|
7,664
|
"0","8","3","6","9","2","5","7","1","4" foreach push to arry php
|
e118ff62170c1463bf3682f6c03cb204
|
{
"intermediate": 0.31253454089164734,
"beginner": 0.3386688232421875,
"expert": 0.34879666566848755
}
|
7,665
|
“0”,“8”,“3”,“6”,“9”,“2”,“5”,“7”,“1”,“4” foreach push to arry php
|
b3fb905c860f922130ead5820c1a3a0d
|
{
"intermediate": 0.3310457468032837,
"beginner": 0.3735198676586151,
"expert": 0.2954343855381012
}
|
7,666
|
write a python code that will output a hmac authentication header
|
f9c4832a404334218d7e3df44ca171f2
|
{
"intermediate": 0.407176673412323,
"beginner": 0.21914324164390564,
"expert": 0.37368008494377136
}
|
7,667
|
Write an Eggdrop module in Rust that performs the same functions as woobie.mod
|
cd0ea67e2fcf14cdf1b3b67463b749fb
|
{
"intermediate": 0.4834497272968292,
"beginner": 0.23788055777549744,
"expert": 0.2786697447299957
}
|
7,668
|
ihave array in php and i need to display position by value
|
87244e904180c7b8dcd97ed4773a7816
|
{
"intermediate": 0.5382978320121765,
"beginner": 0.23317323625087738,
"expert": 0.2285289615392685
}
|
7,669
|
In python make a clan tracker on a map that goes from A0 to U25. The data you got are the previos locations of the clan in a list: ['Q8', 'Q10', 'K4', 'N6', 'K5', 'R10', 'S9', 'S11', 'R9', 'O9', 'R8', 'O5', 'O10']
. Use machine learning and give the top 3 most likely locations for the clan to be.
|
0ce3bbf4f932fd720bbf9161ab8d4dee
|
{
"intermediate": 0.17228953540325165,
"beginner": 0.11043049395084381,
"expert": 0.7172799706459045
}
|
7,670
|
Can you generate a complicated C code? It can be of any type.
|
550e7b6e3349428b0d8977f6d4432e19
|
{
"intermediate": 0.31037142872810364,
"beginner": 0.36810940504074097,
"expert": 0.3215191662311554
}
|
7,671
|
Создай векторную анимация для плавного перехода между фрагментами (сдвиг фрагмента влево или в право) , для AndroidStduio пиши на языке java , я хочу что эта анимация срабатывала при заходе и выходе в FirstFragmetn
|
81ee47eddfb144c3626316b2db8fcece
|
{
"intermediate": 0.5258864164352417,
"beginner": 0.2158077210187912,
"expert": 0.25830575823783875
}
|
7,672
|
Can you teach me power shell for MS Teams administration
|
1e5cf37c5a99c7477fbdaa2662b95ea9
|
{
"intermediate": 0.3605397045612335,
"beginner": 0.5315278768539429,
"expert": 0.10793235898017883
}
|
7,673
|
Tolong ubah vektor representasi kata pada kode Python Analisis Sentimen LSTM-CNN berikut yang awalnya menggunakan Word2Vec menjadi menggunakan IndoBERT!
"import pickle
import pandas as pd
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, LSTM, Dense, Dropout, Conv1D, MaxPooling1D
from keras.layers import Flatten
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
import gensim
from keras.regularizers import l2
# Membaca dataset
data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb'))
data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic'])
data['Isi Berita'] = data['pre_processed']
# Tokenisasi dan Padding
max_words = 10000 # mengurangi jumlah kata maksimum
max_len = 500 # mengurangi panjang input
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(data['Isi Berita'])
sequences = tokenizer.texts_to_sequences(data['Isi Berita'])
X = pad_sequences(sequences, maxlen=max_len)
y = to_categorical(data['Label'].astype('category').cat.codes)
# Membagi data menjadi data latih dan data uji
X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42)
# Menggunakan pre-trained word2vec Bahasa Indonesia
path = 'idwiki_word2vec_300.model'
id_w2v = gensim.models.word2vec.Word2Vec.load(path)
wv = id_w2v.wv
# Membuat matriks embedding
embedding_dim = 300
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in tokenizer.word_index.items():
if i < max_words:
try:
embedding_vector = wv[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
# Membuat model LSTM-CNN
model = Sequential()
model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_len, trainable=False))
model.add(LSTM(64, return_sequences=True, dropout=0.2, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01)))
model.add(Conv1D(64, 5, activation='relu', kernel_regularizer=l2(0.01)))
model.add(MaxPooling1D(pool_size=4))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation='relu', kernel_regularizer=l2(0.01)))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))
# Menyusun model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Melatih model
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)"
|
055f707103d48010d0f500ed60c54a34
|
{
"intermediate": 0.3169499933719635,
"beginner": 0.33348187804222107,
"expert": 0.34956812858581543
}
|
7,674
|
Tolong ubah vektor representasi kata analisis sentimen CNN-LSTM berikut yang awalnya menggunakan Word2Vec menjadi menggunakan IndoBERT!
"import numpy as np
import pandas as pd
import pickle
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from keras.preprocessing.text import Tokenizer
from keras.utils import pad_sequences
from keras.models import Sequential
from keras.layers import Embedding, Conv1D, MaxPooling1D, LSTM, Dense, GlobalMaxPooling1D
from keras.callbacks import EarlyStopping, ModelCheckpoint
import gensim
from gensim.models import Word2Vec
from keras.layers import Dropout
from keras.regularizers import l2
from keras.utils import to_categorical
# Parameter untuk regularisasi L2
l2_coeff = 0.01
# Membaca dataset
data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb'))
data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic'])
data['Isi Berita'] = data['pre_processed']
# Tokenisasi dan Padding
max_words = 10000 # mengurangi jumlah kata maksimum
max_len = 500 # mengurangi panjang input
tokenizer = Tokenizer(num_words=max_words)
tokenizer.fit_on_texts(data['Isi Berita'])
sequences = tokenizer.texts_to_sequences(data['Isi Berita'])
X = pad_sequences(sequences, maxlen=max_len)
y = to_categorical(data['Label'].astype('category').cat.codes)
# Membagi data menjadi data latih dan data uji
X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42)
# Membuka model word2vec
path = 'idwiki_word2vec_300.model'
id_w2v = gensim.models.word2vec.Word2Vec.load(path)
wv = id_w2v.wv
# Membuat embeding matrix
embedding_dim = id_w2v.vector_size
embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in tokenizer.word_index.items():
if i < max_words:
try:
embedding_vector = wv[word]
embedding_matrix[i] = embedding_vector
except KeyError:
pass
# Membangun model CNN-LSTM dengan pre-trained Word2Vec
num_filters = 64
lstm_units = 64
model = Sequential([
Embedding(input_dim=10000,
output_dim=300,
input_length=500,
weights=[embedding_matrix],
trainable=False),
Conv1D(64, 5, activation='relu', kernel_regularizer=l2(0.01)),
MaxPooling1D(pool_size=4),
Dropout(0.25),
LSTM(64, return_sequences=False, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01), dropout=0.2),
Dense(32, activation='relu', kernel_regularizer=l2(0.01)),
Dropout(0.5),
Dense(3, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Melatih model dengan early stopping dan model checkpoint
checkpoint = ModelCheckpoint('model_cnn_lstm.h5', save_best_only=True, monitor='val_accuracy', mode='max')
early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1)
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128)"
|
6fae6adf3a9baec990fecbe247a6065f
|
{
"intermediate": 0.41569340229034424,
"beginner": 0.35970333218574524,
"expert": 0.2246032953262329
}
|
7,675
|
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp_2, PID: 4718
java.lang.RuntimeException: Unknown animator name: translate
at android.animation.AnimatorInflater.createAnimatorFromXml(AnimatorInflater.java:691)
at android.animation.AnimatorInflater.createAnimatorFromXml(AnimatorInflater.java:680)
at android.animation.AnimatorInflater.createAnimatorFromXml(AnimatorInflater.java:642)
at android.animation.AnimatorInflater.loadAnimator(AnimatorInflater.java:126)
at android.animation.AnimatorInflater.loadAnimator(AnimatorInflater.java:106)
at android.animation.AnimatorInflater.loadAnimator(AnimatorInflater.java:91)
at com.example.myapp_2.UI.view.fragments.FirstFragment.onCreate(FirstFragment.java:391)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2949) Мой код : <?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="500"
android:interpolator="@android:anim/accelerate_decelerate_interpolator">
<translate
android:fromXDelta="0%"
android:toXDelta="-100%" />
</set> @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Загружаем аниматор
Animator animator = AnimatorInflater.loadAnimator(getContext(), R.animator.my_animation);
// Получаем ссылку на View, к которой применяем анимацию
View view = getView();
// Применяем аниматор к элементу
animator.setTarget(view);
// Запускаем анимацию
animator.start();
Bundle bundle = this.getArguments();
if (bundle != null) {
int myInt = bundle.getInt("hello world", 123);
String strI = Integer.toString(myInt);
Toast.makeText(getActivity(),strI,Toast.LENGTH_SHORT).show();
}
}
|
435a8480907bd58c7ffb58acc874151a
|
{
"intermediate": 0.26950833201408386,
"beginner": 0.49861666560173035,
"expert": 0.23187504708766937
}
|
7,676
|
Hi
|
8409e94c86bcedc4644a8ed81249153c
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
7,677
|
what is the xpath_expression for https://www.walmart.com/ip/TUSY-Inflatable-Stand-Up-Paddle-Board-10-6-FT-Premium-SUP-Accessories-Backpack-Wide-Stance-Surf-Control-Non-Slip-Deck-Leash-Pump-Standing-Boat-Youth-/544598761.
|
69f7f8ee0ef0256c28d253f1de12d1f0
|
{
"intermediate": 0.3470422923564911,
"beginner": 0.36438214778900146,
"expert": 0.28857558965682983
}
|
7,678
|
How do i console log action.payload from the following code export const wordsSlice = createSlice({
name: 'words',
initialState,
reducers: {
setWord: (state, action) => {
state.word = action.payload;
state.isCorrect = null;
state.correctArticle = null;
state.correctEnding = null;
state.translation = null;
},
|
643b0a89914bec61290a84b5c0df76fc
|
{
"intermediate": 0.638335108757019,
"beginner": 0.24282538890838623,
"expert": 0.11883951723575592
}
|
7,679
|
I have app_settings.py from pydantic import BaseSettings, PostgresDsn
class Settings(BaseSettings):
db_url: PostgresDsn
db_host: str
db_port: int
db_user: str
db_name: str
db_pass: str
port: int
host: str
class Config:
env_file = ".env"
env_file_encoding = "utf-8"
settings = Settings() and .env # app configuration
HOST=127.0.0.1
PORT=8000
# db configuration
DB_HOST=localhost
DB_URL=postgresql://postgres:as@localhost:5432/logging
DB_PORT=5432
DB_NAME=logging
DB_USER=postgres
DB_PASS=as and when I try to do alembic --revision I got en error. Here alembic .env from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from src.settings.app_settings import settings
import os
import sys
sys.path.append(os.path.join(sys.path[0], 'src'))
from src.db.tables import Log
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
section = config.config_ini_section
config.set_section_option(section, "DB_HOST", settings.db_host)
config.set_section_option(section, "DB_PORT", settings.db_port)
config.set_section_option(section, "DB_USER", settings.db_user)
config.set_section_option(section, "DB_NAME", settings.db_name)
config.set_section_option(section, "DB_PASS", settings.db_pass)
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import my model
# target_metadata = my model.Base.metadata
target_metadata = Log.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
802384ef1d20cb864afa9f96541515ae
|
{
"intermediate": 0.28426116704940796,
"beginner": 0.5769257545471191,
"expert": 0.1388131082057953
}
|
7,680
|
Hi, can you help me to translate this pytorch model into a tensorflow model?
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
from matplotlib.patches import Ellipse, Circle
seed = 2
np.random.seed(seed)
torch.manual_seed(seed)
#torch.set_default_tensor_type(torch.DoubleTensor)
class BioLinear(nn.Module):
# BioLinear is just Linear, but each neuron comes with coordinates.
def __init__(self, in_dim, out_dim, in_fold=1, out_fold=1):
super(BioLinear, self).__init__()
self.in_dim = in_dim
self.out_dim = out_dim
self.linear = nn.Linear(in_dim, out_dim)
self.in_fold = in_fold # in_fold is the number of folds applied to input vectors. It only affects coordinates, not computations.
self.out_fold = out_fold # out_fold is the number of folds applied to output vectors. It only affects coordinates, not computations.
assert in_dim % in_fold == 0
assert out_dim % out_fold == 0
#compute in_cor, shape: (in_dim)
in_dim_fold = int(in_dim/in_fold)
out_dim_fold = int(out_dim/out_fold)
self.in_coordinates = torch.tensor(list(np.linspace(1/(2*in_dim_fold), 1-1/(2*in_dim_fold), num=in_dim_fold))*in_fold, dtype=torch.float) # place input neurons in 1D Euclidean space
self.out_coordinates = torch.tensor(list(np.linspace(1/(2*out_dim_fold), 1-1/(2*out_dim_fold), num=out_dim_fold))*out_fold, dtype=torch.float) # place output neurons in 1D Euclidean space
self.input = None
self.output = None
def forward(self, x):
self.input = x.clone()
self.output = self.linear(x).clone()
return self.output
class BioMLP(nn.Module):
# BioMLP is just MLP, but each neuron comes with coordinates.
def __init__(self, in_dim=2, out_dim=2, w=2, depth=2, shp=None, token_embedding=False, embedding_size=None):
super(BioMLP, self).__init__()
if shp == None:
shp = [in_dim] + [w]*(depth-1) + [out_dim]
self.in_dim = in_dim
self.out_dim = out_dim
self.depth = depth
else:
self.in_dim = shp[0]
self.out_dim = shp[-1]
self.depth = len(shp) - 1
linear_list = []
for i in range(self.depth):
if i == 0:
linear_list.append(BioLinear(shp[i], shp[i+1], in_fold=1))
else:
linear_list.append(BioLinear(shp[i], shp[i+1]))
self.linears = nn.ModuleList(linear_list)
if token_embedding == True:
# embedding size: number of tokens * embedding dimension
self.embedding = torch.nn.Parameter(torch.normal(0,1,size=embedding_size))
self.shp = shp
# parameters for the bio-inspired trick
self.l0 = 0.1 # distance between two nearby layers
self.in_perm = torch.nn.Parameter(torch.tensor(np.arange(int(self.in_dim/self.linears[0].in_fold)), dtype=torch.float))
self.out_perm = torch.nn.Parameter(torch.tensor(np.arange(int(self.out_dim/self.linears[-1].out_fold)), dtype=torch.float))
self.top_k = 5 # the number of important neurons (used in Swaps)
self.token_embedding = token_embedding
self.n_parameters = sum(p.numel() for p in self.parameters())
self.original_params = None
def forward(self, x):
shp = x.shape
in_fold = self.linears[0].in_fold
x = x.reshape(shp[0], in_fold, int(shp[1]/in_fold))
x = x[:,:,self.in_perm.long()]
x = x.reshape(shp[0], shp[1])
f = torch.nn.SiLU()
for i in range(self.depth-1):
x = f(self.linears[i](x))
x = self.linears[-1](x)
out_perm_inv = torch.zeros(self.out_dim, dtype=torch.long)
out_perm_inv[self.out_perm.long()] = torch.arange(self.out_dim)
x = x[:,out_perm_inv]
#x = x[:,self.out_perm]
return x
def get_linear_layers(self):
return self.linears
def get_cc(self, weight_factor=1.0, bias_penalize=True, no_penalize_last=False):
# compute connection cost
# bias_penalize = True penalizes biases, otherwise doesn't penalize biases
# no_penalize_last = True means do not penalize last linear layer, False means penalize last layer.
cc = 0
num_linear = len(self.linears)
for i in range(num_linear):
if i == num_linear - 1 and no_penalize_last:
weight_factor = 0.
biolinear = self.linears[i]
dist = torch.abs(biolinear.out_coordinates.unsqueeze(dim=1) - biolinear.in_coordinates.unsqueeze(dim=0))
cc += torch.sum(torch.abs(biolinear.linear.weight)*(weight_factor*dist+self.l0))
if bias_penalize == True:
cc += torch.sum(torch.abs(biolinear.linear.bias)*(self.l0))
if self.token_embedding:
cc += torch.sum(torch.abs(self.embedding)*(self.l0))
#pass
return cc
def swap_weight(self, weights, j, k, swap_type="out"):
# Given a weight matrix, swap the j^th and k^th neuron in inputs/outputs when swap_type = "in"/"out"
with torch.no_grad():
if swap_type == "in":
temp = weights[:,j].clone()
weights[:,j] = weights[:,k].clone()
weights[:,k] = temp
elif swap_type == "out":
temp = weights[j].clone()
weights[j] = weights[k].clone()
weights[k] = temp
else:
raise Exception("Swap type {} is not recognized!".format(swap_type))
def swap_bias(self, biases, j, k):
# Given a bias vector, swap the j^th and k^th neuron.
with torch.no_grad():
temp = biases[j].clone()
biases[j] = biases[k].clone()
biases[k] = temp
def swap(self, i, j, k):
# in the ith layer (of neurons), swap the jth and the kth neuron.
# Note: n layers of weights means n+1 layers of neurons.
linears = self.get_linear_layers()
num_linear = len(linears)
if i == 0:
# input layer, only has outgoing weights; update in_perm
weights = linears[i].linear.weight
infold = linears[i].in_fold
fold_dim = int(weights.shape[1]/infold)
for l in range(infold):
self.swap_weight(weights, j+fold_dim*l, k+fold_dim*l, swap_type="in")
# change input_perm
self.swap_bias(self.in_perm, j, k)
elif i == num_linear:
# output layer, only has incoming weights and biases; update out_perm
weights = linears[i-1].linear.weight
biases = linears[i-1].linear.bias
self.swap_weight(weights, j, k, swap_type="out")
self.swap_bias(biases, j, k)
# change output_perm
self.swap_bias(self.out_perm, j, k)
else:
# middle layer : incoming weights, outgoing weights, and biases
weights_in = linears[i-1].linear.weight
weights_out = linears[i].linear.weight
biases = linears[i-1].linear.bias
self.swap_weight(weights_in, j, k, swap_type="out")
self.swap_weight(weights_out, j, k, swap_type="in")
self.swap_bias(biases, j, k)
def get_top_id(self, i, top_k=20):
# in the ith layer (of neurons), get the top k important neurons (have large weight connections with other neurons)
linears = self.get_linear_layers()
num_linear = len(linears)
if i == 0:
# input layer
weights = linears[i].linear.weight
score = torch.sum(torch.abs(weights), dim=0)
in_fold = linears[0].in_fold
#print(score.shape)
score = torch.sum(score.reshape(in_fold, int(score.shape[0]/in_fold)), dim=0)
elif i == num_linear:
# output layer
weights = linears[i-1].linear.weight
score = torch.sum(torch.abs(weights), dim=1)
else:
weights_in = linears[i-1].linear.weight
weights_out = linears[i].linear.weight
score = torch.sum(torch.abs(weights_out), dim=0) + torch.sum(torch.abs(weights_in), dim=1)
#print(score.shape)
top_index = torch.flip(torch.argsort(score),[0])[:top_k]
return top_index
def relocate_ij(self, i, j):
# In the ith layer (of neurons), relocate the jth neuron
linears = self.get_linear_layers()
num_linear = len(linears)
if i < num_linear:
num_neuron = int(linears[i].linear.weight.shape[1]/linears[i].in_fold)
else:
num_neuron = linears[i-1].linear.weight.shape[0]
ccs = []
for k in range(num_neuron):
self.swap(i,j,k)
ccs.append(self.get_cc())
self.swap(i,j,k)
k = torch.argmin(torch.stack(ccs))
self.swap(i,j,k)
def relocate_i(self, i):
# Relocate neurons in the ith layer
top_id = self.get_top_id(i, top_k=self.top_k)
for j in top_id:
self.relocate_ij(i,j)
def relocate(self):
# Relocate neurons in the whole model
linears = self.get_linear_layers()
num_linear = len(linears)
for i in range(num_linear+1):
self.relocate_i(i)
def plot(self):
fig, ax = plt.subplots(figsize=(3,3))
#ax = plt.gca()
shp = self.shp
s = 1/(2*max(shp))
for j in range(len(shp)):
N = shp[j]
if j == 0:
in_fold = self.linears[j].in_fold
N = int(N/in_fold)
for i in range(N):
if j == 0:
for fold in range(in_fold):
circle = Ellipse((1/(2*N)+i/N, 0.1*j+0.02*fold-0.01), s, s/10*((len(shp)-1)+0.4), color='black')
ax.add_patch(circle)
else:
for fold in range(in_fold):
circle = Ellipse((1/(2*N)+i/N, 0.1*j), s, s/10*((len(shp)-1)+0.4), color='black')
ax.add_patch(circle)
plt.ylim(-0.02,0.1*(len(shp)-1)+0.02)
plt.xlim(-0.02,1.02)
linears = self.linears
for ii in range(len(linears)):
biolinear = linears[ii]
p = biolinear.linear.weight
p_shp = p.shape
p = p/torch.abs(p).max()
in_fold = biolinear.in_fold
fold_num = int(p_shp[1]/in_fold)
for i in range(p_shp[0]):
if ii == 0:
for fold in range(in_fold):
for j in range(fold_num):
plt.plot([1/(2*p_shp[0])+i/p_shp[0], 1/(2*fold_num)+j/fold_num], [0.1*(ii+1),0.1*ii+0.02*fold-0.01], lw=1*np.abs(p[i,j].detach().numpy()), color="blue" if p[i,j]>0 else "red")
else:
for j in range(fold_num):
plt.plot([1/(2*p_shp[0])+i/p_shp[0], 1/(2*fold_num)+j/fold_num], [0.1*(ii+1),0.1*ii], lw=0.5*np.abs(p[i,j].detach().numpy()), color="blue" if p[i,j]>0 else "red")
ax.axis('off')
def thresholding(self, threshold, checkpoint = True):
# snap too small weights (smaller than threshold) to zero. Useful for pruning.
num = 0
if checkpoint:
self.original_params = [param.clone() for param in self.parameters()]
with torch.no_grad():
for param in self.parameters():
num += torch.sum(torch.abs(param)>threshold)
param.data = param*(torch.abs(param)>threshold)
return num
def intervening(self, i, pos, value, ptype="weight", checkpoint = True):
if checkpoint:
self.original_params = [param.clone() for param in self.parameters()]
with torch.no_grad():
if ptype == "weight":
self.linears[i].linear.weight[pos] = value
elif ptype == "bias":
self.linears[i].linear.bias[pos] = value
def revert(self):
with torch.no_grad():
for param, original_param in zip(self.parameters(), self.original_params):
param.data.copy_(original_param.data)
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
# create dataset
seed = 0
np.random.seed(seed)
torch.manual_seed(seed)
def f(data):
x1 = data[:,[0]]
x2 = data[:,[1]]
x3 = data[:,[2]]
x4 = data[:,[3]]
out = np.transpose(np.array([(x1+x3)**3, x2**2+np.sin(np.pi*x4)]))
return out
d_in = 4
d_out = 2
inputs = np.random.rand(100,d_in)*2-1
labels = f(inputs)
inputs = torch.tensor(inputs, dtype=torch.float, requires_grad=True)
labels = torch.tensor(labels, dtype=torch.float, requires_grad=True)
inputs_test = np.random.rand(100,d_in)*2-1
labels_test = f(inputs_test)
inputs_test = torch.tensor(inputs_test, dtype=torch.float, requires_grad=True)
labels_test = torch.tensor(labels_test, dtype=torch.float, requires_grad=True)
width = 20
depth = 3
shp = [d_in, 20, 20, d_out]
model = BioMLP(shp=shp)
# train_type = 1; no L1
# train_type = 2; L1
# train_type = 3: L1 + Local
# train_type = 4: L1 + Swap
# train_type = 5: L1 + Local + Swap
train_type = 5
optimizer = torch.optim.AdamW(model.parameters(), lr=0.002, weight_decay=0.0)
log = 200
lamb = 0 if train_type==1 else 0.001
swap_log = 200 if train_type >= 4 else float('inf')
weight_factor = 1. if train_type == 3 or train_type == 5 else 0.
plot_log = 1000
steps = 20000
for step in range(steps):
if step == int(steps/4):
lamb *= 10
if step == int(3*steps/4):
lamb *= 0.1
optimizer.zero_grad()
pred = model(inputs)
loss = torch.mean((pred-labels)**2)
pred_test = model(inputs_test)
loss_test = torch.mean((pred_test-labels_test)**2)
# do not penalize bias at first (this makes the weight graph look better)
if step < int(3*steps/4):
reg = model.get_cc(bias_penalize=False, weight_factor=weight_factor)
else:
reg = model.get_cc(bias_penalize=True, weight_factor=weight_factor)
#reg = model.get_cc(bias_penalize=True)
total_loss = loss + lamb*reg
total_loss.backward()
optimizer.step()
if step % log == 0:
print("step = %d | total loss: %.2e | train loss: %.2e | test loss %.2e | reg: %.2e "%(step, total_loss.detach().numpy(), loss.detach().numpy(), loss_test.detach().numpy(), reg.detach().numpy()))
if (step+1) % swap_log == 0:
model.relocate()
if step % plot_log == 0:
model.plot()
formulas = [r" $(x_1+x_3)^3$", r"$x_2^2+{\rm sin}(\pi x_4)$"]
fontsize = 12
for j in range(shp[0]):
plt.text(1/(2*shp[1])+5*j/shp[1]+0.04, -0.04, "$x_{}$".format(model.in_perm[j].long()+1), fontsize=fontsize)
for j in range(shp[-1]):
plt.text(1/(2*shp[0])+2*j/shp[0]-0.1, 0.1*(len(shp)-1)+0.02, formulas[model.out_perm[j].long()], fontsize=fontsize)
#plt.title("(a) independence", y=1.1,fontsize=fontsize)
#plt.savefig("./video_figs/sf_id/{0:05d}.png".format(step))
plt.show()
|
58a8db25370f37c47f76308101cfe354
|
{
"intermediate": 0.33751195669174194,
"beginner": 0.4634479284286499,
"expert": 0.19904012978076935
}
|
7,681
|
box-shadow using color from typescript in angular html
|
50a8fe424812ccd574805d0e65aaba1d
|
{
"intermediate": 0.44968634843826294,
"beginner": 0.32698333263397217,
"expert": 0.2233303040266037
}
|
7,682
|
set box-shadow with color returned from type script when radio button is selected in html angular
|
cb9c164cea5c7423779febfe06387347
|
{
"intermediate": 0.45144522190093994,
"beginner": 0.25842341780662537,
"expert": 0.29013127088546753
}
|
7,683
|
make a Python code to generate a random number between 0 and 10
|
cc9000af67a49f6b79ef13dea32a70a5
|
{
"intermediate": 0.38246390223503113,
"beginner": 0.21735648810863495,
"expert": 0.4001796543598175
}
|
7,684
|
from pydantic import BaseSettings, PostgresDsn, Field
class Settings(BaseSettings):
db_url: PostgresDsn
db_port: int
db_user: str
db_name: str
db_pass: str
db_host: str
port: int
host: str
class Config:
env_file = '.env'
settings = Settings()
# app configuration
HOST=127.0.0.1
PORT=8000
# db configuration
DB_HOST=localhost
DB_URL=postgresql+asyncpg://postgres:as@localhost:5432/logging
DB_PORT=5432
DB_NAME=logging
DB_USER=postgres
DB_PASS=as
|
b8a18976e903a2303b17ef3d29138945
|
{
"intermediate": 0.5193352103233337,
"beginner": 0.3274397552013397,
"expert": 0.15322504937648773
}
|
7,685
|
the following code import { createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
const baseUrl = 'http://localhost:5000/api/v1';
//to test logic from the frontend
const masculineEndings = ['age', 'aire', 'isme', 'ment', 'oir', 'sme', 'é'];
const feminineEndings = [
'ade',
'ance',
'ence',
'ette',
'ie',
'ine',
'ion',
'ique',
'isse',
'ité',
'lle',
'ure',
];
const initialState = {
word: null,
currentWordIndex: 0,
isCorrect: null,
score: 0,
correctArticle: null,
correctEnding: null,
translation: null,
};
export const wordsSlice = createSlice({
name: 'words',
initialState,
reducers: {
setWord: (state, action) => {
console.log('Action', action.payload);
state.word = action.payload;
state.isCorrect = null;
state.correctArticle = null;
state.correctEnding = null;
state.translation = null;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
setCorrectArticle: (state, action) => {
state.correctArticle = action.payload.article;
state.correctEnding = action.payload.ending;
},
setTranslation: (state, action) => {
state.translation = action.payload.translation_en;
},
},
});
const config = {
headers: {
Authorization: `Bearer ${
JSON.parse(localStorage.getItem('userInfo')).accessToken
}`,
},
};
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get(`${baseUrl}/words/random`, config);
console.log('Inside fetch', response.data);
dispatch(setWord(response.data));
} catch (error) {
console.error(error);
}
};
export const selectCurrentWord = (state) => state.word;
export const selectIsCorrect = (state) => state.isCorrect;
export const selectScore = (state) => state.score;
export const selectTranslation = (state) => state.translation;
export const submitAnswer = (selected) => (dispatch, getState) => {
const { word, gender } = selectCurrentWord(getState());
const isCorrect = selected === (gender === 'masculine' ? 'LE' : 'LA');
if (isCorrect) {
dispatch(setCorrect());
} else {
dispatch(setWrong());
let correctArticle = gender === 'masculine' ? 'LE' : 'LA';
let correctEnding = '';
for (let ending of gender === 'masculine'
? masculineEndings
: feminineEndings) {
if (word.endsWith(ending)) {
correctEnding = ending;
break;
}
}
if (!correctEnding) {
correctEnding = word;
}
dispatch(
setCorrectArticle({ article: correctArticle, ending: correctEnding })
);
}
dispatch(fetchTranslation(word));
dispatch(nextWord());
};
export const fetchTranslation = (word) => async (dispatch) => {
try {
const response = await axios.get(
`${baseUrl}/words/example?word=${word}`,
config
);
dispatch(setTranslation(response.data.example.translation_en));
} catch (error) {
console.error(error);
}
};
// actions
export const {
setWord,
setCorrect,
setWrong,
setCorrectArticle,
setTranslation,
} = wordsSlice.actions;
// async thunks
export const nextWord = () => (dispatch) => {
dispatch(fetchWord());
};
export default wordsSlice.reducer;
throws caught TypeError: Cannot destructure property 'word' of 'selectCurrentWord(...)' as it is undefined.
at wordsSlice.js?t=1684779511157:86:11
at index.js:16:18
at Object.dispatch (immutableStateInvariantMiddleware.ts:264:32)
at dispatch (<anonymous>:1:55424)
at handleAnswer (GamePage.jsx:30:5)
at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
at invokeGuardedCallback (react-dom.development.js:4277:31)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:25)
at executeDispatch (react-dom.development.js:9041:3)
(
|
9a9638abfe5e50f8babffda72d5afa77
|
{
"intermediate": 0.3131673336029053,
"beginner": 0.5295854210853577,
"expert": 0.15724727511405945
}
|
7,686
|
how to set sqlalchemy.url in alembic.ini if I have from pydantic import BaseSettings, PostgresDsn, Field
class Settings(BaseSettings):
db_url: PostgresDsn
db_port: int
db_user: str
db_name: str
db_pass: str
db_host: str
port: int
host: str
class Config:
env_file = '.env'
settings = Settings() is that correct sqlalchemy.url = f"postgresql+asyncpg://{settings.database_user}:{settings.database_password}@{settings.database_host}:{settings.database_port}/{settings.database_name}"?async_fallback=True
|
58ffc7844dd8bef49f3a03a4e656b5ea
|
{
"intermediate": 0.6211718320846558,
"beginner": 0.2282530665397644,
"expert": 0.15057511627674103
}
|
7,687
|
Write simple vst plug-in
|
2901b4b4fa21fa067c7596bcd06d3518
|
{
"intermediate": 0.31920552253723145,
"beginner": 0.36158668994903564,
"expert": 0.3192078173160553
}
|
7,688
|
set box-shadow with color from typescript in [style]
|
cc5931e42787b387dea584ef4168b8f4
|
{
"intermediate": 0.3360294699668884,
"beginner": 0.3091030418872833,
"expert": 0.35486751794815063
}
|
7,689
|
set the box-shadow with color from typescript in angular html template in [style]
|
bd5942db3e7f03d3ea6081ea4e35425a
|
{
"intermediate": 0.4475940763950348,
"beginner": 0.27695366740226746,
"expert": 0.27545231580734253
}
|
7,690
|
Based on the follwoing instruction Test Technical Task: French Gender Learning Game
Objective
Create a game that helps users learn the gender of French words. The game will show a French word with examples of usage and ask the user to select the correct article ("UN" or "UNE", "LE" or "LA" randomly). The user's selection will be checked for correctness and the end of the word will be highlighted in red or green to indicate correctness, if the word does not match any rule from Appendix A highlight the whole word. The game will also allow users to click on a word to view its translation and examples of usage.
!!! IT'S A TEST TASK, and Never will go to production. If something is not clear, just create how you see the solution.
Technologies
Frontend: Bootstrap 5, Vue.js, Nuxt 3
Backend: NestJS (or Node.js if not familiar with nestjs)
Database: PostgreSQL (or any other SQL database)
Containerization: Docker (docker-compose)
!!! Feel free to use boilerplates, tutorials, ChatGPT. The goal of the task is to show how you understand technologies and can use them.
Features
User authentication: Users will be able to create accounts and log in.
Word database: A database of French words and their genders will be created and populated using PostgreSQL. (list of words in Appendix A)
Game interface: The game will have a simple and intuitive interface, with a French word displayed and a prompt to select the correct article. Users can also click on a word to view its translation and examples of usage.
Feedback mechanism: After the user makes their selection, the game will provide immediate feedback by highlighting the end of the word in red or green to indicate correctness.
Progress tracking: User progress will be tracked and saved in the database. Authenticated Users will be able to see their progress in a list of unknown words, well-known words, and words that need to be learned.
Mobile-responsive design: The game will be mobile-responsive and work well on different screen sizes.
Requirements
The game must be built using NestJS (or NodeJS/Express) for the backend and Vue.js / Nuxt and Bootstrap 5 for the frontend.
The game must use PostgreSQL as the database.
The game must have a database of French words and their genders.
The game must have a simple and intuitive interface.
The game must provide immediate feedback to the user after making a selection.
The game must be mobile-responsive.
The game must allow users to click on a word to view its translation and examples of usage.
The game must be containerized using Docker.
The code should be Linted (es-lint/ts-lint).
Not required but will be plus to have transitions, animation. Have some unit tests.
Deliverables
A GitHub repository with the source code of the project.
A README file with instructions on how to run the game locally and how to deploy it using Docker. For DEV and PROD (only as example) purposes.
Conclusion
This technical task outlines the requirements and features for a French gender learning game. By following this task, the developers can implement a complete project using NestJS or Node.js/Express.js, Vue.js (Nuxt 3), Bootstrap 5, and PostgreSQL(or any other SQL). The game will be containerized using Docker for easy deployment. The total development time for this project is estimated to be 1 week.
Appendix A
Here is an example JSON object that contains the gender endings for French nouns:
{
"masculineEndings": [
"age",
"aire",
"isme",
"ment",
"oir",
"sme",
"é"
],
"feminineEndings": [
"ade",
"ance",
"ence",
"ette",
"ie",
"ine",
"ion",
"ique",
"isse",
"ité",
"lle",
"ure"
]
}
asuming the game is built on react and redux with the backend already setup correct the following frontend GamePage component /* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
fetchWord,
selectCurrentWord,
selectIsCorrect,
selectScore,
selectTranslation,
submitAnswer,
fetchTranslation,
} from '../slices/wordsSlice';
import '../index.css';
function GamePage() {
const dispatch = useDispatch();
const currentWord = useSelector(selectCurrentWord);
const isCorrect = useSelector(selectIsCorrect);
const score = useSelector(selectScore);
const translation = useSelector(selectTranslation);
const [selected, setSelected] = useState('');
const [result, setResult] = useState('');
useEffect(() => {
dispatch(fetchWord());
}, []);
const handleAnswer = () => {
dispatch(submitAnswer(selected));
setSelected('');
};
const handleTranslation = () => {
console.log('Inside handleTranslation', currentWord.word);
dispatch(fetchTranslation(currentWord?.word));
};
return (
<div className='Game'>
<h1>French Word Game</h1>
<p>
<span onClick={handleTranslation}>{currentWord?.word}</span>
</p>
{translation && (
<div className='translation'>
<p>{translation}</p>
</div>
)}
<p>Select the correct article:</p>
<div className='buttons'>
<button
className={selected === 'LE' ? 'selected' : ''}
onClick={() => setSelected('LE')}
>
UN/LE
</button>
<button
className={selected === 'LA' ? 'selected' : ''}
onClick={() => setSelected('LA')}
>
UNE/LA
</button>
</div>
<button disabled={!selected} onClick={handleAnswer}>
Submit
</button>
{isCorrect !== null && (
<div className={result + (isCorrect ? 'correct' : 'wrong')}>
{isCorrect ? 'Correct!' : 'Wrong!'}
{!isCorrect && (
<span className='correct-answer'>
The correct article{' '}
<span className='correct-article'>
{currentWord?.gender === 'M' ? 'LE' : 'LA'}
</span>{' '}
{currentWord?.word.endsWith('e') ? 'is' : 'begins with'}{' '}
<span className='correct-ending'>
{currentWord?.word?.endsWith('e') ? '' : '…'}
{currentWord?.word?.slice(-2)}
</span>
.
</span>
)}
</div>
)}
<p>Score: {score}</p>
</div>
);
}
export default GamePage;
and wordSlice import { createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
const baseUrl = 'http://localhost:5000/api/v1';
//to test logic from the frontend
const masculineEndings = ['age', 'aire', 'isme', 'ment', 'oir', 'sme', 'é'];
const feminineEndings = [
'ade',
'ance',
'ence',
'ette',
'ie',
'ine',
'ion',
'ique',
'isse',
'ité',
'lle',
'ure',
];
const initialState = {
word: null,
currentWordIndex: 0,
isCorrect: null,
score: 0,
correctArticle: null,
correctEnding: null,
translation: null,
};
export const wordsSlice = createSlice({
name: 'words',
initialState,
reducers: {
setWord: (state, action) => {
console.log('Action', action.payload);
state.word = action.payload.word;
state.currentWordIndex = action.payload.index;
state.isCorrect = null;
state.correctArticle = null;
state.correctEnding = null;
state.translation = null;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
setCorrectArticle: (state, action) => {
state.correctArticle = action.payload.article;
state.correctEnding = action.payload.ending;
},
setTranslation: (state, action) => {
state.translation = action.payload.translation_en;
},
},
});
const config = {
headers: {
Authorization: `Bearer ${
JSON.parse(localStorage.getItem('userInfo')).accessToken
}`,
},
};
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get(`${baseUrl}/words/random`, config);
dispatch(setWord(response.data));
console.log('Inside fetch', response.data);
} catch (error) {
console.error(error);
}
};
export const selectCurrentWord = (state) => state.word;
export const selectIsCorrect = (state) => state.isCorrect;
export const selectScore = (state) => state.score;
export const selectTranslation = (state) => state.translation;
export const submitAnswer = (selected) => (dispatch, getState) => {
const { word, gender } = selectCurrentWord(getState());
const isCorrect = selected === (gender === 'masculine' ? 'LE' : 'LA');
if (isCorrect) {
dispatch(setCorrect());
} else {
dispatch(setWrong());
let correctArticle = gender === 'masculine' ? 'LE' : 'LA';
let correctEnding = '';
for (let ending of gender === 'masculine'
? masculineEndings
: feminineEndings) {
if (word.endsWith(ending)) {
correctEnding = ending;
break;
}
}
if (!correctEnding) {
correctEnding = word;
}
dispatch(
setCorrectArticle({ article: correctArticle, ending: correctEnding })
);
}
dispatch(fetchTranslation(word));
dispatch(nextWord());
};
export const fetchTranslation = (word) => async (dispatch) => {
try {
const response = await axios.get(
`${baseUrl}/words/example?word=${word}`,
config
);
dispatch(setTranslation(response.data.example.translation_en));
} catch (error) {
console.error(error);
}
};
// actions
export const {
setWord,
setCorrect,
setWrong,
setCorrectArticle,
setTranslation,
} = wordsSlice.actions;
// async thunks
export const nextWord = () => (dispatch) => {
dispatch(fetchWord());
};
export default wordsSlice.reducer;
|
e9ecf2c5459e7c1ddb89cc86016c1c9c
|
{
"intermediate": 0.4402872920036316,
"beginner": 0.4115786552429199,
"expert": 0.14813406765460968
}
|
7,691
|
i want to set box-shadow with color from typescript in html angular depend on certain condition
|
043cb78f2c4ea89baa653cf6eefd711b
|
{
"intermediate": 0.4416409730911255,
"beginner": 0.27536121010780334,
"expert": 0.28299781680107117
}
|
7,692
|
using of ngClass
|
d65bb0d5165f7da9a90a587595074d96
|
{
"intermediate": 0.2963193356990814,
"beginner": 0.43517622351646423,
"expert": 0.26850447058677673
}
|
7,693
|
Finish the following game code Here’s a possible solution for the French Gender Learning Game using React and Redux:
1. Project Setup
First, we need to set up the project’s directories, install dependencies, and create the necessary files. Here are the basic steps:
1. Create a new project directory and navigate to it using the terminal.
2. Run npm init to initialize the package.json file.
3. Install the required dependencies:
npm install react react-dom redux react-redux @reduxjs/toolkit axios bootstrap
4. Create the following directories inside the project’s root directory:
src/
api/
components/
slices/
5. In the src/ directory, create the following files:
index.js // entry point of the application
App.js // root component of the application
configureStore.js // setup redux store
2. Implementing the Backend API
We’ll use NestJS to create a simple API that provides the game’s functionality. Here’s how you can set it up:
1. Install NestJS globally using the following command:
npm i -g @nestjs/cli
2. Create a new NestJS project using the CLI:
nest new backend
3. Generate a new module and controller for the game:
nest generate module game
nest generate controller game
4. Open the generated game.controller.ts file and implement the following methods:
import { Controller, Get, Req } from ‘@nestjs/common’;
@Controller(‘game’)
export class GameController {
private masculines = [‘age’, ‘aire’, ‘isme’, ‘ment’, ‘oir’, ‘sme’, ‘é’];
private feminines = [
‘ade’,
‘ance’,
‘ence’,
‘ette’,
‘ie’,
‘ine’,
‘ion’,
‘ique’,
‘isse’,
‘ité’,
‘lle’,
‘ure’,
];
private words = [
{ id: 1, word: ‘chat’, gender: ‘m’ },
{ id: 2, word: ‘chaise’, gender: ‘f’ },
{ id: 3, word: ‘ordinateur’, gender: ‘m’ },
{ id: 4, word: ‘feuille’, gender: ‘f’ },
{ id: 5, word: ‘stylo’, gender: ‘m’ },
];
@Get(‘word’)
getWord(@Req() req): string {
const id = Math.floor(Math.random() * this.words.length) + 1;
return JSON.stringify(this.words.find((word) => word.id === id));
}
@Get(‘translation’)
getTranslation(@Req() req): string {
return JSON.stringify({ en: ‘translation goes here’ });
}
}
This code sets up a simple API with two endpoints: /game/word and /game/translation. The getWord() method returns a random word with its gender, and the getTranslation() method returns a dummy translation.
3. Setting Up the Redux Store
We’ll use Redux to manage the game’s state. Here’s how you can set up the store:
1. Open the configureStore.js file and implement the following code:
import { configureStore } from ‘@reduxjs/toolkit’;
import wordsReducer from ‘…/slices/wordsSlice’;
export default configureStore({
reducer: {
words: wordsReducer,
},
});
2. In the slices/ directory, create a new file named wordsSlice.js and implement the following:
import { createSlice } from ‘@reduxjs/toolkit’;
import axios from ‘axios’;
const initialState = {
word: null,
isCorrect: null,
score: 0,
};
export const wordsSlice = createSlice({
name: ‘words’,
initialState,
reducers: {
setWord: (state, action) => {
state.word = action.payload;
state.isCorrect = null;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
},
});
export const { setWord, setCorrect, setWrong } = wordsSlice.actions;
export const selectWord = (state) => state.words.word;
export const selectIsCorrect = (state) => state.words.isCorrect;
export const selectScore = (state) => state.words.score;
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get(‘/api/game/word’);
dispatch(setWord(response.data));
} catch (error) {
console.error(error);
}
};
export const submitAnswer = (selected) => (dispatch, getState) => {
const word = selectWord(getState());
const isCorrect = selected === (word.gender === ‘m’ ? ‘LE’ : ‘LA’);
if (isCorrect) {
dispatch(setCorrect());
} else {
dispatch(setWrong());
}
};
export default wordsSlice.reducer;
This code sets up a basic Redux store with a words slice, which stores the currently displayed word, whether the user’s selection is correct or not, and the user’s score. The fetchWord() and submitAnswer() functions perform API requests to get a random word and submit the user’s selection.
4. Implementing the UI
We’ll use Bootstrap to style the game’s UI components. Here’s how you can create the component files:
1. In the api/ directory, create a new file named api.js and implement the following:
import axios from ‘axios’;
axios.defaults.baseURL = ‘http://localhost:3000’;
export default axios;
This sets up the default API URL for axios.
2. In the components/ directory, create a new file named GamePage.js and implement the following:
import { useEffect, useState } from ‘react’;
import { useDispatch, useSelector } from ‘react-redux’;
import api from ‘…/api/api’;
import { fetchWord, selectIsCorrect, selectScore, submitAnswer } from ‘…/slices/wordsSlice’;
function GamePage() {
const dispatch = useDispatch();
const word = useSelector(state => state.words.word);
const isCorrect = useSelector(selectIsCorrect);
const score = useSelector(selectScore);
const [selected, setSelected] = useState(‘’);
useEffect(() => {
dispatch(fetchWord());
}, [dispatch]);
const handleAnswer = () => {
dispatch(submitAnswer(selected));
setSelected(‘’);
};
return (
<div className=“container mt-5”>
<div className=“row justify-content-center”>
<div className=“col-md-6”>
<h1>French Gender Learning Game</h1>
<h2>Score: {score}</h2>
<div className=“card”>
<div className=“card-body”>
<h3>{word && word.word}</h3>
<div className=“form-check”>
<input
type=“radio”
id=“un-le”
name=“article-group”
value=“UN/LE”
className=“form-check-input”
checked={selected === ‘UN/LE’}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor=“un-le” className=“form-check-label”>
UN/LE
</label>
</div>
<div className=“form-check”>
<input
type=“radio”
id=“une-la”
name=“article-group”
value=“UNE/LA”
className=“form-check-input”
checked={selected === ‘UNE/LA’}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor=“une-la” className=“form-check-label”>
UNE/LA
</label>
</div>
<button
className=“btn btn-primary”
disabled={!selected}
onClick={handleAnswer}
>
Submit
</button>
<p className=“mt-2”>
|
42a2356f0e291e716bc1f70f83fc0adb
|
{
"intermediate": 0.3797833025455475,
"beginner": 0.36269575357437134,
"expert": 0.25752097368240356
}
|
7,694
|
Is it possible to use just the git command, no API access at all, and find PRs to a specific branch?
|
050de8d68b00c4040ea322f0de2dd7f7
|
{
"intermediate": 0.3805707097053528,
"beginner": 0.28430691361427307,
"expert": 0.3351224362850189
}
|
7,695
|
I want you to write me a VBA code for a PowerPoint presentation about the DNA. You are to fill in all the text with your own knowlage, no placeholders. I need 5 slides.
|
e02d6117efcc4097f4f0bbaf67f79d9d
|
{
"intermediate": 0.28523480892181396,
"beginner": 0.49423840641975403,
"expert": 0.22052675485610962
}
|
7,696
|
hi
|
aa45cea113fb865e89b5aa787e502b93
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
7,697
|
Một công ty đa cấp nọ có ba loại nhân viên: Nhân viên văn phòng và Nhân viên sản xuất và Sếp. Mỗi người cần quản lý các thông tin sau: Họ tên (+ thông tin phụ để tính lương hàng tháng). Công ty cần tính lương như sau:
OOP C++:
Đối với nhân viên sản xuất (Loại 1, thông tin phụ là lương căn bản và số sản phẩm): Lương = lương căn bản + số sản phẩm * 5.
Đối với nhân viên văn phòng (Loại 2, thông tin phụ là số ngày làm việc): Lương = số ngày làm việc * 100.
Đối với sếp (Loại 3, không có thông tin phụ): Lương = 100 + số sản phẩm của tất cả nhân viên sản xuất * 2 + số ngày làm việc của tất cả nhân viên văn phòng * 40.
Nhập vào số lượng n, sau đó cho nhập loại nhân viên, tên và thông tin phụ từng người. Ví dụ nhập:
1 NguyenVanA 300000 10
Sau khi nhập xong xuất ra kết quả dưới dịnh dạng:
Tên người 1: lương người 1
Tên người 2: lương người 2
...
Input Format
int String float int (for worker)
int String int (for officer)
int String (for manager)
Constraints
No constraint
Output Format
[String: float]
Sample Input 0
4
1 nvquenA 2000 10
1 nvquenB 3000 20
2 nvquenC 40
3 sep
Sample Output 0
nvquenA: 2050
nvquenB: 3100
nvquenC: 4000
sep: 1760
|
a160b7cc251bbe78b4b44fedbe3802d4
|
{
"intermediate": 0.3183363080024719,
"beginner": 0.3946691155433655,
"expert": 0.286994606256485
}
|
7,698
|
Given a git branch name, can I use the git command alone (no API access) to find out if there is a PR associated with that branch?
|
cd978ec4dc35b1668b01076375253e4e
|
{
"intermediate": 0.45804184675216675,
"beginner": 0.23441118001937866,
"expert": 0.307547003030777
}
|
7,699
|
I have a JSON message. The JSON message is a list of hashes. I want to select one of the hashes. The hash I want to select is the one where the value of its head.ref key is "BLAH"
|
f913a79bd4dfb4877b6abe99e7e627e6
|
{
"intermediate": 0.3427276313304901,
"beginner": 0.21908222138881683,
"expert": 0.4381901025772095
}
|
7,700
|
I have a JSON message. The JSON message is a list of hashes. I want to select one of the hashes. The hash I want to select is the one where the value of its head.ref key is “BLAH”. I want to do this using jq.
|
a49030db69de346a2291104caa3df88a
|
{
"intermediate": 0.3445489704608917,
"beginner": 0.22051608562469482,
"expert": 0.43493494391441345
}
|
7,701
|
Hi
|
cab0450ca2b9bd2a9002dbd1ceeecba3
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
7,702
|
Finish the below code Here’s an updated version of the GameController that uses tables of masculine and feminine nouns fetched from PostgreSQL using TypeORM and a words database with the specified structure:
import { Controller, Get, Req } from ‘@nestjs/common’;
import { InjectRepository } from ‘@nestjs/typeorm’;
import { Repository } from ‘typeorm’;
import { MasculineNoun } from ‘./entities/masculine-noun.entity’;
import { FeminineNoun } from ‘./entities/feminine-noun.entity’;
import { Word } from ‘./entities/word.entity’;
@Controller(‘game’)
export class GameController {
constructor(
@InjectRepository(MasculineNoun)
private masculineNounRepository: Repository<MasculineNoun>,
@InjectRepository(FeminineNoun)
private feminineNounRepository: Repository<FeminineNoun>,
@InjectRepository(Word)
private wordRepository: Repository<Word>,
) {}
@Get(‘word’)
async getWord(@Req() req) {
const randomWord = await this.wordRepository
.createQueryBuilder(‘word’)
.orderBy(‘RANDOM()’)
.getOne();
const wordWithTranslation = { …randomWord };
delete wordWithTranslation.translation_fr;
return JSON.stringify(wordWithTranslation);
}
@Get(‘translation’)
async getTranslation(@Req() req) {
const randomWord = await this.wordRepository
.createQueryBuilder(‘word’)
.orderBy(‘RANDOM()’)
.getOne();
return JSON.stringify({ en: randomWord.translation_en });
}
@Get(‘masculine-nouns’)
async getMasculineNouns(@Req() req) {
const nouns = await this.masculineNounRepository.find();
return JSON.stringify(nouns);
}
@Get(‘feminine-nouns’)
async getFeminineNouns(@Req() req) {
const nouns = await this.feminineNounRepository.find();
return JSON.stringify(nouns);
}
}
The updated GameController uses @InjectRepository to inject the repositories for the MasculineNoun, FeminineNoun, and Word entities. It then uses createQueryBuilder to get a random word from the Word table, strip the translation_fr property, and return it. The getTranslation method does the same but returns only the English translation. Additionally, it includes methods to fetch all the irregular masculine and feminine nouns from their respective tables.
Now update the react and redux based on the above GameController corrections
Here’s an updated version of the React and Redux code based on the corrections made to the GameController:
1. The configureStore.js file should import the new wordSlice reducer:
import { configureStore } from ‘@reduxjs/toolkit’;
import wordsReducer from ‘…/slices/wordsSlice’;
export default configureStore({
reducer: {
words: wordsReducer,
},
});
2. The wordsSlice.js file should be updated to use the new /game/masculine-nouns and /game/feminine-nouns API endpoints to fetch the lists of nouns and update the initial state of the slice accordingly. It should also use the /game/word and /game/translation endpoints to fetch a random word and its translation:
import { createSlice } from ‘@reduxjs/toolkit’;
import axios from ‘…/…/api/api’;
const initialState = {
word: null,
nounList: {
masculine: [],
feminine: [],
},
isCorrect: null,
score: 0,
};
export const wordsSlice = createSlice({
name: ‘words’,
initialState,
reducers: {
setWord: (state, action) => {
state.word = action.payload;
state.isCorrect = null;
},
setNouns: (state, action) => {
state.nounList = action.payload;
},
setCorrect: (state) => {
state.isCorrect = true;
state.score++;
},
setWrong: (state) => {
state.isCorrect = false;
},
},
});
export const { setWord, setNouns, setCorrect, setWrong } = wordsSlice.actions;
export const selectWord = (state) => state.words.word;
export const selectNouns = (state) => state.words.nounList;
export const selectIsCorrect = (state) => state.words.isCorrect;
export const selectScore = (state) => state.words.score;
export const fetchWord = () => async (dispatch) => {
try {
const response = await axios.get(‘/game/word’);
dispatch(setWord(response.data));
} catch (error) {
console.error(error);
}
};
export const fetchNouns = () => async (dispatch) => {
try {
const [masculineResponse, feminineResponse] = await Promise.all([
axios.get(‘/game/masculine-nouns’),
axios.get(‘/game/feminine-nouns’),
]);
dispatch(
setNouns({
masculine: masculineResponse.data,
feminine: feminineResponse.data,
})
);
} catch (error) {
console.error(error);
}
};
export const fetchTranslation = () => async (dispatch) => {
try {
const response = await axios.get(‘/game/translation’);
return response.data.en;
} catch (error) {
console.error(error);
}
};
export const submitAnswer = (selected) => (dispatch, getState) => {
const word = selectWord(getState());
const isCorrect = selected === (word.gender === ‘m’ ? ‘UN/LE’ : ‘UNE/LA’);
if (isCorrect) {
dispatch(setCorrect());
} else {
dispatch(setWrong());
}
};
export default wordsSlice.reducer;
3. The GamePage.js file should be updated to fetch the nouns on load by dispatching the fetchNouns action creator. It should also use the fetchTranslation function to get the translation of the word and display it to the user. Finally, it should update the radio button labels to use the actual articles instead of placeholders:
import { useEffect, useState } from ‘react’;
import { useDispatch, useSelector } from ‘react-redux’;
import api from ‘…/…/api/api’;
import { fetchWord, selectIsCorrect, selectNouns, selectScore, submitAnswer } from ‘…/…/slices/wordsSlice’;
function GamePage() {
const dispatch = useDispatch();
const word = useSelector(selectWord);
const nouns = useSelector(selectNouns);
const isCorrect = useSelector(selectIsCorrect);
const score = useSelector(selectScore);
const [selected, setSelected] = useState(‘’);
const [translation, setTranslation] = useState(‘’);
useEffect(() => {
dispatch(fetchWord());
dispatch(fetchNouns());
}, [dispatch]);
useEffect(() => {
const fetchTranslationPromise = async () => {
const response = await dispatch(fetchTranslation());
setTranslation(response);
};
if (word) {
fetchTranslationPromise();
}
}, [dispatch, word]);
const handleAnswer = () => {
dispatch(submitAnswer(selected));
setSelected(‘’);
};
return (
<div className=“container mt-5”>
<div className=“row justify-content-center”>
<div className=“col-md-6”>
<h1>French Gender Learning Game</h1>
<h2>Score: {score}</h2>
<div className=“card”>
<div className=“card-body”>
<h3>
{word && word.word}
{translation.length > 0 && (
<small className=“text-muted ml-2”>
({translation})
</small>
)}
</h3>
<div className=“form-check”>
<input
type=“radio”
id=“un-le”
name=“article-group”
value=“UN/LE”
className=“form-check-input”
checked={selected === ‘UN/LE’}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor=“un-le” className=“form-check-label”>
{nouns.masculine.length > 0 &&
nouns.masculine[0].article}
</label>
</div>
<div className=“form-check”>
<input
type=“radio”
id=“une-la”
name=“article-group”
value=“UNE/LA”
className=“form-check-input”
checked={selected === ‘UNE/LA’}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor=“une-la” className=“form-check-label”>
{nouns.feminine.length > 0 &&
nouns.feminine[0].article}
</label>
</div>
<button
className=“btn btn-primary”
disabled={!selected}
onClick={handleAnswer}
>
Submit
</button>
<p className=“mt-2”>
{isCorrect !== null &&
(isCorrect ? ‘Correct!’ : ‘Wrong!’)}
</p>
</div>
</div>
</div>
</div>
</div>
);
}
export default GamePage;
These changes should properly make use of
|
f87eac86dee175825b5e4bb713ecd2a3
|
{
"intermediate": 0.3747084140777588,
"beginner": 0.3973085880279541,
"expert": 0.22798298299312592
}
|
7,703
|
Based on the variables from the European Social Survey round 10 (ESS round 10 - 2020. Democracy, Digital social contacts) described on this website:
https://ess-search.nsd.no/en/study/172ac431-2a06-41df-9dab-c1fd8f3877e7
What variables except: eduyrs wrklong wrkextra trdawrk jbprtfp teamfeel colhlp wkdcorga hincfel agea gndr
can best describe the target: stfmjob (that expressess the satisfaction of a person with his job)?
|
5bfb6e3e574bb91bbdded7b809b0ef93
|
{
"intermediate": 0.2165886014699936,
"beginner": 0.6041609644889832,
"expert": 0.17925037443637848
}
|
7,704
|
How can I json.stringify the follwowing return return {
translation_en: targetWord.translation_en,
example: targetWord.example,
};
|
fe8a868397bc52a12832732c9ca09463
|
{
"intermediate": 0.6133874654769897,
"beginner": 0.1629607230424881,
"expert": 0.22365188598632812
}
|
7,705
|
Based on the below userApiSlice * eslint-disable no-unused-vars */
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from '../api/api';
const USERS_URL = '/auth/email';
export const login = createAsyncThunk('user/login', async (data) => {
const response = await axios.post(`${USERS_URL}/login`, data);
return response.data;
});
export const register = createAsyncThunk('user/register', async (data) => {
const response = await axios.post(`${USERS_URL}/register`, data);
return response.data;
});
export const updateUser = createAsyncThunk('user/update', async (data) => {
const response = await axios.put('auth/me', data);
return response.data;
});
const initialState = {
userInfo: localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null,
status: 'idle',
error: null,
};
const userSlice = createSlice({
name: 'user',
initialState,
extraReducers: (builder) => {
builder
.addCase(login.pending, (state) => {
state.status = 'loading';
})
.addCase(login.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(login.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(register.pending, (state) => {
state.status = 'loading';
})
.addCase(register.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(register.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(updateUser.pending, (state) => {
state.status = 'loading';
})
.addCase(updateUser.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(updateUser.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addDefaultCase((state) => {});
},
});
export default userSlice.reducer; how should i update the below LoginScreen component import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Form, Button, Row, Col } from 'react-bootstrap';
import FormContainer from '../components/FormContainer';
import { useDispatch, useSelector } from 'react-redux';
import { useLoginMutation } from '../slices/usersApiSlice';
import { setCredentials } from '../slices/authSlice';
import { toast } from 'react-toastify';
import Loader from '../components/Loader';
const LoginScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const dispatch = useDispatch();
const navigate = useNavigate();
const [login, { isLoading }] = useLoginMutation();
const { userInfo } = useSelector((state) => state.auth);
useEffect(() => {
if (userInfo) {
navigate('/game');
}
}, [navigate, userInfo]);
const submitHandler = async (e) => {
e.preventDefault();
try {
const res = await login({ email, password }).unwrap();
dispatch(setCredentials({ ...res }));
navigate('/game');
} catch (err) {
toast.error(err?.data?.message || err.error);
}
};
return (
<FormContainer>
<h1>Sign In</h1>
<Form onSubmit={submitHandler}>
<Form.Group className='my-2' controlId='email'>
<Form.Label>Email Address</Form.Label>
<Form.Control
type='email'
placeholder='Enter email'
value={email}
onChange={(e) => setEmail(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group className='my-2' controlId='password'>
<Form.Label>Password</Form.Label>
<Form.Control
type='password'
placeholder='Enter password'
value={password}
onChange={(e) => setPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Button
disabled={isLoading}
type='submit'
variant='primary'
className='mt-3'
>
Sign In
</Button>
</Form>
{isLoading && <Loader />}
<Row className='py-3'>
<Col>
New Player? <Link to='/register'>Register</Link>
</Col>
</Row>
</FormContainer>
);
};
export default LoginScreen;
|
60cb6da87e9ae0dd42894160b574e7bc
|
{
"intermediate": 0.3527665436267853,
"beginner": 0.40265321731567383,
"expert": 0.2445802390575409
}
|
7,706
|
Web scrape turbo.az with python and beatifulsoup
|
fc2e51d0cb8f520eb5f4e21606b2bce8
|
{
"intermediate": 0.3624627888202667,
"beginner": 0.2983613908290863,
"expert": 0.339175820350647
}
|
7,707
|
Based on the below userApiSlice * eslint-disable no-unused-vars */
import { createAsyncThunk, createSlice } from ‘@reduxjs/toolkit’;
import axios from ‘…/api/api’;
const USERS_URL = ‘/auth/email’;
export const login = createAsyncThunk(‘user/login’, async (data) => {
const response = await axios.post(${USERS_URL}/login, data);
return response.data;
});
export const register = createAsyncThunk(‘user/register’, async (data) => {
const response = await axios.post(${USERS_URL}/register, data);
return response.data;
});
export const updateUser = createAsyncThunk(‘user/update’, async (data) => {
const response = await axios.put(‘auth/me’, data);
return response.data;
});
const initialState = {
userInfo: localStorage.getItem(‘userInfo’)
? JSON.parse(localStorage.getItem(‘userInfo’))
: null,
status: ‘idle’,
error: null,
};
const userSlice = createSlice({
name: ‘user’,
initialState,
extraReducers: (builder) => {
builder
.addCase(login.pending, (state) => {
state.status = ‘loading’;
})
.addCase(login.fulfilled, (state, action) => {
state.status = ‘succeeded’;
state.userInfo = action.payload;
localStorage.setItem(‘userInfo’, JSON.stringify(action.payload));
})
.addCase(login.rejected, (state, action) => {
state.status = ‘failed’;
state.error = action.error.message;
})
.addCase(register.pending, (state) => {
state.status = ‘loading’;
})
.addCase(register.fulfilled, (state, action) => {
state.status = ‘succeeded’;
state.userInfo = action.payload;
localStorage.setItem(‘userInfo’, JSON.stringify(action.payload));
})
.addCase(register.rejected, (state, action) => {
state.status = ‘failed’;
state.error = action.error.message;
})
.addCase(updateUser.pending, (state) => {
state.status = ‘loading’;
})
.addCase(updateUser.fulfilled, (state, action) => {
state.status = ‘succeeded’;
state.userInfo = action.payload;
localStorage.setItem(‘userInfo’, JSON.stringify(action.payload));
})
.addCase(updateUser.rejected, (state, action) => {
state.status = ‘failed’;
state.error = action.error.message;
})
.addDefaultCase((state) => {});
},
});
export default userSlice.reducer; how should i update the following ProfileScreen Component /* eslint-disable no-unused-vars */
import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Form, Button } from 'react-bootstrap';
import { useDispatch, useSelector } from 'react-redux';
import FormContainer from '../components/FormContainer';
import { toast } from 'react-toastify';
import Loader from '../components/Loader';
import { useUpdateUserMutation } from '../slices/usersApiSlice';
import { setCredentials } from '../slices/authSlice';
const ProfileScreen = () => {
const [email, setEmail] = useState('');
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const dispatch = useDispatch();
const { userInfo } = useSelector((state) => state.auth);
const [updateProfile, { isLoading }] = useUpdateUserMutation();
useEffect(() => {
setFirstName(userInfo.firstName);
setLastName(userInfo.lastName);
setEmail(userInfo.email);
}, [userInfo.email, userInfo.firstName, userInfo.lastName]);
const submitHandler = async (e) => {
e.preventDefault();
if (password !== confirmPassword) {
toast.error('Passwords do not match');
} else {
try {
const res = await updateProfile({
_id: userInfo._id,
firstName,
lastName,
email,
password,
}).unwrap();
console.log(res);
dispatch(setCredentials(res));
toast.success('Profile updated successfully');
} catch (err) {
toast.error(err?.data?.message || err.error);
}
}
};
return (
<FormContainer>
<h1>Update Profile</h1>
<Form onSubmit={submitHandler}>
<Form.Group className='my-2' controlId='name'>
<Form.Label>First Name</Form.Label>
<Form.Control
type='name'
placeholder='Enter first name'
value={name}
onChange={(e) => setFirstName(e.target.value)}
></Form.Control>
<Form.Label>Last Name</Form.Label>
<Form.Control
type='name'
placeholder='Enter last name'
value={name}
onChange={(e) => setLastName(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group className='my-2' controlId='email'>
<Form.Label>Email Address</Form.Label>
<Form.Control
type='email'
placeholder='Enter email'
value={email}
onChange={(e) => setEmail(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group className='my-2' controlId='password'>
<Form.Label>Password</Form.Label>
<Form.Control
type='password'
placeholder='Enter password'
value={password}
onChange={(e) => setPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group className='my-2' controlId='confirmPassword'>
<Form.Label>Confirm Password</Form.Label>
<Form.Control
type='password'
placeholder='Confirm password'
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
></Form.Control>
</Form.Group>
<Button type='submit' variant='primary' className='mt-3'>
Update
</Button>
</Form>
</FormContainer>
);
};
export default ProfileScreen;
|
9309e3f46ed5657771bcf046382172b5
|
{
"intermediate": 0.34025317430496216,
"beginner": 0.3590146005153656,
"expert": 0.30073216557502747
}
|
7,708
|
code an ecommerce website on js
|
0dae168cdcf3bddb941ba543977d9b65
|
{
"intermediate": 0.26088055968284607,
"beginner": 0.518498957157135,
"expert": 0.2206205129623413
}
|
7,710
|
how do i fix the follwoin error TypeError: Cannot destructure property 'userInfo' of 'useSelector(...)' as it is undefined.
at Header (http://localhost:3000/src/components/Header.jsx?t=1684789976484:26:5)
at renderWithHooks (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:12171:26)
at mountIndeterminateComponent (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:14921:21)
at beginWork (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:15902:22)
at beginWork$1 (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:19749:22)
at performUnitOfWork (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:19194:20)
at workLoopSync (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:19133:13)
at renderRootSync (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:19112:15)
at recoverFromConcurrentError (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:18732:28)
at performConcurrentWorkOnRoot (http://localhost:3000/node_modules/.vite/deps/chunk-QJV3R4PZ.js?v=ed509961:18680:30)
based on the following components /* eslint-disable no-unused-vars */
import { Navbar, Nav, Container, NavDropdown, Badge } from 'react-bootstrap';
import { FaSignInAlt, FaSignOutAlt } from 'react-icons/fa';
import { LinkContainer } from 'react-router-bootstrap';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { logout } from '../slices/authSlice';
const Header = () => {
const { userInfo, status, error } = useSelector((state) => state.user);
const dispatch = useDispatch();
const navigate = useNavigate();
const logoutHandler = async () => {
try {
dispatch(logout());
navigate('/login');
} catch (err) {
console.error(err);
}
};
return (
<header>
<Navbar bg='dark' variant='dark' expand='lg' collapseOnSelect>
<Container>
<LinkContainer to='/'>
<Navbar.Brand>French Game</Navbar.Brand>
</LinkContainer>
<Navbar.Toggle aria-controls='basic-navbar-nav' />
<Navbar.Collapse id='basic-navbar-nav'>
<Nav className='ms-auto'>
{userInfo ? (
<>
<NavDropdown title={userInfo.name} id='username'>
<LinkContainer to='/profile'>
<NavDropdown.Item>Profile</NavDropdown.Item>
</LinkContainer>
<NavDropdown.Item onClick={logoutHandler}>
Logout
</NavDropdown.Item>
</NavDropdown>
</>
) : (
<>
<LinkContainer to='/login'>
<Nav.Link>
<FaSignInAlt /> Sign In
</Nav.Link>
</LinkContainer>
<LinkContainer to='/register'>
<Nav.Link>
<FaSignOutAlt /> Sign Up
</Nav.Link>
</LinkContainer>
</>
)}
</Nav>
</Navbar.Collapse>
</Container>
</Navbar>
</header>
);
};
export default Header;
/* eslint-disable no-unused-vars */
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from '../api/api';
const USERS_URL = '/auth/email';
export const login = createAsyncThunk('user/login', async (data) => {
const response = await axios.post(`${USERS_URL}/login`, data);
return response.data;
});
export const register = createAsyncThunk('user/register', async (data) => {
const response = await axios.post(`${USERS_URL}/register`, data);
return response.data;
});
export const updateUser = createAsyncThunk('user/update', async (data) => {
const response = await axios.put('auth/me', data);
return response.data;
});
const initialState = {
userInfo: localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null,
status: 'idle',
error: null,
};
const userSlice = createSlice({
name: 'user',
initialState,
extraReducers: (builder) => {
builder
.addCase(login.pending, (state) => {
state.status = 'loading';
})
.addCase(login.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(login.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(register.pending, (state) => {
state.status = 'loading';
})
.addCase(register.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(register.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(updateUser.pending, (state) => {
state.status = 'loading';
})
.addCase(updateUser.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(updateUser.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addDefaultCase((state) => {});
},
});
export default userSlice.reducer;
// import { apiSlice } from './apiSlice';
// const USERS_URL = '/auth/email';
// export const userApiSlice = apiSlice.injectEndpoints({
// endpoints: (builder) => ({
// login: builder.mutation({
// query: (data) => ({
// url: `${USERS_URL}/login`,
// method: 'POST',
// body: data,
// }),
// }),
// register: builder.mutation({
// query: (data) => ({
// url: `${USERS_URL}/register`,
// method: 'POST',
// body: data,
// }),
// }),
// updateUser: builder.mutation({
// query: (data) => ({
// url: 'auth/me',
// method: 'PUT',
// body: data,
// }),
// }),
// }),
// });
// export const { useLoginMutation, useRegisterMutation, useUpdateUserMutation } =
// userApiSlice;
|
f465a40a8eea7b592b22e277305c4fe2
|
{
"intermediate": 0.40700793266296387,
"beginner": 0.38901641964912415,
"expert": 0.2039756029844284
}
|
7,711
|
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 some of the relevant header and source file code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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 (device == VK_NULL_HANDLE || shutdownInProgress) {
// If the device is already VK_NULL_HANDLE, it means the cleanup has run before
return;
}
shutdownInProgress = true; // Indicate that the cleanup is in progress
std::cout << "Waiting for device idle…" << std::endl;
vkDeviceWaitIdle(device); // Wait for rendering to complete
std::cout << "Cleaning up framebuffers…" << std::endl;
CleanupFramebuffers();
std::cout << "Cleaning up renderpass…" << std::endl;
CleanupRenderPass();
std::cout << "Cleaning up syncobject…" << std::endl;
CleanupSyncObjects();
std::cout << "Cleaning up commandbuffers…" << std::endl;
CleanupCommandBuffers(); // Free command buffers before destroying the command pool
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface
DestroySurface(); // Move this line after CleanupDevice
CleanupInstance();
}
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];
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 = ¤tCommandBuffer;
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);
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.");
}
}
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);
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 ¤tCommandBuffer;
}
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;
}
I am running into errors while trying to render. It seems to be related to a renderer.GetCurrentCommandBuffer call. Please check the code and tell me if you find any errors with how commandbuffers are being managed that might result in an access violation error. It may be related to how the MVP buffer is handled in GameObject.
|
a936bb5415ebaf3d68837444fa4ea364
|
{
"intermediate": 0.36516544222831726,
"beginner": 0.26137372851371765,
"expert": 0.3734608292579651
}
|
7,712
|
modify my code so that once we're at the window Receipt, we can always see the previous order of when the button Ajouter was clicked and everytime Ajouter is clicked, the total that was there before was added to the new total, and also for the total + tax: import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private Map<String, Double> History;
private static String previousHistory;
private List<String> historyList;
private Map<String, Double> historyMap;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(new HashMap<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(Map<String, Double> previousHistory) {
History = previousHistory;
historyList = new ArrayList<>();
historyMap = new HashMap<>();
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " \ngarniture - Cout: " + historytotal;
historyList.add(historyEntry);
historyMap.put(historyEntry, historytotal);
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
panel.add(modifierCommande);
modifierCommande.setBounds(6, 316, 182, 29);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
// Create a new map to store previous history
Map<String, Double> previousHistory = new HashMap<>();
for (String historyEntry : historyList) {
String[] splitEntry = historyEntry.split("- Cout: ");
previousHistory.put(splitEntry[0], Double.valueOf(splitEntry[1]));
}
// Pass the previous history in the constructor of PizzaOrder
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0.0, new ArrayList<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
9b96dfca0890fc6e6d3daefadf3124bc
|
{
"intermediate": 0.3655138611793518,
"beginner": 0.42340996861457825,
"expert": 0.21107620000839233
}
|
7,713
|
modify and fix the errors in my code: import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private Map<String, Double> History;
private static String previousHistory;
private List<String> historyList;
private Map<String, Double> historyMap;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder() {
totales = 0.0;
historyList = new ArrayList<>();
historyMap = new HashMap<>();
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// Calculate total amount
double subTotal = selectedPizzaSize.getPrice() * numPizza +
selectedToppingSize.getPrice() * numTopping +
selectedBreuvage.getPrice() * numBreuvage;
totales += subTotal;
// Update history
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " +
numTopping + " " + selectedToppingSize + " garniture - Cout: " + subTotal;
historyList.add(historyEntry);
// Update the total label
String formattedTotal = String.format("%.2f", totales);
Total.setText("Total: " + formattedTotal + "$");
// Clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Order");
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(45, 65, 406, 200);
panel.add(scrollPane);
for (String historyEntry : historyList) {
model.addRow(new Object[]{historyEntry});
}
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
panel.add(modifierCommande);
modifierCommande.setBounds(6, 316, 182, 29);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
// Create a new map to store previous history
Map<String, Double> previousHistory = new HashMap<>();
for (String historyEntry : historyList) {
String[] splitEntry = historyEntry.split("- Cout: ");
previousHistory.put(splitEntry[0], Double.valueOf(splitEntry[1]));
}
// Pass the previous history in the constructor of PizzaOrder
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0.0, new ArrayList<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
56e26ab813bccde9cd669b875a6b18f3
|
{
"intermediate": 0.23216035962104797,
"beginner": 0.420316606760025,
"expert": 0.3475230038166046
}
|
7,714
|
/* eslint-disable no-unused-vars */
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import axios from '../api/api';
const USERS_URL = '/auth/email';
export const login = createAsyncThunk('user/login', async (data) => {
const response = await axios.post(`${USERS_URL}/login`, data);
return response.data;
});
export const register = createAsyncThunk('user/register', async (data) => {
const response = await axios.post(`${USERS_URL}/register`, data);
return response.data;
});
export const updateUser = createAsyncThunk('user/update', async (data) => {
const response = await axios.put('auth/me', data);
return response.data;
});
const initialState = {
userInfo: localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null,
status: 'idle',
error: null,
};
const userSlice = createSlice({
name: 'user',
initialState,
extraReducers: (builder) => {
builder
.addCase(login.pending, (state) => {
state.status = 'loading';
})
.addCase(login.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(login.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(register.pending, (state) => {
state.status = 'loading';
})
.addCase(register.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(register.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addCase(updateUser.pending, (state) => {
state.status = 'loading';
})
.addCase(updateUser.fulfilled, (state, action) => {
state.status = 'succeeded';
state.userInfo = action.payload;
localStorage.setItem('userInfo', JSON.stringify(action.payload));
})
.addCase(updateUser.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
})
.addDefaultCase((state) => {});
},
});
export default userSlice.reducer;
update the above slice so that it includes logout functonality
|
7347128dec73b38e120f78dc38dcf996
|
{
"intermediate": 0.3308587074279785,
"beginner": 0.464119553565979,
"expert": 0.2050217241048813
}
|
7,715
|
Update GamePages /* eslint-disable no-unused-vars */
import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import api from '../api/api';
import {
fetchNouns,
fetchTranslation,
fetchWord,
selectIsCorrect,
selectNouns,
selectScore,
selectWord,
submitAnswer,
} from '../slices/wordSlice';
function GamePages() {
const dispatch = useDispatch();
const word = useSelector(selectWord);
const nouns = useSelector(selectNouns);
const isCorrect = useSelector(selectIsCorrect);
const score = useSelector(selectScore);
const [selected, setSelected] = useState('');
const [translation, setTranslation] = useState('');
useEffect(() => {
dispatch(fetchWord());
dispatch(fetchNouns());
}, [dispatch]);
useEffect(() => {
const fetchTranslationPromise = async () => {
const response = await dispatch(fetchTranslation());
setTranslation(response);
};
if (word) {
fetchTranslationPromise();
}
}, [dispatch, word]);
const handleAnswer = () => {
dispatch(submitAnswer(selected));
setSelected('');
};
return (
<div className='container mt-5'>
<div className='row justify-content-center'>
<div className='col-md-6'>
<h1>French Gender Learning Game</h1>
<h2>Score: {score}</h2>
<div className='card'>
<div className='card-body'>
<h3>
{word && word.word}
{translation.length > 0 && (
<small className='text-muted ml-2'>({translation})</small>
)}
</h3>
<div className='form-check'>
<input
type='radio'
id='un-le'
name='article-group'
value='UN/LE'
className='form-check-input'
checked={selected === 'UN/LE'}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor='un-le' className='form-check-label'>
{nouns.masculine.length > 0 && nouns.masculine[0].article}
</label>
</div>
<div className='form-check'>
<input
type='radio'
id='une-la'
name='article-group'
value='UNE/LA'
className='form-check-input'
checked={selected === 'UNE/LA'}
onChange={(e) => setSelected(e.target.value)}
/>
<label htmlFor='une-la' className='form-check-label'>
{nouns.feminine.length > 0 && nouns.feminine[0].article}
</label>
</div>
<button
className='btn btn-primary'
disabled={!selected}
onClick={handleAnswer}
>
Submit
</button>
<p className='mt-2'>
{isCorrect !== null && (isCorrect ? 'Correct!' : 'Wrong!')}
</p>
</div>
</div>
</div>
</div>
</div>
);
}
export default GamePages;
so that it can map the response fetched by fetchNouns which looks like [
{
"id": 1,
"ending": "age",
"__entity": "MasculineEnding"
},
{
"id": 2,
"ending": "aire",
"__entity": "MasculineEnding"
},
{
"id": 3,
"ending": "isme",
"__entity": "MasculineEnding"
},
{
"id": 4,
"ending": "ment",
"__entity": "MasculineEnding"
},
{
"id": 5,
"ending": "oir",
"__entity": "MasculineEnding"
},
{
"id": 6,
"ending": "sme",
"__entity": "MasculineEnding"
},
{
"id": 7,
"ending": "é",
"__entity": "MasculineEnding"
}
] and [
{
"id": 1,
"ending": "ade",
"__entity": "FeminineEnding"
},
{
"id": 2,
"ending": "ance",
"__entity": "FeminineEnding"
},
{
"id": 3,
"ending": "ence",
"__entity": "FeminineEnding"
},
{
"id": 4,
"ending": "ette",
"__entity": "FeminineEnding"
},
{
"id": 5,
"ending": "ie",
"__entity": "FeminineEnding"
},
{
"id": 6,
"ending": "ine",
"__entity": "FeminineEnding"
},
{
"id": 7,
"ending": "ion",
"__entity": "FeminineEnding"
},
{
"id": 8,
"ending": "ique",
"__entity": "FeminineEnding"
},
{
"id": 9,
"ending": "isse",
"__entity": "FeminineEnding"
},
{
"id": 10,
"ending": "ité",
"__entity": "FeminineEnding"
},
{
"id": 11,
"ending": "lle",
"__entity": "FeminineEnding"
},
{
"id": 12,
"ending": "ure",
"__entity": "FeminineEnding"
}
] map over the array and display ending
|
96080fbb4c979cad9453e71d5c0b5888
|
{
"intermediate": 0.3168955445289612,
"beginner": 0.550118088722229,
"expert": 0.1329863965511322
}
|
7,716
|
fix my code Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1: import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import javax.swing.border.BevelBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.SoftBevelBorder;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private Map<String, Double> History;
private static String previousHistory;
private List<String> historyList;
private Map<String, Double> historyMap;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(new HashMap<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(Map<String, Double> previousHistory) {
// First use the existing history products and total them
totales = previousHistory.values().stream().reduce(0.0, Double::sum);
History = previousHistory;
historyList = new ArrayList<>(History.keySet());
historyMap = new HashMap<>(History);
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<PizzaSize> ChoixPizza = new JComboBox<>(PizzaSize.values());
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<ToppingSize> ChoixTopping = new JComboBox<>(ToppingSize.values());
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<Breuvages> ChoixBreuvage = new JComboBox<>(Breuvages.values());
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " \ngarniture - Cout: " + historytotal;
historyList.add(historyEntry);
historyMap.put(historyEntry, historytotal);
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, historyList);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListModel;
import javax.swing.JTextArea;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.util.List;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, List<String> historyList) {
this.totales = totales;
this.history = String.join("\n", historyList);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(String.join("\n", historyList));
StringBuilder historyBuilder = new StringBuilder();
for (String historyEntry : historyList) {
historyBuilder.append(historyEntry);
historyBuilder.append("\n");
}
commandArea.setText(historyBuilder.toString());
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
panel.add(modifierCommande);
modifierCommande.setBounds(6, 316, 182, 29);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
// Create a new map to store previous history
Map<String, Double> previousHistory = new HashMap<>();
for (String historyEntry : historyList) {
String[] splitEntry = historyEntry.split(" - Cout: ");
previousHistory.put(splitEntry[0], Double.valueOf(splitEntry[1]));
}
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0.0, new ArrayList<>());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
8bd0b3628678083cd70e97de9b133030
|
{
"intermediate": 0.3228455185890198,
"beginner": 0.5104174017906189,
"expert": 0.16673702001571655
}
|
7,717
|
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 some of the relevant header and source file code:
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
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();
private:
bool shutdownInProgress;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
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 (device == VK_NULL_HANDLE || shutdownInProgress) {
// If the device is already VK_NULL_HANDLE, it means the cleanup has run before
return;
}
shutdownInProgress = true; // Indicate that the cleanup is in progress
std::cout << "Waiting for device idle…" << std::endl;
vkDeviceWaitIdle(device); // Wait for rendering to complete
std::cout << "Cleaning up framebuffers…" << std::endl;
CleanupFramebuffers();
std::cout << "Cleaning up renderpass…" << std::endl;
CleanupRenderPass();
std::cout << "Cleaning up syncobject…" << std::endl;
CleanupSyncObjects();
std::cout << "Cleaning up commandbuffers…" << std::endl;
CleanupCommandBuffers(); // Free command buffers before destroying the command pool
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
CleanupDevice(); // Make sure that CleanupDevice is called before DestroySurface
DestroySurface(); // Move this line after CleanupDevice
CleanupInstance();
}
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];
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 = ¤tCommandBuffer;
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);
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.");
}
}
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);
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 ¤tCommandBuffer;
}
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;
}
I am running into errors while trying to render. It seems to be related to a renderer.GetCurrentCommandBuffer call. Please check the code and tell me if you find any errors with how commandbuffers are being managed that might result in an access violation error. It may be related to how the MVP buffer is handled in GameObject.
|
fa89a1e5704cbb1d9f76f1034d1ff120
|
{
"intermediate": 0.36516544222831726,
"beginner": 0.26137372851371765,
"expert": 0.3734608292579651
}
|
7,718
|
java code How many bits does a number have
|
de3f25b52c05871b5ccc79f9db244e48
|
{
"intermediate": 0.38468292355537415,
"beginner": 0.26204368472099304,
"expert": 0.3532733917236328
}
|
7,719
|
"% Define the matrix
data = [160;201;304;408;507;623;745;888;900;105;117;129;135;NaN;152;161;NaN;158;190;203;218;222;NaN;NaN;255;226;271;285;293;307];
% Find the indices of missing data
missing_indices = find(isnan(data));
% Extract the known data and their indices
known_indices = setdiff(1:numel(data), missing_indices);
known_data = data(known_indices);
% Interpolate to estimate the missing data
predicted_data = interp1(known_indices, known_data, missing_indices, 'spline');
% Replace the missing data with the predicted values
data(missing_indices) = predicted_data;
% Print the original and predicted data
fprintf('Original data: \n');
disp(data);
fprintf('Predicted data: \n');
disp(predicted_data);
% Calculate statistics on the original and predicted data
orig_mean = mean(known_data);
orig_std = std(known_data);
predicted_mean = mean(predicted_data);
predicted_std = std(predicted_data);
fprintf('Original data mean: %f, std: %f \n', orig_mean, orig_std);
fprintf('Predicted data mean: %f, std: %f \n', predicted_mean, predicted_std);
% Create the category labels
category_labels = [repmat({'Known Data'}, size(known_data)); repmat({'Predicted Data'}, size(predicted_data))];
% Plot the original and predicted data
figure;
subplot(1,2,1);
plot(known_indices, known_data, 'ro-', 'MarkerFaceColor', 'r', 'MarkerSize', 6);
hold on;
plot(missing_indices, predicted_data, 'go-', 'MarkerFaceColor', 'g', 'MarkerSize', 6);
title('Interpolation');
xlabel('Index');
xlim([0 numel(data)+1]);
ylim([min(data)-1 max(data)+1]);
grid on;
legend('Known Data', 'Predicted Data');
subplot(1,2,2);
boxplot([known_data; predicted_data], category_labels, 'Colors', ['r', 'g'], 'Whisker', Inf);
title('Data Statistics');
ylabel('Data Value');
grid on;
% Display the correlation coefficient between the known and predicted data
r = corrcoef(known_data, predicted_data);
fprintf("Correlation coefficient between known and predicted data: %.4f\n", r(1,2));"
this code give me this error
"Error using corrcoef
X and Y must have the same number of elements.
Error in Mising_data2 (line 54)
r = corrcoef(known_data, predicted_data);"
|
73190e7f60231c86da3b611e29d941f7
|
{
"intermediate": 0.3841017484664917,
"beginner": 0.37427204847335815,
"expert": 0.24162618815898895
}
|
7,720
|
Give me a brief overview of inheritance in Java
|
1ab48b83b33e8ee85969a7c56d977855
|
{
"intermediate": 0.46113887429237366,
"beginner": 0.34744131565093994,
"expert": 0.19141976535320282
}
|
7,721
|
explain to me how toString() works in Java
|
a76baa0d3a788ec50e149f6e00c412a3
|
{
"intermediate": 0.5015878081321716,
"beginner": 0.43716251850128174,
"expert": 0.061249710619449615
}
|
7,722
|
How not to violate SOLID principles when there is a Unity game where NPCs have inventory, memory, vision, hearing, etc. After all, in order for all this to interact together, we need a single class that would do this
|
d8bded4cf6ed72c28869e15aef640d04
|
{
"intermediate": 0.3934209942817688,
"beginner": 0.42794811725616455,
"expert": 0.17863081395626068
}
|
7,723
|
in python, how to check if email adress is valid
|
6dd59eba66250ef2c0f6ea55efb8741c
|
{
"intermediate": 0.3771045506000519,
"beginner": 0.20536738634109497,
"expert": 0.41752809286117554
}
|
7,724
|
whats a command to freeze all npc in skyrim so i can test damage
|
e531e05c658b1fabd44dfe72390fb2e2
|
{
"intermediate": 0.47542664408683777,
"beginner": 0.1731557846069336,
"expert": 0.35141754150390625
}
|
7,725
|
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public void addFirst(E e) { // adds element e to the front of the list
head = new Node<>(e, head); // create and link a new node
if (size == 0)
tail = head; // special case: new node becomes tail also
size++;
}
/**
* Adds an element to the end of the list.
* @param e the new element to add
*/
public void addLast(E e) { // adds element e to the end of the list
Node<E> newest = new Node<>(e, null); // node will eventually be the tail
if (isEmpty())
head = newest; // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
/**
* Removes and returns the first element of the list.
* @return the removed element (or null if empty)
*/
public E removeFirst() { // removes and returns the first element
if (isEmpty()) return null; // nothing to remove
E answer = head.getElement();
head = head.getNext(); // will become null if list had only one node
size--;
if (size == 0)
tail = null; // special case as list is now empty
return answer;
}
@SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
if (size != other.size) return false;
Node walkA = head; // traverse the primary list
Node walkB = other.head; // traverse the secondary list
while (walkA != null) {
if (!walkA.getElement().equals(walkB.getElement())) return false; //mismatch
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true; // if we reach this, everything matched successfully
}
@SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// always use inherited Object.clone() to create the initial copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.head = new Node<>(head.getElement(), null);
Node<E> walk = head.getNext(); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) { // make a new node storing same element
Node<E> newest = new Node<>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node walk=head; walk != null; walk = walk.getNext()) {
h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
}
return h;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = head;
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
private static void concaticate(SinglyLinkedList<String> list1,SinglyLinkedList<String> list2){
list1.tail.setNext(list2.head);
list1.tail=list2.tail;
}
Use the SinglyLinkedList implementation as above. Write a method for concatenating two singly linked lists L1 and L2, into a single list L that contains all the nodes of L1 followed by all the nodes of L2. Write a main method to test the new method. Hint: Connect the end of L1 into the beginning of L2
|
c759efed44e718ef7f9e1325382ecb50
|
{
"intermediate": 0.30829912424087524,
"beginner": 0.5146454572677612,
"expert": 0.17705535888671875
}
|
7,726
|
使用python 识别输入的是否是合法的 正确的中国大学名称
|
52671a638890b3387af76984977c340d
|
{
"intermediate": 0.25233182311058044,
"beginner": 0.33553561568260193,
"expert": 0.4121325612068176
}
|
7,727
|
Given an array of integer, keep a total score based on the following:
|
5b3289524b74e0896a3bbf649f507663
|
{
"intermediate": 0.3640872836112976,
"beginner": 0.2063407003879547,
"expert": 0.4295720160007477
}
|
7,728
|
I have this code
public class SinglyLinkedList<E> implements Cloneable {
//---------------- nested Node class ----------------
/**
* Node of a singly linked list, which stores a reference to its
* element and to the subsequent node in the list (or null if this
* is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/**
* Creates a node with the given element and next node.
*
* @param e the element to be stored
* @param n reference to a node that should follow the new node
*/
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/**
* Returns the element stored at the node.
* @return the element stored at the node
*/
public E getElement() { return element; }
/**
* Returns the node that follows this one (or null if no such node).
* @return the following node
*/
public Node<E> getNext() { return next; }
// Modifier methods
/**
* Sets the node's next reference to point to Node n.
* @param n the node that should follow this one
*/
public void setNext(Node<E> n) { next = n; }
} //----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() { } // constructs an initially empty list
// access methods
/**
* Returns the number of elements in the linked list.
* @return number of elements in the linked list
*/
public int size() { return size; }
/**
* Tests whether the linked list is empty.
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() { return size == 0; }
/**
* Returns (but does not remove) the first element of the list
* @return element at the front of the list (or null if empty)
*/
public E first() { // returns (but does not remove) the first element
if (isEmpty()) return null;
return head.getElement();
}
/**
* Returns (but does not remove) the last element of the list.
* @return element at the end of the list (or null if empty)
*/
public E last() { // returns (but does not remove) the last element
if (isEmpty()) return null;
return tail.getElement();
}
// update methods
/**
* Adds an element to the front of the list.
* @param e the new element to add
*/
public void addFirst(E e) { // adds element e to the front of the list
head = new Node<>(e, head); // create and link a new node
if (size == 0)
tail = head; // special case: new node becomes tail also
size++;
}
/**
* Adds an element to the end of the list.
* @param e the new element to add
*/
public void addLast(E e) { // adds element e to the end of the list
Node<E> newest = new Node<>(e, null); // node will eventually be the tail
if (isEmpty())
head = newest; // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
/**
* Removes and returns the first element of the list.
* @return the removed element (or null if empty)
*/
public E removeFirst() { // removes and returns the first element
if (isEmpty()) return null; // nothing to remove
E answer = head.getElement();
head = head.getNext(); // will become null if list had only one node
size--;
if (size == 0)
tail = null; // special case as list is now empty
return answer;
}
@SuppressWarnings({"unchecked"})
public boolean equals(Object o) {
if (o == null) return false;
if (getClass() != o.getClass()) return false;
SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
if (size != other.size) return false;
Node walkA = head; // traverse the primary list
Node walkB = other.head; // traverse the secondary list
while (walkA != null) {
if (!walkA.getElement().equals(walkB.getElement())) return false; //mismatch
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true; // if we reach this, everything matched successfully
}
@SuppressWarnings({"unchecked"})
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// always use inherited Object.clone() to create the initial copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.head = new Node<>(head.getElement(), null);
Node<E> walk = head.getNext(); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) { // make a new node storing same element
Node<E> newest = new Node<>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node walk=head; walk != null; walk = walk.getNext()) {
h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
}
return h;
}
/**
* Produces a string representation of the contents of the list.
* This exists for debugging purposes only.
*/
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = head;
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
private static void concaticate(SinglyLinkedList<String> list1,SinglyLinkedList<String> list2){
list1.tail.setNext(list2.head);
list1.tail=list2.tail;
}
Add a method swapTwoNodes to SinglyLinkedList class . This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapTwoNodes method. Hint: You may need to traverse the list.
|
6d94b3f7fa19861e33c683fcaf2a9e43
|
{
"intermediate": 0.33065885305404663,
"beginner": 0.4668091833591461,
"expert": 0.2025318741798401
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.