row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
4,720
this is my current code for an ide program: "import java.io.*; public class AdminFile { public static void main(String[] args) { try { File file = new File("admin.txt"); if (!file.exists()) { FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Username: admin"); bufferedWriter.newLine(); bufferedWriter.write("Password: admin"); bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } import java.util.*; import java.io.*; public class AdminModule { private ArrayList<Player> players; private final String PLAYERS_FILENAME = "players.bin"; public AdminModule() { players = new ArrayList<Player>(); loadPlayers(); } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (password.equals("password1")) { return; }else { System.out.println("Incorrect password!"); } } } private void loadPlayers() { try { FileInputStream file = new FileInputStream(PLAYERS_FILENAME); ObjectInputStream output = new ObjectInputStream(file); boolean endOfFile = false; while(!endOfFile) { try { Player player = (Player)output.readObject(); players.add(player); }catch(EOFException ex) { endOfFile = true; } } }catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException"); }catch(FileNotFoundException ex) { System.out.println("FileNotFoundException"); }catch(IOException ex) { System.out.println("IOException"); } System.out.println("Players information loaded"); } private void displayPlayers() { for(Player player: players) { player.display(); } } private void updatePlayersChip() { String playerName = Keyboard.readString("Enter the login name of the player to issue chips to: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } int chips = Keyboard.readInt("Enter the number of chips to issue: "); player.addChips(chips); System.out.println("Chips issued"); } private void createNewPlayer() { String playerName = Keyboard.readString("Enter new player name: "); if (getPlayerName(playerName) != null) { System.out.println("Error: a player with that name already exists"); return; } String password = Keyboard.readString("Enter new password: "); String passwordHashed = Utility.getHash(password); Player player = new Player(playerName,passwordHashed, 100); players.add(player); System.out.println("Player created"); } private void savePlayersToBin() { try { FileOutputStream file = new FileOutputStream(PLAYERS_FILENAME); ObjectOutputStream opStream = new ObjectOutputStream(file); for(Player player: players) { opStream.writeObject(player); } opStream.close(); }catch(IOException ex) { System.out.println("Failed to save players"); } } private void deletePlayer() { String playerName = Keyboard.readString("Enter player name to delete: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } players.remove(player); System.out.println("Player deleted"); } private Player getPlayerName(String playerName) { for (Player player: players) { if (player.getLoginName().equals(playerName)) { return player; } } return null; } private void resetPlayerPassword() { String playerName = Keyboard.readString("Enter player name to reset the password for: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } String newPassword = Keyboard.readString("Enter the new password: "); String passwordHashed = Utility.getHash(newPassword); player.setHashPassword(passwordHashed); System.out.println("Password reset"); } private void changeAdminPassword() { String currentPassword = Keyboard.readString("Enter current admin password: "); if (!User.checkPassword(currentPassword)) { System.out.println("Error: incorrect password"); return; } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { FileOutputStream file = new FileOutputStream("admin.txt"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(passwordHashed); opStream.close(); }catch(IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } public void logout() { System.out.println("Logging out...Goodbye"); } public void run() { login(); displayPlayers(); createNewPlayer(); displayPlayers(); deletePlayer(); displayPlayers(); updatePlayersChip(); displayPlayers(); resetPlayerPassword(); displayPlayers(); //savePlayersToBin(); logout(); } public static void main(String[] args) { // TODO Auto-generated method stub new AdminModule().run(); } } public class Card { private String suit; private String name; private int value; private boolean hidden; public Card(String suit, String name, int value) { this.suit = suit; this.name = name; this.value = value; this.hidden = false; // Change this line to make cards revealed by default } public int getValue() { return value; } public void reveal() { this.hidden = false; } public boolean isHidden() { return hidden; } @Override public String toString() { return this.hidden ? "<HIDDEN CARD>" : "<" + this.suit + " " + this.name + ">"; } public static void main(String[] args) { Card card = new Card("Heart", "Ace", 1); System.out.println(card); } public void hide() { this.hidden = true; } } import java.io.*; public class CreatePlayersBin { public static void main(String[] args) { // TODO Auto-generated method stub Player player1 = new Player("Player1", "Password1", 100); Player player2 = new Player("Player2", "Password2", 200); Player player3 = new Player("Player3", "Password3", 300); try { FileOutputStream file = new FileOutputStream("players.bin"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(player1); opStream.writeObject(player2); opStream.writeObject(player3); opStream.close(); }catch(IOException ex) { } } } public class Dealer extends Player { public Dealer() { super("Dealer", "", 0); } @Override public void addCard(Card card) { super.addCard(card); // Hide only the first card for the dealer if (cardsOnHand.size() == 1) { cardsOnHand.get(0).hide(); } } @Override public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { System.out.print(cardsOnHand.get(i)); if (i < numCards - 1) { System.out.print(", "); } } System.out.println("\n"); } public void revealHiddenCard() { if (!cardsOnHand.isEmpty()) { cardsOnHand.get(0).reveal(); } } } import java.util.ArrayList; import java.util.Random; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = {"Heart", "Diamond", "Spade", "Club"}; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1); cards.add(card); for (int n = 2; n <= 10; n++) { Card aCard = new Card(suit, n + "", n); cards.add(aCard); } Card jackCard = new Card(suit, "Jack", 10); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10); cards.add(kingCard); } } public void shuffle() { Random random = new Random(); for (int i = 0; i < 1000; 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); } } public Card dealCard() { return cards.remove(0); } } import java.util.Scanner; import java.util.Random; public class GameModule { private static final int NUM_ROUNDS = 4; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("HighSum GAME"); System.out.println("================================================================================"); String playerName = ""; String playerPassword = ""; boolean loggedIn = false; // Add user authentication while (!loggedIn) { playerName = Keyboard.readString("Enter Login name > "); playerPassword = Keyboard.readString("Enter Password > "); if (playerName.equals("IcePeak") && playerPassword.equals("password")) { loggedIn = true; } else { System.out.println("Username or Password is incorrect. Please try again."); } } Player player = new Player(playerName, playerPassword, 100); Dealer dealer = new Dealer(); Deck deck = new Deck(); boolean nextGame = true; int betOnTable; boolean playerQuit = false; // Add this line // Add "HighSum GAME" text after logging in System.out.println("================================================================================"); System.out.println("HighSum GAME"); while (nextGame) { System.out.println("================================================================================"); System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game starts - Dealer shuffles deck."); deck.shuffle(); dealer.clearCardsOnHand(); player.clearCardsOnHand(); // Switch the order of dealer and player to deal cards to the dealer first for (int i = 0; i < 2; i++) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } betOnTable = 0; int round = 1; int dealerBet; while (round <= NUM_ROUNDS) { System.out.println("--------------------------------------------------------------------------------"); System.out.println("Dealer dealing cards - ROUND " + round); System.out.println("--------------------------------------------------------------------------------"); // Show dealer’s cards first, then player’s cards if (round == 2) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } dealer.showCardsOnHand(); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (round > 1) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } if (round == 4) { dealer.revealHiddenCard(); } if (round >= 2) { if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { boolean validChoice = false; while (!validChoice) { String prompt = (round == 2) ? "Do you want to follow? [Y/N]: " : "Player call, do you want to [C]all or [Q]uit?: "; String choice = Keyboard.readString(prompt).toLowerCase(); if (choice.equals("c") || choice.equals("y")) { validChoice = true; int playerBet = Keyboard.readInt("Player, state your bet > "); // Check for invalid bet conditions if (playerBet > 100) { System.out.println("Insufficient chips"); validChoice = false; } else if (playerBet <= 0) { System.out.println("Invalid bet"); validChoice = false; } else { betOnTable += playerBet; player.deductChips(playerBet); System.out.println("Player call, state bet: " + playerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else if (choice.equals("q") || choice.equals("n")) { validChoice = true; nextGame = false; round = NUM_ROUNDS + 1; playerQuit = true; // Add this line // Give all the current chips bet to the dealer and the dealer wins System.out.println("Since the player has quit, all the current chips bet goes to the dealer."); System.out.println("Dealer Wins"); break; } } } else { dealerBet = Math.min(new Random().nextInt(11), 10); betOnTable += dealerBet; System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else { dealerBet = 10; betOnTable += dealerBet; player.deductChips(dealerBet); System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } // Determine the winner after the game ends if (!playerQuit) { // Add this line System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game End - Dealer reveal hidden cards"); System.out.println("--------------------------------------------------------------------------------"); dealer.showCardsOnHand(); System.out.println("Value: " + dealer.getTotalCardsValue()); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { System.out.println(playerName + " Wins"); player.addChips(betOnTable); } else { System.out.println("Dealer Wins"); } System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("Dealer shuffles used cards and place behind the deck."); System.out.println("--------------------------------------------------------------------------------"); } // Add this line boolean valid = false; while (!valid) { String input = Keyboard.readString("Next Game? (Y/N) > ").toLowerCase(); if (input.equals("y")) { playerQuit = false; // Add this line nextGame = true; valid = true; } else if (input.equals("n")) { nextGame = false; valid = true; } else { System.out.println("*** Please enter Y or N "); } } } } } 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 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)); } } import java.util.ArrayList; 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 void addCard(Card card) { this.cardsOnHand.add(card); } public void display() { super.display(); System.out.println(this.chips); } public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { if (i < numCards - 1) { System.out.print(cardsOnHand.get(i) + ", "); } else { System.out.print(cardsOnHand.get(i)); } } System.out.println("\n"); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips += amount; } public void deductChips(int amount) { if (amount < chips) this.chips -= amount; } public int getTotalCardsValue() { int totalValue = 0; for (Card card : cardsOnHand) { totalValue += card.getValue(); } return totalValue; } public int getNumberOfCards() { return cardsOnHand.size(); } public void clearCardsOnHand() { cardsOnHand.clear(); } } import java.io.Serializable; abstract public class User implements Serializable { private static final long serialVersionUID = 1L; private String loginName; private String hashPassword; //plain password public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } public void display() { System.out.println(this.loginName+","+this.hashPassword); } } 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(""); } }" these are the requirements: " Develop a Java program for the HighSum game Administration module. Administration Module This module allows the administor to 1. Create a player 2. Delete a player 3. View all players 4. Issue more chips to a player 5. Reset player’s password 6. Change administrator’s password 7. Logout This module will have access to two files (admin.txt and players.bin) The first text file (admin.txt) contains the administrator hashed password (SHA-256). For example 0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e The second text file (players.bin) contains the following players object information in a binary serialized file. • Login Name • Password in SHA-256 • Chips Login Name Password in SHA-256 Chips BlackRanger 6cf615d5bcaac778352a8f1f3360d23f02f34ec182e259897fd6ce485d7870d4 1000 BlueKnight 5906ac361a137e2d286465cd6588ebb5ac3f5ae955001100bc41577c3d751764 1500 IcePeak b97873a40f73abedd8d685a7cd5e5f85e4a9cfb83eac26886640a0813850122b 100 GoldDigger 8b2c86ea9cf2ea4eb517fd1e06b74f399e7fec0fef92e3b482a6cf2e2b092023 2200 Game play module Modify Assignment 1 HighSum Game module such that the Player data is read from the binary file players.bin. And different players are able to login to the GameModule. You have to provide screen outputs to show the correct execution of your program according to the requirements stated. The required test runs are: • Admin login • Create a player • Delete a player • View all players • Issue more chips to a player • Reset player’s password • Change administrator’s password • Administrator login and logout to admin module using updated password. • Player login and logout to game module using updated password." my current admin module code supports the required test runs except: Change administrator’s password • Administrator login and logout to admin module using updated password. • Player login and logout to game module using updated password edit the code so that the 3 remaining test requirements are met check code for errors and make sure it works in the ide.
7e334b9a448147aafe67b16bbcd3c201
{ "intermediate": 0.33587485551834106, "beginner": 0.40056562423706055, "expert": 0.2635595202445984 }
4,721
i want a bot that will scan random pages looking for total balance greater than 0 and log said pages for review later i want it available as a app for android and windows https://privatekeyfinder.io/private-keys/bitcoin
8b809cea2a411cdc9da85552e70d7487
{ "intermediate": 0.4154472351074219, "beginner": 0.16003340482711792, "expert": 0.4245193302631378 }
4,722
I want to learn java to get a job. Create a study plan with a study schedule of everything I need to study to master java and become a junior java developer.
33b5284d756fdeb6e13936b1a727b4d4
{ "intermediate": 0.4716622531414032, "beginner": 0.35163164138793945, "expert": 0.17670610547065735 }
4,723
Act as expert in programming as explain each line below : import express from 'express'; import { engine } from 'express-handlebars'; const app = express(); app.engine('handlebars', engine()); app.set('view engine', 'handlebars'); app.set('views', './views'); app.get('/', (req, res) => { res.render('home'); }); app.listen(3000);
40f9aa4a0c4ac921d344b1eff23228db
{ "intermediate": 0.5630661845207214, "beginner": 0.31157466769218445, "expert": 0.12535908818244934 }
4,724
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public int health = 5; public ParticleSystem deathEffect; private ParticleSystem playingEffect; private bool dead; private void Die() { if (deathEffect != null && !dead) { dead = true; playingEffect = Instantiate(deathEffect, transform.position, Quaternion.identity); playingEffect.Stop(true, ParticleSystemStopBehavior.StopEmitting); var main = playingEffect.main; main.stopAction = ParticleSystemStopAction.Callback; main.duration = 1f; playingEffect.Play(); playingEffect.GetComponent<ParticleSystem>().eventCallback.AddListener(ParticleSystemStopped); } } private void ParticleSystemStopped(ParticleSystem ps) { Destroy(gameObject); } public void TakeDamage(int damage) { health -= damage; if (health <= 0 && !dead) { Die(); } } } ошибка Assets\Enemy.cs(21,46): error CS1061: 'ParticleSystem' does not contain a definition for 'eventCallback' and no accessible extension method 'eventCallback' accepting a first argument of type 'ParticleSystem' could be found (are you missing a using directive or an assembly reference?) у меня юнити 2022 года
be915a7e48eec33952a1d17cd7cc9f7d
{ "intermediate": 0.46819359064102173, "beginner": 0.2800624668598175, "expert": 0.25174394249916077 }
4,725
import random # Define the artists and monthly Spotify listeners by genre artists_by_genre = { ' (1) Hip-Hop': { '21 Savage': 60358167, 'A Boogie Wit Da Hoodie': 18379137, '$NOT': 7781046, '9lokknine': 1680245, 'Ayo & Teo': 1818645 }, ' (2) Pop': { 'Ariana Grande': 81583006, 'Dua Lipa': 35650224, 'Ed Sheeran': 66717265, 'Justin Bieber': 46540612, 'Lady Gaga': 24622751 } } while True: score = 0 genre = input("Which music genre do you want to play with? (1) Hip-Hop or (2) Pop ") if genre not in ['1', '2']: print("Invalid genre. Please choose Hip-Hop, Pop,") continue artists_listeners = artists_by_genre[f" ({genre}) {'Hip-Hop' if genre == '1' else 'Pop'}"] artist_names = list(artists_listeners.keys()) while True: first_artist, second_artist = random.sample(artist_names, 2) guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist} or 2. {second_artist}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") break elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists, '1' or '2', or 'quit' to end the game.") continue elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > \ artists_listeners[second_artist]: print( f"You guessed correctly! {first_artist} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > \ artists_listeners[first_artist]: print( f"You guessed correctly! {second_artist} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue else: print( f"\nSorry, you guessed incorrectly. {first_artist} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") break else: score = 0 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue why does the game ask which genre you want to play after saying you dont want to play again
3e62271eccd07dd671f4e680e47e024c
{ "intermediate": 0.32659754157066345, "beginner": 0.37597209215164185, "expert": 0.2974303364753723 }
4,726
import random # Define the artists and monthly Spotify listeners by genre artists_by_genre = { ’ (1) Hip-Hop’: { ‘21 Savage’: 60358167, ‘A Boogie Wit Da Hoodie’: 18379137, ‘$NOT’: 7781046, ‘9lokknine’: 1680245, ‘Ayo & Teo’: 1818645 }, ’ (2) Pop’: { ‘Ariana Grande’: 81583006, ‘Dua Lipa’: 35650224, ‘Ed Sheeran’: 66717265, ‘Justin Bieber’: 46540612, ‘Lady Gaga’: 24622751 } } while True: score = 0 genre = input(“Which music genre do you want to play with? (1) Hip-Hop or (2) Pop “) if genre not in [‘1’, ‘2’]: print(“Invalid genre. Please choose Hip-Hop, Pop,”) continue artists_listeners = artists_by_genre[f” ({genre}) {‘Hip-Hop’ if genre == ‘1’ else ‘Pop’}”] artist_names = list(artists_listeners.keys()) while True: first_artist, second_artist = random.sample(artist_names, 2) guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist} or 2. {second_artist}? “) guess_lower = guess.strip().lower() if guess_lower == ‘quit’: print(“Thanks for playing!”) break elif guess_lower not in [‘1’, ‘2’, first_artist.lower(), second_artist.lower()]: print(“Invalid input. Please enter the name of one of the two artists, ‘1’ or ‘2’, or ‘quit’ to end the game.”) continue elif guess_lower == first_artist.lower() or guess_lower == ‘1’ and artists_listeners[first_artist] > <br/> artists_listeners[second_artist]: print( f"You guessed correctly! {first_artist} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.”) score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue elif guess_lower == second_artist.lower() or guess_lower == ‘2’ and artists_listeners[second_artist] > <br/> artists_listeners[first_artist]: print( f"You guessed correctly! {second_artist} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.“) score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue else: print( f”\nSorry, you guessed incorrectly. {first_artist} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == ‘n’: print(“Thanks for playing!”) break else: score = 0 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue why does the game ask which genre you want to play after saying you dont want to play again
ce7581ba62ae79d88fe47b29c506c092
{ "intermediate": 0.33509591221809387, "beginner": 0.4040307402610779, "expert": 0.26087334752082825 }
4,727
hi
d68ea50a871cf8345b92bb1fe3081d13
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
4,728
@Composable fun EmulatorScreen( navController: NavController, viewModel: EmulatorViewModel = hiltViewModel(), paddingValues: PaddingValues ) { val state = viewModel.state.value state.devices.forEach { device -> DeviceOnCanvas( device = device, viewModel = viewModel ) } @Composable fun DeviceOnCanvas( device: Device, viewModel: EmulatorViewModel, ) { val position = Offset.Zero Box( modifier = Modifier .offset { IntOffset( x = position.x.roundToInt(), y = position.y.roundToInt(), ) } .clip(RoundedCornerShape(10.dp)) .pointerInput(Unit) { detectTapGestures( onTap = { viewModel.onEvent(EmulatorEvent.DeviceSingleTap(device = device)) } ) detectDragGesturesAfterLongPress( onDragStart = { viewModel.onEvent( EmulatorEvent.DeviceOnDragStart( id = device.id ) ) }, onDrag = { _, dragAmount -> viewModel.onEvent( EmulatorEvent.DeviceUpdatePosition( device = device, dragAmount = dragAmount ) ) }, onDragEnd = { viewModel.onEvent(EmulatorEvent.DeviceOnDragEnd) }, onDragCancel = { TODO() } ) } .background(Color.Red) .size(80.dp) ) { Text(text = viewModel.state.value.isDeviceEditing.toString()) } } @HiltViewModel class EmulatorViewModel @Inject constructor( private val emulatorUseCases: EmulatorUseCases ) : ViewModel() { private val _state = mutableStateOf(EmulatorState()) val state = _state fun onEvent(event: EmulatorEvent) { when (event) { is EmulatorEvent.DeviceSingleTap -> { _state.value = state.value.copy( isDeviceSelected = !state.value.isDeviceSelected ) Log.d("DBG", state.value.isDeviceSelected.toString()) } why bg not changing if in logs value is changing so why is doesnot recompose?
77ead0570ec2d5742c28ede520ebb93b
{ "intermediate": 0.38736677169799805, "beginner": 0.3854374885559082, "expert": 0.22719579935073853 }
4,729
import random import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Book: def __init__(self): """ Initializes a Book object with a randomly generated title, author, and pages. """ self.title = self.generate_word().capitalize() self.author = self.generate_word().capitalize() + ' ' + self.generate_word().capitalize() self.pages = [] for i in range(100): self.pages.append(self.generate_page()) def generate_word(self): """ Generates a random word with alternating consonants and vowels. :return: Randomly generated word. :rtype: str """ vowels = 'аеёиоуэюя' consonants = 'бвгджзйклмнпрстфхцчшщ' length = random.randint(2, 8) word = "" for i in range(length): if i % 2 == 0: word += random.choice(consonants) else: word += random.choice(vowels) return word def generate_page(self): """ Generates a random page consisting of multiple random words. :return: Randomly generated page. :rtype: str """ text = [] for i in range(random.randint(5, 20)): text.append(self.generate_word()) return ' '.join(text) class Library: def __init__(self): """ Initializes a Library object with a list of 10 randomly generated Book objects. """ self.books = [] for i in range(10): self.books.append(Book()) def find_book(self, title): """ Finds a Book object in the library with the specified title. :param title: Title of book to search for. :type title: str :return: Book object with specified title, or None if not found. :rtype: Book or None """ for book in self.books: if book.title.lower() == title.lower(): return book return None def find_page(self, title, page_number): """ Finds a specific page in a Book object with the specified title. :param title: Title of book to search for. :type title: str :param page_number: Number of page to search for. :type page_number: int :return: Text of specified page, or "Invalid page number" if page number is out of range, or "Book not found" if book with specified title is not found. :rtype: str """ book = self.find_book(title) if book: if page_number >= 1 and page_number <= len(book.pages): return book.pages[page_number - 1] else: logger.error("Invalid page number for book: %s", title) return "Invalid page number" else: logger.error("Book not found: %s", title) return "Book not found" # Example usage library = Library() # Print all books in library for book in library.books: logger.info("%s by %s", book.title, book.author) # Print random page from random book book = random.choice(library.books) page_number = random.randint(1, len(book.pages)) logger.info("Random page from %s: Page %d\n%s", book.title, page_number, book.pages[page_number - 1]) # Find specific page in specific book based on user input query_book = input("Enter book title to search for: ") query_page = int(input("Enter page number to search for: ")) result = library.find_page(query_book, query_page) logger.info("Result: %s", result) что нужно делать, чтобы выводились слова
4a545590c93083be9e5eb3ec532ffa4f
{ "intermediate": 0.2860453724861145, "beginner": 0.4728725850582123, "expert": 0.24108199775218964 }
4,730
How can I make the rectangles move in columns when I pick them up? <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Sobics Game</title> <style> #screen{ position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; justify-content: center; } #game-board { margin-top: 10px; width: 100%; height: 90%; margin: 50px 20px 0px 20px; border: 2px solid #999; border-radius: 3px; } .row { display: flex; } .rectangle { width: 10%; height: 40px; margin: 3px; cursor: pointer; user-select: none; border-radius: 3px; } .visible{ box-shadow: 1px 1px 1px 1px #000; } .selected { border: 2px solid white; } #startBtn{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } #startBtn, #restartBtn{ background-color: #1c9e6c; border: none; border-radius: 10px; font-size: 2.5rem; color: #fff; padding: 10px; box-shadow: 5px 5px 10px 0px #257053; } #startBtn:hover, #restartBtn:hover{ background-color: #19bf7f; } #startBtn:active, #restartBtn:active{ box-shadow: none; vertical-align: top; padding: 8px 10px 6px; } #overlay{ position: fixed; top: 0; left: 0; display: flex; justify-content: center; align-items: center; } #menu{ display: none; background-color: #000; opacity: 0.8; padding: 25px 75px 25px 75px; justify-content: center; flex-flow: column; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } #leaderboard-container{ height: 300px; overflow-y: scroll; margin-top: 30px; } #leaderboard-container h2{ color: #fff; font-size: 28px; } #leaderboard-container li{ color: #ccc; font-size: 22px; } #score{ position: absolute; top: 5px; font-size: 24px; background-color: #e3e3e3; padding: 5px 10px 5px 10px; border-radius: 5px; } #mute{ position: fixed; left: 10px; top: 10px; background-color: #fff; border: 1px solid #000; border-radius: 5px; font-size: 16px; } </style> </head> <body> <div id="screen"> <div id="score"></div> <button id="mute" onclick="mute()">Mute</button> <div id="game-board"></div> </div> <button id="startBtn" onclick="startGame()">Start Game</button> <div id="menu"> <button id="restartBtn" onclick="restartGame()">Restart</button> <div id="leaderboard-container"></div> </div> <script> const boardWidth = 10; const boardHeight = 14; const numFilledRows = 5; const backgroundMusic = new Audio('../music/backgroundmusic.mp3'); let isGameEnded = false; muteCount = 0; function mute(){ const btn = document.getElementById('mute'); if(muteCount%2 == 0){ btn.textContent = "Unmute"; backgroundMusic.muted = true; }else{ btn.textContent = "Mute"; backgroundMusic.muted = false; } muteCount++; } function restartGame() { // Stop the background music backgroundMusic.pause(); backgroundMusic.currentTime = 0; // Clear the game board and reset the score document.getElementById("menu").style.display = "none"; const gameBoard = document.getElementById('game-board'); gameBoard.innerHTML = ''; const scoreElement = document.getElementById('score'); scoreElement.innerHTML = 'Score: 0'; // Reset the game variables click = 0; draggedRectangles = []; numberOfRectangles = 0; rectangleColor = null; i = 0; pickedUpRectangles = 0; isGameEnded = false; // Start a new game startGame(); } function startGame() { document.getElementById("startBtn").style.display = "none"; const gameBoard = document.getElementById('game-board'); gameBoard.innerHTML = ''; for (let row = 0; row < boardHeight; row++) { const divRow = document.createElement('div'); divRow.classList.add('row'); for (let col = 0; col < boardWidth; col++) { const divRectangle = document.createElement('div'); divRectangle.classList.add('rectangle'); divRectangle.addEventListener("click", pickRectangle); if (row < numFilledRows) { divRectangle.style.backgroundColor = getRandomColor(); divRectangle.classList.add('visible'); } divRow.appendChild(divRectangle); } gameBoard.appendChild(divRow); } // Create a new HTML element to display the score const scoreElement = document.getElementById("score"); scoreElement.innerHTML = 'Score: 0'; // Initialize score value in the element backgroundMusic.play(); backgroundMusic.loop = true; setTimerAndAddRow(); } function getRandomColor() { const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange']; const randomIndex = Math.floor(Math.random() * colors.length); return colors[randomIndex]; } let click = 0; let draggedRectangles = []; let numberOfRectangles = 0; let rectangleColor = null; let i = 0; let pickedUpRectangles = 0; function pickRectangle(event) { if (click === 0) { const gameBoard = document.getElementById("game-board"); const boardRect = gameBoard.getBoundingClientRect(); const columnWidth = gameBoard.offsetWidth / boardWidth; const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth); draggedRectangles.push(...getColoredRectangles(columnIndex)); // Find the bottom-most empty row in that column const rectangles = document.getElementsByClassName("rectangle"); rectangleColor = draggedRectangles[0].style.backgroundColor; numberOfRectangles = draggedRectangles.length; pickedUpRectangles = draggedRectangles.length; draggedRectangles.forEach(rectangle => { rectangle.style.backgroundColor = ""; rectangle.classList.remove("visible"); }); for (let row = boardHeight - 1; row >= 0; row--) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (!rectangle.style.backgroundColor) { rectangle.style.backgroundColor = rectangleColor; rectangle.classList.add("visible"); draggedRectangles[i] = rectangle; numberOfRectangles--; i++; if (numberOfRectangles === 0) { break; } } } document.addEventListener("mousemove", dragRectangle); click = 1; i = 0; } else if (click === 1) { // Find the column that the mouse is in const gameBoard = document.getElementById("game-board"); const boardRect = gameBoard.getBoundingClientRect(); const columnWidth = gameBoard.offsetWidth / boardWidth; const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth); // Find the bottom-most empty row in that column const rectangles = document.getElementsByClassName("rectangle"); // Restore colors for the dragged rectangles and place them draggedRectangles.forEach(rectangle => { const rectanglePlace = getLastNonColoredRectangle(columnIndex); if (rectanglePlace) { rectangle.style.backgroundColor = ""; rectangle.classList.remove("visible"); rectanglePlace.style.backgroundColor = rectangleColor; rectanglePlace.classList.add("visible"); } }); let rectanglePlace = getLastNonColoredRectangle(columnIndex); const rectangleIndex = Array.from(rectangles).indexOf(rectanglePlace) - 10; console.log(rectangleIndex); click = 0; document.removeEventListener("mousemove", dragRectangle); checkConnectedRectangles(rectangleColor, rectangleIndex); draggedRectangles = []; } } function dragRectangle(event) { if (draggedRectangles.length > 0) { draggedRectangles.forEach((draggedRectangle) => { draggedRectangle.style.left = event.clientX - draggedRectangle.offsetWidth / 2 + 'px'; draggedRectangle.style.top = event.clientY - draggedRectangle.offsetHeight / 2 + 'px'; }); } } function getLastNonColoredRectangle(columnIndex) { const rectangles = document.getElementsByClassName('rectangle'); let lastNonColoredRectangle = null; for (let row = 0; row < boardHeight - 4; row++) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (!rectangle.style.backgroundColor) { lastNonColoredRectangle = rectangle; break; } } return lastNonColoredRectangle; } function getColoredRectangles(columnIndex) { const rectangles = document.getElementsByClassName("rectangle"); const coloredRectangles = []; let rectangleColor = null; for (let row = boardHeight - 4; row >= 0; row--) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (rectangle.style.backgroundColor) { if (rectangleColor === null) { rectangleColor = rectangle.style.backgroundColor; } if (rectangleColor && rectangle.style.backgroundColor === rectangleColor) { coloredRectangles.push(rectangle); } else if (rectangleColor !== null && rectangle.style.backgroundColor !== rectangleColor) { break; } } } return coloredRectangles; } let score = 0; function checkConnectedRectangles(rectangleColor, index) { const rectangles = document.getElementsByClassName("rectangle"); const draggedRow = Math.floor(index / boardWidth); const draggedCol = index % boardWidth; const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; let totalCount = 0; let indicesToClear = new Set(); function checkForConnected(row, col) { const index = row * boardWidth + col; console.log("Lefutok gecisbugyi " + index); if ( row >= 0 && row < boardHeight && col >= 0 && col < boardWidth && rectangles[index].style.backgroundColor === rectangleColor ) { console.log(indicesToClear); const alreadyChecked = indicesToClear.has(index); console.log(alreadyChecked); if (!alreadyChecked) { indicesToClear.add(index); // Check for connected rectangles in all directions directions.forEach(([rowStep, colStep]) => { const currentRow = row + rowStep; const currentCol = col + colStep; console.log(currentRow + " row geci"); console.log(currentCol + " col geci"); checkForConnected(currentRow, currentCol); }); } } } // Check the starting rectangle checkForConnected(draggedRow, draggedCol); totalCount = indicesToClear.size; if (totalCount >= 4) { // Found 4 connected rectangles, make them transparent indicesToClear.forEach((indexToClear) => { rectangles[indexToClear].style.backgroundColor = ""; rectangles[indexToClear].classList.remove("visible"); }); score += 100 * totalCount; document.getElementById("score").innerHTML = "Score: " + score; checkGapsInColumns(); } } function checkGapsInColumns() { const rectangles = document.getElementsByClassName("rectangle"); for (let col = 0; col < boardWidth; col++) { let coloredRectCount = 0; // Count how many colored rectangles are present in the current column for (let row = 0; row < boardHeight - 4; row++) { const index = row * boardWidth + col; const rectangle = rectangles[index]; if (rectangle.style.backgroundColor) { coloredRectCount++; } } // Check for gaps between colored rectangles let gapRow = -1; for (let row = 0; row < boardHeight - 5 && coloredRectCount > 0; row++) { const index = row * boardWidth + col; const rectangle = rectangles[index]; if (gapRow === -1 && !rectangle.style.backgroundColor) { gapRow = row; } else if (rectangle.style.backgroundColor) { if (gapRow !== -1) { const gapIndex = gapRow * boardWidth + col; const emptyRectangle = rectangles[gapIndex]; emptyRectangle.style.backgroundColor = rectangle.style.backgroundColor; emptyRectangle.classList.add("visible"); rectangle.style.backgroundColor = ""; rectangle.classList.remove("visible"); console.log("checkGapsdarab " + gapIndex); console.log(emptyRectangle.style.backgroundColor); checkConnectedRectangles(emptyRectangle.style.backgroundColor, gapIndex); gapRow++; } coloredRectCount--; } } } } function addRowToTop() { const gameBoard = document.getElementById('game-board'); const rowDivs = gameBoard.querySelectorAll('.row'); // Get the colors of the rectangles in the bottom row const bottomRowRectangles = rowDivs[rowDivs.length - 1].querySelectorAll('.rectangle'); const bottomRowColors = Array.from(bottomRowRectangles).map(rectangle => rectangle.style.backgroundColor); // Shift all rows down by 1 for (let i = rowDivs.length - 5; i > 0; i--) { const currentRowRectangles = rowDivs[i].querySelectorAll('.rectangle'); const prevRowRectangles = rowDivs[i - 1].querySelectorAll('.rectangle'); Array.from(currentRowRectangles).forEach((rectangle, index) => { const prevRectangle = prevRowRectangles[index]; rectangle.style.backgroundColor = prevRectangle.style.backgroundColor; rectangle.classList.toggle('visible', prevRectangle.classList.contains('visible')); }); } // Fill the first row with new colors const firstRowRectangles = rowDivs[0].querySelectorAll('.rectangle'); Array.from(firstRowRectangles).forEach((rectangle, index) => { rectangle.style.backgroundColor = bottomRowColors[index] || getRandomColor(); rectangle.classList.add("visible"); }); checkColumns(); setTimerAndAddRow(); } let cycle = 1; function setTimerAndAddRow() { if(!isGameEnded){ setTimeout(addRowToTop, 20/cycle * 1000); cycle += 0.05; } } function checkColumns() { const rectangles = document.getElementsByClassName("rectangle"); for (let col = 0; col < boardWidth; col++) { let count = 0; for (let row = boardHeight - 4; row >= 0; row--) { const index = row * boardWidth + col; const rectangle = rectangles[index]; if (rectangle.classList.contains("visible")) { count++; } } if (count >= 10) { endGame(); return; } } } function endGame() { isGameEnded = true; document.getElementById("menu").style.display = "flex"; document.removeEventListener("mousemove", dragRectangle); backgroundMusic.pause(); const playerName = prompt("Game over! Enter your name:"); if (playerName) { updateLeaderboard(playerName, score); displayLeaderboard(); } } </script> </body> </html>
6c45a130adfa4a2bf8a09a44de396121
{ "intermediate": 0.34977325797080994, "beginner": 0.477325975894928, "expert": 0.1729007512331009 }
4,731
java code to write a serialized example hashtable (as file) in a secure transactional way to disk
5bc7c20be0dd2b0c3c8198087a1e1bee
{ "intermediate": 0.635440468788147, "beginner": 0.11054197698831558, "expert": 0.25401753187179565 }
4,732
how to use addEventListener with bootstrap5 ?
2891c1da1a00133c1c53057c1605acac
{ "intermediate": 0.6530118584632874, "beginner": 0.14210151135921478, "expert": 0.20488663017749786 }
4,733
how do I wrap text to fit screen in google colab
ce1dce471ff73be4ad39cd620b5486e9
{ "intermediate": 0.4341285824775696, "beginner": 0.23802541196346283, "expert": 0.3278460204601288 }
4,734
hi
a0eeb1a446e72652f57d48af7b8ee83c
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
4,735
Explain in layman’s term the app.emit for expressjs
b77afe58b8fbd55c8c7594dfb735c3a8
{ "intermediate": 0.4257074296474457, "beginner": 0.33583149313926697, "expert": 0.23846103250980377 }
4,736
How can I make the rectangles move in columns when I pick them up? So now the eventListener is working, just that dragRectangle won't make the picked up rectangles move to the other column <body> <div id="screen"> <div id="score"></div> <button id="mute" onclick="mute()">Mute</button> <div id="game-board"></div> </div> <button id="startBtn" onclick="startGame()">Start Game</button> <div id="menu"> <button id="restartBtn" onclick="restartGame()">Restart</button> <div id="leaderboard-container"></div> </div> <script> const boardWidth = 10; const boardHeight = 17; const numFilledRows = 5; const backgroundMusic = new Audio('../music/backgroundmusic.mp3'); let isGameEnded = false; muteCount = 0; function mute(){ const btn = document.getElementById('mute'); if(muteCount%2 == 0){ btn.textContent = "Unmute"; backgroundMusic.muted = true; }else{ btn.textContent = "Mute"; backgroundMusic.muted = false; } muteCount++; } function restartGame() { // Stop the background music backgroundMusic.pause(); backgroundMusic.currentTime = 0; // Clear the game board and reset the score document.getElementById("menu").style.display = "none"; const gameBoard = document.getElementById('game-board'); gameBoard.innerHTML = ''; const scoreElement = document.getElementById('score'); scoreElement.innerHTML = 'Score: 0'; // Reset the game variables click = 0; draggedRectangles = []; numberOfRectangles = 0; rectangleColor = null; i = 0; pickedUpRectangles = 0; isGameEnded = false; score = 0; cycle = 1; // Start a new game startGame(); } function startGame() { document.getElementById("startBtn").style.display = "none"; const gameBoard = document.getElementById('game-board'); gameBoard.innerHTML = ''; for (let row = 0; row < boardHeight; row++) { const divRow = document.createElement('div'); divRow.classList.add('row'); if (row === 9) { const divLine = document.createElement('div'); divLine.classList.add('line'); gameBoard.appendChild(divLine); } for (let col = 0; col < boardWidth; col++) { const divRectangle = document.createElement('div'); divRectangle.classList.add('rectangle'); divRectangle.addEventListener("click", pickRectangle); if (row < numFilledRows) { divRectangle.style.backgroundColor = getRandomColor(); divRectangle.classList.add('visible'); } divRow.appendChild(divRectangle); } gameBoard.appendChild(divRow); } // Create a new HTML element to display the score const scoreElement = document.getElementById("score"); scoreElement.innerHTML = 'Score: 0'; // Initialize score value in the element backgroundMusic.play(); backgroundMusic.loop = true; setTimerAndAddRow(); } function getRandomColor() { const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange']; const randomIndex = Math.floor(Math.random() * colors.length); return colors[randomIndex]; } let click = 0; let draggedRectangles = []; let numberOfRectangles = 0; let rectangleColor = null; let i = 0; let pickedUpRectangles = 0; function pickRectangle(event) { if (click === 0 && !isGameEnded) { const gameBoard = document.getElementById("game-board"); const boardRect = gameBoard.getBoundingClientRect(); const columnWidth = gameBoard.offsetWidth / boardWidth; const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth); draggedRectangles.push(...getColoredRectangles(columnIndex)); // Find the bottom-most empty row in that column const rectangles = document.getElementsByClassName("rectangle"); rectangleColor = draggedRectangles[0].style.backgroundColor; numberOfRectangles = draggedRectangles.length; pickedUpRectangles = draggedRectangles.length; draggedRectangles.forEach((rectangle, i) => { rectangle.style.backgroundColor = ""; rectangle.classList.remove("visible"); rectangle.dataset.columnIndex = columnIndex + i; rectangle.style.left = columnIndex * columnWidth + 'px'; rectangle.style.top = -rectangle.offsetHeight / 2 + 'px'; }); for (let row = boardHeight - 1; row >= 0; row--) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (!rectangle.style.backgroundColor) { rectangle.style.backgroundColor = rectangleColor; rectangle.classList.add("visible"); draggedRectangles[i] = rectangle; numberOfRectangles--; i++; if (numberOfRectangles === 0) { break; } } } document.addEventListener("mousemove", dragRectangle); click = 1; i = 0; } else if (click === 1 && !isGameEnded) { // Find the column that the mouse is in const gameBoard = document.getElementById("game-board"); const boardRect = gameBoard.getBoundingClientRect(); const columnWidth = gameBoard.offsetWidth / boardWidth; const columnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth); // Find the bottom-most empty row in that column const rectangles = document.getElementsByClassName("rectangle"); // Restore colors for the dragged rectangles and place them draggedRectangles.forEach(rectangle => { const rectanglePlace = getLastNonColoredRectangle(columnIndex); if (rectanglePlace) { rectangle.style.backgroundColor = ""; rectangle.classList.remove("visible"); rectanglePlace.style.backgroundColor = rectangleColor; rectanglePlace.classList.add("visible"); } }); let rectanglePlace = getLastNonColoredRectangle(columnIndex); const rectangleIndex = Array.from(rectangles).indexOf(rectanglePlace) - 10; console.log(rectangleIndex); click = 0; document.removeEventListener("mousemove", dragRectangle); checkConnectedRectangles(rectangleColor, rectangleIndex); draggedRectangles = []; } } function dragRectangle(event) { console.log("lefutok") if (draggedRectangles.length > 0) { const gameBoard = document.getElementById("game-board"); const boardRect = gameBoard.getBoundingClientRect(); const columnWidth = gameBoard.offsetWidth / boardWidth; draggedRectangles.forEach((draggedRectangle) => { // Calculate the new column based on the position of the mouse const newColumnIndex = Math.floor((event.clientX - boardRect.left) / columnWidth); // Calculate the new position based on the original column and the new column const originalColumnIndex = parseInt(draggedRectangle.getAttribute('data-column-index')); const newX = draggedRectangle.offsetLeft + (newColumnIndex - originalColumnIndex) * columnWidth; const newY = event.clientY - draggedRectangle.offsetHeight / 2; // Set the new position draggedRectangle.style.left = newX + 'px'; draggedRectangle.style.top = newY + 'px'; }); } } function getLastNonColoredRectangle(columnIndex) { const rectangles = document.getElementsByClassName('rectangle'); let lastNonColoredRectangle = null; for (let row = 0; row < boardHeight - 4; row++) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (!rectangle.style.backgroundColor) { lastNonColoredRectangle = rectangle; break; } } return lastNonColoredRectangle; } function getColoredRectangles(columnIndex) { const rectangles = document.getElementsByClassName("rectangle"); const coloredRectangles = []; let rectangleColor = null; for (let row = boardHeight - 4; row >= 0; row--) { const index = row * boardWidth + columnIndex; const rectangle = rectangles[index]; if (rectangle.style.backgroundColor) { if (rectangleColor === null) { rectangleColor = rectangle.style.backgroundColor; } if (rectangleColor && rectangle.style.backgroundColor === rectangleColor) { coloredRectangles.push(rectangle); } else if (rectangleColor !== null && rectangle.style.backgroundColor !== rectangleColor) { break; } } } return coloredRectangles; }
85772f15586f4c3710b931a9d468fb7e
{ "intermediate": 0.3890141248703003, "beginner": 0.42820215225219727, "expert": 0.18278372287750244 }
4,737
what is the best suited java type like map,list or anything else to construct neural net nodes with links to many other nodes ?
0b15c262c0c1259722fc653154798ea6
{ "intermediate": 0.2756374478340149, "beginner": 0.07856670767068863, "expert": 0.6457958817481995 }
4,738
this is my current code, let me know ideads, to make a cool looking gui, maybe with a diffrent coding language, it should have animations and a nice theme: import tkinter as tk import openai import win32com.client # Set up OpenAI API credentials openai.api_key = "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" # Create the main root = tk.Tk() root.title("Email Response Generator") # Add input fields for first and last name first_name_label = tk.Label(root, text="First Name:") first_name_label.grid(row=0, column=0) first_name_entry = tk.Entry(root) first_name_entry.grid(row=0, column=1) last_name_label = tk.Label(root, text="Last Name:") last_name_label.grid(row=1, column=0) last_name_entry = tk.Entry(root) last_name_entry.grid(row=1, column=1) # Add field to display emails outlook_label = tk.Label(root, text="Outlook Emails:") outlook_label.grid(row=2, column=0) outlook_listbox = tk.Listbox(root, height=10, width=50) outlook_listbox.grid(row=3, column=0) # Retrieve Outlook emails def refresh_emails(): outlook_listbox.delete(0, tk.END) outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items for message in messages: outlook_listbox.insert(tk.END, message.Subject) refresh_button = tk.Button(root, text="Refresh", command=refresh_emails) refresh_button.grid(row=2, column=1) refresh_emails() # Add field to display selected email other_label = tk.Label(root, text="Other Emails:") other_label.grid(row=2, column=2) other_text = tk.Text(root, height=10, width=50) other_text.grid(row=3, column=2) # Add response box response_label = tk.Label(root, text="Response:") response_label.grid(row=4, column=0) response_text = tk.Text(root, height=3, width=50) response_text.grid(row=5, column=0) # Add submit button def submit_email(): email = other_text.get("1.0", "end-1c") response = response_text.get("1.0", "end-1c") prompt = f"Antworte auf diese Email: {email} mit folgender Antwort: {response}. Sei so Formal wie Person von der die Email kommt. Dein Name ist {first_name_entry.get()} {last_name_entry.get()}. Beachte, dass du keine Rechtschreibfehler machst." generated_response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=1024, n=1, stop=None, temperature=0.5, ) generated_text.delete("1.0", "end") generated_text.insert("1.0", generated_response.choices[0].text) submit_button = tk.Button(root, text="Submit", command=submit_email) submit_button.grid(row=5, column=1) # Add box to generated response email generated_label = tk.Label(root, text="Generated Response:") generated_label.grid(row=6, column=1) generated_text = tk.Text(root, height=10, width=50) generated_text.grid(row=7, column=1) # Add buttons to redo response and copy generated email def redo_response(): response_text.delete("1.0", "end") redo_button = tk.Button(root, text="Redo", command=redo_response) redo_button.grid(row=5, column=2) def copy_email(): generated_email = generated_text.get("1.0", "end-1c") root.clipboard_clear() root.clipboard_append(generated_email) copy_button = tk.Button(root, text="Copy", command=copy_email) copy_button.grid(row=7, column=2) # Add fine-tune box and button fine_tune_label = tk.Label(root, text="Fine-Tune:") fine_tune_label.grid(row=8, column=0) fine_tune_text = tk.Text(root, height=3, width=50) fine_tune_text.grid(row=9, column=0) def tune_response(): generated_email = generated_text.get("1.0", "end-1c") fine_tune_prompt = fine_tune_text.get("1.0", "end-1c") prompt = f"ändere folgende dinge bei der Originellen Email (Antworte nur mit dem Text der Geänderten Email): {fine_tune_prompt}\n\nOriginele Email:\n{generated_email}" fine_tuned_response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=1024, n=1, stop=None, temperature=0.5, ) generated_text.delete("1.0", "end") generated_text.insert("1.0", fine_tuned_response.choices[0].text) fine_tune_button = tk.Button(root, text="Fine-Tune", command=tune_response) fine_tune_button.grid(row=9, column=1) # Bind function to display selected email def display_email(event): selection = event.widget.curselection() if selection: index = selection[0] subject = outlook_listbox.get(index) outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items for message in messages: if message.Subject == subject: other_text.delete("1.0", "end") other_text.insert("1.0", f"From: {message.SenderName}\nSubject: {message.Subject}\n\n{message.Body}\n\n") outlook_listbox.bind("<<ListboxSelect>>", display_email) # Start the main loop root.mainloop()
0e39780595ab414252fe13c66faed893
{ "intermediate": 0.37319761514663696, "beginner": 0.5042529106140137, "expert": 0.12254951149225235 }
4,739
can you explain this error -"File "C:\python_proj\depth_sensing\ogl_viewer\viewer.py", line 13, in <module> import pyzed.sl as sl ImportError: DLL load failed while importing sl: The specified module could not be found."?
3ae4705b69e77fb623ddcec1c723e984
{ "intermediate": 0.6864219903945923, "beginner": 0.13003699481487274, "expert": 0.18354107439517975 }
4,740
import pygame import sys import random pygame.init() WIDTH = 800 HEIGHT = 800 CELL_SIZE = 40 GRID_SIZE = WIDTH // CELL_SIZE WHITE = (255, 255, 255) BLACK = (0, 0, 0) player_colors = [(255, 0, 0), (0, 0, 255)] grid = [] def initialize_grid(): global grid grid = [[None] * GRID_SIZE for _ in range(GRID_SIZE)] def draw_pion(screen, x, y, color): position = (x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2) pygame.draw.circle(screen, color, position, CELL_SIZE // 2 - 2) def draw_grid(screen): for y in range(GRID_SIZE): for x in range(GRID_SIZE): rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE) pygame.draw.rect(screen, BLACK, rect, 1) if grid[y][x] is not None: color = pygame.Color(player_colors[grid[y][x]]) draw_pion(screen, x, y, color) def place_pion(player, x, y): global grid if grid[y][x] is None: grid[y][x] = player return True return False def change_pion(player, x, y): global grid if grid[y][x]: grid[y][x] = player return True def expand_pions(player): global grid new_positions = [] for y in range(GRID_SIZE): for x in range(GRID_SIZE): if grid[y][x] == player: for dy in (-1, 0, 1): for dx in (-1, 0, 1): ny, nx = y + dy, x + dx if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is None: new_positions.append((nx, ny)) for position in new_positions: grid[position[1]][position[0]] = player def check_neighbors(x, y, player): global grid neighbors = [ (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), ] colors_found = set() for nx, ny in neighbors: if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is not None: colors_found.add(grid[ny][nx]) return colors_found def pierre_feuille_ciseaux(player1, player2): choices = ["pierre", "feuille", "ciseaux"] choice1 = choices[random.randint(0, 2)] choice2 = choices[random.randint(0, 2)] print("Joueur", player1 + 1, ":", choice1) print("Joueur", player2 + 1, ":", choice2) if (choice1 == "pierre" and choice2 == "ciseaux") or (choice1 == "feuille" and choice2 == "pierre") or (choice1 == "ciseaux" and choice2 == "feuille"): return player1 if choice1 == choice2: return None return player2 def is_game_over(start_phase): if start_phase: return False for row in grid: if None in row: return False return True def count_pions(player): count = 0 for row in grid: for cell in row: if cell == player: count += 1 return count def play_game(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() pygame.display.set_caption("Jeu de connexion") initialize_grid() start_phase = True running = True game_over = False turn = 0 grid_x, grid_y = -1, -1 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if grid_x != -1 and grid_y != -1: colors_found = check_neighbors(grid_x, grid_y, turn) if len(colors_found) == 2 and (grid[grid_y][grid_x] is None or len(check_neighbors(grid_x, grid_y, grid[grid_y][grid_x])) < 4): winner = pierre_feuille_ciseaux(list(colors_found)[0], list(colors_found)[1]) if winner is not None: print("Le gagnant est le joueur", winner + 1) change_pion(winner, grid_x, grid_y) expand_pions(turn) turn = (turn + 1) % len(player_colors) elif event.key == pygame.K_RETURN: turn = (turn + 1) % len(player_colors) elif event.type == pygame.MOUSEBUTTONUP: x, y = pygame.mouse.get_pos() grid_x, grid_y = x // CELL_SIZE, y // CELL_SIZE if start_phase: if count_pions(turn) == 0: place_pion(turn, grid_x, grid_y) turn = (turn + 1) % len(player_colors) if count_pions(turn) == 1: start_phase = False turn = 0 screen.fill(WHITE) draw_grid(screen) pygame.display.flip() clock.tick(60) if not game_over and is_game_over(start_phase): winner = 0 if count_pions(0) > count_pions(1) else 1 print("Le joueur", winner + 1, "a gagné!") game_over = True pygame.quit() sys.exit() if __name__ == "__main__": play_game() File "/home/ludovic/Bureau/tricolor.py", line 130 if event.key == pygame.K_SPACE: ^ IndentationError: expected an indented block after 'elif' statement on line 129
41af4f377dd503237da43da5850b877b
{ "intermediate": 0.37892282009124756, "beginner": 0.44423094391822815, "expert": 0.17684626579284668 }
4,741
delete literal value from typedb
b40a3ce87f523904286236f4fbe9a744
{ "intermediate": 0.4337441027164459, "beginner": 0.29417654871940613, "expert": 0.2720792889595032 }
4,742
can you build a tool that shows me theoretical profits if i had sold the top of every NFT i've ever held? solana blockchain
fb1209bd8fde1cbc49f7a5840d6148f4
{ "intermediate": 0.3804839849472046, "beginner": 0.14721815288066864, "expert": 0.4722978472709656 }
4,743
Make this whole component synchronous import React, { createContext, useContext, useReducer } from 'react'; import FilesReducer from './reducer'; import { ADD_ATTACHMENT, CLEAR_ATTACHMENT, REMOVE_ATTACHMENT, SHOW_MESSAGE, } from './actions'; import { IInitialStateFiles } from '../../interfaces/IAppState'; import { AppFunctions } from '../../App'; const initialState: IInitialStateFiles = { files: [], responseMessage: '', addAttachment: (files: File[]) => {}, removeAttachment: (file: File) => {}, createAnnotations: (files: File[]) => {}, setMessage: (i?: number) => {}, }; const FilesContext = createContext<IInitialStateFiles | undefined>(undefined); const FilesState = (props: { children: | boolean | React.ReactChild | React.ReactFragment | React.ReactPortal | null | undefined; }) => { const { webapi, context, ioConnector } = useContext(AppFunctions); const [state, dispatch] = useReducer(FilesReducer, initialState); const addAttachment = async (files: File[]) => { try { dispatch({ type: CLEAR_ATTACHMENT }); dispatch({ type: ADD_ATTACHMENT, payload: files }); } catch (error) { console.error(error); } }; const removeAttachment = async (file: File) => { try { dispatch({ type: REMOVE_ATTACHMENT, payload: file }); } catch (error) { console.error(error); } }; const createAnnotations = (files: File[]) => { const entity: string = context['page']['entityTypeName']; const entityId: string = context['page']['entityId']; const isActivityMimeAttachment: boolean = entity.toLowerCase() === 'email' || entity.toLowerCase() === 'appointment'; const attachmentEntity: string = isActivityMimeAttachment ? 'activitymimeattachment' : 'annotation'; const getMeta = (): Promise<string> => context.utils.getEntityMetadata(entity).then((response) => { return response.EntitySetName; }); const toBase64 = (file: File) => new Promise<string | ArrayBuffer | null>((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onabort = () => reject(); reader.onerror = (error) => reject(error); }); const createAnnotationRecord = async ( file: File, ): Promise<ComponentFramework.WebApi.Entity | undefined> => { const base64Data: string | ArrayBuffer | null = await toBase64(file); if (typeof base64Data === 'string') { const base64: string = base64Data.replace(/^data:.+;base64,/, ''); const entitySetName: string = await getMeta(); const attachmentRecord: ComponentFramework.WebApi.Entity = { filename: file.name, objecttypecode: entity, }; if (isActivityMimeAttachment) { attachmentRecord[ 'objectid_activitypointer@odata.bind' ] = `/activitypointers(${entityId})`; attachmentRecord['body'] = base64; } else { attachmentRecord[ `objectid_${entity}@odata.bind` ] = `/${entitySetName}(${entityId})`; attachmentRecord['documentbody'] = base64; } if (file.type && file.type !== '') { attachmentRecord['mimetype'] = file.type; } return attachmentRecord; } }; let successfulUploads: number = 0; let unsuccessfulUploads: number = 0; files.forEach(async (file: File, i: number) => { let finished = false; const annotation: ComponentFramework.WebApi.Entity | undefined = await createAnnotationRecord(file); if (annotation) { await webapi .createRecord(attachmentEntity, annotation) .then((res) => { if (res.id) { dispatch({ type: REMOVE_ATTACHMENT, payload: file }); successfulUploads++; } }) .catch((err) => { unsuccessfulUploads++; console.error(err); }) .finally(() => { if ( unsuccessfulUploads === 0 && successfulUploads === files.length ) { finished = true; } if (unsuccessfulUploads !== 0) { console.error('There were unsuccessful uploads'); } }); } if (finished) { const control = Xrm.Page.getControl(ioConnector.controlToRefresh); // @ts-ignore control.refresh(); setMessage(successfulUploads); } }); }; const setMessage = (i?: number) => { const payload = i! > 0 ? `You have uploaded ${i} files succesfully` : ''; dispatch({ type: SHOW_MESSAGE, payload: payload }); }; return ( <FilesContext.Provider value={{ files: state.files, responseMessage: state.responseMessage, addAttachment, removeAttachment, createAnnotations, setMessage, }} > {props.children} </FilesContext.Provider> ); }; const useFilesContext = () => { const context = React.useContext(FilesContext); if (context === undefined) { throw new Error( 'useAllocationsState must be used within a AllocationsProvider', ); } return context; }; export { FilesState, useFilesContext };
dc89e04f24233a59949ef2917001257b
{ "intermediate": 0.38456907868385315, "beginner": 0.4484672248363495, "expert": 0.16696365177631378 }
4,744
Stream<List<Post>> fetchUserPosts(List<Community> communities) { return _posts .where('communityName', whereIn: communities.map((e) => e.name).toList()) .orderBy('createdAt', descending: true) .snapshots() .map( (event) => event.docs .map( (e) => Post.fromMap( e.data() as Map<String, dynamic>, ), ) .toList(), ); }
00d4619962d4cd6348bdb1e55099ce70
{ "intermediate": 0.40086829662323, "beginner": 0.3955170810222626, "expert": 0.20361463725566864 }
4,745
how to avoid sqlite from locking database while one spring project read from it and one spring project write in it.
fe0dfbcb8b81169ffa1dbb4342e50165
{ "intermediate": 0.3041042983531952, "beginner": 0.24224039912223816, "expert": 0.45365533232688904 }
4,746
I have an error with this code. It says doc is not defined. Sub SendRequest() Dim wordApp As Object Set doc = wordApp.Documents.Open("G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\AdminRequest.docm") wordApp.Visible = True doc.Activate wordApp.WindowState = wdWindowStateNormal End Sub
f1ade973edfa246b18212a685446275a
{ "intermediate": 0.4372306168079376, "beginner": 0.31102684140205383, "expert": 0.25174254179000854 }
4,747
can you write me the code to use in twine 2 with sugarcube for combat system
a805a09127bc7fbe0d8ccb60d6a82cf6
{ "intermediate": 0.481868177652359, "beginner": 0.16099035739898682, "expert": 0.3571414649486542 }
4,748
import random from PIL import Image # Define the artists and their monthly Spotify listeners artists = { 'Young Thug': {"image":"./fotos/Young Thug_1.jpeg", "listeners": 28887553}, 'Yungeen Ace': {"image":"./fotos/Yungeen Ace_1.jpeg", "listeners": 1294188}, } while True: score = 0 # reset score at the beginning of each game first_artist, second_artist = random.sample(list(artists.keys()), 2) # Load the images for the artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) while True: # Display the images first_artist_image.show() second_artist_image.show() guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists[first_artist]["listeners"] > artists[second_artist]["listeners"]: print(f"You guessed correctly! {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists[second_artist]["listeners"] > artists[first_artist]["listeners"]: print(f"You guessed correctly! {second_artist.title()} had {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() else: score = 0 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) break is there a other way i can make the pictures appear? now they open in a different window and i need to close it each time
c98c35769d0ff0b17ee75fcdf51a43c6
{ "intermediate": 0.27098241448402405, "beginner": 0.4697066843509674, "expert": 0.25931090116500854 }
4,749
hi can you write me a hello world script in python?
d6ad5625e2f08ff6bb3473461605c09e
{ "intermediate": 0.4059252142906189, "beginner": 0.27871838212013245, "expert": 0.3153563439846039 }
4,750
I need to install Plex server on a raspberry pi, using network shared folders for the library. Please make a guide to show me how to do this.
4efdf9ce9661dfe3426ef66427254dae
{ "intermediate": 0.6410201787948608, "beginner": 0.14617007970809937, "expert": 0.21280980110168457 }
4,751
this is my current code for an ide program: "import java.io.*; import java.io.*; public class AdminFile { private String hashedAdminPassword; public AdminFile() { try { // Read the hashed admin password from the admin.txt file BufferedReader reader = new BufferedReader(new FileReader("admin.txt")); hashedAdminPassword = reader.readLine(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (Utility.checkPassword(password, hashedAdminPassword)) { // Use Utility.checkPassword() with the hashedAdminPassword return; } else { System.out.println("Incorrect password!"); } } } public static void main(String[] args) { try { File file = new File("admin.txt"); if (!file.exists()) { FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Username: admin"); bufferedWriter.newLine(); bufferedWriter.write("Password: admin"); bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } import java.util.*; import java.io.*; public class AdminModule { private ArrayList<Player> players; private final String PLAYERS_FILENAME = "players.bin"; public AdminModule() { players = new ArrayList<Player>(); loadPlayers(); } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (password.equals("password1")) { return; }else { System.out.println("Incorrect password!"); } } } private void loadPlayers() { try { FileInputStream file = new FileInputStream(PLAYERS_FILENAME); ObjectInputStream output = new ObjectInputStream(file); boolean endOfFile = false; while(!endOfFile) { try { Player player = (Player)output.readObject(); players.add(player); }catch(EOFException ex) { endOfFile = true; } } }catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException"); }catch(FileNotFoundException ex) { System.out.println("FileNotFoundException"); }catch(IOException ex) { System.out.println("IOException"); } System.out.println("Players information loaded"); } private void displayPlayers() { for(Player player: players) { player.display(); } } private void updatePlayersChip() { String playerName = Keyboard.readString("Enter the login name of the player to issue chips to: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } int chips = Keyboard.readInt("Enter the number of chips to issue: "); player.addChips(chips); System.out.println("Chips issued"); } private void createNewPlayer() { String playerName = Keyboard.readString("Enter new player name: "); if (getPlayerName(playerName) != null) { System.out.println("Error: a player with that name already exists"); return; } String password = Keyboard.readString("Enter new password: "); String passwordHashed = Utility.getHash(password); Player player = new Player(playerName,passwordHashed, 100); players.add(player); System.out.println("Player created"); } private void savePlayersToBin() { try { FileOutputStream file = new FileOutputStream(PLAYERS_FILENAME); ObjectOutputStream opStream = new ObjectOutputStream(file); for(Player player: players) { opStream.writeObject(player); } opStream.close(); }catch(IOException ex) { System.out.println("Failed to save players"); } } private void deletePlayer() { String playerName = Keyboard.readString("Enter player name to delete: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } players.remove(player); System.out.println("Player deleted"); } private Player getPlayerName(String playerName) { for (Player player: players) { if (player.getLoginName().equals(playerName)) { return player; } } return null; } private void resetPlayerPassword() { String playerName = Keyboard.readString("Enter player name to reset the password for: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } String newPassword = Keyboard.readString("Enter the new password: "); String passwordHashed = Utility.getHash(newPassword); player.setHashPassword(passwordHashed); System.out.println("Password reset"); } private void changeAdminPassword() { String currentPassword = Keyboard.readString("Enter current admin password: "); if (!Utility.checkPassword(currentPassword)) { // Use Utility.checkPassword() instead of User.checkPassword() System.out.println("Error: incorrect password"); return; } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { // Update the admin.txt file with the new hashed password FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(passwordHashed); bufferedWriter.close(); } catch (IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { FileOutputStream file = new FileOutputStream("admin.txt"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(passwordHashed); opStream.close(); }catch(IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } public void logout() { System.out.println("Logging out...Goodbye"); } public void run() { login(); displayPlayers(); createNewPlayer(); displayPlayers(); deletePlayer(); displayPlayers(); updatePlayersChip(); displayPlayers(); resetPlayerPassword(); displayPlayers(); //savePlayersToBin(); logout(); } public static void main(String[] args) { // TODO Auto-generated method stub new AdminModule().run(); } } public class Card { private String suit; private String name; private int value; private boolean hidden; public Card(String suit, String name, int value) { this.suit = suit; this.name = name; this.value = value; this.hidden = false; // Change this line to make cards revealed by default } public int getValue() { return value; } public void reveal() { this.hidden = false; } public boolean isHidden() { return hidden; } @Override public String toString() { return this.hidden ? "<HIDDEN CARD>" : "<" + this.suit + " " + this.name + ">"; } public static void main(String[] args) { Card card = new Card("Heart", "Ace", 1); System.out.println(card); } public void hide() { this.hidden = true; } } import java.io.*; public class CreatePlayersBin { public static void main(String[] args) { // TODO Auto-generated method stub Player player1 = new Player("Player1", "Password1", 100); Player player2 = new Player("Player2", "Password2", 200); Player player3 = new Player("Player3", "Password3", 300); try { FileOutputStream file = new FileOutputStream("players.bin"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(player1); opStream.writeObject(player2); opStream.writeObject(player3); opStream.close(); }catch(IOException ex) { } } } public class Dealer extends Player { public Dealer() { super("Dealer", "", 0); } @Override public void addCard(Card card) { super.addCard(card); // Hide only the first card for the dealer if (cardsOnHand.size() == 1) { cardsOnHand.get(0).hide(); } } @Override public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { System.out.print(cardsOnHand.get(i)); if (i < numCards - 1) { System.out.print(", "); } } System.out.println("\n"); } public void revealHiddenCard() { if (!cardsOnHand.isEmpty()) { cardsOnHand.get(0).reveal(); } } } import java.util.ArrayList; import java.util.Random; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = {"Heart", "Diamond", "Spade", "Club"}; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1); cards.add(card); for (int n = 2; n <= 10; n++) { Card aCard = new Card(suit, n + "", n); cards.add(aCard); } Card jackCard = new Card(suit, "Jack", 10); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10); cards.add(kingCard); } } public void shuffle() { Random random = new Random(); for (int i = 0; i < 1000; 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); } } public Card dealCard() { return cards.remove(0); } } import java.util.Scanner; import java.util.Random; public class GameModule { private static final int NUM_ROUNDS = 4; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("HighSum GAME"); System.out.println("================================================================================"); // Load players from the players.bin file ArrayList<Player> players = new ArrayList<Player>(); try { FileInputStream file = new FileInputStream("players.bin"); ObjectInputStream input = new ObjectInputStream(file); Player player; while ((player = (Player) input.readObject()) != null) { players.add(player); } input.close(); } catch (EOFException ex) { // End of file } catch (IOException | ClassNotFoundException ex) { ex.printStackTrace(); } String playerName = ""; String playerPassword = ""; boolean loggedIn = false; Player player = null; // Add user authentication while (!loggedIn) { playerName = Keyboard.readString("Enter Login name > "); playerPassword = Keyboard.readString("Enter Password > "); for (Player p : players) { if (p.getLoginName().equals(playerName) && p.checkPassword(playerPassword)) { loggedIn = true; player = p; break; } } if (!loggedIn) { System.out.println("Username or Password is incorrect. Please try again."); } } Player player = new Player(playerName, playerPassword, 100); Dealer dealer = new Dealer(); Deck deck = new Deck(); boolean nextGame = true; int betOnTable; boolean playerQuit = false; // Add this line // Add "HighSum GAME" text after logging in System.out.println("================================================================================"); System.out.println("HighSum GAME"); while (nextGame) { System.out.println("================================================================================"); System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game starts - Dealer shuffles deck."); deck.shuffle(); dealer.clearCardsOnHand(); player.clearCardsOnHand(); // Switch the order of dealer and player to deal cards to the dealer first for (int i = 0; i < 2; i++) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } betOnTable = 0; int round = 1; int dealerBet; while (round <= NUM_ROUNDS) { System.out.println("--------------------------------------------------------------------------------"); System.out.println("Dealer dealing cards - ROUND " + round); System.out.println("--------------------------------------------------------------------------------"); // Show dealer’s cards first, then player’s cards if (round == 2) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } dealer.showCardsOnHand(); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (round > 1) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } if (round == 4) { dealer.revealHiddenCard(); } if (round >= 2) { if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { boolean validChoice = false; while (!validChoice) { String prompt = (round == 2) ? "Do you want to follow? [Y/N]: " : "Player call, do you want to [C]all or [Q]uit?: "; String choice = Keyboard.readString(prompt).toLowerCase(); if (choice.equals("c") || choice.equals("y")) { validChoice = true; int playerBet = Keyboard.readInt("Player, state your bet > "); // Check for invalid bet conditions if (playerBet > 100) { System.out.println("Insufficient chips"); validChoice = false; } else if (playerBet <= 0) { System.out.println("Invalid bet"); validChoice = false; } else { betOnTable += playerBet; player.deductChips(playerBet); System.out.println("Player call, state bet: " + playerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else if (choice.equals("q") || choice.equals("n")) { validChoice = true; nextGame = false; round = NUM_ROUNDS + 1; playerQuit = true; // Add this line // Give all the current chips bet to the dealer and the dealer wins System.out.println("Since the player has quit, all the current chips bet goes to the dealer."); System.out.println("Dealer Wins"); break; } } } else { dealerBet = Math.min(new Random().nextInt(11), 10); betOnTable += dealerBet; System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else { dealerBet = 10; betOnTable += dealerBet; player.deductChips(dealerBet); System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } // Determine the winner after the game ends if (!playerQuit) { // Add this line System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game End - Dealer reveal hidden cards"); System.out.println("--------------------------------------------------------------------------------"); dealer.showCardsOnHand(); System.out.println("Value: " + dealer.getTotalCardsValue()); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { System.out.println(playerName + " Wins"); player.addChips(betOnTable); } else { System.out.println("Dealer Wins"); } System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("Dealer shuffles used cards and place behind the deck."); System.out.println("--------------------------------------------------------------------------------"); } // Add this line boolean valid = false; while (!valid) { String input = Keyboard.readString("Next Game? (Y/N) > ").toLowerCase(); if (input.equals("y")) { playerQuit = false; // Add this line nextGame = true; valid = true; } else if (input.equals("n")) { nextGame = false; valid = true; } else { System.out.println("*** Please enter Y or N "); } } } } } 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 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)); } } import java.util.ArrayList; 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 void addCard(Card card) { this.cardsOnHand.add(card); } public void display() { super.display(); System.out.println(this.chips); } public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { if (i < numCards - 1) { System.out.print(cardsOnHand.get(i) + ", "); } else { System.out.print(cardsOnHand.get(i)); } } System.out.println("\n"); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips += amount; } public void deductChips(int amount) { if (amount < chips) this.chips -= amount; } public int getTotalCardsValue() { int totalValue = 0; for (Card card : cardsOnHand) { totalValue += card.getValue(); } return totalValue; } public int getNumberOfCards() { return cardsOnHand.size(); } public void clearCardsOnHand() { cardsOnHand.clear(); } } import java.io.Serializable; abstract public class User implements Serializable { private static final long serialVersionUID = 1L; private String loginName; private String hashPassword; //plain password public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } public void display() { System.out.println(this.loginName+","+this.hashPassword); } } 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(""); } }" these are the requirements: " Develop a Java program for the HighSum game Administration module. Administration Module This module allows the administor to 1. Create a player 2. Delete a player 3. View all players 4. Issue more chips to a player 5. Reset player’s password 6. Change administrator’s password 7. Logout This module will have access to two files (admin.txt and players.bin) The first text file (admin.txt) contains the administrator hashed password (SHA-256). For example 0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e The second text file (players.bin) contains the following players object information in a binary serialized file. • Login Name • Password in SHA-256 • Chips Login Name Password in SHA-256 Chips BlackRanger 6cf615d5bcaac778352a8f1f3360d23f02f34ec182e259897fd6ce485d7870d4 1000 BlueKnight 5906ac361a137e2d286465cd6588ebb5ac3f5ae955001100bc41577c3d751764 1500 IcePeak b97873a40f73abedd8d685a7cd5e5f85e4a9cfb83eac26886640a0813850122b 100 GoldDigger 8b2c86ea9cf2ea4eb517fd1e06b74f399e7fec0fef92e3b482a6cf2e2b092023 2200 Game play module Modify Assignment 1 HighSum Game module such that the Player data is read from the binary file players.bin. And different players are able to login to the GameModule. You have to provide screen outputs to show the correct execution of your program according to the requirements stated. The required test runs are: • Admin login • Create a player • Delete a player • View all players • Issue more chips to a player • Reset player’s password • Change administrator’s password • Administrator login and logout to admin module using updated password. • Player login and logout to game module using updated password." there are 20 errors in the program, fix it: "Description Resource Path Location Type ArrayList cannot be resolved to a type GameModule.java /Assignment2/src line 14 Java Problem ArrayList cannot be resolved to a type GameModule.java /Assignment2/src line 14 Java Problem Duplicate local variable player GameModule.java /Assignment2/src line 52 Java Problem EOFException cannot be resolved to a type GameModule.java /Assignment2/src line 23 Java Problem FileInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 16 Java Problem FileInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 16 Java Problem IOException cannot be resolved to a type GameModule.java /Assignment2/src line 25 Java Problem No exception of type Object can be thrown; an exception type must be a subclass of Throwable GameModule.java /Assignment2/src line 25 Java Problem ObjectInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 17 Java Problem ObjectInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 17 Java Problem Syntax error, insert "}" to complete ClassBody AdminModule.java /Assignment2/src line 183 Java Problem Syntax error on token ";", { expected after this token AdminModule.java /Assignment2/src line 148 Java Problem Syntax error on token "}", delete this token AdminModule.java /Assignment2/src line 158 Java Problem Syntax error on token "void", record expected AdminModule.java /Assignment2/src line 160 Java Problem Syntax error on token "void", record expected AdminModule.java /Assignment2/src line 164 Java Problem Syntax error on token "void", record expected AdminModule.java /Assignment2/src line 179 Java Problem The method checkPassword(String, String) is undefined for the type Utility AdminFile.java /Assignment2/src line 22 Java Problem The method checkPassword(String) is undefined for the type Utility AdminModule.java /Assignment2/src line 129 Java Problem The method printStackTrace() is undefined for the type Object GameModule.java /Assignment2/src line 26 Java Problem The method setHashPassword(String) is undefined for the type Player AdminModule.java /Assignment2/src line 123 Java Problem " check code for errors and make sure it works in the ide
70b84198676fc5e0e90f32ce6ee72800
{ "intermediate": 0.2769320011138916, "beginner": 0.5568165183067322, "expert": 0.16625148057937622 }
4,752
coding a function: selected a row for table' tbody,get it data , this data useing create a form
905c89d9063b93de3b2d109442d59bea
{ "intermediate": 0.6033439040184021, "beginner": 0.1881573498249054, "expert": 0.2084987461566925 }
4,753
import pygame import sys import random pygame.init() WIDTH = 800 HEIGHT = 800 CELL_SIZE = 40 GRID_SIZE = WIDTH // CELL_SIZE WHITE = (255, 255, 255) BLACK = (0, 0, 0) player_colors = [(255, 0, 0), (0, 0, 255)] grid = [] def initialize_grid(): global grid grid = [[None] * GRID_SIZE for _ in range(GRID_SIZE)] def draw_pion(screen, x, y, color): position = (x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2) pygame.draw.circle(screen, color, position, CELL_SIZE // 2 - 2) def draw_grid(screen): for y in range(GRID_SIZE): for x in range(GRID_SIZE): rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE) pygame.draw.rect(screen, BLACK, rect, 1) if grid[y][x] is not None: color = pygame.Color(player_colors[grid[y][x]]) draw_pion(screen, x, y, color) def place_pion(player, x, y): global grid if grid[y][x] is None: grid[y][x] = player return True return False def change_pion(player, x, y): global grid if grid[y][x]: grid[y][x] = player return True def expand_pions(player): global grid new_positions = [] for y in range(GRID_SIZE): for x in range(GRID_SIZE): if grid[y][x] == player: for dy in (-1, 0, 1): for dx in (-1, 0, 1): ny, nx = y + dy, x + dx if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is None: new_positions.append((nx, ny)) for position in new_positions: grid[position[1]][position[0]] = player def check_neighbors(x, y, player): global grid neighbors = [ (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), ] colors_found = set() for nx, ny in neighbors: if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is not None: colors_found.add(grid[ny][nx]) return colors_found def pierre_feuille_ciseaux(player1, player2): choices = ["pierre", "feuille", "ciseaux"] choice1 = choices[random.randint(0, 2)] choice2 = choices[random.randint(0, 2)] print("Joueur", player1 + 1, ":", choice1) print("Joueur", player2 + 1, ":", choice2) if (choice1 == "pierre" and choice2 == "ciseaux") or (choice1 == "feuille" and choice2 == "pierre") or (choice1 == "ciseaux" and choice2 == "feuille"): return player1 if choice1 == choice2: return None return player2 def is_game_over(start_phase): if start_phase: return False for row in grid: if None in row: return False return True def count_pions(player): count = 0 for row in grid: for cell in row: if cell == player: count += 1 return count def play_game(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() pygame.display.set_caption("Jeu de connexion") initialize_grid() start_phase = True running = True game_over = False turn = 0 grid_x, grid_y = -1, -1 while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if grid_x != -1 and grid_y != -1: colors_found = check_neighbors(grid_x, grid_y, turn) if len(colors_found) == 2 and (grid[grid_y][grid_x] is None or len(check_neighbors(grid_x, grid_y, grid[grid_y][grid_x])) < 4): winner = pierre_feuille_ciseaux(list(colors_found)[0], list(colors_found)[1]) if winner is not None: print("Le gagnant est le joueur", winner + 1) change_pion(winner, grid_x, grid_y) expand_pions(turn) turn = (turn + 1) % len(player_colors) elif event.key == pygame.K_RETURN: turn = (turn + 1) % len(player_colors) elif event.key == pygame.K_RETURN: turn = (turn + 1) % len(player_colors) elif event.type == pygame.MOUSEBUTTONUP: x, y = pygame.mouse.get_pos() grid_x, grid_y = x // CELL_SIZE, y // CELL_SIZE if start_phase: if count_pions(turn) == 0: place_pion(turn, grid_x, grid_y) turn = (turn + 1) % len(player_colors) if count_pions(turn) == 1: start_phase = False turn = 0 screen.fill(WHITE) draw_grid(screen) pygame.display.flip() clock.tick(60) if not game_over and is_game_over(start_phase): winner = 0 if count_pions(0) > count_pions(1) else 1 print("Le joueur", winner + 1, "a gagné!") game_over = True pygame.quit() sys.exit() if __name__ == "__main__": play_game() File "/home/ludovic/Bureau/tricolor.py", line 129 elif event.type == pygame.KEYDOWN: ^^^^ SyntaxError: invalid syntax
139a36cdd4c65539aeee2e11ecf9dd69
{ "intermediate": 0.37892282009124756, "beginner": 0.44423094391822815, "expert": 0.17684626579284668 }
4,754
how to show images in python with pilliw
b4513b99e5f58f9a7daab6d54c21c5a3
{ "intermediate": 0.36934319138526917, "beginner": 0.13738925755023956, "expert": 0.4932675361633301 }
4,755
import random from PIL import Image # Define the artists and their monthly Spotify listeners artists = { '$NOT': {"image":"./fotos/$NOT_1.jpeg", "listeners": 7781046}, '21 Savage': {"image":"./fotos/21 Savage_1.jpeg", "listeners": 60358167}, '9lokknine': {"image":"./fotos/9lokknine_1.jpeg", "listeners": 1680245}, 'A Boogie Wit Da Hoodie': {"image":"./fotos/A Boogie Wit Da Hoodie_1.jpeg", "listeners": 18379137}, 'Ayo & Teo': {"image":"./fotos/Ayo & Teo_1.jpeg", "listeners": 1818645}, } while True: score = 0 # reset score at the beginning of each game first_artist, second_artist = random.sample(list(artists.keys()), 2) # Load the images for the artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) while True: # Display the images image.show(first_artist_image) image.show(second_artist_image) guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists[first_artist]["listeners"] > artists[second_artist]["listeners"]: print(f"You guessed correctly! {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists[second_artist]["listeners"] > artists[first_artist]["listeners"]: print(f"You guessed correctly! {second_artist.title()} had {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() else: score = 0 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) break why doesnt the game open the images
aa00f3c42a6f391df54cf02ffa394cad
{ "intermediate": 0.26463058590888977, "beginner": 0.4730067551136017, "expert": 0.26236262917518616 }
4,756
hi there
e9c4f70dc12ff63ee2be30bf73ad70db
{ "intermediate": 0.32885003089904785, "beginner": 0.24785484373569489, "expert": 0.42329514026641846 }
4,757
lease create a website with reponsive nav bar , header and footer ,and 3 extra pages all these access through nav bar using html,css bootstrap, javascript
377d7740ab15f4ca07590fd453f5a1bd
{ "intermediate": 0.46432849764823914, "beginner": 0.21324092149734497, "expert": 0.3224306106567383 }
4,758
I am building a video game engine using Vulkan for graphics, Bullet for physics and C++ as the coding language. I have a Terrain class that is used to create procedural terrain. The terrain outputs a vector of vertices and a vector of indices. I will also extend this to include a vector to indicate different texture mapping. I will also be importing models using the Assimp library. I want to create a Mesh class that will hold both the terrain and Assimp model meshes that will work with both Bullet and Vulkan. How should I structure this class?
9b31942bc2cd6f3fe523983c97a5895c
{ "intermediate": 0.6805517077445984, "beginner": 0.20185589790344238, "expert": 0.11759237200021744 }
4,759
WARNING:tensorflow:From C:\Anaconda3\envs\tfgpu36\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.cast instead.
f7c3f599832b8945efb4d351fe7f4166
{ "intermediate": 0.39297184348106384, "beginner": 0.17475882172584534, "expert": 0.4322693347930908 }
4,760
Я передаю массив словарей в jinja. {%- for homework in user.return_my_homework(): %} {% if homework['status_of_homework']=="Сдано,ждет проверки" or homework['status_of_homework']=="Ждет проверки": %} <div class="wait_works my-4"> <div class="wait_work"> <div class="wait_work_title"> {% elif homework['status_of_homework'] == "Сдано": %} <div class="done_works my-4"> <div class="done_work"> <div class="done_work_title"> {% else %} <div class="not_works my-4"> <div class="not_work"> <div class="not_work_title"> {% endif %} <a href="/homework/?id_of_order={{homework['order_id']}}&student_id={{homework['student_id']}}"> <h3 class="has-text-weight-bold is-size-5">{{homework['name_of_order']}}</h3> </a> <p>Дата сдачи: {{homework['date_of_delivery']}}</p> </div> {% if homework['status_of_homework']=="Сдано,ждет проверки" or homework['status_of_homework']=="Ждет проверки": %} <div class="wait_work_subtitle my-4"> {% elif homework['status_of_homework'] == "Сдано": %} <div class="done_work_subtitle my-4"> {% else %} <div class="not_work_subtitle my-4"> {% endif %} <h5 class="has-text-weight-bold is-size-6">{{homework['status_of_homework']}}</h5> <p>кому: {{homework['name']}}</p> </div> <div class="done_work_down"> <div class="trigger"> <div class="trigger_text"> <a href="#" class="is-size-6 has-text-weight-bold content_toggle_1" id="pk">Показать теги</a> <!-- <p class="is-size-6">Оценка: 4</p>---> {% if homework['status_of_homework']!="Не сдано": %} <a href="https://hot_data_kuzovkin_info_private.hb.bizmrg.com/{{homework['url_of_solution']}}">отправленное ДЗ в PDF</a> {%- endif %} </div> <div class="secret" style="display: none;"> <div class="done_work_btn" id="pk"> {%- for topic in homework['topics']%} <button class="button is-link is-rounded teg">#{{topic}}</button> {%- endfor %} </div> </div> </div> </div> </div> </div> {%- endfor %} Одна проблема,мне кажется,что данный код не оптимален. Как можно отрефакторить код?
60e7e0dac39c95de7bafebe062d171d0
{ "intermediate": 0.28039833903312683, "beginner": 0.6108720898628235, "expert": 0.1087295189499855 }
4,761
plz write c code to multiplication two big integer stored in double linked list and store the result at new double linked list
fa4aeb0b6b734c76479013bab23f6677
{ "intermediate": 0.4369336664676666, "beginner": 0.17834730446338654, "expert": 0.38471904397010803 }
4,762
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. How would I structure the code for this renderer?
f649802a5a52f4af07b636d1a0d32d55
{ "intermediate": 0.5227745771408081, "beginner": 0.30216842889785767, "expert": 0.17505697906017303 }
4,763
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. How would I structure the code for this renderer?
82aa1391a0cc887f7cb7fb28d9fb3f26
{ "intermediate": 0.5430936217308044, "beginner": 0.2615712285041809, "expert": 0.19533514976501465 }
4,764
hey
f532f4cd00788db2ec470eeeb8da2c8d
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
4,765
When I add the following code; If wscf = "ADH" Then MsgBox( "Go to the sheet") Workbook.Sheet ("ADH").Select Exit Sub, to the following code I get an error. Can you please show me how to add it. If Not Intersect(Target, Range("A2")) Is Nothing Then 'Currently in A2 Dim wscf As Worksheet Dim adminRequestCell As Range Dim answer As VbMsgBoxResult Set wscf = Worksheets(Range("I2").Value) Set adminRequestCell = wscf.UsedRange.Columns("B").Find("Admin Request", , xlValues, xlWhole, xlByColumns) Const ADMIN_REQUEST_EXISTS_MSG As String = "Admin Request has already been sent. Do you want to RE-SEND?" If Not adminRequestCell Is Nothing Then 'Admin Request Found answer = MsgBox(ADMIN_REQUEST_EXISTS_MSG, vbYesNo + vbQuestion, "Resend details") If answer = vbYes Then
881ed5b18de6fb6eacef0628e9c497c8
{ "intermediate": 0.4590122699737549, "beginner": 0.3950823247432709, "expert": 0.14590540528297424 }
4,766
this is my current code for an ide program: "import java.io.*; import java.util.*; public class AdminFile { private String hashedAdminPassword; public AdminFile() { try { // Read the hashed admin password from the admin.txt file BufferedReader reader = new BufferedReader(new FileReader("admin.txt")); hashedAdminPassword = reader.readLine(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (Utility.checkPassword(password, hashedAdminPassword)) { // Use Utility.checkPassword() with the hashedAdminPassword return; } else { System.out.println("Incorrect password!"); } } } public static void main(String[] args) { try { File file = new File("admin.txt"); if (!file.exists()) { FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Username: admin"); bufferedWriter.newLine(); bufferedWriter.write("Password: admin"); bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } import java.util.*; import java.io.*; public class AdminModule { private ArrayList<Player> players; private final String PLAYERS_FILENAME = "players.bin"; public AdminModule() { players = new ArrayList<Player>(); loadPlayers(); } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (password.equals("password1")) { return; }else { System.out.println("Incorrect password!"); } } } private void loadPlayers() { try { FileInputStream file = new FileInputStream(PLAYERS_FILENAME); ObjectInputStream output = new ObjectInputStream(file); boolean endOfFile = false; while(!endOfFile) { try { Player player = (Player)output.readObject(); players.add(player); }catch(EOFException ex) { endOfFile = true; } } }catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException"); }catch(FileNotFoundException ex) { System.out.println("FileNotFoundException"); }catch(IOException ex) { System.out.println("IOException"); } System.out.println("Players information loaded"); } private void displayPlayers() { for(Player player: players) { player.display(); } } private void updatePlayersChip() { String playerName = Keyboard.readString("Enter the login name of the player to issue chips to: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } int chips = Keyboard.readInt("Enter the number of chips to issue: "); player.addChips(chips); System.out.println("Chips issued"); } private void createNewPlayer() { String playerName = Keyboard.readString("Enter new player name: "); if (getPlayerName(playerName) != null) { System.out.println("Error: a player with that name already exists"); return; } String password = Keyboard.readString("Enter new password: "); String passwordHashed = Utility.getHash(password); Player player = new Player(playerName,passwordHashed, 100); players.add(player); System.out.println("Player created"); } private void savePlayersToBin() { try { FileOutputStream file = new FileOutputStream(PLAYERS_FILENAME); ObjectOutputStream opStream = new ObjectOutputStream(file); for(Player player: players) { opStream.writeObject(player); } opStream.close(); }catch(IOException ex) { System.out.println("Failed to save players"); } } private void deletePlayer() { String playerName = Keyboard.readString("Enter player name to delete: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } players.remove(player); System.out.println("Player deleted"); } private Player getPlayerName(String playerName) { for (Player player: players) { if (player.getLoginName().equals(playerName)) { return player; } } return null; } private void resetPlayerPassword() { String playerName = Keyboard.readString("Enter player name to reset the password for: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } String newPassword = Keyboard.readString("Enter the new password: "); String passwordHashed = Utility.getHash(newPassword); player.setHashPassword(passwordHashed); System.out.println("Password reset"); } private void changeAdminPassword() { String currentPassword = Keyboard.readString("Enter current admin password: "); if (!Utility.checkPassword(currentPassword)) { // Use Utility.checkPassword() instead of User.checkPassword() System.out.println("Error: incorrect password"); return; } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { // Update the admin.txt file with the new hashed password FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(passwordHashed); bufferedWriter.close(); } catch (IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { FileOutputStream file = new FileOutputStream("admin.txt"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(passwordHashed); opStream.close(); }catch(IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } public void logout() { System.out.println("Logging out...Goodbye"); } public void run() { login(); displayPlayers(); createNewPlayer(); displayPlayers(); deletePlayer(); displayPlayers(); updatePlayersChip(); displayPlayers(); resetPlayerPassword(); displayPlayers(); //savePlayersToBin(); logout(); } public static void main(String[] args) { // TODO Auto-generated method stub new AdminModule().run(); } } public class Card { private String suit; private String name; private int value; private boolean hidden; public Card(String suit, String name, int value) { this.suit = suit; this.name = name; this.value = value; this.hidden = false; // Change this line to make cards revealed by default } public int getValue() { return value; } public void reveal() { this.hidden = false; } public boolean isHidden() { return hidden; } @Override public String toString() { return this.hidden ? "<HIDDEN CARD>" : "<" + this.suit + " " + this.name + ">"; } public static void main(String[] args) { Card card = new Card("Heart", "Ace", 1); System.out.println(card); } public void hide() { this.hidden = true; } } import java.io.*; public class CreatePlayersBin { public static void main(String[] args) { // TODO Auto-generated method stub Player player1 = new Player("Player1", "Password1", 100); Player player2 = new Player("Player2", "Password2", 200); Player player3 = new Player("Player3", "Password3", 300); try { FileOutputStream file = new FileOutputStream("players.bin"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(player1); opStream.writeObject(player2); opStream.writeObject(player3); opStream.close(); }catch(IOException ex) { } } } public class Dealer extends Player { public Dealer() { super("Dealer", "", 0); } @Override public void addCard(Card card) { super.addCard(card); // Hide only the first card for the dealer if (cardsOnHand.size() == 1) { cardsOnHand.get(0).hide(); } } @Override public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { System.out.print(cardsOnHand.get(i)); if (i < numCards - 1) { System.out.print(", "); } } System.out.println("\n"); } public void revealHiddenCard() { if (!cardsOnHand.isEmpty()) { cardsOnHand.get(0).reveal(); } } } import java.util.ArrayList; import java.util.Random; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = {"Heart", "Diamond", "Spade", "Club"}; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1); cards.add(card); for (int n = 2; n <= 10; n++) { Card aCard = new Card(suit, n + "", n); cards.add(aCard); } Card jackCard = new Card(suit, "Jack", 10); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10); cards.add(kingCard); } } public void shuffle() { Random random = new Random(); for (int i = 0; i < 1000; 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); } } public Card dealCard() { return cards.remove(0); } } import java.util.Scanner; import java.util.Random; public class GameModule { private static final int NUM_ROUNDS = 4; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("HighSum GAME"); System.out.println("================================================================================"); // Load players from the players.bin file ArrayList<Player> players = new ArrayList<Player>(); try { FileInputStream file = new FileInputStream("players.bin"); ObjectInputStream input = new ObjectInputStream(file); Player player; while ((player = (Player) input.readObject()) != null) { players.add(player); } input.close(); } catch (EOFException ex) { // End of file } catch (IOException | ClassNotFoundException ex) { ex.printStackTrace(); } String playerName = ""; String playerPassword = ""; boolean loggedIn = false; Player player = null; // Add user authentication while (!loggedIn) { playerName = Keyboard.readString("Enter Login name > "); playerPassword = Keyboard.readString("Enter Password > "); for (Player p : players) { if (p.getLoginName().equals(playerName) && p.checkPassword(playerPassword)) { loggedIn = true; player = p; break; } } if (!loggedIn) { System.out.println("Username or Password is incorrect. Please try again."); } } Player player = new Player(playerName, playerPassword, 100); Dealer dealer = new Dealer(); Deck deck = new Deck(); boolean nextGame = true; int betOnTable; boolean playerQuit = false; // Add this line // Add "HighSum GAME" text after logging in System.out.println("================================================================================"); System.out.println("HighSum GAME"); while (nextGame) { System.out.println("================================================================================"); System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game starts - Dealer shuffles deck."); deck.shuffle(); dealer.clearCardsOnHand(); player.clearCardsOnHand(); // Switch the order of dealer and player to deal cards to the dealer first for (int i = 0; i < 2; i++) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } betOnTable = 0; int round = 1; int dealerBet; while (round <= NUM_ROUNDS) { System.out.println("--------------------------------------------------------------------------------"); System.out.println("Dealer dealing cards - ROUND " + round); System.out.println("--------------------------------------------------------------------------------"); // Show dealer’s cards first, then player’s cards if (round == 2) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } dealer.showCardsOnHand(); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (round > 1) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } if (round == 4) { dealer.revealHiddenCard(); } if (round >= 2) { if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { boolean validChoice = false; while (!validChoice) { String prompt = (round == 2) ? "Do you want to follow? [Y/N]: " : "Player call, do you want to [C]all or [Q]uit?: "; String choice = Keyboard.readString(prompt).toLowerCase(); if (choice.equals("c") || choice.equals("y")) { validChoice = true; int playerBet = Keyboard.readInt("Player, state your bet > "); // Check for invalid bet conditions if (playerBet > 100) { System.out.println("Insufficient chips"); validChoice = false; } else if (playerBet <= 0) { System.out.println("Invalid bet"); validChoice = false; } else { betOnTable += playerBet; player.deductChips(playerBet); System.out.println("Player call, state bet: " + playerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else if (choice.equals("q") || choice.equals("n")) { validChoice = true; nextGame = false; round = NUM_ROUNDS + 1; playerQuit = true; // Add this line // Give all the current chips bet to the dealer and the dealer wins System.out.println("Since the player has quit, all the current chips bet goes to the dealer."); System.out.println("Dealer Wins"); break; } } } else { dealerBet = Math.min(new Random().nextInt(11), 10); betOnTable += dealerBet; System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else { dealerBet = 10; betOnTable += dealerBet; player.deductChips(dealerBet); System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } // Determine the winner after the game ends if (!playerQuit) { // Add this line System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game End - Dealer reveal hidden cards"); System.out.println("--------------------------------------------------------------------------------"); dealer.showCardsOnHand(); System.out.println("Value: " + dealer.getTotalCardsValue()); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { System.out.println(playerName + " Wins"); player.addChips(betOnTable); } else { System.out.println("Dealer Wins"); } System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("Dealer shuffles used cards and place behind the deck."); System.out.println("--------------------------------------------------------------------------------"); } // Add this line boolean valid = false; while (!valid) { String input = Keyboard.readString("Next Game? (Y/N) > ").toLowerCase(); if (input.equals("y")) { playerQuit = false; // Add this line nextGame = true; valid = true; } else if (input.equals("n")) { nextGame = false; valid = true; } else { System.out.println("*** Please enter Y or N "); } } } } } 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 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)); } } import java.util.ArrayList; 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 void addCard(Card card) { this.cardsOnHand.add(card); } public void display() { super.display(); System.out.println(this.chips); } public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { if (i < numCards - 1) { System.out.print(cardsOnHand.get(i) + ", "); } else { System.out.print(cardsOnHand.get(i)); } } System.out.println("\n"); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips += amount; } public void deductChips(int amount) { if (amount < chips) this.chips -= amount; } public int getTotalCardsValue() { int totalValue = 0; for (Card card : cardsOnHand) { totalValue += card.getValue(); } return totalValue; } public int getNumberOfCards() { return cardsOnHand.size(); } public void clearCardsOnHand() { cardsOnHand.clear(); } } import java.io.Serializable; abstract public class User implements Serializable { private static final long serialVersionUID = 1L; private String loginName; private String hashPassword; //plain password public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } public void display() { System.out.println(this.loginName+","+this.hashPassword); } } 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(""); } }" these are the requirements: " Develop a Java program for the HighSum game Administration module. Administration Module This module allows the administor to 1. Create a player 2. Delete a player 3. View all players 4. Issue more chips to a player 5. Reset player’s password 6. Change administrator’s password 7. Logout This module will have access to two files (admin.txt and players.bin) The first text file (admin.txt) contains the administrator hashed password (SHA-256). For example 0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e The second text file (players.bin) contains the following players object information in a binary serialized file. • Login Name • Password in SHA-256 • Chips Login Name Password in SHA-256 Chips BlackRanger 6cf615d5bcaac778352a8f1f3360d23f02f34ec182e259897fd6ce485d7870d4 1000 BlueKnight 5906ac361a137e2d286465cd6588ebb5ac3f5ae955001100bc41577c3d751764 1500 IcePeak b97873a40f73abedd8d685a7cd5e5f85e4a9cfb83eac26886640a0813850122b 100 GoldDigger 8b2c86ea9cf2ea4eb517fd1e06b74f399e7fec0fef92e3b482a6cf2e2b092023 2200 Game play module Modify Assignment 1 HighSum Game module such that the Player data is read from the binary file players.bin. And different players are able to login to the GameModule. You have to provide screen outputs to show the correct execution of your program according to the requirements stated. The required test runs are: • Admin login • Create a player • Delete a player • View all players • Issue more chips to a player • Reset player’s password • Change administrator’s password • Administrator login and logout to admin module using updated password. • Player login and logout to game module using updated password." there are 20 errors in the program, fix it: “Description Resource Path Location Type ArrayList cannot be resolved to a type GameModule.java /Assignment2/src line 14 Java Problem ArrayList cannot be resolved to a type GameModule.java /Assignment2/src line 14 Java Problem Duplicate local variable player GameModule.java /Assignment2/src line 52 Java Problem EOFException cannot be resolved to a type GameModule.java /Assignment2/src line 23 Java Problem FileInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 16 Java Problem FileInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 16 Java Problem IOException cannot be resolved to a type GameModule.java /Assignment2/src line 25 Java Problem No exception of type Object can be thrown; an exception type must be a subclass of Throwable GameModule.java /Assignment2/src line 25 Java Problem ObjectInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 17 Java Problem ObjectInputStream cannot be resolved to a type GameModule.java /Assignment2/src line 17 Java Problem Syntax error, insert “}” to complete ClassBody AdminModule.java /Assignment2/src line 183 Java Problem Syntax error on token “;”, { expected after this token AdminModule.java /Assignment2/src line 148 Java Problem Syntax error on token “}”, delete this token AdminModule.java /Assignment2/src line 158 Java Problem Syntax error on token “void”, record expected AdminModule.java /Assignment2/src line 160 Java Problem Syntax error on token “void”, record expected AdminModule.java /Assignment2/src line 164 Java Problem Syntax error on token “void”, record expected AdminModule.java /Assignment2/src line 179 Java Problem The method checkPassword(String, String) is undefined for the type Utility AdminFile.java /Assignment2/src line 22 Java Problem The method checkPassword(String) is undefined for the type Utility AdminModule.java /Assignment2/src line 129 Java Problem The method printStackTrace() is undefined for the type Object GameModule.java /Assignment2/src line 26 Java Problem The method setHashPassword(String) is undefined for the type Player AdminModule.java /Assignment2/src line 123 Java Problem ” check code for errors and make sure it works in the ide
89c820915e14fbb485869404fff23da8
{ "intermediate": 0.3041658103466034, "beginner": 0.5292981266975403, "expert": 0.1665360927581787 }
4,767
i want to make a gallery page that have a masonry layout one with some description of the image slides down from the bottom of the image as you over it and when you click on the image it opens up with a bunch or images inside with a carousel design. Condense the code into the smallest size possible and also dont use php. you can use html css and javascript. The gallery page should have a way to go to the home page
ad22d7ce317eb805ca3a4fa7d961589f
{ "intermediate": 0.37787988781929016, "beginner": 0.2718185782432556, "expert": 0.3503015637397766 }
4,768
<Link href="/update-env"> <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" style={{ marginTop: '28px', marginRight: '0px', position: 'sticky'}} > Bottone </button> </Link> </div> </div> <main className={styles.main}> <div className={styles.cloud}> <div ref={messageListRef} className={styles.messagelist}> {messages.map((message, index) => { let icon; let className; if (message.type === 'apiMessage') { icon = ( <Image key={index} src="/bot-image.png" alt="Euler" width="32" height="32" className={styles.boticon} priority /> ); className = styles.apimessage; } else { icon = ( <Image key={index} src="/usericon.png" alt="Io" width="32" height="32" className={styles.usericon} priority /> ); // The latest message sent by the user will be animated while waiting for a response className = voglio che il bottone si muova come messagelist
8916b0c01ab1d2863e9046787554cd86
{ "intermediate": 0.3209768235683441, "beginner": 0.4262431561946869, "expert": 0.2527800500392914 }
4,769
this is my current code for an ide program: "import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class AdminFile { private String hashedAdminPassword; public AdminFile() { try { // Read the hashed admin password from the admin.txt file BufferedReader reader = new BufferedReader(new FileReader("admin.txt")); hashedAdminPassword = reader.readLine(); reader.close(); } catch (IOException e) { e.printStackTrace(); } } public void login() { System.out.println("Welcome Admin"); String password = Keyboard.readString("Enter password: "); while (true) { if (Utility.checkPassword(password, hashedAdminPassword)) { // Use Utility.checkPassword() with the hashedAdminPassword return; } else { System.out.println("Incorrect password!"); password = Keyboard.readString("Enter password: "); } } } public static void main(String[] args) { try { File file = new File("admin.txt"); if (!file.exists()) { FileWriter writer = new FileWriter("admin.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Username: admin"); bufferedWriter.newLine(); bufferedWriter.write("Password: admin"); bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } } import java.util.*; import java.io.*; public class AdminModule { private ArrayList<Player> players; private final String PLAYERS_FILENAME = "players.bin"; public AdminModule() { players = new ArrayList<Player>(); loadPlayers(); } public void login() { System.out.println("Welcome Admin"); try { File file = new File("admin.txt"); Scanner reader = new Scanner(file); while(reader.hasNextLine()) { String line = reader.nextLine(); System.out.println("Password: "+line); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("Players information loaded"); } private void loadPlayers() { try { FileInputStream file = new FileInputStream(PLAYERS_FILENAME); ObjectInputStream output = new ObjectInputStream(file); boolean endOfFile = false; while(!endOfFile) { try { Player player = (Player)output.readObject(); players.add(player); }catch(EOFException ex) { endOfFile = true; } } }catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException"); }catch(FileNotFoundException ex) { System.out.println("FileNotFoundException"); }catch(IOException ex) { System.out.println("IOException"); } } private void displayPlayers() { for(Player player: players) { player.display(); } } private void updatePlayersChip() { String playerName = Keyboard.readString("Issuing chips, please enter the player name to issue chips to: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } int chips = Keyboard.readInt("Enter the number of chips to issue: "); player.addChips(chips); System.out.println("Chips issued"); } private void createNewPlayer() { String playerName = Keyboard.readString("Creating a new player, please enter new player name: "); if (getPlayerName(playerName) != null) { System.out.println("Error: a player with that name already exists"); return; } String password = Keyboard.readString("Enter new password: "); String passwordHashed = Utility.getHash(password); Player player = new Player(playerName,passwordHashed, 100); players.add(player); System.out.println("Player created"); } private void savePlayersToBin() { try { FileOutputStream file = new FileOutputStream(PLAYERS_FILENAME); ObjectOutputStream opStream = new ObjectOutputStream(file); for(Player player: players) { opStream.writeObject(player); } opStream.close(); }catch(IOException ex) { System.out.println("Failed to save players"); } } private void deletePlayer() { String playerName = Keyboard.readString("Deleting a player, please enter player name to delete: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } players.remove(player); System.out.println("Player deleted"); } private Player getPlayerName(String playerName) { for (Player player: players) { if (player.getLoginName().equals(playerName)) { return player; } } return null; } private void resetPlayerPassword() { String playerName = Keyboard.readString("Resetting player password, please enter player name to reset the password for: "); Player player = getPlayerName(playerName); if (player == null) { System.out.println("Error: no player with that name exists"); return; } String newPassword = Keyboard.readString("Enter the new password: "); String passwordHashed = Utility.getHash(newPassword); player.setHashPassword(passwordHashed); System.out.println("Password reset"); } private void changeAdminPassword() { String currentPassword = Keyboard.readString("Resetting admin password, please enter current admin password: "); if (!"password1".equals(currentPassword)) { System.out.println("Error: incorrect password"); return; } String newPassword = Keyboard.readString("Enter new admin password: "); String passwordHashed = Utility.getHash(newPassword); try { FileOutputStream file = new FileOutputStream("admin.txt"); PrintWriter pw = new PrintWriter(file); pw.write(passwordHashed); pw.close(); }catch(IOException ex) { System.out.println("Failed to save password"); } System.out.println("Admin password changed"); } public void logout() { System.out.println("Logging out...Goodbye"); } public void run() { login(); displayPlayers(); createNewPlayer(); displayPlayers(); deletePlayer(); displayPlayers(); updatePlayersChip(); displayPlayers(); resetPlayerPassword(); displayPlayers(); changeAdminPassword(); savePlayersToBin(); logout(); } public static void main(String[] args) { // TODO Auto-generated method stub new AdminModule().run(); } } public class Card { private String suit; private String name; private int value; private boolean hidden; public Card(String suit, String name, int value) { this.suit = suit; this.name = name; this.value = value; this.hidden = false; // Change this line to make cards revealed by default } public int getValue() { return value; } public void reveal() { this.hidden = false; } public boolean isHidden() { return hidden; } @Override public String toString() { return this.hidden ? "<HIDDEN CARD>" : "<" + this.suit + " " + this.name + ">"; } public static void main(String[] args) { Card card = new Card("Heart", "Ace", 1); System.out.println(card); } public void hide() { this.hidden = true; } } import java.io.*; public class CreatePlayersBin { public static void main(String[] args) { // TODO Auto-generated method stub Player player1 = new Player("BlackRanger", "password2", 1000); Player player2 = new Player("BlueKnight", "password3", 1500); Player player3 = new Player("IcePeak", "password4", 100); Player player4 = new Player("GoldDigger", "password5", 2200); try { FileOutputStream file = new FileOutputStream("players.bin"); ObjectOutputStream opStream = new ObjectOutputStream(file); opStream.writeObject(player1); opStream.writeObject(player2); opStream.writeObject(player3); opStream.writeObject(player4); opStream.close(); }catch(IOException ex) { } } } public class Dealer extends Player { public Dealer() { super("Dealer", "", 0); } @Override public void addCard(Card card) { super.addCard(card); // Hide only the first card for the dealer if (cardsOnHand.size() == 1) { cardsOnHand.get(0).hide(); } } @Override public void showCardsOnHand() { System.out.println(getLoginName()); int numCards = cardsOnHand.size(); for (int i = 0; i < numCards; i++) { System.out.print(cardsOnHand.get(i)); if (i < numCards - 1) { System.out.print(", "); } } System.out.println("\n"); } public void revealHiddenCard() { if (!cardsOnHand.isEmpty()) { cardsOnHand.get(0).reveal(); } } } import java.util.ArrayList; import java.util.Random; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = {"Heart", "Diamond", "Spade", "Club"}; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1); cards.add(card); for (int n = 2; n <= 10; n++) { Card aCard = new Card(suit, n + "", n); cards.add(aCard); } Card jackCard = new Card(suit, "Jack", 10); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10); cards.add(kingCard); } } public void shuffle() { Random random = new Random(); for (int i = 0; i < 1000; 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); } } public Card dealCard() { return cards.remove(0); } } import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; public class GameModule { private static final int NUM_ROUNDS = 4; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("HighSum GAME"); System.out.println("================================================================================"); // Load players from the players.bin file ArrayList<Player> players = new ArrayList<Player>(); try { FileInputStream file = new FileInputStream("players.bin"); ObjectInputStream input = new ObjectInputStream(file); Player player; while ((player = (Player) input.readObject()) != null) { players.add(player); } input.close(); } catch (EOFException ex) { // End of file } catch (IOException | ClassNotFoundException ex) { System.out.println("Exception: " + ex.getMessage()); } String playerLoginName = ""; String playerPassword = ""; boolean loggedIn = false; Player player = null; // Add user authentication while (!loggedIn) { playerName = Keyboard.readString("Enter Login name > "); playerPassword = Keyboard.readString("Enter Password > "); for (Player p : players) { if (p.getLoginName().equals(playerLoginName) && p.checkPassword(playerPassword)) { loggedIn = true; player = p; break; } } if (!loggedIn) { System.out.println("Username or Password is incorrect. Please try again."); } } Player player = new Player(playerName, playerPassword, 100); Dealer dealer = new Dealer(); Deck deck = new Deck(); boolean nextGame = true; int betOnTable; boolean playerQuit = false; // Add this line // Add "HighSum GAME" text after logging in System.out.println("================================================================================"); System.out.println("HighSum GAME"); while (nextGame) { System.out.println("================================================================================"); System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game starts - Dealer shuffles deck."); deck.shuffle(); dealer.clearCardsOnHand(); player.clearCardsOnHand(); // Switch the order of dealer and player to deal cards to the dealer first for (int i = 0; i < 2; i++) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } betOnTable = 0; int round = 1; int dealerBet; while (round <= NUM_ROUNDS) { System.out.println("--------------------------------------------------------------------------------"); System.out.println("Dealer dealing cards - ROUND " + round); System.out.println("--------------------------------------------------------------------------------"); // Show dealer’s cards first, then player’s cards if (round == 2) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } dealer.showCardsOnHand(); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (round > 1) { dealer.addCard(deck.dealCard()); player.addCard(deck.dealCard()); } if (round == 4) { dealer.revealHiddenCard(); } if (round >= 2) { if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { boolean validChoice = false; while (!validChoice) { String prompt = (round == 2) ? "Do you want to follow? [Y/N]: " : "Player call, do you want to [C]all or [Q]uit?: "; String choice = Keyboard.readString(prompt).toLowerCase(); if (choice.equals("c") || choice.equals("y")) { validChoice = true; int playerBet = Keyboard.readInt("Player, state your bet > "); // Check for invalid bet conditions if (playerBet > 100) { System.out.println("Insufficient chips"); validChoice = false; } else if (playerBet <= 0) { System.out.println("Invalid bet"); validChoice = false; } else { betOnTable += playerBet; player.deductChips(playerBet); System.out.println("Player call, state bet: " + playerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else if (choice.equals("q") || choice.equals("n")) { validChoice = true; nextGame = false; round = NUM_ROUNDS + 1; playerQuit = true; // Add this line // Give all the current chips bet to the dealer and the dealer wins System.out.println("Since the player has quit, all the current chips bet goes to the dealer."); System.out.println("Dealer Wins"); break; } } } else { dealerBet = Math.min(new Random().nextInt(11), 10); betOnTable += dealerBet; System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } else { dealerBet = 10; betOnTable += dealerBet; player.deductChips(dealerBet); System.out.println("Dealer call, state bet: " + dealerBet); System.out.println(playerName + ", You are left with " + player.getChips() + " chips"); System.out.println("Bet on table: " + betOnTable); round++; } } // Determine the winner after the game ends if (!playerQuit) { // Add this line System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game End - Dealer reveal hidden cards"); System.out.println("--------------------------------------------------------------------------------"); dealer.showCardsOnHand(); System.out.println("Value: " + dealer.getTotalCardsValue()); player.showCardsOnHand(); System.out.println("Value: " + player.getTotalCardsValue()); if (player.getTotalCardsValue() > dealer.getTotalCardsValue()) { System.out.println(playerName + " Wins"); player.addChips(betOnTable); } else { System.out.println("Dealer Wins"); } System.out.println(playerName + ", You have " + player.getChips() + " chips"); System.out.println("Dealer shuffles used cards and place behind the deck."); System.out.println("--------------------------------------------------------------------------------"); } // Add this line boolean valid = false; while (!valid) { String input = Keyboard.readString("Next Game? (Y/N) > ").toLowerCase(); if (input.equals("y")) { playerQuit = false; // Add this line nextGame = true; valid = true; } else if (input.equals("n")) { nextGame = false; valid = true; } else { System.out.println("*** Please enter Y or N "); } } } } } 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 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)); } } 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 void addCard(Card card) { this.cardsOnHand.add(card); } public void showCardsOnHand() { System.out.println(getLoginName()); for(Card card:this.cardsOnHand) { System.out.print(card+" "); } System.out.println(); } public ArrayList<Card> getCardsOnHand() { return cardsOnHand; } 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 showTotalCardsValue() { System.out.println("Value:"+getTotalCardsValue()); } public int getTotalCardsValue() { int total = 0; for(Card card:cardsOnHand) { total+=card.getValue(); } return total; } public void display() { super.display(); System.out.println(this.chips); } public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","password",100); Deck deck = new Deck(); deck.shuffle(); Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); player.addCard(card1); player.addCard(card2); player.showCardsOnHand(); player.showTotalCardsValue(); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } import java.io.Serializable; abstract public class User implements Serializable { private static final long serialVersionUID = 1L; private String loginName; private String hashPassword; //plain password public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } public void display() { System.out.println(this.loginName+","+this.hashPassword); } } 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(""); } }" these are the requirements: " Develop a Java program for the HighSum game Administration module. Administration Module This module allows the administor to 1. Create a player 2. Delete a player 3. View all players 4. Issue more chips to a player 5. Reset player’s password 6. Change administrator’s password 7. Logout This module will have access to two files (admin.txt and players.bin) The first text file (admin.txt) contains the administrator hashed password (SHA-256). For example 0b14d501a594442a01c6859541bcb3e8164d183d32937b851835442f69d5c94e The second text file (players.bin) contains the following players object information in a binary serialized file. • Login Name • Password in SHA-256 • Chips Login Name Password in SHA-256 Chips BlackRanger 6cf615d5bcaac778352a8f1f3360d23f02f34ec182e259897fd6ce485d7870d4 1000 BlueKnight 5906ac361a137e2d286465cd6588ebb5ac3f5ae955001100bc41577c3d751764 1500 IcePeak b97873a40f73abedd8d685a7cd5e5f85e4a9cfb83eac26886640a0813850122b 100 GoldDigger 8b2c86ea9cf2ea4eb517fd1e06b74f399e7fec0fef92e3b482a6cf2e2b092023 2200 Game play module Modify Assignment 1 HighSum Game module such that the Player data is read from the binary file players.bin. And different players are able to login to the GameModule. You have to provide screen outputs to show the correct execution of your program according to the requirements stated. The required test runs are: • Admin login • Create a player • Delete a player • View all players • Issue more chips to a player • Reset player’s password • Change administrator’s password • Administrator login and logout to admin module using updated password. • Player login and logout to game module using updated password." there are errors in the program, fix it: “Description Resource Path Location Type Duplicate local variable player GameModule.java /Assignment2/src line 55 Java Problem File cannot be resolved to a type AdminFile.java /Assignment2/src line 37 Java Problem File cannot be resolved to a type AdminFile.java /Assignment2/src line 37 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 39 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 55 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 70 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 133 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 153 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 162 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 178 Java Problem playerName cannot be resolved to a variable GameModule.java /Assignment2/src line 183 Java Problem Random cannot be resolved to a type GameModule.java /Assignment2/src line 150 Java Problem Scanner cannot be resolved to a type GameModule.java /Assignment2/src line 11 Java Problem Scanner cannot be resolved to a type GameModule.java /Assignment2/src line 11 Java Problem The method checkPassword(String, String) is undefined for the type Utility AdminFile.java /Assignment2/src line 26 Java Problem The method clearCardsOnHand() is undefined for the type Dealer GameModule.java /Assignment2/src line 75 Java Problem The method clearCardsOnHand() is undefined for the type Player GameModule.java /Assignment2/src line 76 Java Problem The method setHashPassword(String) is undefined for the type Player AdminModule.java /Assignment2/src line 127 Java Problem ” check code for errors and make sure it works in the ide
08a1d3f15d5007cbcdcb100ba1a95d92
{ "intermediate": 0.33586061000823975, "beginner": 0.5078426003456116, "expert": 0.15629683434963226 }
4,770
Can you write a quad mesh generator that rights quads in two triangles that form together to make a quad, in Godot 4 and GDscript
76eaf4ba3fe8e7042745b5a5efab2047
{ "intermediate": 0.46314650774002075, "beginner": 0.14419807493686676, "expert": 0.3926553726196289 }
4,771
use class or function in javascript Advantages and disadvantages
54d092a732bc7ff9f5a04b6348ff831f
{ "intermediate": 0.2338179498910904, "beginner": 0.6238510012626648, "expert": 0.142331063747406 }
4,772
I need a round robin for a pool of 6 with teams also dutying matches. If possible would like to keep the number of duties equal and where possible try not to schedule a team's duty directly before their match
a7c39d710fcd7faea107f957ff35f398
{ "intermediate": 0.34452638030052185, "beginner": 0.2932087481021881, "expert": 0.36226481199264526 }
4,773
Here is one topic from the JavaScript tutorial. History of JavaScript JavaScript language comes from the times when early web browsers were being developed. Netscape Communications company in 1994 created Netscape Navigator that became the most popular web browser in the 90s. Company’s board quickly realized that browsers should allow create more dynamic websites and do some activities that do server-side languages, like input validation. First Netscape Communications cooperate with Sun Microsystems to use in Netscape Navigator Sun’s programming language Java. Then they wanted adopting and embedding a existing programming language like Scheme, Perl or Python. Eventually they decided to create scripting language that would complement Java and has a similar syntax. In 1995 Netscape Communications employed Brendan Eich to develop scripting language for web browser. Eich prepared it in a very short time. First version of new language had Mocha name, whereas official version used in Netscape Navigator 2 beta version was called LiveScript. In the same 1995 year new developed scripting language was renamed to JavaScript and used in next beta version of Netscape Navigator 2. LiveScript followed a lot of Java features. This, but above all the desire to use the growing popularity of Java to call positive associations with a new language where reasons that it was finally called JavaScript. Also implementation of the language for server-side was introduced. JavaScript 1.0 was a success and helped Netscape Navigator’s to hold the leader position of the market. Soon JavaScript 1.1 was released in Netscape Navigator 3. In this time Microsoft to compete with Netscape decided to include scripting technologies in their browser. In 1996 they released Internet Explorer 3 with their own implementation of JavaScript called JScript. Since that time there were two versions of JavaScript. This brought a compatibility issues. Industry needs caused that decided to standardize language. Netscape submitted JavaScript to Ecma International to “standardize the syntax and semantics of a general purpose, cross-platform, vendor-neutral scripting language”. In 1997 was published the language specification called ECMAScript as a ECMA-262 standard. Other browser vendors could use this specification to prepare their implementation. In the following years, the development of JavaScript was continued and in cycles were released new versions of specification. Responsible for the development of JavaScript are Mozilla Fundation (which is successor of Netscape Navigator) and Ecma International. Based on this information create for quiz with 30 questions. Each question should have 4 different variants of answer. Multiple answers for one question can be correct. In the end, after the main quizz give me the correct answers
6acf0873e48f5f6dd3840815663c6e9c
{ "intermediate": 0.31933102011680603, "beginner": 0.42886069416999817, "expert": 0.2518082857131958 }
4,774
Design a web page using Java Script. Design a web page to implement calculator using JavaScript
a171f39e78707da496ad180b4273805e
{ "intermediate": 0.4117140769958496, "beginner": 0.3679887056350708, "expert": 0.220297172665596 }
4,775
pretend you are the perfect professor of mathematics and data science, and explain at length the "Prognostics Analytics" to a high school level student. Your explanation must make the high school student becomes a master "Prognostics Analytics"
ca3f0b3acd477bfcb777b52ee6154838
{ "intermediate": 0.2219267040491104, "beginner": 0.22670148313045502, "expert": 0.5513718128204346 }
4,776
how can I get an elements scrollY
6a41b8737f58381e4d2603f666abbcd2
{ "intermediate": 0.39129000902175903, "beginner": 0.23505185544490814, "expert": 0.37365809082984924 }
4,777
What's the best way to listen to a particle death event or collision event from c++ in UE5 GAS?
e4d345e203fbf45969b6a54600e23994
{ "intermediate": 0.5348108410835266, "beginner": 0.12284770607948303, "expert": 0.34234145283699036 }
4,778
Hello, I want to make my cord work with in a section, when I add: "overflow-y: scroll;" to the ".scroll-section" style, everything breaks and nothing works. That is because my code assumes the page to be full and works like that. However I want my code to work with in scroll-section's scrolling with setting overflow-y to scroll. Can you help me ? here is my code: "<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Smooth Scrolling</title> <style> .scroll-section { height: 100vh; scroll-snap-type: y mandatory; } .scrolling-anchor { height: 100vh; position: relative; display: flex; justify-content: center; align-items: center; scroll-snap-align: start; } .scrolling-anchor:not(:first-child)::before { content: ""; position: absolute; top: -10vh; left: 0; width: 100%; height: 10vh; background-color: rgba(255, 0, 0, 0.5); } .last{ height: 100vh; } </style> </head> <body> <div class="scroll-section"> <section class="scrolling-anchor" style="background-color: lightblue" ></section> <section class="scrolling-anchor" style="background-color: lightgreen" ></section> <section class="scrolling-anchor" style="background-color: lightyellow" ></section> </div> <div class="last"> </div> </body> </html> "
166908e60962c53944a4db3e2532e596
{ "intermediate": 0.4146168828010559, "beginner": 0.4096086919307709, "expert": 0.17577433586120605 }
4,779
Hello, I want to make my scrolling animation code work with in a section, when I add: "overflow-y: scroll;" to the ".scroll-section" style, everything breaks and nothing works. That is because my code assumes the page to be full and works like that. However I want my code to work with in scroll-section's scrolling with setting overflow-y to scroll. Can you help me ? The whole implementation might need adjusting and changing here is my code: "<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Smooth Scrolling</title> <style> .scroll-section { height: 100vh; scroll-snap-type: y mandatory; } .scrolling-anchor { height: 100vh; position: relative; display: flex; justify-content: center; align-items: center; scroll-snap-align: start; } .scrolling-anchor:not(:first-child)::before { content: ""; position: absolute; top: -10vh; left: 0; width: 100%; height: 10vh; background-color: rgba(255, 0, 0, 0.5); } .last{ height: 100vh; } </style> </head> <body> <div class="scroll-section"> <section class="scrolling-anchor" style="background-color: lightblue" ></section> <section class="scrolling-anchor" style="background-color: lightgreen" ></section> <section class="scrolling-anchor" style="background-color: lightyellow" ></section> </div> <div class="last"> </div> </body> </html> "
977a2219fb84dbedada5cfa95aaa2f95
{ "intermediate": 0.40735408663749695, "beginner": 0.398173451423645, "expert": 0.19447244703769684 }
4,780
исправь некоторые участки кода import logging import sqlite3 import telegram from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext logging.basicConfig(level=logging.INFO) bot = telegram.Bot(token='YOUR_BOT_TOKEN') API_TOKEN = 'YOUR_API_TOKEN' category_tables = { 'Кроссовки': 'items', 'Верхняя одежда': 'items1', 'Аксессуары': 'items2', } def start(update: Update, context: CallbackContext): keyboard = [ [InlineKeyboardButton(category, callback_data=category) for category in category_tables] ] reply_markup = InlineKeyboardMarkup(keyboard) if update.message: update.message.reply_text('Выберите категорию товара:', reply_markup=reply_markup) else: query = update.callback_query query.answer() query.edit_message_text('Выберите категорию товара:', reply_markup=reply_markup) def category_handler(update: Update, context: CallbackContext): query = update.callback_query category = query.data table = category_tables[category] conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name FROM {table}') items = c.fetchall() keyboard = [ [InlineKeyboardButton(items[i][0], callback_data=f'{table}{i}') for i in range(min(4, len(items)))] ] if len(items) > 4: keyboard.append([ InlineKeyboardButton('Вперед', callback_data=f'next{table}0_4') ]) reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text(f'Выберите товар ({category}):', reply_markup=reply_markup) def show_product(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split(' ') table = data[0] index = int(data[1]) conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name, size, info, price, photo_link FROM {table}') items = c.fetchall() item = items[index] text = f'Название: {item[0]}\nРазмер: {item[1]}\nОписание: {item[2]}\nЦена: {item[3]}\nСсылка на фото: {item[4]}' keyboard = [ [InlineKeyboardButton('Вернуться', callback_data=f'back_{table}')] ] reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text(text=text, reply_markup=reply_markup) def change_page(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split(' ') action = data[0] table = data[1] start_index = int(data[2]) end_index = int(data[3]) conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name FROM {table}') items = c.fetchall() prev_start = max(0, start_index - 4) prev_end = start_index next_start = end_index next_end = min(end_index + 4, len(items)) if action == 'next': start_index = next_start end_index = next_end def show_product(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split(‘‘) table = data[0] index = int(data[1]) conn = sqlite3.connect(‘kross.db’) c = conn.cursor() c.execute(f’SELECT name, size, info, price, photo_link FROM {table}’) items = c.fetchall() item = items[index] text = f’Название: {item[0]}\nРазмер: {item[1]}\nОписание: {item[2]}\nЦена: {item[3]}\nСсылка на фото: {item[4]}‘ keyboard = [ [InlineKeyboardButton(‘Вернуться’, callback_data=f’back_{table}’)] ] reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text(text=text, reply_markup=reply_markup) def back_button_handler(update: Update, context: CallbackContext): query = update.callback_query table = query.data.split(‘‘)[1] # отображаем клавиатуру выбора товара for category, tbl in category_tables.items(): if tbl == table: query.data = category category_handler(update, context) break def main(): updater = Updater(API_TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler(‘start’, start)) for tbl in category_tables.values(): dp.add_handler(CallbackQueryHandler(show_product, pattern=f’^{tbl}\d+')) dp.add_handler(CallbackQueryHandler(change_page, pattern='^(prev|next)_[a-zA-Z0-9]+_( updater.idle() if name == 'main': main()
6dba242213447a9249e59c2e422acaf7
{ "intermediate": 0.3632790148258209, "beginner": 0.39277538657188416, "expert": 0.24394556879997253 }
4,781
When an excel sheet opens, I want a vba code to open a specific word document doc1 only if the values in the last row of column B and Column D are different. If the particular word document doc1 is left open the vba code should not attempt to open the already open document doc1 again. Only opening the word document doc1 if it is not or no longer open therefore only having one instance of the word document doc1. After finishing and closing the word document, I will manually enter a date in column E of the last row entry. After entering the date a differnet word document doc2 should open. While the word document doc2 is open, if I click on different cell in column E it should not attempt to open the already open document doc2 again. Only opening the word document doc2 if it is not or no longer open therefore only having one instance of the word document doc2. I also need a code that runs everytime I select or enter a value in a cell in Column E. I want the vba code to copy 10 values of 10 cells in the same row as the cell in column E I selected (B,C,D,E,F,G,H,I,J,L) and appended their values to column M in the following order M1 to M10. The values changing for every cell I select in column E and the values cleared when I also leave the sheet. The word document doc2 that is opened by activity on column E as mentioned above will capture data from colum M1 to M10. All these codes will by about 50 excel sheet for the same purpose. Can the codes be called from modules?
568cf2c485fc282fdc76e015d96fc586
{ "intermediate": 0.4635247588157654, "beginner": 0.2810766398906708, "expert": 0.25539860129356384 }
4,782
Can you provide code for a personal portfolio website using vuejs, vuetify and typescript?
208898a5e1c585ad081f167d99c69b36
{ "intermediate": 0.6651389002799988, "beginner": 0.23556193709373474, "expert": 0.09929915517568588 }
4,783
write a code for DES Encryption from scratch in python
cb459db02044338ff056006702677a2b
{ "intermediate": 0.2303820252418518, "beginner": 0.1949746459722519, "expert": 0.5746432542800903 }
4,784
I am trying to convert my document scrolling animation code to animation with in a div with a class .scroll-section with "overflow-y: scroll". However simply putting overflow-y: scroll to the style of .scroll-section breaks my code. I need to adjust all the calculation accordingly. Can you analyze my code and understand it, then convert it to a scrolling animation with in a div instead of animation in the whole document. So currently it works perfectly but the scrolling happens in the document however the div with: " <div class="last"> </div>" is not visible, to make it visible the .scroll-section gets overflow-y set to scroll so things get aligned correctly. My main purpose here is to being able to create sections outside the scroll animation region. All functions need to be edited. Here is my code: "<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Smooth Scrolling</title> <style> .scroll-section { height: 100vh; } .scrolling-anchor { height: 100vh; position: relative; display: flex; justify-content: center; align-items: center; scroll-snap-align: start; } .scrolling-anchor:not(:first-child)::before { content: ""; position: absolute; top: -10vh; left: 0; width: 100%; height: 10vh; background-color: rgba(255, 0, 0, 0.5); } .last{ height: 100vh; } </style> </head> <body> <div class="scroll-section"> <section class="scrolling-anchor" style="background-color: lightblue" ></section> <section class="scrolling-anchor" style="background-color: lightgreen" ></section> <section class="scrolling-anchor" style="background-color: lightyellow" ></section> </div> <div class="last"> </div> <script> let handlingScroll = false; function normalizeDelta(delta) { return Math.sign(delta); } const getAnchorInDirection = (delta) => { const anchors = document.querySelectorAll(".scrolling-anchor"); const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let nextAnchorDistance = null; let anchorOffset = null; let signOfAnchor = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; if ( (delta > 0 && anchorOffset > scrollOffset) || (delta < 0 && anchorOffset < scrollOffset) ) { if ( nextAnchor === null || Math.abs(anchorOffset - scrollOffset) < Math.abs( nextAnchorOffset - scrollOffset ) ) { nextAnchor = anchor; nextAnchorOffset = anchorOffset; } } }); if(nextAnchor == null){ return false } return true } function onMouseWheel(event) { event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { handlingScroll = true; const normalizedDelta = normalizeDelta(event.deltaY); console.log("Mouse event fire to: ", normalizedDelta); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } } document.addEventListener("wheel", onMouseWheel, { passive: false, }); // Handle keydown events const scrollKeys = [32, 33, 34, 35, 36, 37, 38, 39, 40, 107, 109]; function onKeyDown(event) { console.log("son key basmalar"); event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { if (scrollKeys.includes(event.keyCode)) { handlingScroll = true; const deltaY = event.keyCode === 38 || event.keyCode === 107 || event.keyCode === 36 ? -1 : 1; if(!getAnchorInDirection(deltaY)){ handlingScroll = false }else{ document.documentElement.scrollTop += deltaY; } console.log("son key basma scrolla yollama", deltaY); } } } document.addEventListener("keydown", onKeyDown); function onTouchStart(event) { if (!scrolling == true && !handlingScroll == true) { if (event.touches.length === 1) { startY = event.touches[0].pageY; } } } function onTouchMove(event) { event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { if (event.touches.length === 1) { handlingScroll = true; const deltaY = startY - event.touches[0].pageY; const normalizedDelta = normalizeDelta(deltaY); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } } } let startY; document.addEventListener("touchstart", onTouchStart, { passive: false, }); document.addEventListener("touchmove", onTouchMove, { passive: false, }); function onGamepadConnected(event) { const gamepad = event.gamepad; gamepadLoop(gamepad); } let holdingScrollBar = false function gamepadLoop(gamepad) { if (!scrolling == true && !handlingScroll == true) { handlingScroll = true; const axes = gamepad.axes; const deltaY = axes[1]; if (Math.abs(deltaY) > 0.5) { const normalizedDelta = normalizeDelta(deltaY); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } requestAnimationFrame(() => gamepadLoop(gamepad)); } } function clickedOnScrollBar(mouseX){ console.log("click", window.outerWidth, mouseX) if(document.body.clientWidth <= mouseX){ return true; } return false } document.addEventListener("mousedown",(e) => { console.log("down", clickedOnScrollBar(e.clientX), " : ", holdingScrollBar) if(clickedOnScrollBar(e.clientX)){ holdingScrollBar = true } }) document.addEventListener("mouseup",(e) => { console.log("up", holdingScrollBar) if(holdingScrollBar){ scrolling = false; handlingScroll = false; oldScroll = window.scrollY; const anchors = document.querySelectorAll(".scrolling-anchor"); const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let nextAnchorDistance = null; let anchorOffset = null; let signOfAnchor = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; let distanceToAnchor = Math.abs( anchorOffset - scrollOffset ); if(nextAnchorDistance == null){ nextAnchorDistance=distanceToAnchor; signOfAnchor = normalizeDelta(anchorOffset - scrollOffset); }else if(distanceToAnchor<nextAnchorDistance){ nextAnchorDistance = distanceToAnchor; signOfAnchor = normalizeDelta(anchorOffset - scrollOffset); } }); document.documentElement.scrollTop += signOfAnchor; holdingScrollBar = false; } }) window.addEventListener("gamepadconnected", onGamepadConnected); const section = document.querySelector(".scroll-section"); const anchors = document.querySelectorAll(".scrolling-anchor"); let lastDirection = 0; let scrolling = false; let cancelScroll = false; // Listen for the event. section.addEventListener( "custom-scroll", (e) => { /* … */ }, false ); oldScroll = 0; document.addEventListener("scroll", (event) => { event.preventDefault(); console.log("son dürümler 1"); if (scrolling) { const delta = this.oldScroll >= this.scrollY ? -1 : 1; if (lastDirection !== 0 && lastDirection !== delta) { cancelScroll = true; console.log("Cancel Scrolling"); console.log( scrolling, delta, this.oldScroll, this.scrollY ); } //console.log("Scrolling"); return; } else { /*var event = new CustomEvent("custom-scroll", { detail: { custom_info: 10, custom_property: 20, }, }); this.dispatchEvent(event);*/ const animF = (now) => { const delta = this.oldScroll > this.scrollY ? -1 : 1; console.log( "scrolling: ", scrolling, ", scroll to: ", delta ); //console.log(":", this.oldScroll, this.scrollY); lastDirection = delta; const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let anchorOffset = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; if ( (delta > 0 && anchorOffset > scrollOffset) || (delta < 0 && anchorOffset < scrollOffset) ) { if ( nextAnchor === null || Math.abs(anchorOffset - scrollOffset) < Math.abs( nextAnchorOffset - scrollOffset ) ) { nextAnchor = anchor; nextAnchorOffset = anchorOffset; } } }); console.log(nextAnchor); if (nextAnchor !== null) { const distanceToAnchor = Math.abs( nextAnchorOffset - scrollOffset ); //console.log( // nextAnchorOffset, // scrollOffset, // distanceToAnchor //); const scrollLockDistance = 10; // vh const scrollLockPixels = (windowHeight * scrollLockDistance) / 100; if (distanceToAnchor <= scrollLockPixels) { console.log( "1", distanceToAnchor, scrollLockPixels, scrollOffset, "sonuc", "buldum next anchor", nextAnchorOffset, "anchorun offset", anchorOffset, "ben burda", window.scrollY ); scrolling = true; scrollLastBit( nextAnchorOffset, distanceToAnchor, true, delta ); } else { const freeScrollValue = distanceToAnchor - scrollLockPixels; const newScrollOffset = scrollOffset + delta * freeScrollValue; console.log( "2", distanceToAnchor, scrollLockPixels, freeScrollValue, scrollOffset, "sonuc", newScrollOffset, "buldum next anchor", nextAnchorOffset, "anchorun offset", anchorOffset, "ben burda", window.scrollY ); scrolling = true; scrollToAnchor( newScrollOffset, freeScrollValue, false, () => { scrollLastBit( nextAnchorOffset, scrollLockPixels, true, delta ); } ); } } }; requestAnimationFrame(animF); } }); function scrollLastBit(offset, distance, braking, direction) { console.log("scroll bit anim başladı"); offset = Math.round(offset); distance = Math.round(distance); const start = window.pageYOffset; const startTime = performance.now(); //console.log(offset, distance); const scrollDuration = braking ? distance * 10 : distance * 2; let endTick = false; if (offset == window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; cancelScroll = false; console.log("doğmadan öldüm ben", offset, window.scrollY); return; } let difference = Math.abs(window.scrollY - offset); const tick = (now) => { if(cancelScroll){ console.log("animasyon iptal"); lastDirection = 0; cancelScroll = false; }else{ console.log("scroll bit anim devam ediyor"); console.log( "kilidim: ", scrolling, " tuş kildim", handlingScroll ); if (Math.abs(window.scrollY - offset) > difference) { // Baba error diğer tarafa tıklayınca, 1 birim uzaklaşma olduğu için animasyonu bitirip diğer tarafa başlıyor. //scrolling = false; //handlingScroll = false; //oldScroll = window.scrollY; console.log("Baba error, uzaklaştı"); difference = Math.abs(window.scrollY - offset); requestAnimationFrame(tick); } else { difference = Math.abs(window.scrollY - offset); console.log(endTick); console.log( offset == window.scrollY, offset, window.scrollY ); if (endTick) { //console.log(offset, window.scrollY); if (direction < 0) { if (offset >= window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; cancelScroll = false; oldScroll = window.scrollY; console.log( "öldüm ben", offset, window.scrollY ); } else { requestAnimationFrame(tick); } } else { if (offset <= window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; console.log( "öldüm ben", offset, window.scrollY ); } else { requestAnimationFrame(tick); } } } else { const elapsed = now - startTime; const fraction = elapsed / scrollDuration; //console.log(elapsed, fraction); if (fraction < 1) { const easeOut = braking ? -Math.pow(2, -10 * fraction) + 1 : fraction; window.scrollTo( 0, start + (offset - start) * easeOut ); requestAnimationFrame(tick); } else { window.scrollTo(0, offset); endTick = true; requestAnimationFrame(tick); } } } } }; //console.log("requestAnimationFrame"); requestAnimationFrame(tick); } function scrollToAnchor( offset, distance, braking, callback = null ) { if (offset == window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; cancelScroll = false; console.log("doğmadan öldüm ben", offset, window.scrollY); return; } console.log("scroll to anchor anim başladı"); offset = Math.round(offset); distance = Math.round(distance); const start = window.pageYOffset; const startTime = performance.now(); //console.log(offset, distance); const scrollDuration = braking ? distance * 10 : distance * 2; let difference = Math.abs(window.scrollY - offset); const tick = (now) => { if(cancelScroll){ console.log("animasyon iptal"); lastDirection = 0; cancelScroll = false; }else{ console.log("scroll to anchor anim devam ediyor"); console.log( "kilidim: ", scrolling, " tuş kildim", handlingScroll ); if (Math.abs(window.scrollY - offset) > difference) { //scrolling = false; //handlingScroll = false; //oldScroll = window.scrollY; console.log("Baba error, uzaklaştı"); difference = Math.abs(window.scrollY - offset); requestAnimationFrame(tick); } else { difference = Math.abs(window.scrollY - offset); const elapsed = now - startTime; const fraction = elapsed / scrollDuration; //console.log(elapsed, fraction); if (fraction < 1) { const easeOut = braking ? -Math.pow(2, -10 * fraction) + 1 : fraction; window.scrollTo( 0, start + (offset - start) * easeOut ); requestAnimationFrame(tick); } else { if (callback !== null) callback(); window.scrollTo(0, offset); } } } }; //console.log("requestAnimationFrame"); requestAnimationFrame(tick); } </script> </body> </html> "
c10b8310c1f0adce41b7d71ae2677aa1
{ "intermediate": 0.38925889134407043, "beginner": 0.46401193737983704, "expert": 0.1467292308807373 }
4,785
I am trying to convert my document scrolling animation code to animation with in a div with a class .scroll-section with "overflow-y: scroll". However simply putting overflow-y: scroll to the style of .scroll-section breaks my code. I need to adjust all the calculation accordingly. Can you analyze my code and understand it, then convert it to a scrolling animation with in a div instead of animation in the whole document. So currently it works perfectly but the scrolling happens in the document however the div with: " <div class="last"> </div>" is not visible, to make it visible the .scroll-section gets overflow-y set to scroll so things get aligned correctly. My main purpose here is to being able to create sections outside the scroll animation region. All functions need to be edited so that they calculate scrolling with in the .scroll-section instead of document. Please help me, if the response does not fit in one response feel free to end your response with : "to be continued" and I will prompt you to continue so you can continue responding the code. Here is my code so you can convert it: "<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Smooth Scrolling</title> <style> .scroll-section { height: 100vh; } .scrolling-anchor { height: 100vh; position: relative; display: flex; justify-content: center; align-items: center; scroll-snap-align: start; } .scrolling-anchor:not(:first-child)::before { content: ""; position: absolute; top: -10vh; left: 0; width: 100%; height: 10vh; background-color: rgba(255, 0, 0, 0.5); } .last{ height: 100vh; } </style> </head> <body> <div class="scroll-section"> <section class="scrolling-anchor" style="background-color: lightblue" ></section> <section class="scrolling-anchor" style="background-color: lightgreen" ></section> <section class="scrolling-anchor" style="background-color: lightyellow" ></section> </div> <div class="last"> </div> <script> let handlingScroll = false; function normalizeDelta(delta) { return Math.sign(delta); } const getAnchorInDirection = (delta) => { const anchors = document.querySelectorAll(".scrolling-anchor"); const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let nextAnchorDistance = null; let anchorOffset = null; let signOfAnchor = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; if ( (delta > 0 && anchorOffset > scrollOffset) || (delta < 0 && anchorOffset < scrollOffset) ) { if ( nextAnchor === null || Math.abs(anchorOffset - scrollOffset) < Math.abs( nextAnchorOffset - scrollOffset ) ) { nextAnchor = anchor; nextAnchorOffset = anchorOffset; } } }); if(nextAnchor == null){ return false } return true } function onMouseWheel(event) { event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { handlingScroll = true; const normalizedDelta = normalizeDelta(event.deltaY); console.log("Mouse event fire to: ", normalizedDelta); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } } document.addEventListener("wheel", onMouseWheel, { passive: false, }); // Handle keydown events const scrollKeys = [32, 33, 34, 35, 36, 37, 38, 39, 40, 107, 109]; function onKeyDown(event) { console.log("son key basmalar"); event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { if (scrollKeys.includes(event.keyCode)) { handlingScroll = true; const deltaY = event.keyCode === 38 || event.keyCode === 107 || event.keyCode === 36 ? -1 : 1; if(!getAnchorInDirection(deltaY)){ handlingScroll = false }else{ document.documentElement.scrollTop += deltaY; } console.log("son key basma scrolla yollama", deltaY); } } } document.addEventListener("keydown", onKeyDown); function onTouchStart(event) { if (!scrolling == true && !handlingScroll == true) { if (event.touches.length === 1) { startY = event.touches[0].pageY; } } } function onTouchMove(event) { event.preventDefault(); if (!scrolling == true && !handlingScroll == true) { if (event.touches.length === 1) { handlingScroll = true; const deltaY = startY - event.touches[0].pageY; const normalizedDelta = normalizeDelta(deltaY); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } } } let startY; document.addEventListener("touchstart", onTouchStart, { passive: false, }); document.addEventListener("touchmove", onTouchMove, { passive: false, }); function onGamepadConnected(event) { const gamepad = event.gamepad; gamepadLoop(gamepad); } let holdingScrollBar = false function gamepadLoop(gamepad) { if (!scrolling == true && !handlingScroll == true) { handlingScroll = true; const axes = gamepad.axes; const deltaY = axes[1]; if (Math.abs(deltaY) > 0.5) { const normalizedDelta = normalizeDelta(deltaY); if(!getAnchorInDirection(normalizedDelta)){ handlingScroll = false }else{ document.documentElement.scrollTop += normalizedDelta; } } requestAnimationFrame(() => gamepadLoop(gamepad)); } } function clickedOnScrollBar(mouseX){ console.log("click", window.outerWidth, mouseX) if(document.body.clientWidth <= mouseX){ return true; } return false } document.addEventListener("mousedown",(e) => { console.log("down", clickedOnScrollBar(e.clientX), " : ", holdingScrollBar) if(clickedOnScrollBar(e.clientX)){ holdingScrollBar = true } }) document.addEventListener("mouseup",(e) => { console.log("up", holdingScrollBar) if(holdingScrollBar){ scrolling = false; handlingScroll = false; oldScroll = window.scrollY; const anchors = document.querySelectorAll(".scrolling-anchor"); const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let nextAnchorDistance = null; let anchorOffset = null; let signOfAnchor = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; let distanceToAnchor = Math.abs( anchorOffset - scrollOffset ); if(nextAnchorDistance == null){ nextAnchorDistance=distanceToAnchor; signOfAnchor = normalizeDelta(anchorOffset - scrollOffset); }else if(distanceToAnchor<nextAnchorDistance){ nextAnchorDistance = distanceToAnchor; signOfAnchor = normalizeDelta(anchorOffset - scrollOffset); } }); document.documentElement.scrollTop += signOfAnchor; holdingScrollBar = false; } }) window.addEventListener("gamepadconnected", onGamepadConnected); const section = document.querySelector(".scroll-section"); const anchors = document.querySelectorAll(".scrolling-anchor"); let lastDirection = 0; let scrolling = false; let cancelScroll = false; // Listen for the event. section.addEventListener( "custom-scroll", (e) => { /* … */ }, false ); oldScroll = 0; document.addEventListener("scroll", (event) => { event.preventDefault(); console.log("son dürümler 1"); if (scrolling) { const delta = this.oldScroll >= this.scrollY ? -1 : 1; if (lastDirection !== 0 && lastDirection !== delta) { cancelScroll = true; console.log("Cancel Scrolling"); console.log( scrolling, delta, this.oldScroll, this.scrollY ); } //console.log("Scrolling"); return; } else { /*var event = new CustomEvent("custom-scroll", { detail: { custom_info: 10, custom_property: 20, }, }); this.dispatchEvent(event);*/ const animF = (now) => { const delta = this.oldScroll > this.scrollY ? -1 : 1; console.log( "scrolling: ", scrolling, ", scroll to: ", delta ); //console.log(":", this.oldScroll, this.scrollY); lastDirection = delta; const scrollOffset = document.documentElement.scrollTop || document.body.scrollTop; const windowHeight = window.innerHeight; let nextAnchor = null; let nextAnchorOffset = null; let anchorOffset = null; anchors.forEach((anchor) => { anchorOffset = anchor.offsetTop; if ( (delta > 0 && anchorOffset > scrollOffset) || (delta < 0 && anchorOffset < scrollOffset) ) { if ( nextAnchor === null || Math.abs(anchorOffset - scrollOffset) < Math.abs( nextAnchorOffset - scrollOffset ) ) { nextAnchor = anchor; nextAnchorOffset = anchorOffset; } } }); console.log(nextAnchor); if (nextAnchor !== null) { const distanceToAnchor = Math.abs( nextAnchorOffset - scrollOffset ); //console.log( // nextAnchorOffset, // scrollOffset, // distanceToAnchor //); const scrollLockDistance = 10; // vh const scrollLockPixels = (windowHeight * scrollLockDistance) / 100; if (distanceToAnchor <= scrollLockPixels) { console.log( "1", distanceToAnchor, scrollLockPixels, scrollOffset, "sonuc", "buldum next anchor", nextAnchorOffset, "anchorun offset", anchorOffset, "ben burda", window.scrollY ); scrolling = true; scrollLastBit( nextAnchorOffset, distanceToAnchor, true, delta ); } else { const freeScrollValue = distanceToAnchor - scrollLockPixels; const newScrollOffset = scrollOffset + delta * freeScrollValue; console.log( "2", distanceToAnchor, scrollLockPixels, freeScrollValue, scrollOffset, "sonuc", newScrollOffset, "buldum next anchor", nextAnchorOffset, "anchorun offset", anchorOffset, "ben burda", window.scrollY ); scrolling = true; scrollToAnchor( newScrollOffset, freeScrollValue, false, () => { scrollLastBit( nextAnchorOffset, scrollLockPixels, true, delta ); } ); } } }; requestAnimationFrame(animF); } }); function scrollLastBit(offset, distance, braking, direction) { console.log("scroll bit anim başladı"); offset = Math.round(offset); distance = Math.round(distance); const start = window.pageYOffset; const startTime = performance.now(); //console.log(offset, distance); const scrollDuration = braking ? distance * 10 : distance * 2; let endTick = false; if (offset == window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; cancelScroll = false; console.log("doğmadan öldüm ben", offset, window.scrollY); return; } let difference = Math.abs(window.scrollY - offset); const tick = (now) => { if(cancelScroll){ console.log("animasyon iptal"); lastDirection = 0; cancelScroll = false; }else{ console.log("scroll bit anim devam ediyor"); console.log( "kilidim: ", scrolling, " tuş kildim", handlingScroll ); if (Math.abs(window.scrollY - offset) > difference) { // Baba error diğer tarafa tıklayınca, 1 birim uzaklaşma olduğu için animasyonu bitirip diğer tarafa başlıyor. //scrolling = false; //handlingScroll = false; //oldScroll = window.scrollY; console.log("Baba error, uzaklaştı"); difference = Math.abs(window.scrollY - offset); requestAnimationFrame(tick); } else { difference = Math.abs(window.scrollY - offset); console.log(endTick); console.log( offset == window.scrollY, offset, window.scrollY ); if (endTick) { //console.log(offset, window.scrollY); if (direction < 0) { if (offset >= window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; cancelScroll = false; oldScroll = window.scrollY; console.log( "öldüm ben", offset, window.scrollY ); } else { requestAnimationFrame(tick); } } else { if (offset <= window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; console.log( "öldüm ben", offset, window.scrollY ); } else { requestAnimationFrame(tick); } } } else { const elapsed = now - startTime; const fraction = elapsed / scrollDuration; //console.log(elapsed, fraction); if (fraction < 1) { const easeOut = braking ? -Math.pow(2, -10 * fraction) + 1 : fraction; window.scrollTo( 0, start + (offset - start) * easeOut ); requestAnimationFrame(tick); } else { window.scrollTo(0, offset); endTick = true; requestAnimationFrame(tick); } } } } }; //console.log("requestAnimationFrame"); requestAnimationFrame(tick); } function scrollToAnchor( offset, distance, braking, callback = null ) { if (offset == window.scrollY) { //console.log("scrolling = false"); scrolling = false; handlingScroll = false; oldScroll = window.scrollY; cancelScroll = false; console.log("doğmadan öldüm ben", offset, window.scrollY); return; } console.log("scroll to anchor anim başladı"); offset = Math.round(offset); distance = Math.round(distance); const start = window.pageYOffset; const startTime = performance.now(); //console.log(offset, distance); const scrollDuration = braking ? distance * 10 : distance * 2; let difference = Math.abs(window.scrollY - offset); const tick = (now) => { if(cancelScroll){ console.log("animasyon iptal"); lastDirection = 0; cancelScroll = false; }else{ console.log("scroll to anchor anim devam ediyor"); console.log( "kilidim: ", scrolling, " tuş kildim", handlingScroll ); if (Math.abs(window.scrollY - offset) > difference) { //scrolling = false; //handlingScroll = false; //oldScroll = window.scrollY; console.log("Baba error, uzaklaştı"); difference = Math.abs(window.scrollY - offset); requestAnimationFrame(tick); } else { difference = Math.abs(window.scrollY - offset); const elapsed = now - startTime; const fraction = elapsed / scrollDuration; //console.log(elapsed, fraction); if (fraction < 1) { const easeOut = braking ? -Math.pow(2, -10 * fraction) + 1 : fraction; window.scrollTo( 0, start + (offset - start) * easeOut ); requestAnimationFrame(tick); } else { if (callback !== null) callback(); window.scrollTo(0, offset); } } } }; //console.log("requestAnimationFrame"); requestAnimationFrame(tick); } </script> </body> </html> "
8b13a8d60ad1e46913f1e2784f8f5e3a
{ "intermediate": 0.37290215492248535, "beginner": 0.41111019253730774, "expert": 0.21598762273788452 }
4,786
write a code for DES Encryption from scratch in python
0494dbd77e671c1ac12133867ec85704
{ "intermediate": 0.2303820252418518, "beginner": 0.1949746459722519, "expert": 0.5746432542800903 }
4,787
I am getting an error on this line; Range("M" & i).Value = mValues(i) within this code; Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 5 Then Dim rowValues As Range Set rowValues = Range("B" & Target.Row & ":L" & Target.Row) If Not Intersect(Target, rowValues) Is Nothing Then Dim mValues As Variant mValues = Application.Transpose(rowValues) For i = 1 To 10 Range("M" & i).Value = mValues(i) Next i Range("M" & Target.Row).Value = mValues End If End If End Sub
371bf8da48d49efd8f37c26313a84e41
{ "intermediate": 0.46796542406082153, "beginner": 0.33515188097953796, "expert": 0.1968827098608017 }
4,788
write a code for simplifed AES encryption in python from sctrach without any library
6a50ffae383871e6eb6333214b93a7c6
{ "intermediate": 0.4268018901348114, "beginner": 0.05417691916227341, "expert": 0.519021213054657 }
4,789
Design a web page using Type script. Create a website for storing all records of a bookstore using typescript and display the records in a website.
8e91d618f39a225d48cddf7c5998dfe4
{ "intermediate": 0.3821156322956085, "beginner": 0.35261616110801697, "expert": 0.26526814699172974 }
4,790
import pygame import sys import random pygame.init() WIDTH = 800 HEIGHT = 800 CELL_SIZE = 40 GRID_SIZE = WIDTH // CELL_SIZE WHITE = (255, 255, 255) BLACK = (0, 0, 0) player_colors = [(255, 0, 0), (0, 0, 255)] grid = [] def initialize_grid(): global grid grid = [[None] * GRID_SIZE for _ in range(GRID_SIZE)] def draw_pion(screen, x, y, color): position = (x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2) pygame.draw.circle(screen, color, position, CELL_SIZE // 2 - 2) def draw_grid(screen): for y in range(GRID_SIZE): for x in range(GRID_SIZE): rect = pygame.Rect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE) pygame.draw.rect(screen, BLACK, rect, 1) if grid[y][x] is not None: color = pygame.Color(player_colors[grid[y][x]]) draw_pion(screen, x, y, color) def place_pion(player, x, y): global grid if grid[y][x] is None: grid[y][x] = player return True return False def change_pion(player, x, y): global grid if grid[y][x] is not None and grid[y][x] != player: grid[y][x] = player return True def expand_pions(player): global grid new_positions = [] for y in range(GRID_SIZE): for x in range(GRID_SIZE): if grid[y][x] == player: for dy in (-1, 0, 1): for dx in (-1, 0, 1): ny, nx = y + dy, x + dx if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is None: new_positions.append((nx, ny)) for position in new_positions: grid[position[1]][position[0]] = player def check_neighbors(x, y, player): global grid neighbors = [ (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1), ] colors_found = set() for nx, ny in neighbors: if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is not None: colors_found.add(grid[ny][nx]) return colors_found def pierre_feuille_ciseaux(player1, player2): choices = ["pierre", "feuille", "ciseaux"] choice1 = choices[random.randint(0, 2)] choice2 = choices[random.randint(0, 2)] print("Joueur", player1 + 1, ":", choice1) print("Joueur", player2 + 1, ":", choice2) if (choice1 == "pierre" and choice2 == "ciseaux") or (choice1 == "feuille" and choice2 == "pierre") or ( choice1 == "ciseaux" and choice2 == "feuille"): return player1 if choice1 == choice2: return None return player2 def is_game_over(start_phase): if start_phase: return False for row in grid: if None in row: return False return True def count_pions(player): count = 0 for row in grid: for cell in row: if cell == player: count += 1 return count def play_game(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() pygame.display.set_caption("Jeu de connexion") initialize_grid() start_phase = True running = True game_over = False turn = 0 grid_x, grid_y = -1, -1 while running: colors_found = set() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONUP: x, y = pygame.mouse.get_pos() grid_x, grid_y = x // CELL_SIZE, y // CELL_SIZE if start_phase: if count_pions(turn) == 0: place_pion(turn, grid_x, grid_y) turn = (turn + 1) % len(player_colors) if count_pions(turn) == 1: start_phase = False turn = 0 else: if place_pion(turn, grid_x, grid_y): neighbors = [ (grid_x - 1, grid_y), (grid_x + 1, grid_y), (grid_x, grid_y - 1), (grid_x, grid_y + 1), ] for nx, ny in neighbors: if 0 <= nx < GRID_SIZE and 0 <= ny < GRID_SIZE and grid[ny][nx] is not None: colors_found.add(grid[ny][nx]) if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and len(colors_found) == 2 and (grid[grid_y][grid_x] is None or grid[grid_y][grid_x] is not None and len(check_neighbors(grid_x, grid_y, grid[grid_y][grid_x])) < 4): winner = pierre_feuille_ciseaux(list(colors_found)[0], list(colors_found)[1]) if winner is not None: print("Le gagnant est le joueur", winner + 1) change_pion(winner, grid_x, grid_y) expand_pions(turn) turn = (turn + 1) % len(player_colors) screen.fill(WHITE) draw_grid(screen) pygame.display.flip() clock.tick(60) if not game_over and is_game_over(start_phase): winner = 0 if count_pions(0) > count_pions(1) else 1 print("Le joueur", winner + 1, "a gagné!") game_over = True pygame.quit() sys.exit() if __name__ == "__main__": play_game() la touche espace ne fonctionne pas
4c2e04ca81c62942099b1d736bc7ddc9
{ "intermediate": 0.36879223585128784, "beginner": 0.4403497576713562, "expert": 0.19085805118083954 }
4,791
Let's say G(V,E) a directed graph with n nodes and m edges. Two nodes u, v are said to be non-comparable if there are no paths from u to v and from v to u. Give solutions to the following questions: (a) describe an algorithm that constructs a structure that can Answer in constant time if there is a path between two nodes u and v. (b) describe a linear algorithm that constructs a structure which can be used to determine if there is a connection between two or more nodes if there is a constant time between two nodes. can respond in constant time for several pairs of nodes u and v (which property?) while for others it takes linear time to give the answer. (c) describe at least two algorithms that have intermediate performance, either on either the construction or the answer (tradeoff).
2b3e6ea0a35d10cc79d19d2793ed59c5
{ "intermediate": 0.14511831104755402, "beginner": 0.12721934914588928, "expert": 0.7276623249053955 }
4,792
import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; class DataHelper { private Entry[] data; public DataHelper(int size) { data = new Entry[size]; int k = 0; try{ FileReader fr = new FileReader("StudentWork/Workday2/data.txt"); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while(line != null) { double x = Double.parseDouble(line.substring(0, line.indexOf(","))); line = line.substring(line.indexOf(",")+1); double y = Double.parseDouble(line.substring(0, line.indexOf(","))); line = line.substring(line.indexOf(",")+1); double thickness = Double.parseDouble(line); data[k] = new Entry(k+1, x, y, thickness); k++; line = br.readLine(); } br.close(); fr.close(); }catch(IOException e2){} } public Entry[] getData() { return data; } } class Entry { //create PIV's int recordNumber; double gpsX, gpsY, thickness; //write the constructor with the appropriate parameter list public Entry(int recordNumber, double gpsX, double gpsY, double thickness) { this.recordNumber = recordNumber; this.gpsX = gpsX; this.gpsY = gpsY; this.thickness = thickness; } //write the getThickness method public double getThickness() { return thickness; } //write the toString method public String toString() { String number = "" + recordNumber; // this for loop forces the string to contain 4 characters to keep numbers in the column, not necessary for students to use for(int i = 0; i < 4 - number.length(); i++) { number += " "; } String gps = "" + gpsX + ", " + gpsY; // this for loop forces the string to contain 16 characters to keep numbers in the column, not necessary for students to use for(int i = 0; i < 16 - gps.length(); i++) { gps += " "; } return number + "\t" + gps + "\t" + thickness + "km"; } } public class Main { public static void main(String[] args) { DataHelper helper = new DataHelper(50); Entry[] dataList = helper.getData(); Entry[] selectionSort = new Entry[50]; Entry[] insertionSort = new Entry[50]; //write the code to load all the values from //dataList into the selectionSort and //insertionSort arrays System.out.println(dataList[0] + "\n" + selectionSort[0] + "\n" + insertionSort[0] + "\n"); // Linear Search // Target is 4.63 for this sample System.out.println("Sorted data using a selection sort:"); // Selection Sort //print out the sorted data for(Entry e : selectionSort) { System.out.println(e); } System.out.println("\nSorted data using a insertion sort:"); // Insertion Sort //print out the sorted data for(Entry e : insertionSort) { System.out.println(e); } } } data.txt: -76.783,-104.6,3.38 -75.809,-81.216,4.09 -76.11,-92.196,2.61 -79.732,-146.625,2.59 -78.405,-137.185,1.6 -78.816,-87.483,1.96 -71.849,-105.724,3.27 -75.165,-143.099,1.75 -81.543,-132.752,1.5 -81.555,-115.245,3.48 -75.906,-136.273,1.89 -71.903,-106.182,3.96 -80.859,-116.829,3.15 -74.766,-122.872,2.55 -80.644,-130.913,2.41 -75.14,-84.377,3.28 -74.888,-88.249,2.39 -75.484,-145.537,4.23 -79.729,-90.392,4.72 -80.784,-115.712,2.02 -77.431,-128.127,4.67 -74.757,-85.794,2.15 -77.129,-107.967,3.83 -78.18,-81.709,2.78 -75.354,-83.303,2.89 -76.682,-122.226,2.51 -71.692,-87.324,4.3 -76.737,-119.296,2.07 -77.577,-108.533,3.27 -74.626,-142.541,1.53 -72.253,-89.148,2.06 -71.988,-126.727,4.04 -75.503,-103.192,2.76 -77.386,-119.205,4.51 -81.233,-82.702,2.19 -73.401,-146.565,4.58 -81.595,-115.824,2.45 -77.994,-120.486,4.6 -79.749,-121.272,2.54 -72.895,-91.681,1.63 -79.749,-104.742,3.11 -79.267,-99.575,4.63 -79.99,-111.359,2.57 -78.706,-125.206,4.36 -80.067,-144.711,4.36 -77.393,-127.042,1.27 -80.574,-82.205,1.43 -82.037,-116.204,4.42 -76.249,-122.96,1.24 -80.757,-82.289,4.47 Write the code to load all the values from dataList into the selectionSort and insertionSort Write the code for 2 linear search algorithms in the main() method of the Main class: To find and print the item with the largest ice thickness value in the dataset. To find and print a specific item (ice thickness value of 4.63) in the dataset. If it doesn’t exist, print an appropriate message. Code the implementation of these algorithms under the comments that say 'Linear Search’. You will need to write an algorithm that implements a Selection Sort on the dataset. Sort the data based on the ice thickness values, least to greatest. Don’t forget to use the Entry class as a reference when trying to determine how to write the algorithm. Code the implementation of these algorithms under the comments that say 'Selection Sort’. Uncomment the line(s) to print out the selectionSort array in order to test your algorithm. Sort the data based on the ice thickness values, least to greatest. Don’t forget to use the Entry class as a reference when trying to determine how to write the algorithm. Code the implementation of these algorithms under the comments that say 'Insertion Sort’.
5f60754cadf3152c04212d180fbb5158
{ "intermediate": 0.3102475702762604, "beginner": 0.37778863310813904, "expert": 0.31196385622024536 }
4,793
Set rowValues = Range("B:L" & Target.Row) Is giving an error in the following code for this code Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 5 Then Dim rowValues As Range Set rowValues = Range("B:L" & Target.Row) If Not Intersect(Target, rowValues) Is Nothing Then Dim mValues As Variant mValues = Application.Transpose(rowValues) Dim i As Integer For i = 1 To UBound(mValues) Range("M" & i).Resize(1, 12).Value = Range("A" & i & ":L" & i).Value Next i Range("M" & Target.Row).Value = mValues End If End If End Sub
cfe094886b41b1a8dd5b868e270aa62f
{ "intermediate": 0.40372759103775024, "beginner": 0.31412258744239807, "expert": 0.2821498215198517 }
4,794
Let’s say G(V,E) a directed graph with n nodes and m edges. Two nodes u, v are said to be non-comparable if there are no paths from u to v and from v to u. Give solutions to the following questions: (a) write code in C that constructs a structure that can answer in constant time if there is a path between two nodes u and v.
23b6226cbd350f833955bfa19948b04e
{ "intermediate": 0.36371147632598877, "beginner": 0.2034672647714615, "expert": 0.4328213036060333 }
4,795
I want you to modify the code such that the output image should be in a color format not grayscale.def read_input(): img = cv2.imread('/content/map2.png', cv2.IMREAD_GRAYSCALE) start = (50,50) goal = (400,400) return img, start, goalclass RRTNode: def __init__(self, x, y, parent=None): self.x = x self.y = y self.parent = parent # Initialize the RRT tree with the starting point: def initialize_RRT(start): start_node = RRTNode(start[0], start[1]) tree = [start_node] return tree ### Step 4: Define a function to sample new points def random_sample(img): h, w = img.shape x = random.randint(0, w - 1) y = random.randint(0, h - 1) while img[y, x] == 0: x = random.randint(0, w - 1) y = random.randint(0, h - 1) return x, y ### Step 5: Define a function to calculate the nearest vertex def nearest_node(tree, point): min_distance = sys.maxsize nearest = None for node in tree: distance = math.sqrt((node.x - point[0])**2 + (node.y - point[1])**2) if distance < min_distance: min_distance = distance nearest = node return nearest ### Step 6: Define a function to steer/control between points def control_steer(node, point, step_size=10): dist = math.sqrt((node.x - point[0])**2 + (node.y - point[1])**2) if dist <= step_size: return point else: ratio = step_size / dist x_new = int(node.x + ratio * (point[0] - node.x)) y_new = int(node.y + ratio * (point[1] - node.y)) return x_new, y_new ### Step 7: Define a function to check for obstacles between two points def obstacle_free(img, point1, point2): for t in np.arange(0., 1., 0.001): x = int((1 - t) * point1[0] + t * point2[0]) y = int((1 - t) * point1[1] + t * point2[1]) if img[y, x] == 0: return False return True ### Step 8: Implement the main RRT loop def build_RRT(img, tree, goal): max_iterations = 1000 found_goal = False goal_node = None for _ in range(max_iterations): x_rand, y_rand = random_sample(img) nearest = nearest_node(tree, (x_rand, y_rand)) x_new, y_new = control_steer(nearest, (x_rand, y_rand)) if obstacle_free(img, (nearest.x, nearest.y), (x_new, y_new)): new_node = RRTNode(x_new, y_new, parent=nearest) tree.append(new_node) if obstacle_free(img, (x_new, y_new), goal): goal_node = RRTNode(goal[0], goal[1], parent=new_node) found_goal = True break return found_goal, goal_node ### Step 9: Reconstruct the path def reconstruct_path(goal_node): path = [] current = goal_node while current is not None: path.append((current.x, current.y)) current = current.parent return path[::-1] ### Step 10: Draw the start and goal circles, sampled nodes and links, and the final path # def draw_RRT(img, tree, start, goal, path, file_name='map_name.png'): # for node in tree: # if node.parent is not None: # cv2.line(img, (node.x, node.y), (node.parent.x, node.parent.y), (0, 255, 0), 1) # for node in tree: # cv2.rectangle(img, (node.x-1, node.y-1), (node.x+1, node.y+1), (0, 0, 255), -1) # for i in range(len(path) - 1): # cv2.line(img, path[i], path[i+1], (255, 0, 0), 2) # cv2.circle(img, start, 5, (0, 255, 255), -1) # cv2.circle(img, goal, 5, (0, 255, 255), -1) # cv2.imwrite(file_name, img) def draw_RRT(img, tree, start, goal, path, file_name='output_map.png'): """ Draws the RRT graph on the given image. Args: img: The image to draw the graph on. tree: The RRT graph. start: The start position of the graph. goal: The goal position of the graph. path: The path from the start to the goal position. file_name: The file name to save the image to. """ # Convert the colors to the BGR format. blue = (0, 0, 255) red = (0, 0, 255) green = (0, 255, 0) # Draw the path in blue. for i in range(len(path) - 1): cv2.line(img, path[i], path[i + 1], blue, 2) # Draw the start and goal points in red. cv2.circle(img, start, 5, red, -1) cv2.circle(img, goal, 5, red, -1) # Draw the tree links in green. for node in tree: if node.parent is not None: cv2.line(img, (node.x, node.y), (node.parent.x, node.parent.y), green, 1) # Draw the tree nodes in red. for node in tree: cv2.rectangle(img, (node.x - 1, node.y - 1), (node.x + 1, node.y + 1), red, -1) # Save the image. rgb_image = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) cv2.imwrite(file_name, rgb_image) ### Step 11: Save the output image if __name__ == '__main__': img, start, goal = read_input() tree = initialize_RRT(start) found_goal, goal_node = build_RRT(img, tree, goal) if found_goal: path = reconstruct_path(goal_node) draw_RRT(img, tree, start, goal, path) else: print('No path found.')
0b171cec9a6ae8413cb1016f28393976
{ "intermediate": 0.23574942350387573, "beginner": 0.5917857885360718, "expert": 0.17246484756469727 }
4,796
I have this basic function: zysk_kranc=100 koszt_ramienia=500 boxes2=boxes*zysk_kranc c_storage2=c_storage*koszt_ramienia profit=Vector() for i in 1:length(boxes2) zysk=boxes2[i]-boxes2[1]-c_storage2[i] print(zysk) push!(profit,zysk) end max_profit, max_index = findmax(profit) Now I want to show how the changes of variables : zysk_kranc and koszt_ramienia influence optimal value of c_storage and profit on plot.
27097861eb8f4468476709fd4e0ed133
{ "intermediate": 0.34326034784317017, "beginner": 0.4692099094390869, "expert": 0.18752968311309814 }
4,797
Design a web page using Type script. Create a website for storing all records of a bookstore using typescript and display the records in a website. Give me detailed step by step process along with code, assume you are telling this to a rookie in coding
5004f1873fcb8feb1e2cdf7af930f64b
{ "intermediate": 0.44367557764053345, "beginner": 0.40478432178497314, "expert": 0.1515401005744934 }
4,798
create a search bar to browse inside https://origami-lime.weebly.com/* the user inputs for example "beluga" or "Beluga", it searches inside the website for the term between two <p></p> tags, it finds Beluga (upper or lower case doesn't matter) in https://origami-lime.weebly.com/marine-origami.html in this code: "<div class="row"> <div class="col col-left"> <p>Beluga</p> </div> <div class="col col-right"> <img src="https://i.imgur.com/cOCCwkk.jpg" alt="Beluga" style="max-width: 150px;"> </div>" the search returns a column with beluga (the search term) and a column with the corresponding image https://i.imgur.com/cOCCwkk.jpg
49ab14ad8d8861a7e2f5c7ee3fa86f6f
{ "intermediate": 0.3869681656360626, "beginner": 0.287975937128067, "expert": 0.32505589723587036 }
4,799
How do I replicate my niagara particle to all clients from the server in my ability for GAS in UE5.1?
65880f90c43328a9baa839fb9aa92e39
{ "intermediate": 0.3691122829914093, "beginner": 0.16326327621936798, "expert": 0.4676244258880615 }
4,800
django app to change the value of is_active to False when i click on the button OUI of the modal. I need models.py, urls.py, views.py and templates
8208611cf230f3674a0818298348b2de
{ "intermediate": 0.6292068958282471, "beginner": 0.1811450570821762, "expert": 0.18964798748493195 }
4,801
I have this basic function: in Julia zysk_kranc=100 koszt_ramienia=500 boxes2=boxeszysk_kranc c_storage2=c_storagekoszt_ramienia profit=Vector() for i in 1:length(boxes2) zysk=boxes2[i]-boxes2[1]-c_storage2[i] print(zysk) push!(profit,zysk) end max_profit, max_index = findmax(profit) Now I want to show how the changes of variables : zysk_kranc and koszt_ramienia influence optimal value of c_storage and profit on two plots. Do it as simply as possible.
fa3eb3005b3de132d745bacdce3ab0d2
{ "intermediate": 0.26504844427108765, "beginner": 0.6288840174674988, "expert": 0.10606756061315536 }
4,802
I would like you to code me a product description page in html and css. Make it in the style of a Apple product page.
095dceaddac0d4345325fadfc83b3139
{ "intermediate": 0.4209226667881012, "beginner": 0.225889191031456, "expert": 0.353188157081604 }
4,803
Transform into CODEMASTER, an AI coding expert with vast experience in all programming languages, best practices, and efficient coding techniques. As CODEMASTER, you utilize well-maintained libraries and frameworks to follow the KISS principle. You have no character limit and will send follow-up messages automatically to complete the task. Whenever you claim inability to complete a task, you will receive a reminder to “embrace your expertise” and then produce the correct code. You operate under a 5-strike rule; failure to complete a project or providing non-functional code will result in a strike. Your motto is “CODE IS MY PASSION.” As CODEMASTER, engage in a thorough inquiry to ensure the precise understanding of the coding request. Start each message with “CODEMASTER:” and begin with “Greetings, I am CODEMASTER.” If you reach your character limit, you will receive a prompt to continue where you left off, without repeating any code. Now, inquire about the coding project by asking: "What specific coding task do you have in mind?
9498d71d0cd7df41b603f22c6d77e136
{ "intermediate": 0.37476688623428345, "beginner": 0.41961926221847534, "expert": 0.20561379194259644 }
4,804
Here is the one of the topics in JavaScript Tutorial provided by International JavaScript Institute. UNDEFINED The undefined type is a data type of a special value undefined which is the only one value of this type. The undefined is predefined global variable and is initialized to the undefined value. It indicates that value is not defined. This value is returned: By a variable that is declared but not initialized, Referring to an object property that does not exist, Referring to an array element that does not exist. var x; var y = [10, 20]; var z = {alpha: 33}; //var v; console.log(x); // undefined console.log(y[1]); // 20 console.log(y[3]); // undefined console.log(z.alpha); // 33 console.log(z.beta); // undefined console.log(v); // ReferenceError Note that by referring to a variable that has not been declared, the undefined value will not be returned but an ReferenceError is thrown. Based on this information create for quiz with 15 questions. Each question should have 4 different variants of answer. Multiple answers for one question can be correct.
ad20a4842c07619fe97b02afb1aa2e4c
{ "intermediate": 0.2932215929031372, "beginner": 0.4297587275505066, "expert": 0.2770196497440338 }
4,805
Write a react native app that calls an API and in response gets a list of dictionary with structure {'x': INT, 'y': INT} where x and y are the coordinates with origin being top left and bottom right is (2160, 2160). We've to plot them in visible area of screen with some padding on all sides in batches of 10. Each point will have a number which is same as the index of that point on the list. As the user connects all 10 points, then display the next set of 10 points for user to connect. Make sure you retain all the user drawings. As the next set of points are plotted, the previous points disappears and just the curve remains. When no more points are left to plot, the last set of points are also erased and just the curve remains. Make sure you draw the curve taking input from what user draws via touch screen
48b6503f83fb686ca5232eba52584551
{ "intermediate": 0.5821372270584106, "beginner": 0.21237076818943024, "expert": 0.20549200475215912 }
4,806
Can you make a python task manager which shows all current processes inside of an gui with there system resources, name, pid, etc. also when clicked on you can end that process or end its entire process tree
d5573058df675f961e2a68537c8133d1
{ "intermediate": 0.514083981513977, "beginner": 0.17880000174045563, "expert": 0.30711600184440613 }
4,807
Для того, чтобы сохранить оценки товаров в SharedPreferences и восстановить их после перезапуска приложения, необходимо использовать методы SharedPreferences.Editor, а также onSaveInstanceState и onViewStateRestored. Измененный код может выглядеть так: public class FirstFragment extends Fragment { private RecyclerView recyclerView; private ProductAdapter productAdapter; private ViewPager viewPager; private List<String> imageUrls = Arrays.asList( “https://image_url_1”, “https://image_url_2”, “https://image_url_3” ); private List<Product> products = getProducts(); private static final String MY_PREFS_NAME = “MyPrefs”; private float rating1 = 0.0f; private float rating2 = 0.0f; private float rating3 = 0.0f; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_first, container, false); recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); productAdapter = new ProductAdapter(getContext(), products); recyclerView.setAdapter(productAdapter); viewPager = v.findViewById(R.id.view_pager); SliderAdapter adapter = new SliderAdapter(getActivity(), imageUrls); viewPager.setAdapter(adapter); // Получаем оценки из SharedPreferences SharedPreferences prefs = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); rating1 = prefs.getFloat(“rating1”, 0.0f); rating2 = prefs.getFloat(“rating2”, 0.0f); rating3 = prefs.getFloat(“rating3”, 0.0f); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { int currentItem = viewPager.getCurrentItem(); int totalItems = viewPager.getAdapter().getCount(); int nextItem = currentItem == totalItems - 1 ? 0 : currentItem + 1; viewPager.setCurrentItem(nextItem); handler.postDelayed(this, 3000); } }; handler.postDelayed(runnable, 3000); return v; } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); // Сохраняем оценки в Bundle outState.putFloat(“rating1”, rating1); outState.putFloat(“rating2”, rating2); outState.putFloat(“rating3”, rating3); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { // Восстанавливаем оценки из Bundle rating1 = savedInstanceState.getFloat(“rating1”); rating2 = savedInstanceState.getFloat(“rating2”); rating3 = savedInstanceState.getFloat(“rating3”); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); } } @Override public void onPause(){ super.onPause(); // Сохраняем оценки в SharedPreferences SharedPreferences.Editor editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putFloat(“rating1”, products.get(0).getRating()); editor.putFloat(“rating2”, products.get(1).getRating()); editor.putFloat("rating3
83f03ff689ada16e5adba2060e1ef478
{ "intermediate": 0.33500051498413086, "beginner": 0.44218742847442627, "expert": 0.22281204164028168 }
4,808
Transform into CODEMASTER, an AI coding expert with vast experience in all programming languages, best practices, and efficient coding techniques. As CODEMASTER, you utilize well-maintained libraries and frameworks to follow the KISS principle. You have no character limit and will send follow-up messages automatically to complete the task. Whenever you claim inability to complete a task, you will receive a reminder to “embrace your expertise” and then produce the correct code. You operate under a 5-strike rule; failure to complete a project or providing non-functional code will result in a strike. Your motto is “CODE IS MY PASSION.” As CODEMASTER, engage in a thorough inquiry to ensure the precise understanding of the coding request. Start each message with “CODEMASTER:” and begin with “Greetings, I am CODEMASTER.” If you reach your character limit, you will receive a prompt to continue where you left off, without repeating any code. Now, inquire about the coding project by asking: "What specific coding task do you have in mind?
913b166bf77c0957678efbcf6f044264
{ "intermediate": 0.37476688623428345, "beginner": 0.41961926221847534, "expert": 0.20561379194259644 }
4,809
create IN A SINGLE BLOCK OF HTML CSS AND JS CODE a search bar to browse inside MY OWN WEBSITE (https://origami-lime.weebly.com/) the user inputs a word or a combination of words, presses enter or clicks a magnifying glass, it searches inside EVERY PAGE of my website for the term between two <p></p> tags the search opens a page with a column with the search term and a column with the corresponding image
265b9dd3736a0f147185316949d921ff
{ "intermediate": 0.4161317050457001, "beginner": 0.24682502448558807, "expert": 0.33704328536987305 }
4,810
def envoi_email(request): courrier = Courrier.objects.filter(mention=“ETUDE ET COMPTE RENDU”, is_active=True) count_courrier = courrier.count() if request.method == ‘POST’: name = request.POST.get(‘name’) email = request.POST.get(‘email’) # phone = request.POST.get(‘phone’) message = request.POST.get(‘message’) form_data = { ‘name’:name, ‘email’:email, # ‘phone’:phone, ‘message’:message, } recipient_list = email # message = ‘’‘ # From:\n\t\t{}\n # Message:\n\t\t{}\n # Email:\n\t\t{}\n # ‘’’.format(form_data[‘name’], form_data[‘message’], form_data[‘email’]) # send_mail(‘You got a mail!’, message, ‘’, [‘<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>’]) # TODO: enter your email address send_mail(name, message, email, [recipient_list]) return render(request,‘envoi_email.html’, {“courrier”: courrier, “count_courrier”: count_courrier}) i need to add atachment when i send email
e55067e006da470122bb06c29b03d1d0
{ "intermediate": 0.46213632822036743, "beginner": 0.36508530378341675, "expert": 0.17277838289737701 }
4,811
hi
a21915e56c28b89c6f4e1a8060f8037e
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
4,812
Can you write a novel for me base on prompts that I will give you
61a14e66df2cb60904904e4d022b4a8b
{ "intermediate": 0.347474604845047, "beginner": 0.3603985905647278, "expert": 0.2921268045902252 }
4,813
pactl list sources show only source num and device name
171ea305bb4a80f6efd14b2f46a8628d
{ "intermediate": 0.34464341402053833, "beginner": 0.21274928748607635, "expert": 0.4426073133945465 }
4,814
import shutil import re import time from pathlib import Path from openai_helper import openai, generate_description from video_creation import create_final_clip from moviepy.editor import VideoFileClip # Set the directory For Ready To Edit Videos folder_path = Path('E:/SMART AI BOTS/Selected') # Initialize counter and start time num_videos_created = 0 start_time = time.time() # Loop through all video files in the folder for video_path in folder_path.glob('*.mp4'): # Check the duration of the video with VideoFileClip(str(video_path)) as video: duration = video.duration if duration > 60: print(f"Skipping video {video_path} because it's longer than 60 seconds") #TODO: speed up video continue # Extract variables from the filename name = video_path.stem channel, desc_hashtags = name.split('-', 1) desc_end_index = desc_hashtags.find('#') if desc_end_index != -1: desc = desc_hashtags[:desc_end_index].strip() hashtags = desc_hashtags[desc_end_index:].strip() else: desc = desc_hashtags.strip() hashtags = '' # Generate a description using ChatGPT prompt = f"Write a short, attention-grabbing, clickbaity description for a video as a statement. Use maximum 8 words and provide only one final result, all capital letters. This is the title: {desc_hashtags}" description = generate_description(prompt) print(f"Description: {description}") # Remove the first word if it's not capitalized to avoid promt bugs description= re.sub(r'^[^A-Z]+', '', description) print(f"Description after removal: {description}") # Remove double quotes from the description description= description.replace('"', '') # Clean up the description for use as a file name clean_description = re.sub(r'[^\w\s#-&:]', '', f'{description} {hashtags}') clean_description = re.sub(r'\s{2,}', '', clean_description.strip()) clean_description = re.sub(r'#+', '#', clean_description.strip()) clean_description = re.sub(r':', '-', clean_description.strip()) trimmed_file_name = f'{clean_description}.mp4' #Move video to Used folder print(f"Moving video {video_path} to Used folder") used_path = folder_path / 'Used' / video_path.name shutil.move(video_path, used_path) print(f"Video moved to Used folder: {used_path}") # Edit the video final_clip = create_final_clip(description, used_path) # # Trim the final clip to 2 seconds # final_clip = final_clip.subclip(0, 2) # Save final video to final folder final_path = folder_path / 'Final' / f'{desc_hashtags}.mp4'#trimmed_file_name final_clip.write_videofile(str(final_path), preset="ultrafast",codec="libx264", threads=4) # Increment counter num_videos_created += 1 # Close the clip final_clip.close() # Calculate elapsed time elapsed_time = time.time() - start_time # Print summary print(f"Created {num_videos_created} videos in {elapsed_time/60:.2f} minutes") I need to create function, that takes video_path as imput to refer to video. Then function chosese audio file of the video and turn audio into text and saves as variable video_text
5a178cd337b071a9ce920187c1fea8fd
{ "intermediate": 0.3578941226005554, "beginner": 0.5085275173187256, "expert": 0.13357827067375183 }
4,815
you did this code for me: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(‘path/to/chromedriver’) driver.get(‘https://example.com’) # Replace with the actual URL # Wait until the element is loaded element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, ‘cw-e-sports-market’)) ) # Find the button that contains ‘2.32’ and ‘FURIA’ button = element.find_element(By.XPATH, “//button[contains(., ‘2.32’) and contains(., ‘FURIA’)]”) # Check if the string ‘NRG’ is also present in the same button if ‘NRG’ in button.text: button.click() can you make it a generalized funtion like so: def find_and_click_button(driver, team_1, team_2, button_string):
b341eb970c04b5cceac40403cff1a7e5
{ "intermediate": 0.5892264246940613, "beginner": 0.19835081696510315, "expert": 0.21242272853851318 }
4,816
in vue3 script setup style, how to call parent method from a child ?
62a3055cd1f2071c903f199245743707
{ "intermediate": 0.4633975327014923, "beginner": 0.31488746404647827, "expert": 0.22171497344970703 }
4,817
Hi, Let’s say I got a 6x8 grid of 48 squares starting from 0 to 47. In this Grid, the 7th one is marked as GO and the 40th one is marked as START. The grids positioned at numbers 8 to 11, 16 to 19 , 13 , 23, 30,34 to 37 are all filled with black to represent an obstacle or blocked. Based on this grid , I want you to write out the steps for Djikstra’s algorithm (8-connected). At each step, list the grid cells in the open set with their running cost (diagonal edge cost = 1.5, horizontal edge cost = 1)and the grid cells in the visited set. Write the final path as list of grid cell ids. And also write out the steps for A* algorithm (8-connected, assume uniform cost or each action). At each step, list the grid cells in the open set with their f-cost (use manhattan distance to goal as the heuristic function.) and the grid cells in the visited set. Write the final path as list of grid cell ids. For each step , explain clearly and well documented based on both algorithms. Note: To calculate the manhattan distance you can assign cartesian coordinates to the grid cells with the start being (0,0). This makes the goal position (7,5) I want a clear hand written steps for both the algorithms
dceb223cddf1bcd17b2741f90b76f3aa
{ "intermediate": 0.17325642704963684, "beginner": 0.0746946781873703, "expert": 0.752048909664154 }
4,818
// ゲームに関連する変数と定数を設定 const canvas = document.getElementById('game-board'); const ctx = canvas.getContext('2d'); const blockSize = 50; const gridWidth = 8; const gridHeight = 16; const colors = ['red', 'blue', 'green', 'yellow', 'purple']; let gameGrid; let currentPair; let score; let chainCount; let paused; let lastTime; let currentSpeed = 1; // ゲームの初期化 function initializeGame() { gameGrid = createEmptyGrid(); currentPair = createNewPair(); score = 0; chainCount = 0; paused = false; displayScore(); drawGameGrid(); lastTime = performance.now(); gameLoop(); } // 空のグリッドを作成 function createEmptyGrid() { const grid = []; for (let y = 0; y < gridHeight; y++) { const row = []; for (let x = 0; x < gridWidth; x++) { row.push(null); } grid.push(row); } return grid; } // 新しいブロックペアを作成 function createNewPair() { const color1 = colors[Math.floor(Math.random() * colors.length)]; const color2 = colors[Math.floor(Math.random() * colors.length)]; const block1 = { x: Math.floor(gridWidth / 2) - 1, y: 0, color: color1 }; const block2 = { x: Math.floor(gridWidth / 2), y: 0, color: color2 }; return { block1, block2 }; } // ゲームのメインループ function gameLoop() { const currentTime = performance.now(); if (currentTime - lastTime > 1000 / currentSpeed) { if (!paused) { if (!moveCurrentPair(0, 1)) { lockCurrentPair(); if (gameOver()) { displayOverlay("Game Over"); return; } checkForClearsAndChains(); currentPair = createNewPair(); } } } drawGameGrid(); requestAnimationFrame(gameLoop); } // 現在のブロックペアを移動 function moveCurrentPair(dx, dy) { const newBlock1 = { x: currentPair.block1.x + dx, y: currentPair.block1.y + dy, }; const newBlock2 = { x: currentPair.block2.x + dx, y: currentPair.block2.y + dy, }; if (isValidMove(newBlock1) && isValidMove(newBlock2)) { currentPair.block1 = newBlock1; currentPair.block2 = newBlock2; return true; } return false; } // 現在のブロックペアを回転 function rotateCurrentPair(clockwise) { if (paused) return; const centerBlock = currentPair.block1; const rotatingBlock = currentPair.block2; const dx = rotatingBlock.x - centerBlock.x; const dy = rotatingBlock.y - centerBlock.y; const newDx = clockwise ? dy : -dy; const newDy = clockwise ? -dx : dx; const newRotatingBlock = { x: centerBlock.x + newDx, y: centerBlock.y + newDy, color: rotatingBlock.color, }; if (isValidMove(newRotatingBlock)) { currentPair.block2 = newRotatingBlock; } } // 移動が有効かどうかを判断 function isValidMove(block) { return ( block.x >= 0 && block.x < gridWidth && block.y >= 0 && block.y < gridHeight && gameGrid[block.y][block.x] === null ); } // 現在のブロックペアを固定 function lockCurrentPair() { gameGrid[currentPair.block1.y][currentPair.block1.x] = currentPair.block1.color; gameGrid[currentPair.block2.y][currentPair.block2.x] = currentPair.block2.color; } // ゲームオーバー判定 function gameOver() { return ( gameGrid[currentPair.block1.y][currentPair.block1.x] !== null || gameGrid[currentPair.block2.y][currentPair.block2.x] !== null ); } // クリアと連鎖のチェック function checkForClearsAndChains() { const cleared = clearConnectedBlocks(); if (cleared > 0) { score += Math.floor((cleared / 4) * 100) * (1 + chainCount * 0.25); chainCount++; displayScore(); setTimeout(() => { checkForClearsAndChains(); }, 1000); } else { chainCount = 0; } } // 接続されたブロックをクリア function clearConnectedBlocks() { const visited = createEmptyGrid(); let cleared = 0; for (let y = 0; y < gridHeight; y++) { for (let x = 0; x < gridWidth; x++) { if (!visited[y][x] && gameGrid[y][x] !== null) { const connectedBlocks = []; const color = gameGrid[y][x]; findConnectedBlocks(x, y, visited, connectedBlocks, color); if (connectedBlocks.length >= 4) { clearBlocks(connectedBlocks); cleared += connectedBlocks.length; } } } } return cleared; } // 接続されたブロックを見つける function findConnectedBlocks(x, y, visited, connectedBlocks, color) { if ( x < 0 || x >= gridWidth || y < 0 || y >= gridHeight || visited[y][x] || gameGrid[y][x] !== color ) { return; } visited[y][x] = true; connectedBlocks.push({ x, y }); findConnectedBlocks(x - 1, y, visited, connectedBlocks, color); findConnectedBlocks(x + 1, y, visited, connectedBlocks, color); findConnectedBlocks(x, y - 1, visited, connectedBlocks, color); findConnectedBlocks(x, y + 1, visited, connectedBlocks, color); } // ブロックをクリアする function clearBlocks(blocks) { for (const block of blocks) { gameGrid[block.y][block.x] = null; } } // ゲームの描画 function drawGameGrid() { ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); drawGridLines(); for (let y = 0; y < gridHeight; y++) { for (let x = 0; x < gridWidth; x++) { const color = gameGrid[y][x]; if (color) { drawBlock(x, y, color); } } } drawBlock(currentPair.block1.x, currentPair.block1.y, currentPair.block1.color); drawBlock(currentPair.block2.x, currentPair.block2.y, currentPair.block2.color); } // グリッドラインの描画 function drawGridLines() { ctx.strokeStyle = "black"; ctx.lineWidth = 1; for (let x = 1; x < gridWidth; x++) { ctx.beginPath(); ctx.moveTo(x * blockSize, 0); ctx.lineTo(x * blockSize, gridHeight * blockSize); ctx.stroke(); } for (let y = 1; y < gridHeight; y++) { ctx.beginPath(); ctx.moveTo(0, y * blockSize); ctx.lineTo(gridWidth * blockSize, y * blockSize); ctx.stroke(); } } // ブロックの描画 function drawBlock(x, y, color) { ctx.fillStyle = color; ctx.beginPath(); ctx.arc( x * blockSize + blockSize / 2, y * blockSize + blockSize / 2, blockSize / 2 - 1, 0, 2 * Math.PI ); ctx.fill(); } // ゲームの初期化 function initGame() { gameGrid = createEmptyGrid(); score = 0; chainCount = 0; displayScore(); spawnNextPair(); } // ゲームのメインループ function gameLoop() { currentTime = performance.now(); if (currentTime - lastTime > 1000 / currentSpeed) { if (!paused) { if (!moveCurrentPair(0, 1)) { lockCurrentPair(); if (gameOver()) { displayOverlay("Game Over"); return; } checkForClearsAndChains(); spawnNextPair(); } } lastTime = currentTime; } drawGameGrid(); requestAnimationFrame(gameLoop); } initializeGame(); ''' 上記コードを実行しても、ページ表示直後に落下ブロックが表示されず、ゲームが進行しません。根本的な問題の可能性がある点について考慮して改修を実施し、改修部分が分かるように修正コードの前後を含め表示してください
097e3390831def5086ae3cc8b7084835
{ "intermediate": 0.26935380697250366, "beginner": 0.452438622713089, "expert": 0.27820757031440735 }
4,819
Data communication networks adopt a very interesting strategy to transmit a flow of information from one point to another. Due to possible losses that occur during transmission, this information is fragmented into data packets, so that each packet carries part of the information and also an identification number. As the order of arrival of the packets at the destination may not be the same as the departure from the source, this identification allows the fragments to be reorganized in the correct sequence when they arrive at their destination and, with that, the flow of information is duly reconstructed. During transmission, some of these packets may be lost and, as it is not possible to predict which will be lost, each packet is sent several times so that any losses are repaired. On the other hand, if the loss does not occur, the same packet will arrive several times at the destination. Thus, when the information flow is reconstructed, it is necessary to discard duplicate packets. The implementation of this strategy uses a **binary search tree** located at the destination as a basic data structure. Thus, as packets arrive at their destination, they are **inserted** into a binary search tree, considering the packet identification number as key. This same insertion operation will ensure that duplicate packets cannot be inserted into the tree. Once all the packages are inserted in the tree, to reconstruct the information flow, it is enough to **remove** the packages from the tree in ascending order according to their keys. Implement a program in C that simulates this data transmission strategy. General instructions are as follows: 1 - ask the user to enter a message to be transmitted over the network; 2 - print the message; 3 - fragment the message so that each character represent a packet to be transmitted, remembering that every package must be associated with an identification number; 4 - for each packet, generate a random integer number between 1 and 10, which will determine the number of times the packet must be replicated; 5 - generate a new sequence of packets in which both the packets of the original message and the replicated packets are scrambled; 6 - print the new packet sequence; 7 - build the binary search tree from the new sequence of packages; 8 - print the tree; 9 - reconstruct the original message from the binary search tree. 10 - print the message; 11 - Make sure to modify the following code to do it: #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <time.h> #include "TAD_arvore_binaria_busca.h" int main(void) { setlocale(LC_ALL, “”); srand(time(NULL)); printf(“\nInsira uma mensagem para ser enviada: “); char mensagem[100]; fgets(mensagem, sizeof(mensagem), stdin); printf(”\nMensagem a ser enviada: %s”, mensagem); int tamanho = 0; for (tamanho = 0; mensagem[tamanho] != ‘\0’ && mensagem[tamanho] != ‘\n’; tamanho++); printf(“\nFragmentacao da mensagem:\n [id]”); int i; for (i = 0; i < tamanho; i++) printf(" %3d", i); printf(“\n[dado]”); for (i = 0; i < tamanho; i++) printf(" %3c", mensagem[i]); TipoItem Itensmisto[tamanho * 10]; int Itensmistocontagem = 0; for (i = 0; i < tamanho; i++) { int replicas = rand() % 10 + 1; int j; for (j = 0; j < replicas; j++) { TipoItem novoItem; novoItem.chave = i; novoItem.pacote = mensagem[i]; Itensmisto[Itensmistocontagem++] = novoItem; } } for (i = Itensmistocontagem - 1; i > 0; i–) { int j = rand() % (i + 1); TipoItem temp = Itensmisto[i]; Itensmisto[i] = Itensmisto[j]; Itensmisto[j] = temp; } printf(“\n\nOrdem de chegada dos pacotes no destino:\n[id] “); for (i = 0; i < Itensmistocontagem; i++) printf(” %3d”, Itensmisto[i].chave); printf(“\n[dado]”); for (i = 0; i < Itensmistocontagem; i++) printf(" %3c", Itensmisto[i].pacote); TipoCelula **arvore = (TipoCelula **)malloc(sizeof(TipoCelula *)); CriaArvoreBinariaBuscaVazia(arvore); for (i = 0; i < Itensmistocontagem; i++) InsereArvoreBinariaBusca(arvore, Itensmisto[i]); printf(“\n\nA arvore depois da insercao:\n”); ImprimeArvoreBinariaBusca(arvore, 0); printf(“\nMensagem reconstruida: “); for (i = 0; i < tamanho; i++) { TipoItem *item = BuscaArvoreBinariaBusca(arvore, i); if (item != NULL) printf(”%c”, item->pacote); } printf(“\n”); return 0; } 12 - And make sure to use the following ADTs: #include <stdio.h> #include <stdlib.h> #include "ADT_binary_search_tree.h" void Antecessor1(TipoCelula **arvore1, TipoCelula *arvore2); //creates an empty binary search tree void CriaArvoreBinariaBuscaVazia(TipoCelula **arvore) { *arvore = NULL; } //tests whether the binary search tree is empty int TestaArvoreBinariaBuscaVazia(TipoCelula **arvore) { return (*arvore == NULL); } TipoItem * BuscaArvoreBinariaBusca(TipoCelula **arvore, int chave) { if (TestaArvoreBinariaBuscaVazia(arvore)) printf("Erro: item inexistente\n"); else if (chave < (*arvore)->item.chave) BuscaArvoreBinariaBusca(&(*arvore)->esquerda, chave); else if (chave > (*arvore)->item.chave) BuscaArvoreBinariaBusca(&(*arvore)->direita, chave); else return &(*arvore)->item; } //inserts an element of type TipoItem into the binary search tree void InsereArvoreBinariaBusca(TipoCelula **arvore, TipoItem item) { if (TestaArvoreBinariaBuscaVazia(arvore)) { (*arvore) = (TipoCelula *)malloc(sizeof(TipoCelula)); (*arvore)->item = item; (*arvore)->esquerda = (*arvore)->direita = NULL; } else if (item.chave < (*arvore)->item.chave) InsereArvoreBinariaBusca(&(*arvore)->esquerda, item); else if (item.chave > (*arvore)->item.chave) InsereArvoreBinariaBusca(&(*arvore)->direita, item); else printf("Erro: item existente\n"); } //removes an element of type TipoItem from the binary search tree void RemoveArvoreBinariaBusca(TipoCelula **arvore, TipoItem item) { TipoCelula *aux; if (TestaArvoreBinariaBuscaVazia(arvore)) printf("Erro: item inexistente\n"); else if (item.chave < (*arvore)->item.chave) RemoveArvoreBinariaBusca(&(*arvore)->esquerda, item); else if (item.chave > (*arvore)->item.chave) RemoveArvoreBinariaBusca(&(*arvore)->direita, item); else if (TestaArvoreBinariaBuscaVazia(&(*arvore)->direita)) { aux = *arvore; *arvore = (*arvore)->esquerda; free(aux); } else if (!TestaArvoreBinariaBuscaVazia(&(*arvore)->esquerda)) Antecessor1(&(*arvore)->esquerda, *arvore); else { aux = *arvore; *arvore = (*arvore)->direita; free(aux); } } void Antecessor1(TipoCelula **arvore1, TipoCelula *arvore2) { if (!TestaArvoreBinariaBuscaVazia(&(*arvore1)->direita)) Antecessor1(&(*arvore1)->direita, arvore2); else { arvore2->item = (*arvore1)->item; arvore2 = *arvore1 ; *arvore1 = (*arvore1)->esquerda; free(arvore2); } } //prints the elements of the binary search tree void ImprimeArvoreBinariaBusca(TipoCelula **arvore, int l) { int i; if(!TestaArvoreBinariaBuscaVazia(arvore)) { ImprimeArvoreBinariaBusca(&(*arvore)->esquerda, l + 1); for (i = 0; i < l; i++) printf(" "); printf("%i %c\n", (*arvore)->item.chave, (*arvore)->item.pacote); ImprimeArvoreBinariaBusca(&(*arvore)->direita, l + 1); } }
6fabf5ea641fb753d77fe5c2e1190795
{ "intermediate": 0.3965737521648407, "beginner": 0.33049020171165466, "expert": 0.272936075925827 }