row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
31,220
public Garage() { this.items.add(((Item)GarageItemsLoader.items.get("up_score_small")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("smoky")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("wasp")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("green")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("holiday")).clone()); this.mountItem("wasp_m0"); this.mountItem("smoky_m0"); this.mountItem("green_m0"); } public boolean containsItem(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return true; } } return false; } public Item getItemById(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return item; } } return null; } public boolean mountItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); if (item != null && Integer.parseInt(id.substring(id.length() - 1, id.length())) == item.modificationIndex) { if (item.itemType == ItemType.WEAPON) { this.mountTurret = item; return true; } if (item.itemType == ItemType.ARMOR) { this.mountHull = item; return true; } if (item.itemType == ItemType.COLOR) { this.mountColormap = item; return true; } } return false; } public boolean updateItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); int modificationID = Integer.parseInt(id.substring(id.length() - 1)); if (modificationID < 3 && item.modificationIndex == modificationID) { ++item.modificationIndex; item.nextPrice = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].price; item.nextProperty = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].propertys; item.nextRankId = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].rank; this.replaceItems(this.getItemById(id.substring(0, id.length() - 3)), item); return true; } else { return false; } } public boolean buyItem(String id, int count) { Item temp = (Item)GarageItemsLoader.items.get(id.substring(0, id.length() - 3)); if (temp.specialItem) { return false; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.isInventory) { item.count += count; } this.items.add(item); return true; } else if (item.isInventory) { Item fromUser = this.getItemById(id); fromUser.count += count; return true; } else { return false; } } } public Item buyItem(String id, int count, int nul) { id = id.substring(0, id.length() - 3); Item temp = (Item)GarageItemsLoader.items.get(id); if (temp.specialItem) { return null; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.itemType == ItemType.INVENTORY) { item.count += count; } // Проверка, на то что id предмета не равен косярю опыта if (!id.equals("1000_scores")) { this.items.add(item); } return item; } else if (item.itemType == ItemType.INVENTORY) { Item fromUser = this.getItemById(id); fromUser.count += count; return fromUser; } else { return null; } } } private void replaceItems(Item old, Item newItem) { if (this.items.contains(old)) { this.items.set(this.items.indexOf(old), newItem); } } public ArrayList<Item> getInventoryItems() { ArrayList<Item> _items = new ArrayList(); Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.itemType == ItemType.INVENTORY) { _items.add(item); } } return _items; } public void parseJSONData() { JSONObject hulls = new JSONObject(); JSONArray _hulls = new JSONArray(); JSONObject colormaps = new JSONObject(); JSONArray _colormaps = new JSONArray(); JSONObject turrets = new JSONObject(); JSONArray _turrets = new JSONArray(); JSONObject inventory_items = new JSONObject(); JSONArray _inventory = new JSONArray(); JSONObject effects_items = new JSONObject(); JSONArray _effects = new JSONArray(); Iterator var10 = this.items.iterator(); while(var10.hasNext()) { Item item = (Item)var10.next(); JSONObject inventory; if (item.itemType == ItemType.ARMOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountHull); _hulls.add(inventory); } if (item.itemType == ItemType.COLOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountColormap); _colormaps.add(inventory); } if (item.itemType == ItemType.WEAPON) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountTurret); _turrets.add(inventory); } if (item.itemType == ItemType.INVENTORY) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("count", item.count); _inventory.add(inventory); } if (item.itemType == ItemType.PLUGIN) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("time", item.time); _effects.add(inventory); } } hulls.put("hulls", _hulls); colormaps.put("colormaps", _colormaps); turrets.put("turrets", _turrets); inventory_items.put("inventory", _inventory); effects_items.put("effects", _effects); this._json_colormaps = colormaps.toJSONString(); this._json_hulls = hulls.toJSONString(); this._json_turrets = turrets.toJSONString(); this._json_inventory = inventory_items.toJSONString(); this._json_effects = effects_items.toJSONString(); } public void unparseJSONData() throws ParseException { this.items.clear(); JSONParser parser = new JSONParser(); JSONObject turrets = (JSONObject)parser.parse(this._json_turrets); JSONObject colormaps = (JSONObject)parser.parse(this._json_colormaps); JSONObject hulls = (JSONObject)parser.parse(this._json_hulls); JSONObject inventory; if (this._json_inventory != null && !this._json_inventory.isEmpty()) { inventory = (JSONObject)parser.parse(this._json_inventory); } else { inventory = null; } JSONObject effects; if ((this._json_effects != null) && (!this._json_effects.isEmpty())) effects = (JSONObject)parser.parse(this._json_effects); else { effects = null; } Iterator var7 = ((JSONArray)turrets.get("turrets")).iterator(); Object inventory_item; JSONObject _item; Item item; while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountTurret = item; } } var7 = ((JSONArray)colormaps.get("colormaps")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountColormap = item; } } var7 = ((JSONArray)hulls.get("hulls")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountHull = item; } } if (inventory != null) { var7 = ((JSONArray)inventory.get("inventory")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.count = (int)(long)_item.get("count"); if (item.itemType == ItemType.INVENTORY) { this.items.add(item); } } } if (effects != null) { var7 = ((JSONArray)effects.get("effects")).iterator(); while (var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.time = (long)_item.get("time"); new SimpleTimer(this, item); if (item.itemType == ItemType.PLUGIN) { this.items.add(item); } } } } как для предмета 1000_scores добавить this.tanksServices.addScore() с добавлением 1000 едениц опыта для игрока
6209af58915e7ca4ded653ead918257f
{ "intermediate": 0.27162498235702515, "beginner": 0.672165036201477, "expert": 0.056210000067949295 }
31,221
How can I make an NPC spouse in skyrim? Let's say I made them a follower using these commands:
e852baab590b965ab07fc7aac379beb6
{ "intermediate": 0.4665208160877228, "beginner": 0.24995677173137665, "expert": 0.283522367477417 }
31,222
How can I make an NPC spouse in skyrim? I already made the NPC a follower using these commands:
138a172e8d4ef433c30bfaa525248689
{ "intermediate": 0.4258086681365967, "beginner": 0.33057257533073425, "expert": 0.24361875653266907 }
31,223
How can I make an NPC spouse in skyrim? I already made the NPC a follower using these commands:
3a4004392e09ff14c815eb6efe3c916a
{ "intermediate": 0.4258086681365967, "beginner": 0.33057257533073425, "expert": 0.24361875653266907 }
31,224
How can I make an NPC spouse in skyrim? I already made the NPC a follower using these commands:
06fcb04b0aa4dcd34a7db9572fc20b09
{ "intermediate": 0.4258086681365967, "beginner": 0.33057257533073425, "expert": 0.24361875653266907 }
31,225
Here is my code so far: master.c: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <semaphore.h> #include <errno.h> typedef struct { int index; // Add any other variables you need in the shared memory structure } shared_data; int main(int argc, char* argv[]) { const char shmName = argv[1]; / shared memory name from command line */ const char semName = argv[2]; / semaphore name from command line */ const int SIZE = sizeof(shared_data); printf(“Master begins execution\n”); int shm_fd; shared_data *shm_ptr; // Open the shared memory segment shm_fd = shm_open(shmName, O_CREAT | O_RDWR, 0666); if (shm_fd == -1) { printf(“Master: Shared memory failed: %s\n”, strerror(errno)); exit(1); } // Configure size of shared memory segment ftruncate(shm_fd, SIZE); // Map shared memory segment in the address space of the process shm_ptr = (shared_data *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); if (shm_ptr == MAP_FAILED) { printf(“Master: Map failed: %s\n”, strerror(errno)); exit(1); } // Initialize index in the shared memory structure to zero shm_ptr->index = 0; printf(“Master initialized index in the shared structure to zero\n”); // Create a named semaphore for mutual exclusion sem_t mutex_sem = sem_open(semName, O_CREAT, 0660, 1); if (mutex_sem == SEM_FAILED) { printf(“Master: sem_open failed: %s\n”, strerror(errno)); exit(1); } printf(“Master created a semaphore named %s\n”, semName); // Create n child processes to execute slave int n = atoi(argv[3]); printf(“Master created %d child processes to execute slave\n”, n); // Wait for all child processes to terminate printf(“Master waits for all child processes to terminate\n”); int i; for (i = 0; i < n; i++) { wait(NULL); } printf(“Master received termination signals from all %d child processes\n”, n); printf(“Updated content of shared memory segment after access by child processes:\n”); printf(“— content of shared memory —\n”); printf(“[ Current content of shared memory ]\n”); // Remove the semaphore if (sem_close(mutex_sem) == -1) { printf(“Master: sem_close failed: %s\n”, strerror(errno)); exit(1); } printf(“Master removed the semaphore\n”); // Close access to shared memory, remove shared memory segment, and exit if (sem_unlink(semName) == -1) { printf(“Master: sem_unlink failed: %s\n”, strerror(errno)); exit(1); } if (munmap(shm_ptr, SIZE) == -1) { printf(“Master: Unmap failed: %s\n”, strerror(errno)); exit(1); } if (close(shm_fd) == -1) { printf(“Master: Close failed: %s\n”, strerror(errno)); exit(1); } if (shm_unlink(shmName) == -1) { printf(“Master: Error removing %s: %s\n”, shmName, strerror(errno)); exit(1); } printf(“Master closed access to shared memory, removed shared memory segment, and is exiting\n”); return 0; } slave.c: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <semaphore.h> #include <errno.h> typedef struct { int index; // Add any other variables you need in the shared memory structure } shared_data; int main(int argc, char argv[]) { printf(“Slave begins execution\n”); int child_number = atoi(argv[1]); const char *shmName = argv[2]; const char *semName = argv[3];}
9be9fe34a4ee28af9c539359699ac77c
{ "intermediate": 0.39655613899230957, "beginner": 0.4017828106880188, "expert": 0.20166097581386566 }
31,226
Write a C++ Program to print the letter K using stars. Note: 1) Using nested For Loop 2) The number of lines is given by user. 3) Using one Outer loop to print your letter
d82d741dcce9867239b2121f60d03806
{ "intermediate": 0.24581018090248108, "beginner": 0.5523070096969604, "expert": 0.20188279449939728 }
31,227
Make a python webserver that returns a randomly generated page (based on the seed give in the url), the page contents are two links to other random urls to the same site, just a diffrent randomly genrwted url/seed and also 1000 random words from a new line seperated words.txt
41c3f8b0ae8e4278bcdd70b5ea206f78
{ "intermediate": 0.35898154973983765, "beginner": 0.17861036956310272, "expert": 0.4624081552028656 }
31,228
Make a stripe hitter in python 💳
a335e4d6abca832fec0a92ff24e8ca7e
{ "intermediate": 0.21344757080078125, "beginner": 0.1884044110774994, "expert": 0.5981480479240417 }
31,229
Can you give the python code to train a phone-to-wordpiece model in sentencepiece given a phoneme lexicon?
36d7cc05611a3063a9afb4a9e76bee7b
{ "intermediate": 0.22084452211856842, "beginner": 0.0456865094602108, "expert": 0.7334690093994141 }
31,230
import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Read data from file with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/EngArb.txt', 'r',encoding='utf8') as file: data = file.readlines() # Split data into train, validate, and test train_ratio = 0.6 val_ratio = 0.2 test_ratio = 0.2 num_examples = len(data) num_train = int(num_examples * train_ratio) num_val = int(num_examples * val_ratio) train_data = data[:num_train] val_data = data[num_train:num_train+num_val] test_data = data[num_train+num_val:] # Extract English and Arabic sentences from data english_sentences_train = [] arabic_sentences_train = [] english_sentences_val = [] arabic_sentences_val = [] english_test = [] arabic_test = [] for line in train_data: english, arabic = line.strip().split('\t') english_sentences_train.append(english) arabic_sentences_train.append(arabic) for line in val_data: english, arabic = line.strip().split('\t') english_sentences_val.append(english) arabic_sentences_val.append(arabic) for line in test_data: english, arabic = line.strip().split('\t') english_test.append(english) arabic_test.append(arabic) # Tokenize the sentences and convert them into numerical representations tokenizer = Tokenizer(oov_token='<OOV>') tokenizer.fit_on_texts(english_sentences_train + arabic_sentences_train) english_train_sequences = tokenizer.texts_to_sequences(english_sentences_train) arabic_train_sequences = tokenizer.texts_to_sequences(arabic_sentences_train) english_val_sequences = tokenizer.texts_to_sequences(english_sentences_val) arabic_val_sequences = tokenizer.texts_to_sequences(arabic_sentences_val) english_test_sequences = tokenizer.texts_to_sequences(english_test) arabic_test_sequences = tokenizer.texts_to_sequences(arabic_test) # Pad or truncate the sentences to a fixed length max_length = 10 english_train_padded = pad_sequences(english_train_sequences, maxlen=max_length, padding='post', truncating='post') arabic_train_padded = pad_sequences(arabic_train_sequences, maxlen=max_length, padding='post', truncating='post') english_val_padded = pad_sequences(english_val_sequences, maxlen=max_length, padding='post', truncating='post') arabic_val_padded = pad_sequences(arabic_val_sequences, maxlen=max_length, padding='post', truncating='post') english_test_padded = pad_sequences(english_test_sequences, maxlen=max_length, padding='post', truncating='post') arabic_test_padded = pad_sequences(arabic_test_sequences, maxlen=max_length, padding='post', truncating='post') # Define the BiLSTM encoder-decoder model input_dim = len(tokenizer.word_index) + 1 output_dim = len(tokenizer.word_index) + 1 latent_dim = 256 embedding_dim = 100 encoder_inputs = tf.keras.layers.Input(shape=(max_length,)) encoder_embedding = tf.keras.layers.Embedding(input_dim, embedding_dim, input_length=max_length)(encoder_inputs) encoder_lstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(latent_dim, return_state=True)) encoder_outputs, forward_h, forward_c, backward_h, backward_c = encoder_lstm(encoder_embedding) state_h = tf.keras.layers.Concatenate()([forward_h, backward_h]) state_c = tf.keras.layers.Concatenate()([forward_c, backward_c]) decoder_inputs = tf.keras.layers.Input(shape=(max_length,)) decoder_embedding = tf.keras.layers.Embedding(input_dim, embedding_dim, input_length=max_length)(decoder_inputs) decoder_lstm = tf.keras.layers.LSTM(latent_dim * 2, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm(decoder_embedding, initial_state=[state_h, state_c]) decoder_dense = tf.keras.layers.Dense(output_dim, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) model = tf.keras.models.Model([encoder_inputs, decoder_inputs], decoder_outputs) # Compile and train the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit([english_train_padded, arabic_train_padded], np.expand_dims(arabic_train_padded, -1), epochs=30, batch_size=16, validation_data=([english_val_padded, arabic_val_padded], np.expand_dims(arabic_val_padded, -1))) # Use test data to evaluate and example translation predictions = model.predict([english_test_padded, arabic_test_padded]) predicted_sequences = np.argmax(predictions, axis=2) predicted_sentences = tokenizer.sequences_to_texts(predicted_sequences) for i in range(len(english_test)): print(f'English: {english_test[i]}') print(f'Arabic (Actual): {arabic_test[i]}') print(f'Arabic (Predicted): {predicted_sentences[i]}') print() How Use BiLStM Encoder and BiGRU decoder
2c2a27d688f074092b138a08d0def6b1
{ "intermediate": 0.4068979322910309, "beginner": 0.3116045296192169, "expert": 0.2814975678920746 }
31,231
my cube is not visible from all sides. What's the problem in the geometry shader? #version 450 core layout (points) in; layout(location = 20) uniform mat4 projection; layout (triangle_strip, max_vertices = 14) out; out vec4 gColor; in vec4 vertexColor[]; void main() {{ vec4 center = gl_in[0].gl_Position; vec4 dx = vec4(0,0,0.45f,0); vec4 dy = vec4(0,-0.45f,0,0); vec4 dz = vec4(-0.45f,0,0,0); vec4 p1 = center; vec4 p2 = center + dx; vec4 p3 = center + dy; vec4 p4 = p2 + dy; vec4 p5 = p1 + dz; vec4 p6 = p2 + dz; vec4 p7 = p3 + dz; vec4 p8 = p4 + dz; p1 = projection * p1; p2 = projection * p2; p3 = projection * p3; p4 = projection * p4; p5 = projection * p5; p6 = projection * p6; p7 = projection * p7; p8 = projection * p8; gColor = vertexColor[0]; gl_Position = p7; EmitVertex(); gl_Position = p8; EmitVertex(); gl_Position = p5; EmitVertex(); gl_Position = p6; EmitVertex(); gl_Position = p2; EmitVertex(); gl_Position = p8; EmitVertex(); gl_Position = p4; EmitVertex(); gl_Position = p7; EmitVertex(); gl_Position = p3; EmitVertex(); gl_Position = p5; EmitVertex(); gl_Position = p1; EmitVertex(); gl_Position = p2; EmitVertex(); gl_Position = p3; EmitVertex(); gl_Position = p4; EmitVertex(); EndPrimitive(); }}
dbcc1c6c1e2e770b774404fc6cce3a32
{ "intermediate": 0.3816375136375427, "beginner": 0.35092437267303467, "expert": 0.267438143491745 }
31,232
Python script to embed lexical knowledge into a sentencepiece model
c309faa97a6235280358b098a714422e
{ "intermediate": 0.2948342263698578, "beginner": 0.2761414647102356, "expert": 0.42902424931526184 }
31,233
make so it generate platforms as you go either directions as a pralax: import React, { useState, useEffect, useRef } from "react"; // Constants for gravity, jumping, and movement const GRAVITY = 150; const JUMP_STRENGTH = -25; const MOVE_SPEED = 700; const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({ position }) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${position.x}px`, top: `${position.y}px`, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: 100, y: 300 }); const [isGrounded, setIsGrounded] = useState(false); const [doubleJumped, setDoubleJumped] = useState(false); const playerVelocityRef = useRef({ x: 0, y: 0 }); const requestIdRef = useRef(null); const lastTimeRef = useRef(null); const keysPressed = useRef({ left: false, right: false, up: false, jump: false }); const platform = { width: 400, height: 20, top: 450, left: 100 }; const checkCollisionWithPlatform = (position, width, height) => { const playerRect = { left: position.x, top: position.y, right: position.x + width, bottom: position.y + height, }; const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; return ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ); }; const updateGame = (time) => { const deltaTime = (time - (lastTimeRef.current || time)) / 1000; lastTimeRef.current = time; // Calculate new velocity let velocity = { x: keysPressed.current.left ? -MOVE_SPEED * deltaTime : keysPressed.current.right ? MOVE_SPEED * deltaTime : 0, y: playerVelocityRef.current.y + GRAVITY * deltaTime, }; // Store the x velocity playerVelocityRef.current.x = velocity.x; if (keysPressed.current.jump && isGrounded || keysPressed.current.jump && !doubleJumped) { if(!isGrounded){ setDoubleJumped(true) } velocity.y = JUMP_STRENGTH; keysPressed.current.jump = false; } // Calculate new position let newPosition = { x: playerPosition.x + velocity.x, y: playerPosition.y + velocity.y, }; if (checkCollisionWithPlatform(newPosition, PLAYER_WIDTH, PLAYER_HEIGHT)) { newPosition.y = platform.top - PLAYER_HEIGHT; velocity.y = 0; setIsGrounded(true); setDoubleJumped(false); } else { setIsGrounded(false); } setPlayerPosition(prevPosition => ({ x: prevPosition.x + velocity.x, y: prevPosition.y + velocity.y, })); playerVelocityRef.current = velocity; // Request the next animation frame requestIdRef.current = requestAnimationFrame(updateGame); }; useEffect(() => { const handleKeyDown = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = true; if (event.key === "ArrowRight") keysPressed.current.right = true; if (event.key === "ArrowUp" && isGrounded || event.key === "ArrowUp" && !doubleJumped) keysPressed.current.jump = true; }; const handleKeyUp = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = false; if (event.key === "ArrowRight") keysPressed.current.right = false; }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestIdRef.current = requestAnimationFrame(updateGame); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); cancelAnimationFrame(requestIdRef.current); }; }, [playerPosition,isGrounded, doubleJumped]); // add isGrounded to the dependency array return ( <div style={{ position: "relative", width: "100%", height: "500px" }}> <Player position={playerPosition} /> <Platform {...platform} /> </div> ); } export default GameMain;
580f257e6b0d1bfaa4197b8bec32b16a
{ "intermediate": 0.3000774681568146, "beginner": 0.4828229546546936, "expert": 0.21709951758384705 }
31,234
rewrite all this code for me and make sure it works as indented, right now the platforms are all over the place and you don't follow the player as you move left and right: import React, { useState, useEffect, useRef } from "react"; // Constants for gravity, jumping, and movement const GRAVITY = 150; const JUMP_STRENGTH = -25; const MOVE_SPEED = 700; const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 400; const PLATFORM_HEIGHT = 20; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 500; // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({ position }) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${position.x}px`, top: `${position.y}px`, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: 100, y: 300 }); const [isGrounded, setIsGrounded] = useState(false); const [doubleJumped, setDoubleJumped] = useState(false); const [platforms, setPlatforms] = useState([ { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: 450, left: VIEW_WIDTH / 2 - PLATFORM_WIDTH / 2 }, ]); const backgroundXRef = useRef(0); // Horizontal offset for parallax background const playerVelocityRef = useRef({ x: 0, y: 0 }); const requestIdRef = useRef(null); const lastTimeRef = useRef(null); const keysPressed = useRef({ left: false, right: false, up: false, jump: false }); const platform = { width: 400, height: 20, top: 450, left: 100 }; const checkCollisionWithPlatform = (position, width, height) => { const playerRect = { left: position.x, top: position.y, right: position.x + width, bottom: position.y + height, }; const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; return ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ); }; const updateGame = (time) => { const deltaTime = (time - (lastTimeRef.current || time)) / 1000; lastTimeRef.current = time; // Calculate new velocity let velocity = { x: keysPressed.current.left ? -MOVE_SPEED * deltaTime : keysPressed.current.right ? MOVE_SPEED * deltaTime : 0, y: playerVelocityRef.current.y + GRAVITY * deltaTime, }; // Store the x velocity playerVelocityRef.current.x = velocity.x; if (keysPressed.current.jump && isGrounded || keysPressed.current.jump && !doubleJumped) { if(!isGrounded){ setDoubleJumped(true) } velocity.y = JUMP_STRENGTH; keysPressed.current.jump = false; } // Calculate new position let newPosition = { x: playerPosition.x + velocity.x, y: playerPosition.y + velocity.y, }; // Platform creation and removal const firstPlatform = platforms[0]; const lastPlatform = platforms[platforms.length - 1]; // Remove off-screen platforms const visiblePlatforms = platforms.filter(platform => { const platformRightEdge = platform.left + platform.width - backgroundXRef.current; return platformRightEdge >= 0 && platform.left - backgroundXRef.current <= VIEW_WIDTH; }); // Add a new platform if needed if (newPosition.x > lastPlatform.left - 200) { // Generate new platform on the right visiblePlatforms.push(createNewPlatform(newPosition, "right")); } else if (newPosition.x < firstPlatform.left + 200) { // Generate new platform on the left visiblePlatforms.unshift(createNewPlatform(newPosition, "left")); } setPlatforms(visiblePlatforms); // Update background position for parallax effect if (keysPressed.current.left && backgroundXRef.current < 0) { backgroundXRef.current += MOVE_SPEED * deltaTime; } else if (keysPressed.current.right) { backgroundXRef.current -= MOVE_SPEED * deltaTime; } if (checkCollisionWithPlatform(newPosition, PLAYER_WIDTH, PLAYER_HEIGHT)) { newPosition.y = platform.top - PLAYER_HEIGHT; velocity.y = 0; setIsGrounded(true); setDoubleJumped(false); } else { setIsGrounded(false); } setPlayerPosition(prevPosition => ({ x: prevPosition.x + velocity.x, y: prevPosition.y + velocity.y, })); playerVelocityRef.current = velocity; // Request the next animation frame requestIdRef.current = requestAnimationFrame(updateGame); }; const createNewPlatform = (playerPosition, direction) => { const newTop = Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT); return direction === "right" ? { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: newTop, left: playerPosition.x + 300 } : { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: newTop, left: playerPosition.x - 300 - PLATFORM_WIDTH }; }; useEffect(() => { const handleKeyDown = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = true; if (event.key === "ArrowRight") keysPressed.current.right = true; if (event.key === "ArrowUp" && isGrounded || event.key === "ArrowUp" && !doubleJumped) keysPressed.current.jump = true; }; const handleKeyUp = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = false; if (event.key === "ArrowRight") keysPressed.current.right = false; }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestIdRef.current = requestAnimationFrame(updateGame); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); cancelAnimationFrame(requestIdRef.current); }; }, [playerPosition,isGrounded, doubleJumped]); // add isGrounded to the dependency array return ( <div style={{ position: "relative", width: "100%", height: `${VIEW_HEIGHT}px`, overflow: "hidden" }}> <Player position={{ ...playerPosition, x: playerPosition.x - backgroundXRef.current }} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - backgroundXRef.current} /> ))} </div> ); } export default GameMain;
2eebc7d31e175952b4d94c7cc91002d6
{ "intermediate": 0.4177147448062897, "beginner": 0.4115956723690033, "expert": 0.170689657330513 }
31,235
The best books to learn to built strong softwore in python in 2023
555011485d1038d849d63149996ab791
{ "intermediate": 0.29547402262687683, "beginner": 0.16068308055400848, "expert": 0.5438429117202759 }
31,236
I need code for C++ to say "Hello World!"
3512fa63b4e3cf9254d779796e3f898d
{ "intermediate": 0.22637981176376343, "beginner": 0.5284926891326904, "expert": 0.24512745440006256 }
31,237
python code using BiLSTM encoder and LSTM decoder rnn to translate English text to Arabic text by splitting data from file into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example translation from test
21897a39241ec95697f54862004c3321
{ "intermediate": 0.41345879435539246, "beginner": 0.10121564567089081, "expert": 0.48532557487487793 }
31,238
the platforms are all over the place and the camera doesn't follow the player: import React, { useState, useEffect, useRef } from "react"; // Constants for gravity, jumping, and movement const GRAVITY = 150; const JUMP_STRENGTH = -25; const MOVE_SPEED = 700; const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 400; const PLATFORM_HEIGHT = 20; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 500; // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({ position }) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${position.x}px`, top: `${position.y}px`, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: 100, y: 300 }); const [isGrounded, setIsGrounded] = useState(false); const [doubleJumped, setDoubleJumped] = useState(false); const [platforms, setPlatforms] = useState([ { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: 450, left: VIEW_WIDTH / 2 - PLATFORM_WIDTH / 2 }, ]); const backgroundXRef = useRef(0); // Horizontal offset for parallax background const playerVelocityRef = useRef({ x: 0, y: 0 }); const requestIdRef = useRef(null); const lastTimeRef = useRef(null); const keysPressed = useRef({ left: false, right: false, up: false, jump: false }); const platform = { width: 400, height: 20, top: 450, left: 100 }; const checkCollisionWithPlatform = (position, width, height) => { const playerRect = { left: position.x, top: position.y, right: position.x + width, bottom: position.y + height, }; const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; return ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ); }; const updateGame = (time) => { const deltaTime = (time - (lastTimeRef.current || time)) / 1000; lastTimeRef.current = time; // Calculate new velocity let velocity = { x: keysPressed.current.left ? -MOVE_SPEED * deltaTime : keysPressed.current.right ? MOVE_SPEED * deltaTime : 0, y: playerVelocityRef.current.y + GRAVITY * deltaTime, }; // Store the x velocity playerVelocityRef.current.x = velocity.x; if (keysPressed.current.jump && isGrounded || keysPressed.current.jump && !doubleJumped) { if(!isGrounded){ setDoubleJumped(true) } velocity.y = JUMP_STRENGTH; keysPressed.current.jump = false; } // Calculate new position let newPosition = { x: playerPosition.x + velocity.x, y: playerPosition.y + velocity.y, }; // Platform creation and removal const firstPlatform = platforms[0]; const lastPlatform = platforms[platforms.length - 1]; // Remove off-screen platforms const visiblePlatforms = platforms.filter(platform => { const platformRightEdge = platform.left + platform.width - backgroundXRef.current; return platformRightEdge >= 0 && platform.left - backgroundXRef.current <= VIEW_WIDTH; }); // Add a new platform if needed if (newPosition.x > lastPlatform.left - 200) { // Generate new platform on the right visiblePlatforms.push(createNewPlatform(newPosition, "right")); } else if (newPosition.x < firstPlatform.left + 200) { // Generate new platform on the left visiblePlatforms.unshift(createNewPlatform(newPosition, "left")); } setPlatforms(visiblePlatforms); // Update background position for parallax effect if (keysPressed.current.left && backgroundXRef.current < 0) { backgroundXRef.current += MOVE_SPEED * deltaTime; } else if (keysPressed.current.right) { backgroundXRef.current -= MOVE_SPEED * deltaTime; } if (checkCollisionWithPlatform(newPosition, PLAYER_WIDTH, PLAYER_HEIGHT)) { newPosition.y = platform.top - PLAYER_HEIGHT; velocity.y = 0; setIsGrounded(true); setDoubleJumped(false); } else { setIsGrounded(false); } setPlayerPosition(prevPosition => ({ x: prevPosition.x + velocity.x, y: prevPosition.y + velocity.y, })); playerVelocityRef.current = velocity; // Request the next animation frame requestIdRef.current = requestAnimationFrame(updateGame); }; const createNewPlatform = (playerPosition, direction) => { const newTop = Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT); return direction === "right" ? { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: newTop, left: playerPosition.x + 300 } : { width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: newTop, left: playerPosition.x - 300 - PLATFORM_WIDTH }; }; useEffect(() => { const handleKeyDown = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = true; if (event.key === "ArrowRight") keysPressed.current.right = true; if (event.key === "ArrowUp" && isGrounded || event.key === "ArrowUp" && !doubleJumped) keysPressed.current.jump = true; }; const handleKeyUp = (event) => { if (event.key === "ArrowLeft") keysPressed.current.left = false; if (event.key === "ArrowRight") keysPressed.current.right = false; }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestIdRef.current = requestAnimationFrame(updateGame); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); cancelAnimationFrame(requestIdRef.current); }; }, [playerPosition,isGrounded, doubleJumped]); // add isGrounded to the dependency array return ( <div style={{ position: "relative", width: "100%", height: `${VIEW_HEIGHT}px`, overflow: "hidden" }}> <Player position={{ ...playerPosition, x: playerPosition.x - backgroundXRef.current }} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - backgroundXRef.current} /> ))} </div> ); } export default GameMain;
b6d6f74d84ccf04da741455df4a8ea63
{ "intermediate": 0.3850279152393341, "beginner": 0.4336523115634918, "expert": 0.18131983280181885 }
31,239
write a C# script for unity that allows an enemy character to move around the map on its own
e17461a62ec283932e32919afb169c95
{ "intermediate": 0.44470298290252686, "beginner": 0.1699453741312027, "expert": 0.38535159826278687 }
31,240
import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Read data from file with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/EngArb.txt', 'r',encoding='utf8') as file: data = file.readlines() # Split data into train, validate, and test train_ratio = 0.6 val_ratio = 0.2 test_ratio = 0.2 num_examples = len(data) num_train = int(num_examples * train_ratio) num_val = int(num_examples * val_ratio) train_data = data[:num_train] val_data = data[num_train:num_train+num_val] test_data = data[num_train+num_val:] # Extract English and Arabic sentences from data english_sentences_train = [] arabic_sentences_train = [] english_sentences_val = [] arabic_sentences_val = [] english_test = [] arabic_test = [] for line in train_data: english, arabic = line.strip().split('\t') english_sentences_train.append(english) arabic_sentences_train.append(arabic) for line in val_data: english, arabic = line.strip().split('\t') english_sentences_val.append(english) arabic_sentences_val.append(arabic) for line in test_data: english, arabic = line.strip().split('\t') english_test.append(english) arabic_test.append(arabic) # Tokenize the sentences and convert them into numerical representations tokenizer = Tokenizer(oov_token='<OOV>') tokenizer.fit_on_texts(english_sentences_train + arabic_sentences_train) english_train_sequences = tokenizer.texts_to_sequences(english_sentences_train) arabic_train_sequences = tokenizer.texts_to_sequences(arabic_sentences_train) english_val_sequences = tokenizer.texts_to_sequences(english_sentences_val) arabic_val_sequences = tokenizer.texts_to_sequences(arabic_sentences_val) english_test_sequences = tokenizer.texts_to_sequences(english_test) arabic_test_sequences = tokenizer.texts_to_sequences(arabic_test) # Pad or truncate the sentences to a fixed length max_length = 10 english_train_padded = pad_sequences(english_train_sequences, maxlen=max_length, padding='post', truncating='post') arabic_train_padded = pad_sequences(arabic_train_sequences, maxlen=max_length, padding='post', truncating='post') english_val_padded = pad_sequences(english_val_sequences, maxlen=max_length, padding='post', truncating='post') arabic_val_padded = pad_sequences(arabic_val_sequences, maxlen=max_length, padding='post', truncating='post') english_test_padded = pad_sequences(english_test_sequences, maxlen=max_length, padding='post', truncating='post') arabic_test_padded = pad_sequences(arabic_test_sequences, maxlen=max_length, padding='post', truncating='post') # Define the BiLSTM encoder-decoder model input_dim = len(tokenizer.word_index) + 1 output_dim = len(tokenizer.word_index) + 1 latent_dim = 256 embedding_dim = 100 encoder_inputs = tf.keras.layers.Input(shape=(max_length,)) encoder_embedding = tf.keras.layers.Embedding(input_dim, embedding_dim, input_length=max_length)(encoder_inputs) encoder_gru = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(latent_dim, return_state=True)) encoder_outputs, forward_h, forward_c, backward_h, backward_c = encoder_gru(encoder_embedding) state_h = tf.keras.layers.Concatenate()([forward_h, backward_h]) state_c = tf.keras.layers.Concatenate()([forward_c, backward_c]) decoder_inputs = tf.keras.layers.Input(shape=(max_length,)) decoder_embedding = tf.keras.layers.Embedding(input_dim, embedding_dim, input_length=max_length)(decoder_inputs) decoder_lstm = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(latent_dim * 2, return_sequences=True, return_state=True)) decoder_outputs, _ = decoder_lstm(decoder_embedding, initial_state=state_h) decoder_dense = tf.keras.layers.Dense(output_dim, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) model = tf.keras.models.Model([encoder_inputs, decoder_inputs], decoder_outputs) # Compile and train the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit([english_train_padded, arabic_train_padded], np.expand_dims(arabic_train_padded, -1), epochs=30, batch_size=16, validation_data=([english_val_padded, arabic_val_padded], np.expand_dims(arabic_val_padded, -1))) # Use test data to evaluate and example translation predictions = model.predict([english_test_padded, arabic_test_padded]) predicted_sequences = np.argmax(predictions, axis=2) predicted_sentences = tokenizer.sequences_to_texts(predicted_sequences) for i in range(len(english_test)): print(f'English: {english_test[i]}') print(f'Arabic (Actual): {arabic_test[i]}') print(f'Arabic (Predicted): {predicted_sentences[i]}') print()
8d600d6c8cb904e31b2f051a9d8c5d99
{ "intermediate": 0.40821146965026855, "beginner": 0.3092000484466553, "expert": 0.28258851170539856 }
31,241
python code using BiGRUencoder and BiLSTMdecoder rnn to translate English text to Arabic text by splitting example data into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example prediction translation from test
d7984447e5ae91ef0e34754ad219c27a
{ "intermediate": 0.44287797808647156, "beginner": 0.08860763907432556, "expert": 0.4685143828392029 }
31,242
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private Animator anim; private void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); player = GameObject.FindGameObjectWithTag("Player").transform; // Set initial target position as the current position targetPosition = rb.position; } private void Update() { // Calculate the distance to the player float distanceToPlayer = Vector2.Distance(rb.position, player.position); // If the player is within chase range, set player’s position as the target if (distanceToPlayer < chaseRange) { targetPosition = player.position; } else { // If the enemy reached the target position, set a new random target position float distanceToTarget = Vector2.Distance(rb.position, targetPosition); if (distanceToTarget < 0.1f) { targetPosition = GetRandomPosition(); } } // Move towards the target position Vector2 direction = (targetPosition - rb.position).normalized; rb.MovePosition(rb.position + direction * speed * Time.deltaTime); anim.SetFloat("moveX", direction.x); anim.SetFloat("moveY", direction.y); } private Vector2 GetRandomPosition() { // Get a random position within the map boundaries float x = Random.Range(-5f, 5f); float y = Random.Range(-5f, 5f); return new Vector2(x, y); } } make it so when the enemy is walking in a -x direction its sprite flips on the animator
4519c04bddef818f8a457a3bab37d269
{ "intermediate": 0.4689893126487732, "beginner": 0.3041344881057739, "expert": 0.2268761843442917 }
31,243
import pandas as pd import numpy as np import tensorflow as tf from sklearn.model_selection import train_test_split import tkinter as tk from tkinter import filedialog # Import filedialog for file selection from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # Generate sample data for X and y X = np.random.rand(100, 3) y = np.random.rand(100, 1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) def upload_data(): global X_train, X_test, y_train, y_test file_path = filedialog.askopenfilename() # Open file dialog for file selection # Process the uploaded data and split into training and testing sets # ... def train_model(learning_method): if learning_method == 'Deep Learning': # Build and train the deep learning model model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(1) ]) model.compile(optimizer='adam', loss='mean_squared_error') history = model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test)) # Display training progress display_training_progress(history) elif learning_method == 'Neural Network': # Build and train the neural network model using a different approach # This could involve using a different library or custom implementation # ... else: print("Invalid learning method selected") def display_training_progress(history): # Create a new window for displaying training progress progress_window = tk.Toplevel(root) progress_window.title('Training Progress') # Create a figure for displaying training progress fig = Figure(figsize=(6, 4), dpi=100) plot = fig.add_subplot(111) plot.plot(history.history['loss'], label='Training Loss') plot.plot(history.history['val_loss'], label='Validation Loss') plot.set_title('Model Training Progress') plot.set_xlabel('Epochs') plot.set_ylabel('Loss') plot.legend() # Add the figure to the window using canvas canvas = FigureCanvasTkAgg(fig, master=progress_window) canvas.draw() canvas.get_tk_widget().pack() # Create the main window root = tk.Tk() root.title('Deep Learning Model Training') # Add a button for data upload upload_button = tk.Button(root, text="Upload Training Data", command=upload_data) upload_button.pack() # Add a dropdown menu for selecting the learning method learning_method_var = tk.StringVar(root) learning_method_var.set('Deep Learning') # Set the default option learning_method_menu = tk.OptionMenu(root, learning_method_var, 'Deep Learning', 'Neural Network') learning_method_menu.pack() # Create a button to trigger the model training based on the selected method train_button = tk.Button(root, text="Train Model", command=lambda: train_model(learning_method_var.get())) train_button.pack() root.mainloop()
9f58448590706ed2f746b59dd7f124b2
{ "intermediate": 0.3625524342060089, "beginner": 0.3460328280925751, "expert": 0.2914147973060608 }
31,244
write me a python code that uses deep learning and neural network to analyze a given data and builds a strategy to predict the future price and explain the strategy to me write it in python to work no jupyter notebook add a button to chose training methode and abutton to upload the data and a window to visualize the progress of training and a window to explain the strategy and future price
fb87cb631d223abfa7855547a84c010b
{ "intermediate": 0.2529495358467102, "beginner": 0.03605136275291443, "expert": 0.7109991312026978 }
31,245
write a C# script that spawns in the Enemy prefab at the positions: (-5.5,3.5), (-5.5,-3.5), (5.5,3.5), (5.5,-3.5) every 10 seconds
1cf24344a70ff26697f9f7f16c834aec
{ "intermediate": 0.3795911967754364, "beginner": 0.2804144024848938, "expert": 0.3399943709373474 }
31,246
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private Animator anim; private SpriteRenderer spriteRenderer; private void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); player = GameObject.FindGameObjectWithTag("Player").transform; // Set initial target position as the current position targetPosition = rb.position; } private void Update() { // Calculate the distance to the player float distanceToPlayer = Vector2.Distance(rb.position, player.position); // If the player is within chase range, set player’s position as the target if (distanceToPlayer < chaseRange) { targetPosition = player.position; } else { // If the enemy reached the target position, set a new random target position float distanceToTarget = Vector2.Distance(rb.position, targetPosition); if (distanceToTarget < 0.1f) { targetPosition = GetRandomPosition(); } } // Move towards the target position Vector2 direction = (targetPosition - rb.position).normalized; rb.MovePosition(rb.position + direction * speed * Time.deltaTime); anim.SetFloat("moveX", direction.x); anim.SetFloat("moveY", direction.y); // Flip the sprite horizontally if moving in negative x direction if (direction.x < 0) { spriteRenderer.flipX = true; } else { spriteRenderer.flipX = false; } } private Vector2 GetRandomPosition() { // Get a random position within the map boundaries float x = Random.Range(-5f, 5f); float y = Random.Range(-5f, 5f); return new Vector2(x, y); } } add health to this script and make it so if health = 0 than the game object is destroyed
cf2d84c31893c41c9f4a1acbabd0b2eb
{ "intermediate": 0.3185126781463623, "beginner": 0.3912956416606903, "expert": 0.2901916801929474 }
31,247
使用正则表达式匹配一下的java日志,以下是3行java日志(时间开头),请帮我编写正则表达式来匹配每一行的日志,其中有些日志会有多行 2023-11-17 08:59:53.003 ERROR 1 --- [r-http-epoll-11] o.s.g.filter.MonitorResponseFilter : /blade-medical-technology/mobileterminal/getAllAppointment<-:->[{"code":500,"success":false,"data":null,"msg":"nested exception is org.apache.ibatis.exceptions.PersistenceException: \r\n### Error querying database. Cause: java.lang.NullPointerException\r\n### Cause: java.lang.NullPointerException"}] 2023-11-17 08:59:53.004 INFO 1 --- [or-http-epoll-8] o.s.g.filter.GlobalResponseLogFilter : ================ Gateway Response Start ================ <=== 500 GET: /blade-medical-technology/mobileterminal/getAllAppointment?cardNo=0001213311&inspectOrderStatus&inspectTypeName ===Headers=== transfer-encoding: ["chunked"] ===Headers=== Content-Type: ["application/json;charset=UTF-8"] ===Headers=== Date: ["Fri, 17 Nov 2023 00:59:52 GMT"] ================ Gateway Response End ================= 2023-11-17 08:59:57.186 ERROR 1 --- [r-http-epoll-44] o.s.g.handler.ErrorExceptionHandler : 404:[GET:http://10.10.1.2:8060/]:404 NOT_FOUND
9e1a981fa724f22245c496d514ee68ac
{ "intermediate": 0.4376530349254608, "beginner": 0.30628862977027893, "expert": 0.25605836510658264 }
31,248
write a python script that takes all images in a folder and makes them black and white
a81d45a390643555557e708ef7720a37
{ "intermediate": 0.3134464919567108, "beginner": 0.20967577397823334, "expert": 0.47687774896621704 }
31,249
write a python script that takes all images in a folder and makes them black and white
1c3167bf334e68b041c9a4964fac6e4e
{ "intermediate": 0.3134464919567108, "beginner": 0.20967577397823334, "expert": 0.47687774896621704 }
31,250
hello
ad1162092d8da8960e55db575b723b3c
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
31,251
como hago con este código para que pueda ver los otros componentes que no sean el de login y el de registro sin logearme import Pillsfront from "./components/Add_pills/Pills_front"; import { Device } from "./components/Device_connect/main"; import { Caddy } from "./components/Caddy_Log/Caddy/Caddy"; import { PeopleConnect } from "./components/Community/PeopleConnect"; // import { Main } from "./components/Home/Main"; import Signin from "./components/SignIn/Signin" import Signup from "./components/SignUp/Signup"; import { CommunityGroups } from "./components/Community/Groups/CommunityGroups"; import { ActiveGroups } from "./components/Community/Groups/ActiveGroups"; import { GroupMembers } from "./components/Community/Groups/GroupMembers.jsx"; import LinkDevice from './components/linkdevices/LinkDevice' import { Menu } from "./components/Menu/menu"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; import style from "./App.module.css"; // Header Icons import img1 from "./components/Header/menu.svg" import img2 from "./components/Header/bell.svg" // import img3 from "./components/Header/watch.svg" import img4 from "./components/Header/watchinactive.svg" // Footer Icons import homeIconActive from "./components/Footer/homeimgactive.svg"; import communityIcon from "./components/Footer/groupimg.svg"; import caddyIcon from "./components/Footer/VectorTab1.svg"; import Render from "./components/Render/Render"; // import Headerrr from "./components/Header/Header"; function App() { const handle_user_name = (data) => { localStorage.setItem("userName", data); } return ( <Router> <div> {/* header */} <div className={style.headerbody}> <div> <Link to="/Menu"> <span className={style.div1}><img src={img1} alt="menu"></img></span> </Link> </div> {/* <div className={style.div1}><img src={img1} alt="menu"></img></div> */} <div> <span><img src={img2} alt="bell"></img></span> <Link to="/linkdevice"><span><img src={img4} alt="deviceConnect"></img></span></Link> </div> </div> {/* Body */} <div className={style.appBody}> <Switch> <Route path="/" exact> <Render /> </Route> <Route path="/signin" exact> <Signin /* handle_user_name={handle_user_name} */ /> </Route> <Route path="/signup"> <Signup /> </Route> <Route path="/Home" exact> <Device style={{zIndex:"1"}}/> </Route> <Route path="/Menu" exact> <Device style={{zIndex:"1"}}/> <Menu style={{zIndex:"-1"}}/> </Route> <Route path="/PeopleConnect" exact> <PeopleConnect /> </Route> <Route path="/CommunityGroups" exact> <CommunityGroups /> </Route> <Route path="/ActiveGroups" exact> <ActiveGroups /> </Route> <Route path="/GroupMembers" exact> <GroupMembers /> </Route> <Route path="/Pills_front" exact> <Pillsfront /> </Route> <Route path="/Caddy" exact> <Caddy /> </Route> <Route path="/linkdevice" exact> <LinkDevice /> </Route> <Route> {/* 404 not found */} <Device /> </Route> </Switch> </div> {/* Footer */} <div className={style.footerbody}> <Link to="/Home"> <div> <img src={homeIconActive} id="homeicon" alt="home"></img> </div> </Link> <Link to="/PeopleConnect"> <div> <img src={communityIcon} id="communityicon" alt="community"></img> </div> </Link> <Link to="/Pills_front"> <div> <img className={style.fix} src={caddyIcon} id="caddyicon" alt="caddy"></img> </div> </Link> </div > </div > </Router > ); } export default App;
21dc9f2a7d24c297a5dbce46edb7e17d
{ "intermediate": 0.3440806269645691, "beginner": 0.48108330368995667, "expert": 0.1748361587524414 }
31,252
What is sql table, index, and trigger and how are they connected
a856dd59b63782a5abf9386c4a13cb98
{ "intermediate": 0.40393319725990295, "beginner": 0.20803380012512207, "expert": 0.3880329728126526 }
31,253
how get value of header cell in excel vb.net?
c3e060566ba4fe26d77968f050989ff7
{ "intermediate": 0.41781240701675415, "beginner": 0.19159331917762756, "expert": 0.3905942440032959 }
31,254
ты gpt 4 ?
8429e0bb32ea0d4a69cb5aeb4c491db2
{ "intermediate": 0.28412529826164246, "beginner": 0.3576904237270355, "expert": 0.3581843674182892 }
31,255
как на выходе из транзакции spring, при исключении передать данные другому объекту?
6153c3a9decb8a6cda6c1528408e46e0
{ "intermediate": 0.3232966661453247, "beginner": 0.23156802356243134, "expert": 0.44513532519340515 }
31,256
Is there a way to make explicit the source ofIs there a way to make explicit the source of the information from where a large language model gets its information for generating a specific output?
7749be02f16a1ad7806aa1ca574d106c
{ "intermediate": 0.2977682948112488, "beginner": 0.20894289016723633, "expert": 0.49328887462615967 }
31,257
import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; import java.net.*; import javax.swing.*; class MyFrame extends JFrame{ JTextField port;//端口 JButton start;//启动服务器 JTextArea content;//聊天框 JTextField tex;//消息 JButton say;//发送 Socket socket;//套接字 //Myframe类构造函数 MyFrame(){ /*this.setTitle("网络通信服务器"); this.setVisible(true); this.setResizable(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/ FlowLayout flowLayout=new FlowLayout(); setLayout(flowLayout); //设置窗体为流式布局 setSize(500,460); setLocation(500,100); JLabel showport=new JLabel("Port:"); add(showport);//"Port" port = new JTextField("8888",15); add(port); start = new JButton("Start"); add(start); content = new JTextArea(15,50); JScrollPane scroll = new JScrollPane(content); //设置滚动条 add(scroll); add(new JLabel("Say:")); tex = new JTextField("Hello,this is server.",30); add(tex); say = new JButton("Say"); add(say); StartListen startListen = new StartListen(); SayListen sayListen = new SayListen(); start.addActionListener(startListen); //为按钮 start 注册一个监听器 say.addActionListener(sayListen); //为按钮 say注册一个监听器 } class StartListen implements ActionListener{ public void actionPerformed(ActionEvent event){ start.setEnabled(false); try { int portnum=Integer.parseInt(port.getText());//端口号 ServerSocket myserver = new ServerSocket(portnum); // 创建一个服务器套接字对象,形参为端口号 socket = myserver.accept(); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);// 创建一个打印输出流对象,其形参为从套接字 socket 对象中获取的输出流 out.println("Connected");//连接响应 content.append("Client connected"+"\n"); ServerThread st = new ServerThread(); //创建一个 ServerThread 对象st st.start(); //启动一个线程,调用 run()方法 } catch (IOException e) { System.out.println(e); } } }//start监听器 class SayListen implements ActionListener{ public void actionPerformed(ActionEvent event){ try { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);// 创建一个打印输出流,形参为从套接字socket 中获取的输出流 String str=tex.getText(); if(!str.isEmpty()){ out.println(new Date()+"\n"+str); //打印输出日期和发送的消息至客户端 content.append(new Date()+" \n Me:"+str+"\n");//将消息显示在jtextarea中 out.flush(); //清空缓存区 } tex.setText("");//清空输入栏 } catch (Exception e) { System.out.println(e); } } }//say监听器 class ServerThread extends Thread{ ServerThread(){} public void run(){ try { BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //创建一个缓冲输出流,其形参为从套接字 socket 中获取的输入流 String str; while(true){ str = in.readLine(); //按行读取 content.append( str+"\n");//将输入显示在聊天框中 } } catch (Exception e) { System.out.println(e); } } } } public class Main{ public static void main(String[] args){ MyFrame server = new MyFrame(); server.setTitle("网络通信服务器"); server.setVisible(true); server.setResizable(false); //设置此窗体是否可由用户调整大小 server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置默认关闭操作 } }请详细分析这段代码的构建过程
ff375d896574d88a72d373a04c1f7ce8
{ "intermediate": 0.33578816056251526, "beginner": 0.5465909838676453, "expert": 0.11762084811925888 }
31,258
How exactly could I import a SFM model into blender, modify it, then export it back into SFM?
bde15c4c10f3098c9c5ba8975816dc06
{ "intermediate": 0.3914300203323364, "beginner": 0.20168232917785645, "expert": 0.4068876802921295 }
31,259
add jump to this: import React, { useState, useEffect, useRef } from "react"; // Constants const GRAVITY = 980; // Pixels per second squared const JUMP_STRENGTH = -600; // Pixels per second const MOVE_SPEED = 500; // Pixels per second const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 300; // Reduced width to make the game more challenging const PLATFORM_HEIGHT = 120; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 600; // Increased height for more vertical space // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({position}) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${VIEW_WIDTH / 2 - PLAYER_WIDTH / 2}px`, top: `${position.y}px`, zIndex: 2, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: VIEW_WIDTH / 2, // Start player in the center of the view y: VIEW_HEIGHT - PLATFORM_HEIGHT - PLAYER_HEIGHT, // Start player on top of initial platform }); const [playerVelocity, setPlayerVelocity] = useState({ x: 0, y: 0 }); const [isGrounded, setIsGrounded] = useState(true); // Start player as grounded const [platforms, setPlatforms] = useState([ // Initial platform to cover the bottom of the screen { width: VIEW_WIDTH, height: PLATFORM_HEIGHT, top: VIEW_HEIGHT - PLATFORM_HEIGHT, left: 0 }, ]); const lastTimeRef = useRef(performance.now()); const keysPressed = useRef({ left: false, right: false, jump: false }); // Create new platform to the right of the last platform const createNewPlatform = () => ({ width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: Math.max(PLATFORM_HEIGHT, Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT - 10)), left: platforms[platforms.length - 1].left + PLATFORM_WIDTH + Math.random() * 400 + 200, }); // Check collision between player and platforms const checkCollisionWithPlatforms = () => { const playerRect = { left: playerPosition.x - PLAYER_WIDTH / 2, top: playerPosition.y, right: playerPosition.x + PLAYER_WIDTH / 2, bottom: playerPosition.y + PLAYER_HEIGHT, }; return platforms.some((platform) => { const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; return ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ); }); }; // Game loop const gameLoop = () => { const now = performance.now(); const deltaTime = (now - lastTimeRef.current) / 1000.0; lastTimeRef.current = now; // Update player velocity and position const newVelocity = { ...playerVelocity }; if (keysPressed.current.left) { playerPosition.x -= MOVE_SPEED * deltaTime; } if (keysPressed.current.right) { playerPosition.x += MOVE_SPEED * deltaTime; } if (!isGrounded) { newVelocity.y += GRAVITY * deltaTime; // Gravity } else { newVelocity.y = 0; } if (keysPressed.current.jump && isGrounded) { newVelocity.y = JUMP_STRENGTH; // Jump setIsGrounded(false); keysPressed.current.jump = false; // Prevent multi-jumping } const newPosition = { x: playerPosition.x, y: playerPosition.y + newVelocity.y * deltaTime }; // Check for collisions const collided = checkCollisionWithPlatforms(); if (collided) { setIsGrounded(true); newPosition.y = VIEW_HEIGHT - PLATFORM_HEIGHT - PLAYER_HEIGHT; // Snap player to the top of the platform } else { setIsGrounded(false); } // Create new platform if the last platform is at a certain distance to the left if (platforms[platforms.length - 1].left < playerPosition.x + VIEW_WIDTH) { setPlatforms([...platforms, createNewPlatform()]); } // Remove platforms that have gone offscreen to the left const visiblePlatforms = platforms.filter((platform) => platform.left > playerPosition.x - VIEW_WIDTH); setPlayerPosition(newPosition); setPlayerVelocity(newVelocity); setPlatforms(visiblePlatforms); requestAnimationFrame(gameLoop); }; useEffect(() => { function handleKeyDown({ key }) { if (key === "ArrowLeft") keysPressed.current.left = true; if (key === "ArrowRight") keysPressed.current.right = true; if (key === "ArrowUp") keysPressed.current.jump = true; } function handleKeyUp({ key }) { if (key === "ArrowLeft") keysPressed.current.left = false; if (key === "ArrowRight") keysPressed.current.right = false; if (key === "ArrowUp") keysPressed.current.jump = false; // Handle Space key for jumping on key up } window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestAnimationFrame(gameLoop); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); }; }, []); return ( <div style={{ position: "relative", width: `${VIEW_WIDTH}px`, height: `${VIEW_HEIGHT}px`, overflow: "hidden", backgroundColor: "lightblue", }} > {/* Update Player component prop */} <Player position={playerPosition} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - playerPosition.x + VIEW_WIDTH / 2} top={platform.top} /> ))} </div> ); } export default GameMain;
1948d9507171a6c0fbe63fa7e459f55d
{ "intermediate": 0.37258267402648926, "beginner": 0.5100222826004028, "expert": 0.11739510297775269 }
31,260
rewrite the game for me to make it more responsible and smooth: import React, { useState, useEffect, useRef } from "react"; // Constants const GRAVITY = 980; // Pixels per second squared const JUMP_STRENGTH = -600; // Pixels per second const MOVE_SPEED = 500; // Pixels per second const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 300; // Reduced width to make the game more challenging const PLATFORM_HEIGHT = 120; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 600; // Increased height for more vertical space // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({position}) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${VIEW_WIDTH / 2 - PLAYER_WIDTH / 2}px`, top: `${position.y}px`, zIndex: 2, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: VIEW_WIDTH / 2, // Start player in the center of the view y: VIEW_HEIGHT - PLATFORM_HEIGHT - PLAYER_HEIGHT, // Start player on top of initial platform }); const [playerVelocity, setPlayerVelocity] = useState({ x: 0, y: 0 }); const [isGrounded, setIsGrounded] = useState(true); // Start player as grounded const [platforms, setPlatforms] = useState([ // Initial platform to cover the bottom of the screen { width: VIEW_WIDTH, height: PLATFORM_HEIGHT, top: VIEW_HEIGHT - PLATFORM_HEIGHT, left: 0 }, ]); const lastTimeRef = useRef(performance.now()); const keysPressed = useRef({ left: false, right: false, jump: false }); // Create new platform to the right of the last platform const createNewPlatform = () => ({ width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: Math.max(PLATFORM_HEIGHT, Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT - 10)), left: platforms[platforms.length - 1].left + PLATFORM_WIDTH + Math.random() * 400 + 200, }); // Check collision between player and platforms // Check collision between player and platforms const checkCollisionWithPlatforms = () => { const playerRect = { left: playerPosition.x - PLAYER_WIDTH / 2, top: playerPosition.y, right: playerPosition.x + PLAYER_WIDTH / 2, bottom: playerPosition.y + PLAYER_HEIGHT, }; for (let i = 0; i < platforms.length; i++) { const platform = platforms[i]; const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; if ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.top > platformRect.top && playerRect.top < platformRect.bottom ) { // Colliding with platform, return the platform return platform; } } // No collision with any platforms return null; }; // Game loop const gameLoop = () => { const now = performance.now(); const deltaTime = (now - lastTimeRef.current) / 1000.0; lastTimeRef.current = now; // Check for collisions const collided = checkCollisionWithPlatforms(); // Update player velocity and position const newVelocity = { ...playerVelocity }; let newPositionX = playerPosition.x; if (keysPressed.current.left) { newPositionX -= MOVE_SPEED * deltaTime; } if (keysPressed.current.right) { newPositionX += MOVE_SPEED * deltaTime; } let newPositionY = playerPosition.y; if (!isGrounded) { newVelocity.y += GRAVITY * deltaTime; // Gravity } else { newVelocity.y = 0; } if (keysPressed.current.jump && isGrounded) { newVelocity.y = JUMP_STRENGTH; // Jump setIsGrounded(false); keysPressed.current.jump = false; // Prevent multi-jumping } newPositionY = Math.max(0, newPositionY + newVelocity.y * deltaTime); // Collision response if (collided) { setIsGrounded(true); newPositionY = collided.top - PLAYER_HEIGHT; // Now, the newPositionY is set to the top of the collided platform } else { setIsGrounded(false); } // Create new platform if the last platform is at a certain distance to the left if (platforms[platforms.length - 1].left < playerPosition.x + VIEW_WIDTH) { setPlatforms([...platforms, createNewPlatform()]); } // Remove platforms that have gone offscreen to the left const visiblePlatforms = platforms.filter((platform) => platform.left > playerPosition.x - VIEW_WIDTH); // Set the new position state setPlayerPosition({ x: newPositionX, y: newPositionY }); setPlayerVelocity(newVelocity); setPlatforms(visiblePlatforms); requestAnimationFrame(gameLoop); }; useEffect(() => { function handleKeyDown({ key }) { if (key === "ArrowLeft") keysPressed.current.left = true; if (key === "ArrowRight") keysPressed.current.right = true; if (key === "ArrowUp") keysPressed.current.jump = true; } function handleKeyUp({ key }) { if (key === "ArrowLeft") keysPressed.current.left = false; if (key === "ArrowRight") keysPressed.current.right = false; if (key === "ArrowUp") keysPressed.current.jump = false; // Handle Space key for jumping on key up } window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestAnimationFrame(gameLoop); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); }; }, []); return ( <div style={{ position: "relative", width: `${VIEW_WIDTH}px`, height: `${VIEW_HEIGHT}px`, overflow: "hidden", backgroundColor: "lightblue", }} > {/* Update Player component prop */} <Player position={playerPosition} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - playerPosition.x + VIEW_WIDTH / 2} top={platform.top} /> ))} </div> ); } export default GameMain;
da7cf0087d3e4ceb7463822635b2e0a1
{ "intermediate": 0.38633623719215393, "beginner": 0.47586801648139954, "expert": 0.13779576122760773 }
31,261
as an expert reacty/typescript expert fix this game so it works correctly as a platformer: import React, { useState, useEffect, useRef } from "react"; // Constants const GRAVITY = 980; // Pixels per second squared const JUMP_STRENGTH = -600; // Pixels per second const MOVE_SPEED = 500; // Pixels per second const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 300; const PLATFORM_HEIGHT = 120; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 600; // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({ x, y }) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${x - PLAYER_WIDTH / 2}px`, top: `${y}px`, zIndex: 2, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: VIEW_WIDTH / 2, y: VIEW_HEIGHT - PLATFORM_HEIGHT - PLAYER_HEIGHT, }); const [playerVelocity, setPlayerVelocity] = useState({ x: 0, y: 0 }); const [isGrounded, setIsGrounded] = useState(true); const [platforms, setPlatforms] = useState([ { width: VIEW_WIDTH, height: PLATFORM_HEIGHT, top: VIEW_HEIGHT - PLATFORM_HEIGHT, left: 0, }, ]); const lastTimeRef = useRef(performance.now()); const keysPressed = useRef({ left: false, right: false, jump: false }); const createNewPlatform = () => ({ width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: Math.max(PLATFORM_HEIGHT, Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT - 10)), left: platforms[platforms.length - 1].left + PLATFORM_WIDTH + Math.random() * 400 + 200, }); // Check collision between player and platforms const checkCollisionWithPlatforms = () => { const playerRect = { left: playerPosition.x - PLAYER_WIDTH / 2, top: playerPosition.y, right: playerPosition.x + PLAYER_WIDTH / 2, bottom: playerPosition.y + PLAYER_HEIGHT, }; for (const platform of platforms) { const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; if ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ) { return platform; // Colliding with platform } } return null; }; // Game loop const gameLoop = () => { const now = performance.now(); const deltaTime = (now - lastTimeRef.current) / 1000.0; lastTimeRef.current = now; // Update player velocity and position const newVelocity = { ...playerVelocity }; let newPositionX = playerPosition.x; if (keysPressed.current.left) { newPositionX -= MOVE_SPEED * deltaTime; } if (keysPressed.current.right) { newPositionX += MOVE_SPEED * deltaTime; } let newPositionY = playerPosition.y; if (!isGrounded) { newVelocity.y += GRAVITY * deltaTime; // Apply gravity } else { newVelocity.y = 0; } if (keysPressed.current.jump && isGrounded) { newVelocity.y = JUMP_STRENGTH; // Apply jump setIsGrounded(false); keysPressed.current.jump = false; } newPositionY = Math.max(0, newPositionY + newVelocity.y * deltaTime); // Check for collisions const collided = checkCollisionWithPlatforms(); // Collision response if (collided) { setIsGrounded(true); newPositionY = collided.top - PLAYER_HEIGHT; } else { setIsGrounded(false); } setPlayerPosition({ x: newPositionX, y: newPositionY }); setPlayerVelocity(newVelocity); // Create new platform if needed if (platforms[platforms.length - 1].left < playerPosition.x + VIEW_WIDTH) { setPlatforms((prevPlatforms) => [...prevPlatforms, createNewPlatform()]); } // Remove platforms that are offscreen setPlatforms((prevPlatforms) => prevPlatforms.filter((platform) => platform.left > playerPosition.x - VIEW_WIDTH)); requestAnimationFrame(gameLoop); }; useEffect(() => { const handleKeyDown = ({ key }) => { if (key === "ArrowLeft") keysPressed.current.left = true; if (key === "ArrowRight") keysPressed.current.right = true; if (key === "ArrowUp" || key === " ") keysPressed.current.jump = true; }; const handleKeyUp = ({ key }) => { if (key === "ArrowLeft") keysPressed.current.left = false; if (key === "ArrowRight") keysPressed.current.right = false; if (key === "ArrowUp" || key === " ") keysPressed.current.jump = false; // Added "Space" for jump }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestAnimationFrame(gameLoop); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); }; }, []); return ( <div style={{ position: "relative", width: `${VIEW_WIDTH}px`, height: `${VIEW_HEIGHT}px`, overflow: "hidden", backgroundColor: "lightblue", }} > <Player x={playerPosition.x + VIEW_WIDTH / 2} y={playerPosition.y} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - playerPosition.x + VIEW_WIDTH / 2} /> ))} </div> ); } export default GameMain;
cdb55ed60c7f2960a4e5f42ed3a8bd00
{ "intermediate": 0.36756235361099243, "beginner": 0.4851113557815552, "expert": 0.14732635021209717 }
31,262
completely rewrite this for me so it works smoothly spawns platforms correctly: import React, { useState, useEffect, useRef } from "react"; // Constants const GRAVITY = 980; // Pixels per second squared const JUMP_STRENGTH = -600; // Pixels per second const MOVE_SPEED = 500; // Pixels per second const PLAYER_WIDTH = 50; const PLAYER_HEIGHT = 50; const PLATFORM_WIDTH = 300; const PLATFORM_HEIGHT = 120; const VIEW_WIDTH = 800; const VIEW_HEIGHT = 600; // Platform component const Platform = ({ width, height, top, left }) => ( <div style={{ position: "absolute", width: `${width}px`, height: `${height}px`, backgroundColor: "brown", left: `${left}px`, top: `${top}px`, }} /> ); // Player component const Player = ({ x, y }) => ( <div style={{ position: "absolute", width: `${PLAYER_WIDTH}px`, height: `${PLAYER_HEIGHT}px`, backgroundColor: "blue", left: `${x - PLAYER_WIDTH / 2}px`, top: `${y}px`, zIndex: 2, }} /> ); function GameMain() { const [playerPosition, setPlayerPosition] = useState({ x: VIEW_WIDTH / 2, y: VIEW_HEIGHT - PLATFORM_HEIGHT - PLAYER_HEIGHT, }); const [playerVelocity, setPlayerVelocity] = useState({ x: 0, y: 0 }); const [isGrounded, setIsGrounded] = useState(true); const [platforms, setPlatforms] = useState([ { width: VIEW_WIDTH, height: PLATFORM_HEIGHT, top: VIEW_HEIGHT - PLATFORM_HEIGHT, left: 0, }, ]); const lastTimeRef = useRef(performance.now()); const keysPressed = useRef({ left: false, right: false, jump: false }); const createNewPlatform = () => ({ width: PLATFORM_WIDTH, height: PLATFORM_HEIGHT, top: Math.max(PLATFORM_HEIGHT, Math.random() * (VIEW_HEIGHT - PLATFORM_HEIGHT - 10)), left: platforms[platforms.length - 1].left + PLATFORM_WIDTH + Math.random() * 400 + 200, }); // Check collision between player and platforms const checkCollisionWithPlatforms = () => { const playerRect = { left: playerPosition.x - PLAYER_WIDTH / 2, top: playerPosition.y, right: playerPosition.x + PLAYER_WIDTH / 2, bottom: playerPosition.y + PLAYER_HEIGHT, }; for (const platform of platforms) { const platformRect = { left: platform.left, top: platform.top, right: platform.left + platform.width, bottom: platform.top + platform.height, }; if ( playerRect.right > platformRect.left && playerRect.left < platformRect.right && playerRect.bottom > platformRect.top && playerRect.top < platformRect.bottom ) { return platform; // Colliding with platform } } return null; }; // Game loop const gameLoop = () => { const now = performance.now(); const deltaTime = (now - lastTimeRef.current) / 1000.0; lastTimeRef.current = now; // Update player velocity and position const newVelocity = { ...playerVelocity }; let newPositionX = playerPosition.x; if (keysPressed.current.left) { newPositionX -= MOVE_SPEED * deltaTime; } if (keysPressed.current.right) { newPositionX += MOVE_SPEED * deltaTime; } let newPositionY = playerPosition.y; if (!isGrounded) { newVelocity.y += GRAVITY * deltaTime; // Apply gravity } else { newVelocity.y = 0; } if (keysPressed.current.jump && isGrounded) { newVelocity.y = JUMP_STRENGTH; // Apply jump setIsGrounded(false); keysPressed.current.jump = false; } newPositionY = Math.max(0, newPositionY + newVelocity.y * deltaTime); // Check for collisions const collided = checkCollisionWithPlatforms(); // Collision response if (collided) { setIsGrounded(true); newPositionY = collided.top - PLAYER_HEIGHT; } else { setIsGrounded(false); } setPlayerPosition({ x: newPositionX, y: newPositionY }); setPlayerVelocity(newVelocity); // Create new platform if needed if (platforms[platforms.length - 1].left < playerPosition.x + VIEW_WIDTH) { setPlatforms((prevPlatforms) => [...prevPlatforms, createNewPlatform()]); } // Remove platforms that are offscreen setPlatforms((prevPlatforms) => prevPlatforms.filter((platform) => platform.left > playerPosition.x - VIEW_WIDTH)); requestAnimationFrame(gameLoop); }; useEffect(() => { const handleKeyDown = ({ key }) => { if (key === "ArrowLeft") keysPressed.current.left = true; if (key === "ArrowRight") keysPressed.current.right = true; if (key === "ArrowUp" || key === " ") keysPressed.current.jump = true; }; const handleKeyUp = ({ key }) => { if (key === "ArrowLeft") keysPressed.current.left = false; if (key === "ArrowRight") keysPressed.current.right = false; if (key === "ArrowUp" || key === " ") keysPressed.current.jump = false; // Added "Space" for jump }; window.addEventListener("keydown", handleKeyDown); window.addEventListener("keyup", handleKeyUp); requestAnimationFrame(gameLoop); return () => { window.removeEventListener("keydown", handleKeyDown); window.removeEventListener("keyup", handleKeyUp); }; }, []); return ( <div style={{ position: "relative", width: `${VIEW_WIDTH}px`, height: `${VIEW_HEIGHT}px`, overflow: "hidden", backgroundColor: "lightblue", }} > <Player x={playerPosition.x + VIEW_WIDTH / 2} y={playerPosition.y} /> {platforms.map((platform, index) => ( <Platform key={index} {...platform} left={platform.left - playerPosition.x + VIEW_WIDTH / 2} /> ))} </div> ); } export default GameMain;
862c63e16c1d312ce110e9d1f6ca180a
{ "intermediate": 0.3618495464324951, "beginner": 0.4408906102180481, "expert": 0.1972597986459732 }
31,263
Explain
ed3f1d5bdb89059f4e40ea9144eacf43
{ "intermediate": 0.36335062980651855, "beginner": 0.3253214657306671, "expert": 0.31132787466049194 }
31,264
Create a python crypto trading bot that uses Binance api, this bot should be able to analize the market trends and generate strategies that can be saved. Strategies should be in pinecone v5
5e5c3bbfbdb9d25c59c4e3a728ca1370
{ "intermediate": 0.31550318002700806, "beginner": 0.11562372744083405, "expert": 0.5688731670379639 }
31,265
can you give me code in order to display a spinner into an existing iframe, when i clic on a link, before the real content ?
3b6aadc011067f55200dc34bcdf5494c
{ "intermediate": 0.6291637420654297, "beginner": 0.13708029687404633, "expert": 0.2337559014558792 }
31,266
test case is not entring another class inspite being passed during debugging
9495f6c2a99a98c85df039ed32dd812b
{ "intermediate": 0.3815038204193115, "beginner": 0.5343034267425537, "expert": 0.08419283479452133 }
31,267
напиши модульный тест на c# для программы: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyCalc { public class MyCalcLib { static double Otr(double x1, double y1, double x2, double y2) { return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)); } static double Perim(double Ax, double Ay, double Bx, double By, double Cx, double Cy) { double AB = Otr(Ax, Ay, Bx, By); double BC = Otr(Bx, By, Cx, Cy); double CA = Otr(Cx, Cy, Ax, Ay); return AB + BC + CA; } static void Main() { double Ax = 0, Ay = 0; double Bx = 3, By = 0; double Cx = 0, Cy = 4; double Dx = 4, Dy = 2; double Perim_ABC = Perim(Ax, Ay, Bx, By, Cx, Cy); double Perim_ABD = Perim(Ax, Ay, Bx, By, Dx, Dy); double Perim_ACD = Perim(Ax, Ay, Cx, Cy, Dx, Dy); } } }
d0d942f06748077b6d2232f8a8c4d89f
{ "intermediate": 0.30497077107429504, "beginner": 0.4695426821708679, "expert": 0.22548653185367584 }
31,268
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Барабаны останавливаются одновременно. Как сделать, чтобы, сначала останавливались только первые барабаны из 3 рядов, потом вторые, третьи, четвертые и пятые последовательно?
ecdd15bcf202d2683c99b3ec12f40104
{ "intermediate": 0.26611724495887756, "beginner": 0.5244644284248352, "expert": 0.20941835641860962 }
31,269
ionic
79034ac08b6a33c53f893ea62e84ad4f
{ "intermediate": 0.31868302822113037, "beginner": 0.27207598090171814, "expert": 0.4092410206794739 }
31,270
у меня есть метод, мне нужно до того как выбросился AbsErrorException, чтобы слушатель зафиксировал и выполнил изменения, которые произошли в методе sendDisposals(disposalCaption), через @TransactionalEventListener @Override @Transactional public AbsDisposalResponse sendDisposals(AbsDisposalPayload disposalPayload) { AbsDisposalCaption disposalCaption = absDisposalHelpService.createDisposals(disposalPayload); if (disposalCaption == null) { throw new IllegalArgumentException("[getDisposalPayload] AbsDisposalPayload validation error"); } absDisposalHelpService.sendDisposals(disposalCaption); if (AbsState.PASSED.equals(disposalCaption.getState())) { return absDisposalHelpService.convertToResponse(disposalCaption); } else if (AbsState.NOT_PASS.equals(disposalCaption.getState())) { throw new AbsFailException(); } else if (AbsState.ERROR.equals(disposalCaption.getState())) { throw new AbsErrorException(absDisposalHelpService.convertToResponse(disposalCaption)); } else { throw new AbsFailException(); } }
b0996b64da433b49461cc1cead04fb7d
{ "intermediate": 0.4391237497329712, "beginner": 0.37030985951423645, "expert": 0.190566286444664 }
31,271
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Барабаны останавливаются одновременно. Как сделать, чтобы, сначала останавливались только первые барабаны из 3 рядов, потом вторые, третьи, четвертые и пятые последовательно?
3a314c88a6ca489bddb01c59e0d9a976
{ "intermediate": 0.26809585094451904, "beginner": 0.522678554058075, "expert": 0.20922555029392242 }
31,272
<form class="p-3 p-xl-4" method="post"> <div class="mb-3"><input class="form-control" type="text" id="name-1" name="name" placeholder="Имя"><div data-lastpass-icon-root="true" style="position: relative !important; height: 0px !important; width: 0px !important; float: left !important;"></div></div> <div class="mb-3"><input class="form-control" type="email" id="email-1" name="email" placeholder="телефон"></div> <div class="mb-3"><textarea class="form-control" id="message-1" name="message" rows="6" placeholder="Сообщение"></textarea></div> <div><button class="btn btn-primary shadow d-block w-100" type="submit">Отправить</button></div> </form> добавить к этой форме обработчик на js для проверки что все поля заплнены. что почта верная. что телефон верный. и отправлть на телеграмм бота
4f0e3fe9138b402ddfd49b26997fb76c
{ "intermediate": 0.29997560381889343, "beginner": 0.3961806297302246, "expert": 0.30384379625320435 }
31,273
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Где устанавливается время вращения барабанов?
331dcd4b0e04e797bd22c870ed072494
{ "intermediate": 0.26809585094451904, "beginner": 0.522678554058075, "expert": 0.20922555029392242 }
31,274
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Как сделать что бы спустя 2 секунды после запуска барабанов, остановился каждый 1 барабан из 3 рядов
16dbdca23c9f28654aa407665aeba097
{ "intermediate": 0.26809585094451904, "beginner": 0.522678554058075, "expert": 0.20922555029392242 }
31,275
How to add the name of Excel file in pandas DataFrame in each row?
760ed2ee83758e25b469f51aa9f8fcf7
{ "intermediate": 0.6857469081878662, "beginner": 0.1190648004412651, "expert": 0.19518829882144928 }
31,276
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Как сделать что бы спустя 2 секунды после запуска барабанов, остановился каждый 1 барабан из 3 рядов
6412f5f7cc3ba5e39f4b8780e3f9e2ac
{ "intermediate": 0.26809585094451904, "beginner": 0.522678554058075, "expert": 0.20922555029392242 }
31,277
how to start 2 to 3 application's in windows 11 at once?
e35238098bb4a71bbe0bb04cfd015001
{ "intermediate": 0.45458123087882996, "beginner": 0.18276895582675934, "expert": 0.3626498579978943 }
31,278
I have a number 86399 in JS, how do I round it up to 86400?
b3b63ad4c9f6534d9e147231e836c386
{ "intermediate": 0.3251413106918335, "beginner": 0.2674466669559479, "expert": 0.40741196274757385 }
31,279
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Как вернуть все барабаны в исходное положение?
15b79e683b5a087962c568fe788125c7
{ "intermediate": 0.26809585094451904, "beginner": 0.522678554058075, "expert": 0.20922555029392242 }
31,280
would you pls write a service for the game "Ball-Match 3D"?
2ff994fcb387f9753934d68cd24b1532
{ "intermediate": 0.4209924340248108, "beginner": 0.2632867693901062, "expert": 0.315720796585083 }
31,281
how can I call this audio <audio> from my python code? @app.get("/audio") async def playAudio(): with open("audio.mp3", "rb") as f: audio_data = f.read() # Playback the audio return "playing audio": ] if stable_frame is not None: frame_diff = cv2.absdiff(combined_area, stable_frame) non_zero_count = np.count_nonzero(frame_diff) print("heythere") print(non_zero_count) if non_zero_count > frame_diff_threshold: # A significant difference is detected, update the stable frame and reset timestamp last_frame_change_time = datetime.now() stable_frame = np.copy(combined_area) print("Frame has changed significantly. Updating stable frame.") else: # No stable frame yet, so assign one and start the timer stable_frame = np.copy(combined_area) # Check if the frame has been stable for at least 1.5 seconds print(datetime.now() - last_frame_change_time) if ( datetime.now() - last_frame_change_time >= minimum_stable_time and found_weight == False ): print("Frame has been stable for 1.5 seconds. Running OCR.") kg_result = check_picture(kg_area) hg_result = check_picture(hg_area) combined_result = check_picture(combined_area) await generate_audio(combined_result) await playAudio() print(f"Weight {kg_result}.{hg_result}") print(f"combined: {combined_result}") await update_csv(combined_result) <!DOCTYPE html> <html> <head> <title>Video</title> </head> <body> <button onclick="captureImage()">Capture Image</button> <audio id="audioPlayer" src="/audio"></audio> <script> function captureImage() { fetch('/start_processing', { method: 'POST' }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error('Network response was not ok'); } }) .then(data => { console.log('Data received:', data); // Log the data for debugging purposes // The rest of your logic for handling the successful POST request }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); } </script> </body> </html>
9aa936f54e28963391dd2b937a6d41e8
{ "intermediate": 0.3407663106918335, "beginner": 0.4554935097694397, "expert": 0.2037401795387268 }
31,282
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> #include <vector> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } void resetDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.currentTexture = 0; drum.rotation = 0; } } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { Uint32 stopTime = 0; bool isStopping = false; SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); // Остановка барабанов по очереди if (!isStopping && SDL_GetTicks() - startTime >= 2000) { drums[0].speed = 0; drums[0].rotation = drums[0].currentTexture * 120; drums[5].speed = 0; drums[5].rotation = drums[5].currentTexture * 120; drums[10].speed = 0; drums[10].rotation = drums[10].currentTexture * 120; isStopping = true; stopTime = SDL_GetTicks(); // Запоминаем время остановки } if (isStopping && SDL_GetTicks() - stopTime >= 2000) { drums[0].speed = drumSpeeds[0] * 10; drums[5].speed = drumSpeeds[0] * 10; drums[10].speed = drumSpeeds[0] * 10; isStopping = false; } } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Как сделать что бы при нажатии на пробел проверялось что все барабаны уже не крутятся если не крутятся то крутить барабаны?
45f098cdecf52265d2300ecc69632661
{ "intermediate": 0.30762791633605957, "beginner": 0.4315859377384186, "expert": 0.2607862055301666 }
31,283
esse codigo //Arrange string parametro = "1111,2222,3333"; string url = $"/nana/v1/nana?nana?lista={parametro}"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _jwt); //Act HttpResponseMessage response = await _client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); var token = JToken.Parse(body); //Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Single(token.SelectTokens("$.data[*]")); nao esta enviando um fromquery nessa minha rota [HttpGet] public async Task<IActionResult> List([FromQuery(Name = "lista")] string entrada) {
dea5e037b4edffbed562fce4737b9a4c
{ "intermediate": 0.35148367285728455, "beginner": 0.37773337960243225, "expert": 0.2707829475402832 }
31,284
FeignClient Com Spring Boot e config properties, implementando maximo de conexoes e timeout
5ddd79450da3cf0c597c7afee5fb10e1
{ "intermediate": 0.5926928520202637, "beginner": 0.204868882894516, "expert": 0.20243825018405914 }
31,285
how to properly manage null values in C# ?
814a4b6e450590986e4ba43e7884f906
{ "intermediate": 0.5055475234985352, "beginner": 0.2663547098636627, "expert": 0.22809776663780212 }
31,286
how to use string interpolation in c#?
61a79be3bceb6b301194c5542dad3da4
{ "intermediate": 0.6694049835205078, "beginner": 0.1594831645488739, "expert": 0.1711118072271347 }
31,287
how to use string interpolation in c#?
d09de5d6c120f1381e19759fbec2aa6f
{ "intermediate": 0.6694049835205078, "beginner": 0.1594831645488739, "expert": 0.1711118072271347 }
31,288
how to use string interpolation in c#?
fab3e5342670882d090c33410a389271
{ "intermediate": 0.6694049835205078, "beginner": 0.1594831645488739, "expert": 0.1711118072271347 }
31,289
how to use object and collection initializers and target-typed new expressions in c#?
74ff59c88985e639170b997da304b0fb
{ "intermediate": 0.5656495690345764, "beginner": 0.3504958748817444, "expert": 0.08385449647903442 }
31,290
#include "Window.h" Window::Window(const std::string& aTitle, int w, int h) { SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_PNG); TTF_Init(); m_window = SDL_CreateWindow(aTitle.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_SHOWN); m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED); m_font = TTF_OpenFont("arial.ttf", 16); } Window::~Window() { SDL_DestroyRenderer(m_renderer); SDL_DestroyWindow(m_window); TTF_CloseFont(m_font); IMG_Quit(); SDL_Quit(); } bool Window::loadResources() { // Загрузка фонового изображения m_backgroundSurface = IMG_Load("res/back.png"); if (!m_backgroundSurface) return false; m_backgroundTexture = SDL_CreateTextureFromSurface(m_renderer, m_backgroundSurface); if(!m_backgroundTexture) return false; // Загрузка текстур для барабанов std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; int totalSpacingWidth = (NUM_DRUMS - 1) * 20; int totalWidth = totalDrumsWidth + totalSpacingWidth; int startX = (SDL_GetWindowSurface(m_window)->w - totalWidth) / 2; int startY = (SDL_GetWindowSurface(m_window)->h - (DRUM_HEIGHT * 3)) / 2; for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.m_currentTexture = 0; drum.m_rotation = 0; drum.m_speed = m_drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(m_renderer, texturePaths[i][j].c_str()); if (!tmp) return false; drum.m_textures.push_back(tmp); } m_drums.push_back(drum); } } return true; } void Window::runEventLoop() { Uint32 stopTime1 = 0; bool isStopping1 = false; Uint32 stopTime2 = 0; bool isStopping2 = false; Uint32 stopTime3 = 0; bool isStopping3 = false; Uint32 stopTime4 = 0; bool isStopping4 = false; Uint32 stopTime5 = 0; bool isStopping5 = false; SDL_Event event; bool running = true; bool rotating = false; Uint32 startTime = 0; int mouseX, mouseY; bool canRotate = true; while (running) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; } else if (event.type == SDL_MOUSEBUTTONDOWN) { SDL_GetMouseState(&mouseX, &mouseY); if (mouseX >= m_buttonRect.x && mouseX <= m_buttonRect.x + m_buttonRect.w && mouseY >= m_buttonRect.y && mouseY <= m_buttonRect.y + m_buttonRect.h) { // Проверяем, остановился ли последний барабан if (canRotate) { canRotate = false; rotating = true; startTime = SDL_GetTicks(); } } } } if (rotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; // Установка времени вращения барабанов if (elapsedTime >= 5000) { rotating = false; canRotate = true; printPosition(); } else { handleButton(); // Остановка барабанов по очереди в 1 секунду if (!isStopping1 && SDL_GetTicks() - startTime >= 1000) { m_drums[0].m_speed = 0; m_drums[5].m_speed = 0; m_drums[10].m_speed = 0; isStopping1 = true; stopTime1 = SDL_GetTicks(); // Запоминаем время остановки } if (isStopping1 && SDL_GetTicks() - stopTime1 >= 1000) { m_drums[0].m_speed = m_drumSpeeds[0] * 10; m_drums[5].m_speed = m_drumSpeeds[0] * 10; m_drums[10].m_speed = m_drumSpeeds[0] * 10; isStopping1 = false; } //------------------------------------------------------- if (!isStopping2 && SDL_GetTicks() - startTime >= 2000) { m_drums[1].m_speed = 0; m_drums[6].m_speed = 0; m_drums[11].m_speed = 0; isStopping2 = true; stopTime2 = SDL_GetTicks(); } if (isStopping2 && SDL_GetTicks() - stopTime2 >= 2000) { m_drums[1].m_speed = m_drumSpeeds[1] * 10; m_drums[6].m_speed = m_drumSpeeds[1] * 10; m_drums[11].m_speed = m_drumSpeeds[1] * 10; isStopping2 = false; } //------------------------------------------------------- if (!isStopping3 && SDL_GetTicks() - startTime >= 3000) { m_drums[2].m_speed = 0; m_drums[7].m_speed = 0; m_drums[12].m_speed = 0; isStopping3 = true; stopTime3 = SDL_GetTicks(); } if (isStopping3 && SDL_GetTicks() - stopTime3 >= 3000) { m_drums[2].m_speed = m_drumSpeeds[2] * 10; m_drums[7].m_speed = m_drumSpeeds[2] * 10; m_drums[12].m_speed = m_drumSpeeds[2] * 10; isStopping3 = false; } //------------------------------------------------------- if (!isStopping4 && SDL_GetTicks() - startTime >= 4000) { m_drums[3].m_speed = 0; m_drums[8].m_speed = 0; m_drums[13].m_speed = 0; isStopping4 = true; stopTime4 = SDL_GetTicks(); } if (isStopping4 && SDL_GetTicks() - stopTime4 >= 4000) { m_drums[3].m_speed = m_drumSpeeds[3] * 10; m_drums[8].m_speed = m_drumSpeeds[3] * 10; m_drums[13].m_speed = m_drumSpeeds[3] * 10; isStopping4 = false; } //------------------------------------------------------- if (!isStopping5 && SDL_GetTicks() - startTime >= 4500) { m_drums[4].m_speed = 0; m_drums[9].m_speed = 0; m_drums[14].m_speed = 0; isStopping5 = true; stopTime5 = SDL_GetTicks(); } if (isStopping5 && SDL_GetTicks() - stopTime5 >= 4500) { m_drums[4].m_speed = m_drumSpeeds[4] * 10; m_drums[9].m_speed = m_drumSpeeds[4] * 10; m_drums[14].m_speed = m_drumSpeeds[4] * 10; isStopping5 = false; } //------------------------------------------------------- } } // Очистка рендера SDL_RenderClear(m_renderer); //---------- drawBackground(); drawFPS(); drawButton(255, m_g, 180); drawDrum(); //---------- // Обновление рендера SDL_RenderPresent(m_renderer); } } void Window::drawBackground() { SDL_RenderCopy(m_renderer, m_backgroundTexture, nullptr, nullptr); } void Window::drawFPS() { m_fps.setRect(SDL_GetWindowSurface(m_window)->w - 150, SDL_GetWindowSurface(m_window)->h - 90, 100, 50); m_fps.m_frames++; Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - m_fps.m_prevTime; if (elapsedTime >= 1) { std::stringstream ss; ss << "FPS: " << int(m_fps.m_frames / (elapsedTime / 1000.0f)); std::string fpsString = ss.str(); m_fps.m_fpsSurface = TTF_RenderText_Solid(m_font, fpsString.c_str(), { 255, 255, 255 }); m_fps.m_fpsTexture = SDL_CreateTextureFromSurface(m_renderer, m_fps.m_fpsSurface); SDL_FreeSurface(m_fps.m_fpsSurface); SDL_RenderCopy(m_renderer, m_fps.m_fpsTexture, nullptr, &m_fps.m_fpsRect); m_fps.m_prevTime = currentTime; m_fps.m_frames = 0; SDL_DestroyTexture(m_fps.m_fpsTexture); } } void Window::drawButton(int r, int g, int b) { if (m_g > 0) { m_g -= 1; } else { m_g = 255; } SDL_Surface* surface = TTF_RenderText_Solid(m_font, "Click Me", { 255, 255, 255 }); SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer, surface); SDL_FreeSurface(surface); int buttonWidth = 100; int buttonHeight = 50; m_buttonRect.x = SDL_GetWindowSurface(m_window)->w - buttonWidth - 10; m_buttonRect.y = 10; m_buttonRect.w = buttonWidth; m_buttonRect.h = buttonHeight; SDL_SetRenderDrawColor(m_renderer, r, g, b, 255); SDL_RenderFillRect(m_renderer, &m_buttonRect); SDL_RenderCopy(m_renderer, texture, nullptr, &m_buttonRect); SDL_DestroyTexture(texture); } void Window::handleButton() { updateDrums(m_drums); } void Window::drawDrum() { for (size_t i = 0; i < m_drums.size(); i++) { SDL_Rect drumRect = { m_drums[i].x, m_drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_RenderCopy(m_renderer, m_drums[i].m_textures[m_drums[i].m_currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (m_drums[i].m_currentTexture == 0) { // Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < m_drums.size()) { m_drums[i + NUM_DRUMS].m_currentTexture = 1; } if (i + (NUM_DRUMS * 2) < m_drums.size()) { m_drums[i + (NUM_DRUMS * 2)].m_currentTexture = 2; } } } } void Window::printPosition() { for (int r = 0; r < 3; r++) { for (int i = 0; i < NUM_DRUMS; i++) { std::cout << m_drums[i + r * NUM_DRUMS].m_currentTexture; if (i != NUM_DRUMS - 1) { std::cout << ", "; } } std::cout << std::endl; } } void Window::updateDrums(std::vector<Drum>& aDrums) { for (Drum& drum : aDrums) { drum.m_rotation += drum.m_speed; if (drum.m_rotation >= 360) { drum.m_rotation = 0; drum.m_currentTexture++; if (drum.m_currentTexture >= NUM_TEXTURES) { drum.m_currentTexture = 0; } } } }Почему повторный запуск барабанов запускается по очереди а не сразу? как исправить?
3cb9dc5176e9f704f636699fd931da0a
{ "intermediate": 0.34050384163856506, "beginner": 0.4571469724178314, "expert": 0.2023492455482483 }
31,291
a=1. b=2. do 10 i=3,20 c=a+b v=c/b write(1,20)i,v a=b 10 b=c 20 format(1x,i3,f13.8) end переведи код на c++
c3b05de64ad281f112186146a60620bd
{ "intermediate": 0.20108599960803986, "beginner": 0.6121168732643127, "expert": 0.18679717183113098 }
31,292
Filter column Date to be not equal to 01.01.2022 using pandas
892d964593fb57099704d5b203cff4d0
{ "intermediate": 0.39202243089675903, "beginner": 0.227146714925766, "expert": 0.380830854177475 }
31,293
create a sintement analysis python code to grab tweets about gold for the day from twitter simplify it and organize it and give a conclusion about the future price
f30c4ded559a20958c81956daceb6999
{ "intermediate": 0.4124854505062103, "beginner": 0.19776415824890137, "expert": 0.3897503614425659 }
31,294
In Natural Language Processing we have an object called Embedding Space ES. Subwords, words, subsententences, sentences etcera are represented as vectors in ES. They all have the same dimensions (number of elements in each of those vectors). What can you tell me about the structure of ES?
8c4f3f182d245b5a70ac2fbad41ad28d
{ "intermediate": 0.3535776436328888, "beginner": 0.38004714250564575, "expert": 0.2663751542568207 }
31,295
#include <iostream> #include <cstdlib> #include <string> using namespace std; int main (int argc, char* argv[]) { if (argc == 1) { while (true) { system("printf $USER@$HOST"); char* cmd; cin >> cmd; system(cmd); } } } I got segmentation fault
f05a6ab6eeb7c19c14e51bdd69be2d11
{ "intermediate": 0.3331151008605957, "beginner": 0.5004057288169861, "expert": 0.16647911071777344 }
31,296
create sql database
6631ea30596c9791cf47f5b23e469922
{ "intermediate": 0.40218642354011536, "beginner": 0.2210177779197693, "expert": 0.37679576873779297 }
31,297
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> #include <vector> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } void resetDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.currentTexture = 0; drum.rotation = 0; } } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { Uint32 stopTime = 0; bool isStopping = false; SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); // Остановка барабанов по очереди if (!isStopping && SDL_GetTicks() - startTime >= 2000) { drums[0].speed = 0; drums[0].rotation = drums[0].currentTexture * 120; drums[5].speed = 0; drums[5].rotation = drums[5].currentTexture * 120; drums[10].speed = 0; drums[10].rotation = drums[10].currentTexture * 120; isStopping = true; stopTime = SDL_GetTicks(); // Запоминаем время остановки } if (isStopping && SDL_GetTicks() - stopTime >= 2000) { drums[0].speed = drumSpeeds[0] * 10; drums[5].speed = drumSpeeds[0] * 10; drums[10].speed = drumSpeeds[0] * 10; isStopping = false; } } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Как сделать остановку m_drums[0] m_drums[5] m_drums[10] барабанов спустя одну секунду?
e66a49ed58429bd0f00b74c932d84ef5
{ "intermediate": 0.30762791633605957, "beginner": 0.4315859377384186, "expert": 0.2607862055301666 }
31,298
help me implement json database so I can use it as memory for a openai bot
83e18ef690badadbb4864ce3d49e4045
{ "intermediate": 0.7842502593994141, "beginner": 0.08415793627500534, "expert": 0.13159185647964478 }
31,299
#include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> #include <random> #include <vector> // Размеры окна const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; // Размеры барабанов const int DRUM_WIDTH = 100; const int DRUM_HEIGHT = 100; // Общее количество барабанов const int NUM_DRUMS = 5; // Количество текстур на каждом барабане const int NUM_TEXTURES = 3; // Скорость вращения барабанов std::vector<int> drumSpeeds = { 1, 4, 3, 2, 100 }; // Структура для хранения информации о барабане struct Drum { int x; // Позиция по X int y; // Позиция по Y int currentTexture; // Индекс текущей текстуры на барабане int rotation; // Угол поворота барабана int speed; // Скорость вращения барабана std::vector<SDL_Texture*> textures; // Вектор текстур для барабана }; // Инициализация SDL и создание окна bool init(SDL_Window*& window, SDL_Renderer*& renderer) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl; return false; } if (!IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) { std::cerr << "Failed to initialize SDL_image: " << IMG_GetError() << std::endl; return false; } window = SDL_CreateWindow("Slot Machine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if (!window) { std::cerr << "Failed to create window: " << SDL_GetError() << std::endl; return false; } renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (!renderer) { std::cerr << "Failed to create renderer: " << SDL_GetError() << std::endl; return false; } return true; } // Освобождение ресурсов void cleanup(SDL_Window* window, SDL_Renderer* renderer, std::vector<Drum>& drums) { for (Drum& drum : drums) { for (size_t i = 0; i < drum.textures.size(); i++) { SDL_DestroyTexture(drum.textures[i]); } } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); } void resetDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.currentTexture = 0; drum.rotation = 0; } } // Инициализация барабанов void initDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { std::vector<std::vector<std::string>> texturePaths = { { "res/01spin.png", "res/11spin.png", "res/21spin.png" }, { "res/02spin.png", "res/12spin.png", "res/22spin.png" }, { "res/03spin.png", "res/13spin.png", "res/23spin.png" }, { "res/04spin.png", "res/14spin.png", "res/24spin.png" }, { "res/05spin.png", "res/15spin.png", "res/25spin.png" } }; int totalDrumsWidth = NUM_DRUMS * DRUM_WIDTH; // Ширина всех барабанов int totalSpacingWidth = (NUM_DRUMS - 1) * 20; // Ширина промежутков между барабанами int totalWidth = totalDrumsWidth + totalSpacingWidth; // Общая ширина всех барабанов и промежутков int startX = (WINDOW_WIDTH - totalWidth) / 2; // Начальная позиция по X для первого барабана int startY = (WINDOW_HEIGHT - (DRUM_HEIGHT * 3)) / 2; // Начальная позиция по Y для первого ряда for (int r = 0; r < 3; r++) // Цикл для формирования трех рядов барабанов { for (int i = 0; i < NUM_DRUMS; i++) // Цикл для формирования барабанов в ряду { Drum drum; drum.x = startX + i * (DRUM_WIDTH + 20); drum.y = startY + r * DRUM_HEIGHT; drum.currentTexture = 0; drum.rotation = 0; drum.speed = drumSpeeds[i] * 10; for (int j = 0; j < NUM_TEXTURES; j++) { SDL_Texture* tmp = IMG_LoadTexture(renderer, texturePaths[i][j].c_str()); drum.textures.push_back(tmp); } drums.push_back(drum); } } } // Отрисовка барабанов void renderDrums(SDL_Renderer* renderer, std::vector<Drum>& drums) { for (size_t i = 0; i < drums.size(); i++) { SDL_Rect drumRect = { drums[i].x, drums[i].y, DRUM_WIDTH, DRUM_HEIGHT }; SDL_SetTextureAlphaMod(drums[i].textures[drums[i].currentTexture], 128); SDL_RenderCopy(renderer, drums[i].textures[drums[i].currentTexture], nullptr, &drumRect); // Проверка индекса текущей текстуры if (drums[i].currentTexture == 0) { // … Изменение индекса текущей текстуры для других рядов и барабанов if (i + NUM_DRUMS < drums.size()) { drums[i + NUM_DRUMS].currentTexture = 1; } if (i + (NUM_DRUMS * 2) < drums.size()) { drums[i + (NUM_DRUMS * 2)].currentTexture = 2; } } } } // Обновление барабанов void updateDrums(std::vector<Drum>& drums) { for (Drum& drum : drums) { drum.rotation += drum.speed; if (drum.rotation >= 360) { drum.rotation = 0; drum.currentTexture++; if (drum.currentTexture >= NUM_TEXTURES) { drum.currentTexture = 0; } } } } int main(int argc, char* args[]) { Uint32 stopTime = 0; bool isStopping = false; SDL_Window* window = nullptr; SDL_Renderer* renderer = nullptr; std::vector<Drum> drums; if (!init(window, renderer)) { return 1; } initDrums(renderer, drums); SDL_Event event; bool isRunning = true; bool isRotating = false; Uint32 startTime = 0; while (isRunning) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { isRunning = false; } else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { isRotating = true; startTime = SDL_GetTicks(); } } if (isRotating) { Uint32 currentTime = SDL_GetTicks(); Uint32 elapsedTime = currentTime - startTime; if (elapsedTime >= 4000) { isRotating = false; } else { updateDrums(drums); // Остановка барабанов по очереди if (!isStopping && SDL_GetTicks() - startTime >= 2000) { drums[0].speed = 0; drums[0].rotation = drums[0].currentTexture * 120; drums[5].speed = 0; drums[5].rotation = drums[5].currentTexture * 120; drums[10].speed = 0; drums[10].rotation = drums[10].currentTexture * 120; isStopping = true; stopTime = SDL_GetTicks(); // Запоминаем время остановки } if (isStopping && SDL_GetTicks() - stopTime >= 2000) { drums[0].speed = drumSpeeds[0] * 10; drums[5].speed = drumSpeeds[0] * 10; drums[10].speed = drumSpeeds[0] * 10; isStopping = false; } } } SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_RenderClear(renderer); renderDrums(renderer, drums); SDL_RenderPresent(renderer); } cleanup(window, renderer, drums); return 0; } Нужно по истечению 1 секунды остановить 1 2 и 3 и 4 и 5 барабан потом после 2 секунд 6 7 8 9 10 потом после 3 секунд 10 11 12 13 14 барабаны.
c70b8deda7c5b9d96e87909af75610c4
{ "intermediate": 0.30762791633605957, "beginner": 0.4315859377384186, "expert": 0.2607862055301666 }
31,300
реши на python такую задачу: CODE CHALLENGE: Solve the Multiple Longest Common Subsequence Problem. Input: Three DNA strings of length at most 8. Output: The length of a longest common subsequence of these three strings, followed by a multiple alignment of the three strings corresponding to such an alignment. Sample Input: ATATCCG TCCGA ATGTACTG Sample Output: 3 A-TAT---CC--G- --T-----C-C-GA -AT--GTAC--TG-
caa2d1bde92c9018d85f2d1de413b1f5
{ "intermediate": 0.3939148783683777, "beginner": 0.19487378001213074, "expert": 0.4112112820148468 }
31,301
how to filter by group an done valu ein python
14e00befb1b136dc1829223d178817e1
{ "intermediate": 0.2586289048194885, "beginner": 0.17288491129875183, "expert": 0.5684862732887268 }
31,302
Check if /misc file system is mounted on the redhat system and echo the hostname otherwise no output is needed
7c0a318e62cb3212a254329096af893a
{ "intermediate": 0.3772560954093933, "beginner": 0.2639595866203308, "expert": 0.35878437757492065 }
31,303
I have created 3 user subpages as examples of how a revamp of this template can be done. (User:Equalizer5118/Cite, User:Equalizer5118/Ref, User:Equalizer5118/References) I want some feedback on this and, if everyone agrees, help implementing it. Ideas? 1: This is some text {{:{{FULLPAGENAME}}|cite id=1}} <includeonly><onlyinclude><span id="cite{{{cite id|}}}" style="font-size:10px"><sup>[[#ref{{{cite id|}}}|[{{{cite id|}}}]]]</sup></span>{{#if:{{{cite id|}}}||{{Warning|Missing essential param {{param|cite id}} for {{tl|cite}}}}}}</onlyinclude></includeonly> 2: {{:{{FULLPAGENAME}}|[https://en.wikipedia.org/wiki/Trumpet Trumpet] - Trumpets are cool ig|cite id=1}} <includeonly><onlyinclude><div id=ref{{{cite id|}}} style=padding 0px 5px> :{| style="background:transparent" |- |[[#cite{{{cite id|}}}|{{{cite id|}}}.]] |{{{1|}}} |}</div></onlyinclude></includeonly> 3: == References == {{{1|{{Warning|Missing essential parameter {{param|1}} in {{tl|Refernces}}}}}}}
b5558fbfbf36f1b48e773972bfa3a229
{ "intermediate": 0.30883362889289856, "beginner": 0.45593324303627014, "expert": 0.23523306846618652 }
31,304
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="styles.css"> <script src="https://unpkg.com/lightweight-charts@3.4.0/dist/lightweight-charts.standalone.production.js"></script> </head> <body> <div id="chart-container"></div> <script> var chart = LightweightCharts.createChart(document.getElementById('chart-container'), { crosshair: { mode: LightweightCharts.CrosshairMode.Normal }, layout: { background: { color: '#222' }, textColor: '#D2D5DC'}, grid: {vertLines: { color: 'rgba(0, 0, 0, 0)' }, horzLines: { color: 'rgba(0, 0, 0, 0)' }}, timeScale: { visible: false }, priceScale:{borderColor: '#D2D5DC'}, }); var candleSeries = chart.addCandlestickSeries(); var historicalData = []; async function fetchHistoricalData() { try { const response = await fetch('https://fapi.binance.com/fapi/v1/klines?symbol=BTCUSDT&interval=5m&limit=1500'); historicalData = (await response.json()).map(item => ({ time: item[0] / 1000, open: parseFloat(item[1]), high: parseFloat(item[2]), low: parseFloat(item[3]), close: parseFloat(item[4]) })); candleSeries.setData(historicalData); // After the historical data is set, add the marker addMarker(); } catch (error) { console.error('Error fetching historical data:', error); } } function addMarker() { // Replace with the correct timestamp. This is just an example timestamp. const markerTimestamp = 1700173200; // Converted to seconds (from milliseconds) // Find the candle that matches the timestamp const candle = historicalData.find(c => c.time === markerTimestamp); if (candle) { // Use the 'high' price to place the marker above the candle candleSeries.setMarkers([{ time: markerTimestamp, position: 'aboveBar', color: 'orange', shape: 'circle', text: 'A', // Text inside the marker, could be empty or any character size: 2 // Size of the marker }]); } } const socket = new WebSocket('wss://fstream.binance.com/ws/btcusdt@kline_5m'); socket.onmessage = (event) => { const data = JSON.parse(event.data); const kline = data.k; const candleData = { time: kline.t / 1000, open: parseFloat(kline.o), high: parseFloat(kline.h), low: parseFloat(kline.l), close: parseFloat(kline.c) }; if (historicalData.length > 0) { const lastDataPoint = historicalData[historicalData.length - 1]; if (lastDataPoint.time === candleData.time) { lastDataPoint.close = candleData.close; lastDataPoint.high = Math.max(lastDataPoint.high, candleData.high); lastDataPoint.low = Math.min(lastDataPoint.low, candleData.low); candleSeries.update(lastDataPoint); } else if (candleData.time > lastDataPoint.time) { historicalData.push(candleData); candleSeries.update(candleData); } } else { historicalData.push(candleData); candleSeries.setData(historicalData); } }; socket.onclose = (event) => { console.error('WebSocket closed:', event); }; socket.onerror = (error) => { console.error('WebSocket error:', error); }; async function initializeChart() { historicalData = await fetchHistoricalData(); candleSeries.setData(historicalData); } initializeChart(); </script> </body> </html> the most recent bar is no longer updating live after I added the marker code
e4b677add104014ae619b1e3fd05ffe4
{ "intermediate": 0.4378500282764435, "beginner": 0.3670956492424011, "expert": 0.1950543075799942 }
31,305
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private Animator anim; private SpriteRenderer spriteRenderer; private void Start() { rb = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); spriteRenderer = GetComponent<SpriteRenderer>(); player = GameObject.FindGameObjectWithTag("Player").transform; // Set initial target position as the current position targetPosition = rb.position; } private void Update() { // Calculate the distance to the player float distanceToPlayer = Vector2.Distance(rb.position, player.position); // If the player is within chase range, set player’s position as the target if (distanceToPlayer < chaseRange) { targetPosition = player.position; } else { // If the enemy reached the target position, set a new random target position float distanceToTarget = Vector2.Distance(rb.position, targetPosition); if (distanceToTarget < 0.1f) { targetPosition = GetRandomPosition(); } } // Move towards the target position Vector2 direction = (targetPosition - rb.position).normalized; rb.MovePosition(rb.position + direction * speed * Time.deltaTime); anim.SetFloat("moveX", direction.x); anim.SetFloat("moveY", direction.y); // Flip the sprite horizontally if moving in negative x direction if (direction.x < 0) { spriteRenderer.flipX = true; } else { spriteRenderer.flipX = false; } } private Vector2 GetRandomPosition() { // Get a random position within the map boundaries float x = Random.Range(-5f, 5f); float y = Random.Range(-5f, 5f); return new Vector2(x, y); } } add add health to the enemy and make it so if the health reaches 0 it calls the Die() method which will just destroy the game object
f1abc6311dcbb168427720135c768562
{ "intermediate": 0.35937535762786865, "beginner": 0.3884212374687195, "expert": 0.2522033751010895 }
31,306
What is the Vba code to lock a sheet in a specific workbook
066bf411f6835904dbe91a518b7dca3d
{ "intermediate": 0.5772000551223755, "beginner": 0.17581388354301453, "expert": 0.24698607623577118 }
31,307
write a C# script so if the player walks within 0.5 units of a chest and clicks Z, then there is a 25% chance a knife prefab will be spawned and set as the child of the player
18832646d7aafc3b99ad905eeb411f53
{ "intermediate": 0.499983549118042, "beginner": 0.1734251230955124, "expert": 0.3265913128852844 }
31,308
write a C# script that when a player collides with a chest it has a 50 percent chance of spawning a knife and making it the child of the player
0f49ea76bfa071fdae74e4fc1187b465
{ "intermediate": 0.401644766330719, "beginner": 0.15318283438682556, "expert": 0.44517236948013306 }
31,309
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public GameObject knifePrefab; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { // Generate a random number (between 0 and 1) to determine if knife spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a knife GameObject knife = Instantiate(knifePrefab, collision.transform); knife.transform.localPosition = Vector3.zero; knife.transform.localRotation = Quaternion.identity; } // Disable the chest to prevent spawning multiple knives gameObject.SetActive(false); } } } make it so that after 10 seconds the chest is re-enabled
b9b4c9d416aee37b05c6f04fdd0fe4ab
{ "intermediate": 0.3832376301288605, "beginner": 0.39409276843070984, "expert": 0.2226695567369461 }
31,310
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public GameObject knifePrefab; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { // Generate a random number (between 0 and 1) to determine if knife spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a knife GameObject knife = Instantiate(knifePrefab, collision.transform); knife.transform.localPosition = Vector3.zero; knife.transform.localRotation = Quaternion.identity; } // Disable the chest to prevent spawning multiple knives gameObject.SetActive(false); } } } make it so after gameObject.SetActive(false) happens, it waits 5 seconds and sets it back to gameObject.SetActive(true)
5d03e28a78ce3363b282bd0b33d6e362
{ "intermediate": 0.44869568943977356, "beginner": 0.36382588744163513, "expert": 0.1874784529209137 }
31,311
what birth in stat command means ?
bd9f127e9de0ae32718691d46e00792e
{ "intermediate": 0.4368073344230652, "beginner": 0.3133849501609802, "expert": 0.24980765581130981 }
31,312
import React, { FormEvent, useState } from "react"; import style from "./ToDoList.module.scss"; export type PropsToDoList = { id: number; text: string; completed: boolean; }; export const ToDoList = (props: PropsToDoList) => { const {} = props; //-- const [todos, setTodos] = useState<PropsToDoList[]>([]); const checkboxChange = (idClick: number, newStatus: boolean) => { setTodos((prev) => prev.map((item) => item.id === idClick ? { ...item, completed: newStatus } : item ) ); }; //- const removeToDo = (idClick: number) => { setTodos((prev) => [...prev.filter((item) => item.id !== idClick)]); }; //- return ( <> <ul> {todos.map((item) => { const onCheckboxChangeHandler = ( event: FormEvent<HTMLInputElement> ) => { checkboxChange(item.id, event.currentTarget.checked); }; const onRemoveToDo = () => { removeToDo(item.id); }; return ( <li key={item.id}> <input type="checkbox" checked={item.completed} onChange={onCheckboxChangeHandler} /> <span>{item.text}</span> <button onClick={onRemoveToDo}>X</button> </li> ); })} </ul>import React, { FormEvent, useState } from "react"; import { PropsToDoList, ToDoList } from "./Components/ToDoList/ToDoList"; function App() { // Функция генерации уникального id const generateUniqueId = (): number => { const timestamp = Date.now(); // Получаем текущую временную метку const random = Math.floor(Math.random() * 10000); // Генерируем случайное число от 0 до 9999 const uniqueId = timestamp + random; // Комбинируем временную метку и случайное число return uniqueId; }; const [todos, setTodos] = useState<PropsToDoList[]>([]); const [text, setText] = useState(""); console.log(todos); const onAddToDoHandler = () => { if (text.trim().length) { setTodos((prev) => [ ...prev, { id: generateUniqueId(), text: text, completed: true, }, ]); setText(""); } }; const onTextChangeHandler = (event: FormEvent<HTMLInputElement>) => { setText(event.currentTarget.value); }; return ( <> <label> <input value={text} onChange={onTextChangeHandler} /> <button onClick={onAddToDoHandler}>Add ToDo</button> </label> <ToDoList id={0} text={""} completed={false} /> </> )есть компонент тудулист он экспортируется в апп но он не отображвет добавленных задач и в пропсы требует непонятно чего что делать может мне вытащить состояние ту ду листа в апп и добавить оброботчики и передать их пропсами как и что делать } export default App; t </> ); };
32347ca922327dc28848a3d8ce5df38d
{ "intermediate": 0.22686037421226501, "beginner": 0.676903486251831, "expert": 0.09623610973358154 }
31,313
G Major Scales Songs remix
4cab53adf393d775a678bc5f939428b8
{ "intermediate": 0.3647873103618622, "beginner": 0.32634469866752625, "expert": 0.30886802077293396 }
31,314
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public float delayTime = 5f; public GameObject knifePrefab; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { // Generate a random number (between 0 and 1) to determine if knife spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a knife GameObject knife = Instantiate(knifePrefab, collision.transform); knife.transform.localPosition = Vector3.zero; knife.transform.localRotation = Quaternion.identity; } // Disable the chest to prevent spawning multiple knives gameObject.SetActive(false); // Enable the chest after a delay Invoke("EnableChest", delayTime); } } private void EnableChest() { gameObject.SetActive(true); } } make it so when the knife's position spawns at (-0.41, -0.02, 0) relative to where the player is
a99d81989fc36478b793913eb418b6a0
{ "intermediate": 0.4720843434333801, "beginner": 0.31400829553604126, "expert": 0.21390733122825623 }
31,315
namespace Spv.Usuarios.Bff.ViewModels.UsuarioController.CommonUsuario.Input { /// <summary> /// Cambio de clave model /// </summary> [JsonObject(Title = "CambioDeClaveModelRequest")] public class CambioDeClaveModelRequest { /// <summary> /// Identificador de Persona. /// </summary> [FromHeader(Name = ParameterNames.IdPersona), DomainValidation(typeof(IdPersona))] [JsonProperty(PropertyName = ParameterNames.IdPersona)] public long IdPersona { get; set; } /// <summary> /// Nueva Clave /// </summary> [JsonProperty(PropertyName = ParameterNames.NuevaClave)] public string NuevaClave { get; set; } /// <summary> /// Clave de Canales /// </summary> [FromHeader(Name = ParameterNames.ClaveCanales)] [JsonProperty(PropertyName = ParameterNames.ClaveCanales)] public string ClaveCanales { get; set; } /// <summary> /// Identificador de Persona ClaveCanal - SoftToken - Biometría. /// </summary> [JsonProperty(PropertyName = ParameterNames.Identifier)][] public string Identifier { get; set; } /// <summary> /// Retorna la representación en json del objeto con nueva_clave y clave_canales ofuscados /// </summary> public override string ToString() { return "{ IdPersona: '" + IdPersona + "', nueva_clave: '************', clave_canales: '************' }"; } /// <summary> /// ToRequestBody /// </summary> /// <returns></returns> public IRequestBody<CambioDeClaveModelInput> ToRequestBody(ApiHeadersDeviceId headers) { return headers?.ToRequestBody( new CambioDeClaveModelInput() { PersonId = IdPersona, NewPassword = NuevaClave, ChannelKey = ClaveCanales, DeviceId = headers.DeviceId, Identifier = Identifier }); } } como hacer que el campo "Identifier " sea requerido dentro del body c#
23eda3918b33c7814d204d3531295dc6
{ "intermediate": 0.5085027813911438, "beginner": 0.38606545329093933, "expert": 0.10543176531791687 }
31,316
write a program in java which loops through the following questions: "Where did pumpkin carving originate?", "In what century was halloween first introduced?", "Who brought Halloween to the United States?", "When will the next full moon be on halloween?", "Which state produces the most amount of pumpkins?", "Who wrote the horror book frankenstein?", "What colors make up Freddy Krueger’s shirt in A nightmare on elms street?", "What is the least favorite Halloween candy?", "How many pounds of candy corn are produced every year?", "How many pounds of chocolate are sold during halloween week?" and loops through 4 possible answers: "Ireland (a)" , "Scotland (b)", "Germany (c)", "Greece (d)\n", "19th century (a)", "18th century (b)", "15th century (c)", "17th century (d)\n", "Irish (a)", "Scottish (b)", "Finnish (c)", "German (d)\n", "2039 (a)", "2041 (b)","2050 (c)", "2042 (d)\n", "Illinois (a)", "Nevada (b)", "Colorado (c)", "Minnesota (d)\n", "Mary Shelly (a)", "John Booth (b)", "John Booth (c)", "John Booth (d)\n", "Red and green (a)", "Blue and yellow (b)", "Black and white (c)", "Purple and orange (d)\n", "Candy Corn (a)", "Snickers (b)", "Twizzlers (c)", "Skittles (d)\n", "35 million pounds (a)", "50 million pounds (b)", "20 million pounds (c)", "10 million pounds (d)\n", "90 million pounds (a)", "60 million pounds (b)", "80 million pounds (c)", "100 million pounds (d)\n" using the scanner class. A is the correct answer for each question when the correct answer is selected, the int score is incremented by 1 then implement the following code: if (score <= 2) { System.out.println("Your halloween knowledge are rusty"); } else if (score <= 5) { System.out.println("close to 50%, bruh, never in my dreams"); } else if (score <= 8) { System.out.println("not bad"); } else if (score == 10) { System.out.println("ace"); }
aa2cbf572e039e0186f408a66f18a09f
{ "intermediate": 0.3698550760746002, "beginner": 0.4741530120372772, "expert": 0.15599189698696136 }
31,317
How can I lock certain sheets in a workbook when the workbook opens
3558919fef1498894fa3c82865153622
{ "intermediate": 0.49981409311294556, "beginner": 0.19122414290905, "expert": 0.3089617192745209 }
31,318
python code using LSTM encoder and LSTM decoder rnn to translate English text to Arabic text by splitting data from file into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example translation from test
b3c7596b93cd2d2e764071839a83d066
{ "intermediate": 0.40904030203819275, "beginner": 0.10582292079925537, "expert": 0.4851367175579071 }
31,319
Design a combinational circuit that converts the gray code of a four bit number to it's equivalent binary number. Implement the circuit using XOR gates only
da32c8c9c2bd631f86271e74f6885e04
{ "intermediate": 0.2633683383464813, "beginner": 0.14680613577365875, "expert": 0.5898255705833435 }