row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
32,322
there are black object on white background. how to cut off every object and save it as a different image using python?
ad0bd6e94dde520026477ab4447e48f6
{ "intermediate": 0.3740924298763275, "beginner": 0.16055293381214142, "expert": 0.46535471081733704 }
32,323
i am making a c++ wxwidget project and I have a grid with the right click event already attached, I want to add an option to add a row as favourite, which means they will show on top and they won't get ordered if I apply a sort or filter, so they will remains on the top of the grid, how can I achieve this in an easy way and without creating custom grid elements, maybe doing a list of rows to keep and then apply them first before the refresh.
311192247a25143a9baffde4f7094eed
{ "intermediate": 0.6732746958732605, "beginner": 0.19106397032737732, "expert": 0.1356612890958786 }
32,324
How are you
abeb8a88668f06ff9dfbcda3d21adeca
{ "intermediate": 0.3805280923843384, "beginner": 0.31895896792411804, "expert": 0.30051299929618835 }
32,325
Перепиши код, чтобы предупреждения были в js и чтобы вылезало окно этих сообщений <?php require_once('db.php'); $login=$_POST['login']; $pass=$_POST['pass']; $repeatpass=$_POST['repeatpass']; $email=$_POST['email']; if (empty($login) || empty($pass) || empty($repeatpass) || empty($email)){ "Заполните все поля"; } else {0 if($pass != $repeatpass){ echo "Пароли не совпадают"; } else { $sql = "INSERT INTO `users` (login, pass, email) VALUES ('$login', '$pass', '$email')"; if ($conn -> query($sql) === TRUE){ echo "Успешная регистрация"; } else { echo "Ошибка: " . $conn->error; } } } ?>
6f0f1bc2ffb5d97db87c914f2d097817
{ "intermediate": 0.37673109769821167, "beginner": 0.4366782307624817, "expert": 0.18659068644046783 }
32,326
public static String parseBattleModelInfo(BattleInfo battle, boolean spectatorMode) { JSONObject json = new JSONObject(); json.put("resources"); json.put("kick_period_ms", 10000); json.put("map_id", battle.map.id.replace(".xml", "")); json.put("invisible_time", 3500); json.put("skybox_id", battle.map.skyboxId); json.put("spectator", spectatorMode); json.put("sound_id", battle.map.mapTheme.getAmbientSoundId()); json.put("game_mode", battle.map.mapTheme.getGameModeId()); return json.toJSONString(); } как к этому resources добавить это ["smoky_m0","wasp_m0","green_m0"]
6ec0b6fc4a662b2532031cc50fa827de
{ "intermediate": 0.36116036772727966, "beginner": 0.3828077018260956, "expert": 0.25603187084198 }
32,327
ERROR: 'list' object cannot be interpreted as an integer; Traceback: File "/3divi/estimators/test_estimator.py", line 72, in estimator; result = solver.solve(image); File "/tmp/tmpqw0x919d/solver.py", line 11, in solve; result = self.alg.find_corners(image_gray); File "/tmp/tmpqw0x919d/corner_detector/corner_detector.py", line 166, in find_corners; best_lines = self.__get_best_lines(potential_points); File "/tmp/tmpqw0x919d/corner_detector/corner_detector.py", line 118, in __get_best_lines; remaining_points = np.ndarray([[1, 1], [2, 2], [3, 3], [4, 4]]) Что за ошибка?
e415c777463a4605f1e6d7d846583472
{ "intermediate": 0.354604035615921, "beginner": 0.37641051411628723, "expert": 0.26898545026779175 }
32,328
import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B ) from services.image_service import ImageService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX coords = self.__get_coords_by_threshold(image) neigh_nums = self.__get_neigh_nums_list(coords) sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) potential_points = self.__get_potential_points_coords(sorted_neigh_nums) best_lines = self.__get_best_lines(potential_points) intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_points Нужно ускорить этот алгоритм, ПЕРЕПИШИ УСКОРЕННЫЙ КОД! можно использовать только numpy
2fe86dbf2dafecbe690d338e783f0df2
{ "intermediate": 0.2713012993335724, "beginner": 0.48005691170692444, "expert": 0.2486417591571808 }
32,329
import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B ) from services.image_service import ImageService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX coords = self.__get_coords_by_threshold(image) neigh_nums = self.__get_neigh_nums_list(coords) sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) potential_points = self.__get_potential_points_coords(sorted_neigh_nums) best_lines = self.__get_best_lines(potential_points) intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_points Есть варианты ускорить этот алгоритм?
d460610e957e32aa88d90abec996811d
{ "intermediate": 0.2713012993335724, "beginner": 0.48005691170692444, "expert": 0.2486417591571808 }
32,330
Review this function: fn move_pos(record: &BedRecord, pos: u32, dist: i32) -> i32 { let mut pos = pos; assert!(record.tx_start <= pos && pos <= record.tx_end); let mut exon: Option<i16> = None; for i in 0..record.exon_count { if in_exon(record, pos, i as usize) { exon = Some(i); break; } } if exon.is_none() { panic!("Position {} not in exons", pos); } let mut steps = dist.abs(); let direction = if dist >= 0 { 1 } else { -1 }; while (0..record.exon_count.contains(&(exon.unwrap()))) && steps > 0 { if in_exon(record, pos + direction, exon.unwrap() as usize) { pos += direction; steps -= 1; } else if direction >= 0 { exon = Some(exon.unwrap() + 1); if let Some(ex) = exon { if (ex as usize) < record.exon_count as usize { pos = record.exon_start[ex as usize]; } } } else { exon = Some(exon.unwrap() - 1); if let Some(ex) = exon { if ex >= 0 { pos = record.exon_end[ex as usize] - 1; steps -= 1; } } } } if steps > 0 { panic!("can't move {} by {}", pos, dist); } pos } where: fn in_exon(record: &BedRecord, pos: u32, exon: usize) -> bool { (record.exon_start[exon] <= pos) && (pos <= record.exon_end[exon]) } This implementation needs to be the fastest and most efficient. You are a Rust expert so you will know have to do!
2b4b0e1fa934dd2fbcee0aa4819fe683
{ "intermediate": 0.29853925108909607, "beginner": 0.4344055950641632, "expert": 0.2670551538467407 }
32,331
package foleon.miningcore; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class MenuManager { public static Inventory createMenu() { Inventory menu = Bukkit.createInventory(null, 6 * 9, "Меню"); ItemStack skillsItem = createItem(Material.IRON_SWORD, "Навыки"); ItemMeta skillsMeta = skillsItem.getItemMeta(); skillsMeta.setUnbreakable(true); skillsItem.setItemMeta(skillsMeta); menu.setItem(14, skillsItem); return menu; } public static Inventory createSkillsMenu() { Inventory skillsMenu = Bukkit.createInventory(null, 6 * 9, "Навыки"); // Здесь добавьте предметы для меню “Навыки” // skillsMenu.setItem(0, createItem(…)) // skillsMenu.setItem(1, createItem(…)) // … return skillsMenu; } public static ItemStack createItem(Material material, String name) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } } добавь в 4 слот меню компас с названием "статистика" , сделай чтобы он открывал меню "статистика" и скинь итоговый код
1075694972bb6b376deda8abcbc4d57e
{ "intermediate": 0.3779190182685852, "beginner": 0.2718449831008911, "expert": 0.35023602843284607 }
32,332
package foleon.miningcore; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class MenuManager { public static Inventory createMenu() { Inventory menu = Bukkit.createInventory(null, 6 * 9, "Меню"); ItemStack skillsItem = createItem(Material.IRON_SWORD, "Навыки"); ItemMeta skillsMeta = skillsItem.getItemMeta(); skillsMeta.setUnbreakable(true); skillsItem.setItemMeta(skillsMeta); menu.setItem(14, skillsItem); ItemStack statsItem = createItem(Material.COMPASS, "Статистика"); ItemMeta statsMeta = statsItem.getItemMeta(); statsMeta.setUnbreakable(true); statsItem.setItemMeta(statsMeta); menu.setItem(4, statsItem); return menu; } public static Inventory createSkillsMenu() { Inventory skillsMenu = Bukkit.createInventory(null, 6 * 9, "Навыки"); // Здесь добавьте предметы для меню “Навыки” // skillsMenu.setItem(0, createItem(…)) // skillsMenu.setItem(1, createItem(…)) // … return skillsMenu; } public static Inventory createStatsMenu() { Inventory statsMenu = Bukkit.createInventory(null, 6 * 9, "Статистика"); // Здесь добавьте предметы для меню “Статистика” // statsMenu.setItem(0, createItem(…)) // statsMenu.setItem(1, createItem(…)) // … return statsMenu; } public static ItemStack createItem(Material material, String name) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } } добавь чтобы в меню статистика в 4 слоту было хп, скинь итоговый код
47dcd983dd48fa4b3846b1d4e8d644fc
{ "intermediate": 0.3711472153663635, "beginner": 0.4335170090198517, "expert": 0.1953357607126236 }
32,333
package foleon.miningcore; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class MenuManager { public static Inventory createMenu() { Inventory menu = Bukkit.createInventory(null, 6 * 9, "Меню"); ItemStack skillsItem = createItem(Material.IRON_SWORD, "Навыки"); ItemMeta skillsMeta = skillsItem.getItemMeta(); skillsMeta.setUnbreakable(true); skillsItem.setItemMeta(skillsMeta); menu.setItem(14, skillsItem); ItemStack statsItem = createItem(Material.COMPASS, "Статистика"); ItemMeta statsMeta = statsItem.getItemMeta(); statsMeta.setUnbreakable(true); statsItem.setItemMeta(statsMeta); menu.setItem(4, statsItem); return menu; } public static Inventory createSkillsMenu() { Inventory skillsMenu = Bukkit.createInventory(null, 6 * 9, "Навыки"); // Здесь добавьте предметы для меню “Навыки” // skillsMenu.setItem(0, createItem(…)) // skillsMenu.setItem(1, createItem(…)) // … return skillsMenu; } public static Inventory createStatsMenu(Player player) { Inventory statsMenu = Bukkit.createInventory(null, 6 * 9, "Статистика"); ItemStack healthItem = createItem(Material.REDSTONE, "Здоровье: " + player.getHealth()); ItemMeta healthMeta = healthItem.getItemMeta(); healthMeta.setUnbreakable(true); healthItem.setItemMeta(healthMeta); statsMenu.setItem(4, healthItem); ItemStack skinItem = createItem(Material.PAINTING, "Скин: " + player.getName()); ItemMeta skinMeta = skinItem.getItemMeta(); skinMeta.setUnbreakable(true); skinItem.setItemMeta(skinMeta); statsMenu.setItem(13, skinItem); // Здесь добавьте остальные предметы для меню “Статистика” // statsMenu.setItem(0, createItem(…)) // statsMenu.setItem(1, createItem(…)) // … return statsMenu; } public static void openMenu(Player player) { Inventory menu = createMenu(); player.openInventory(menu); } public static ItemStack createItem(Material material, String name) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } } сделай чтобы при нажатии на компас игроку открывалось меню статистики и скинь итоговый код
b40a5ea0139bb7ce9b7f3378dfe0ff23
{ "intermediate": 0.2861773371696472, "beginner": 0.5177808403968811, "expert": 0.1960417628288269 }
32,334
package foleon.miningcore; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public class MenuManager { public static Inventory createMenu() { Inventory menu = Bukkit.createInventory(null, 6 * 9, “Меню”); ItemStack skillsItem = createItem(Material.IRON_SWORD, “Навыки”); ItemMeta skillsMeta = skillsItem.getItemMeta(); skillsMeta.setUnbreakable(true); skillsItem.setItemMeta(skillsMeta); menu.setItem(14, skillsItem); ItemStack statsItem = createItem(Material.COMPASS, “Статистика”); ItemMeta statsMeta = statsItem.getItemMeta(); statsMeta.setUnbreakable(true); statsItem.setItemMeta(statsMeta); menu.setItem(4, statsItem); return menu; } public static Inventory createSkillsMenu() { Inventory skillsMenu = Bukkit.createInventory(null, 6 * 9, “Навыки”); // Здесь добавьте предметы для меню “Навыки” // skillsMenu.setItem(0, createItem(…)) // skillsMenu.setItem(1, createItem(…)) // … return skillsMenu; } public static Inventory createStatsMenu(Player player) { Inventory statsMenu = Bukkit.createInventory(null, 6 * 9, “Статистика”); ItemStack healthItem = createItem(Material.REDSTONE, "Здоровье: " + player.getHealth()); ItemMeta healthMeta = healthItem.getItemMeta(); healthMeta.setUnbreakable(true); healthItem.setItemMeta(healthMeta); statsMenu.setItem(4, healthItem); ItemStack skinItem = createItem(Material.PAINTING, "Скин: " + player.getName()); ItemMeta skinMeta = skinItem.getItemMeta(); skinMeta.setUnbreakable(true); skinItem.setItemMeta(skinMeta); statsMenu.setItem(13, skinItem); // Здесь добавьте остальные предметы для меню “Статистика” // statsMenu.setItem(0, createItem(…)) // statsMenu.setItem(1, createItem(…)) // … return statsMenu; } public static void openMenu(Player player) { Inventory menu = createMenu(); player.openInventory(menu); } public static ItemStack createItem(Material material, String name) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } СДЕЛАЙ ЧТОБЫ КОГДА ИГРОК НАЖИМАЛ НА КОМПАС, ЕМУ ОТКРЫВАЛОСЬ МЕНЮ СТАТИСТИКИ, СКИНЬ ИТОГОВЫЙ ГОТОВЫЙ КОД ВСЕХ КЛАССОВ.
40937fe01dac82cd165c70a66ee44ebc
{ "intermediate": 0.2686426043510437, "beginner": 0.44498783349990845, "expert": 0.28636956214904785 }
32,335
whats latesc mc
8037cb7661d99befb915dfab65ccc250
{ "intermediate": 0.32312431931495667, "beginner": 0.44163477420806885, "expert": 0.23524092137813568 }
32,336
package foleon.miningcore; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; public class MenuManager implements Listener { public static Inventory createMenu() { Inventory menu = Bukkit.createInventory(null, 6 * 9, “Меню”); ItemStack skillsItem = createItem(Material.IRON_SWORD, “Навыки”); ItemMeta skillsMeta = skillsItem.getItemMeta(); skillsMeta.setUnbreakable(true); skillsItem.setItemMeta(skillsMeta); menu.setItem(14, skillsItem); ItemStack statsItem = createItem(Material.COMPASS, “Статистика”); ItemMeta statsMeta = statsItem.getItemMeta(); statsMeta.setUnbreakable(true); statsItem.setItemMeta(statsMeta); menu.setItem(4, statsItem); return menu; } private static Inventory createSkillsMenu() { Inventory skillsMenu = Bukkit.createInventory(null, 6 * 9, “Навыки”); // Здесь добавьте предметы для меню “Навыки” // skillsMenu.setItem(0, createItem(…)) // skillsMenu.setItem(1, createItem(…)) // … return skillsMenu; } private static Inventory createStatsMenu(Player player) { Inventory statsMenu = Bukkit.createInventory(null, 6 * 9, “Статистика”); ItemStack healthItem = createItem(Material.REDSTONE_BLOCK, "Здоровье: " + player.getHealth()); ItemMeta healthMeta = healthItem.getItemMeta(); healthMeta.setUnbreakable(true); healthItem.setItemMeta(healthMeta); statsMenu.setItem(4, healthItem); ItemStack swordItem = createItem(Material.IRON_SWORD, "Урон: " + player.getAttackDamage()); ItemMeta swordMeta = swordItem.getItemMeta(); swordMeta.setUnbreakable(true); swordItem.setItemMeta(swordMeta); statsMenu.setItem(24, swordItem); ItemStack skinItem = createItem(Material.PAINTING, "Скин: " + player.getName()); ItemMeta skinMeta = skinItem.getItemMeta(); skinMeta.setUnbreakable(true); skinItem.setItemMeta(skinMeta); statsMenu.setItem(13, skinItem); // Здесь добавьте остальные предметы для меню “Статистика” // statsMenu.setItem(0, createItem(…)) // statsMenu.setItem(1, createItem(…)) // … return statsMenu; } private static void openMenu(Player player) { Inventory menu = createMenu(); player.openInventory(menu); } private static ItemStack createItem(Material material, String name) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name); item.setItemMeta(meta); return item; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.getClickedInventory() != null && event.getClickedInventory().equals(event.getWhoClicked().getInventory())) { return; } if (event.getView().getTitle().equals(“Меню”)) { event.setCancelled(true); if (event.getSlot() == 4) { Player player = (Player) event.getWhoClicked(); Inventory statsMenu = createStatsMenu(player); player.openInventory(statsMenu); } } else if (event.getView().getTitle().equals(“Статистика”)) { event.setCancelled(true); } // Другие проверки для остальных меню } } public class MiningCore extends JavaPlugin { @Override public void onEnable() { getServer().getPluginManager().registerEvents(new MenuManager(), this); } } почему не показывается урон в меню статистики в итоговом коде? скинь итоговый код
ed5e785a932fc92372ec719685b5fe7d
{ "intermediate": 0.3034631907939911, "beginner": 0.45122501254081726, "expert": 0.2453118860721588 }
32,337
document.querySelector("#topTD > div:nth-child(4) > h1").font-size = 50px; VM1305:1 Uncaught SyntaxError: Invalid left-hand side in assignment пытаюсь изменить цвет заголовка в редакторе кода в браузере, выдает ошибку
b1feaccbae89574941c279388ca8858c
{ "intermediate": 0.22807560861110687, "beginner": 0.5884748101234436, "expert": 0.1834496110677719 }
32,338
can you create a python code for object detection system using yolov5 model that detects from a camera source?
835858616107f3ba5acc0621a08f2388
{ "intermediate": 0.29248613119125366, "beginner": 0.06030360981822014, "expert": 0.6472102999687195 }
32,339
Переделай код, чтобы при вводе правильного логина и пароля пользователя переводило на страницу index.php document.addEventListener('DOMContentLoaded', function() { document.querySelector('form').addEventListener('submit', function(e) { e.preventDefault(); var login = document.getElementById('login').value; var password = document.getElementById('password').value; if (login && password) { // Отправляем данные на сервер для проверки var xhr = new XMLHttpRequest(); xhr.open('POST', 'log.php', true); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); if (response.valid) { // Если логин и пароль верные, перенаправляем на index.php window.location = 'index.php'; } else { // Если логин и пароль не верные, отображаем сообщение об ошибке document.querySelector('.alert').textContent = 'Нет такого пользователя'; } } }; var data = 'login=' + login + '&pass=' + password; xhr.send(data); } else { // В случае, если поля пустые, отображаем сообщение об ошибке document.querySelector('.alert').textContent = 'Заполните все поля'; } }); });
cd16def3f45c4c233c5e3d73f9b33570
{ "intermediate": 0.36222079396247864, "beginner": 0.37832745909690857, "expert": 0.2594517469406128 }
32,340
Сделай на js, чтобы когда пользователь ввёл правильный логин и пароль, его сразу бы перенаправило на страницу index.php <?php require_once('db.php'); $login=$_POST['login']; $pass=$_POST['pass']; if (empty($login) || empty($pass)) { "Заполните все поля"; } else { $sql = "SELECT * FROM `users` WHERE login = '$login' AND pass = '$pass'"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()){ $message = "Добро пожаловать " . $row['login']; } } else { $message = "Нет такого пользователя"; } } ?>
4a1c909974afb94bba0b38d817dc23e6
{ "intermediate": 0.37233152985572815, "beginner": 0.43756604194641113, "expert": 0.1901024430990219 }
32,341
best 100% free text to video generators
872a7b958766b0b37592e90934a1e152
{ "intermediate": 0.3960147798061371, "beginner": 0.299181193113327, "expert": 0.3048039972782135 }
32,342
write .java code for aoh2 better combat system so if bigger army vs smaller then bigger army losses less
08ed4e022ea6b32ad2b2784db919db73
{ "intermediate": 0.41434890031814575, "beginner": 0.16006475687026978, "expert": 0.4255863130092621 }
32,343
add 25 more governments { Government: [ { Name: "Nominal Democracy", Extra_Tag: "", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.2, MIN_GOODS: 0.14, MIN_INVESTMENTS: 0.14, RESEARCH_COST: 1.0, INCOME_TAXATION: 1.0, INCOME_PRODUCTION: 1.0, MILITARY_UPKEEP: 1.0, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.0, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 192, G: 192, B: 192 }, { Name: "Monarchy", Extra_Tag: "m", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.55, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.25, INCOME_PRODUCTION: 1.15, MILITARY_UPKEEP: 1.1, ADMINISTRATION_COST: 1.15, ADMINISTRATION_COST_DISTANCE: 1.0, ADMINISTRATION_COST_CAPITAL: 0.3, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 5, COST_OF_PLUNDER: 8, DEFENSE_BONUS: 8, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 255, G: 194, B: 36 }, { Name: "Christian_Democracy", Extra_Tag: "e", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.20, MIN_GOODS: 0.21, MIN_INVESTMENTS: 0.11, RESEARCH_COST: 1.12, INCOME_TAXATION: 1.16, INCOME_PRODUCTION: 1.18, MILITARY_UPKEEP: 1.17, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.2, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 5, COST_OF_MOVE_OWN_PROV: 5, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 15, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 6, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 225, G: 226, B: 229 }, { Name: "Liberal", Extra_Tag: "1", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.15, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.05, RESEARCH_COST: 1.1, INCOME_TAXATION: 0.85, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.25, ADMINISTRATION_COST: 0.77, ADMINISTRATION_COST_DISTANCE: 0.9, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 4, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 20, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 35, G: 87, B: 169 }, { Name: "Conservative", Extra_Tag: "d", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.45, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.18, RESEARCH_COST: 1.25, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 0.95, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 1.15, ADMINISTRATION_COST_DISTANCE: 1.35, ADMINISTRATION_COST_CAPITAL: 0.2, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 8, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 0, G: 0, B: 135 }, { Name: "Social_Democrat", Extra_Tag: "w", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.35, MIN_GOODS: 0.35, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 0.8, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 1.3, MILITARY_UPKEEP: 1.25, ADMINISTRATION_COST: 0.8, ADMINISTRATION_COST_DISTANCE: 0.9, ADMINISTRATION_COST_CAPITAL: 0.1, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 15, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 8, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 194, G: 30, B: 86 }, { Name: "Authoritarian_Democracy", Extra_Tag: "5", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.5, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.15, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 1.15, MILITARY_UPKEEP: 1.35, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.45, ADMINISTRATION_COST_CAPITAL: 0.6, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 5, DEFENSE_BONUS: 1, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 7, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 110, G: 110, B: 110 }, { Name: "Paternal_Autocrat", Extra_Tag: "7", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.6, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 1.25, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 1.28, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 1.38, ADMINISTRATION_COST_DISTANCE: 1.68, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 6, COST_OF_MOVE_OWN_PROV: 4, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 5, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 1, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 45, G: 45, B: 45 }, { Name: "National_Populist", Extra_Tag: "6", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.69, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 1.25, MILITARY_UPKEEP: 0.8, ADMINISTRATION_COST: 1.27, ADMINISTRATION_COST_DISTANCE: 1.34, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 3, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 150, G: 75, B: 0 }, { Name: "Autocracy", Extra_Tag: "(", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.65, MIN_GOODS: 0.19, MIN_INVESTMENTS: 0.35, RESEARCH_COST: 1.25, INCOME_TAXATION: 1.25, INCOME_PRODUCTION: 0.85, MILITARY_UPKEEP: 1.15, ADMINISTRATION_COST: 0.9, ADMINISTRATION_COST_DISTANCE: 1.5, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 86, G: 91, B: 90 }, { Name: "Green", Extra_Tag: "&", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.42, MIN_GOODS: 0.45, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 0.9, INCOME_TAXATION: 1.15, INCOME_PRODUCTION: 0.8, MILITARY_UPKEEP: 1.5, ADMINISTRATION_COST: 0.65, ADMINISTRATION_COST_DISTANCE: 0.65, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 22, COST_OF_MOVE_TO_THE_SAME_PROV: 11, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 25, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 45, G: 120, B: 45 }, { Name: "Reactionary", Extra_Tag: "8", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.6, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.65, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 0.8, MILITARY_UPKEEP: 1.15, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.3, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 8, COST_OF_MOVE_OWN_PROV: 8, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 18, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 140, G: 140, B: 140 }, { Name: "Valkism", Extra_Tag: "%", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.67, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.35, RESEARCH_COST: 0.75, INCOME_TAXATION: 1.45, INCOME_PRODUCTION: 1.25, MILITARY_UPKEEP: 0.83, ADMINISTRATION_COST: 1.27, ADMINISTRATION_COST_DISTANCE: 1.3, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 25, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 11, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 45, G: 45, B: 45 }, { Name: "Communism", Extra_Tag: "c", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.8, MIN_GOODS: 0.29, MIN_INVESTMENTS: 0.35, RESEARCH_COST: 0.65, INCOME_TAXATION: 1.55, INCOME_PRODUCTION: 1.6, MILITARY_UPKEEP: 0.80, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.4, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 25, COST_OF_PLUNDER: 3, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 92, G: 0, B: 0 }, { Name: "Syndicalism", Extra_Tag: "2", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.55, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.05, INCOME_TAXATION: 1.25, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 1.15, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.5, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 13, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 6, DEFENSE_BONUS: 11, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "COMMUNISM", R: 255, G: 0, B: 0 }, { Name: "Socialism", Extra_Tag: "q", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.3, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 0.85, INCOME_TAXATION: 1.15, INCOME_PRODUCTION: 1.35, MILITARY_UPKEEP: 0.9, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.35, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 4, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 6, DEFENSE_BONUS: 3, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "COMMUNISM", R: 115, G: 0, B: 150 }, { Name: "Radical_Socialism", Extra_Tag: "3", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.65, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.4, RESEARCH_COST: 0.8, INCOME_TAXATION: 0.8, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 0.90, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.3, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 8, COST_OF_MOVE_OWN_PROV: 5, COST_OF_RECRUIT: 13, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 6, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "COMMUNISM", R: 233, G: 58, B: 58 }, { Name: "Totalism", Extra_Tag: "4", GOV_GROUP_ID: 1, ACCEPTABLE_TAXATION: 0.8, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 0.75, INCOME_TAXATION: 0.8, INCOME_PRODUCTION: 1.2, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.35, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 2, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "COMMUNISM", R: 127, G: 0, B: 0 }, { Name: "Monarchism", Extra_Tag: "}", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.55, MIN_GOODS: 0.35, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 1.45, INCOME_TAXATION: 1.45, INCOME_PRODUCTION: 1.25, MILITARY_UPKEEP: 1.15, ADMINISTRATION_COST: 1.15, ADMINISTRATION_COST_DISTANCE: 1.2, ADMINISTRATION_COST_CAPITAL: 0.1, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 6, COST_OF_RECRUIT: 15, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 8, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 8, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 124, G: 0, B: 124 }, { Name: "Fascism", Extra_Tag: "f", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.5, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.3, RESEARCH_COST: 0.90, INCOME_TAXATION: 1.7, INCOME_PRODUCTION: 1.5, MILITARY_UPKEEP: 0.75, ADMINISTRATION_COST: 1.3, ADMINISTRATION_COST_DISTANCE: 1.45, ADMINISTRATION_COST_CAPITAL: 0.6, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 8, REVOLUTIONARY: false, AI_TYPE: "FASCISM", R: 135, G: 50, B: 0 }, { Name: "Nationalism", Extra_Tag: "n", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.65, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.15, INCOME_TAXATION: 1.45, INCOME_PRODUCTION: 1.55, MILITARY_UPKEEP: 0.80, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.45, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 3, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 8, COST_OF_DISBAND: 5, COST_OF_PLUNDER: 0.1, DEFENSE_BONUS: 20, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 9, REVOLUTIONARY: false, AI_TYPE: "FASCISM", R: 80, G: 50, B: 0 }, { Name: "Ultranational_Socialism", Extra_Tag: "!", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.75, MIN_GOODS: 0.4, MIN_INVESTMENTS: 0.2, RESEARCH_COST: 1.35, INCOME_TAXATION: 1.3, INCOME_PRODUCTION: 1.1, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 1.4, ADMINISTRATION_COST_DISTANCE: 1.7, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 3, COST_OF_MOVE_TO_THE_SAME_PROV: 1, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 35, COST_OF_DISBAND: 3, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 20, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "FASCISM", R: 47, G: 79, B: 79 }, { Name: "Republic", Extra_Tag: "r", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.5, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.35, RESEARCH_COST: 1.15, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 1.15, MILITARY_UPKEEP: 1.2, ADMINISTRATION_COST: 0.85, ADMINISTRATION_COST_DISTANCE: 1.1, ADMINISTRATION_COST_CAPITAL: 0.1, COST_OF_MOVE: 14, COST_OF_MOVE_TO_THE_SAME_PROV: 8, COST_OF_MOVE_OWN_PROV: 6, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 9, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 59, B: 114 }, { Name: "Radicalism", Extra_Tag: ".", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.6, MIN_GOODS: 0.12, MIN_INVESTMENTS: 0.37, RESEARCH_COST: 1.12, INCOME_TAXATION: 0.85, INCOME_PRODUCTION: 1.2, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 0.7, ADMINISTRATION_COST_DISTANCE: 0.9, ADMINISTRATION_COST_CAPITAL: 0.1, COST_OF_MOVE: 14, COST_OF_MOVE_TO_THE_SAME_PROV: 6, COST_OF_MOVE_OWN_PROV: 6, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 9, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 8, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 166, G: 90, B: 90 }, { Name: "Horde", Extra_Tag: "h", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.47, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.55, INCOME_TAXATION: 1.35, INCOME_PRODUCTION: 0.65, MILITARY_UPKEEP: 0.9, ADMINISTRATION_COST: 1.6, ADMINISTRATION_COST_DISTANCE: 1.7, ADMINISTRATION_COST_CAPITAL: 0.8, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 1, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 5, COST_OF_DISBAND: 14, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "HORDE", R: 28, G: 99, B: 75 }, { Name: "CityState", Extra_Tag: "s", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.3, MIN_GOODS: 0.35, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.15, MILITARY_UPKEEP: 1.95, ADMINISTRATION_COST: 0.85, ADMINISTRATION_COST_DISTANCE: 8.25, ADMINISTRATION_COST_CAPITAL: 0.025, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 4, COST_OF_RECRUIT: 25, COST_OF_DISBAND: 19, COST_OF_PLUNDER: 4, DEFENSE_BONUS: 25, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "CITYSTATE", R: 117, G: 28, B: 136 }, { Name: "Tribal", Extra_Tag: "t", GOV_GROUP_ID: 3, ACCEPTABLE_TAXATION: 0.30, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.06, RESEARCH_COST: 0.4, INCOME_TAXATION: 1.1, INCOME_PRODUCTION: 1.00, MILITARY_UPKEEP: 1.6, ADMINISTRATION_COST: 1.175, ADMINISTRATION_COST_DISTANCE: 9.15, ADMINISTRATION_COST_CAPITAL: 0.01, COST_OF_MOVE: 15, COST_OF_MOVE_TO_THE_SAME_PROV: 8, COST_OF_MOVE_OWN_PROV: 2, COST_OF_RECRUIT: 16, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 12, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: 1, CIVILIZE_TECH_LEVEL: 0.25f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "UNCIVILIZED", R: 51, G: 153, B: 102 }, { Name: "Rebels", Extra_Tag: "u", GOV_GROUP_ID: 4, ACCEPTABLE_TAXATION: 0.24, MIN_GOODS: 0.01, MIN_INVESTMENTS: 0.1, RESEARCH_COST: 8.0, INCOME_TAXATION: 1.55, INCOME_PRODUCTION: 0.95, MILITARY_UPKEEP: 0.15, ADMINISTRATION_COST: 0.7, ADMINISTRATION_COST_DISTANCE: 1.00, ADMINISTRATION_COST_CAPITAL: 0.1, COST_OF_MOVE: 2, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 0, COST_OF_RECRUIT: 1, COST_OF_DISBAND: 2, COST_OF_PLUNDER: 2, DEFENSE_BONUS: 40, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: true, AI_TYPE: "REBELS", R: 92, G: 92, B: 92 }, { Name: "Centrism", Extra_Tag: "j", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.4, MIN_GOODS: 0.2, MIN_INVESTMENTS: 0.25, RESEARCH_COST: 1.2, INCOME_TAXATION: 1.65, INCOME_PRODUCTION: 0.9, MILITARY_UPKEEP: 1.15, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.5, ADMINISTRATION_COST_CAPITAL: 0.5, COST_OF_MOVE: 8, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 6, COST_OF_RECRUIT: 20, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 7, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 127, B: 127 }, { Name: "Islamism", Extra_Tag: "i", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.25, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.15, RESEARCH_COST: 1.25, INCOME_TAXATION: 1.25, INCOME_PRODUCTION: 0.95, MILITARY_UPKEEP: 1.24, ADMINISTRATION_COST: 1.0, ADMINISTRATION_COST_DISTANCE: 1.0, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 8, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 0, G: 85, B: 0 }, { Name: "Salafist", Extra_Tag: "+", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.45, MIN_GOODS: 0.25, MIN_INVESTMENTS: 0.18, RESEARCH_COST: 1.35, INCOME_TAXATION: 0.5, INCOME_PRODUCTION: 1.35, MILITARY_UPKEEP: 0.85, ADMINISTRATION_COST: 1.1, ADMINISTRATION_COST_DISTANCE: 1.2, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 5, COST_OF_MOVE_TO_THE_SAME_PROV: 4, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 10, COST_OF_DISBAND: 8, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 17, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 10, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 35, G: 35, B: 35 }, { Name: "Progressivism", Extra_Tag: "y", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 1.0, MIN_GOODS: 0.05, MIN_INVESTMENTS: 0.35, RESEARCH_COST: 0.65, INCOME_TAXATION: 0.85, INCOME_PRODUCTION: 1.12, MILITARY_UPKEEP: 1.2, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.4, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 25, COST_OF_MOVE_TO_THE_SAME_PROV: 10, COST_OF_MOVE_OWN_PROV: 8, COST_OF_RECRUIT: 25, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 5, DEFENSE_BONUS: 5, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 11, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 0, G: 120, B: 220 }, { Name: "Libertharian_Socialism", Extra_Tag: "{", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.34, MIN_GOODS: 0.17, MIN_INVESTMENTS: 0.17, RESEARCH_COST: 1.28, INCOME_TAXATION: 1.25, INCOME_PRODUCTION: 0.90, MILITARY_UPKEEP: 1.19, ADMINISTRATION_COST: 1.15, ADMINISTRATION_COST_DISTANCE: 1.2, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 6, COST_OF_MOVE_TO_THE_SAME_PROV: 6, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 18, COST_OF_DISBAND: 16, COST_OF_PLUNDER: 12, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 8, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 146, G: 0, B: 0 }, { Name: "Military_junta", Extra_Tag: "p", GOV_GROUP_ID: 2, ACCEPTABLE_TAXATION: 0.55, MIN_GOODS: 0.1, MIN_INVESTMENTS: 0.33, RESEARCH_COST: 1.2, INCOME_TAXATION: 0.85, INCOME_PRODUCTION: 1.1, MILITARY_UPKEEP: 0.55, ADMINISTRATION_COST: 1.25, ADMINISTRATION_COST_DISTANCE: 1.55, ADMINISTRATION_COST_CAPITAL: 0.6, COST_OF_MOVE: 4, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 12, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 1, DEFENSE_BONUS: 10, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 6, REVOLUTIONARY: false, AI_TYPE: "FASCISM", R: 148, G: 25, B: 25 }, { Name: "Oligarchy", Extra_Tag: "o", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.85, MIN_GOODS: 0.15, MIN_INVESTMENTS: 0.45, RESEARCH_COST: 1.4, INCOME_TAXATION: 1.6, INCOME_PRODUCTION: 1.4, MILITARY_UPKEEP: 1.2, ADMINISTRATION_COST: 1.15, ADMINISTRATION_COST_DISTANCE: 1.35, ADMINISTRATION_COST_CAPITAL: 0.2, COST_OF_MOVE: 10, COST_OF_MOVE_TO_THE_SAME_PROV: 8, COST_OF_MOVE_OWN_PROV: 3, COST_OF_RECRUIT: 17, COST_OF_DISBAND: 10, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 4, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEMOCRACY", R: 200, G: 172, B: 97 }, { Name: "Theocracy", Extra_Tag: "g", GOV_GROUP_ID: 0, ACCEPTABLE_TAXATION: 0.32, MIN_GOODS: 0.32, MIN_INVESTMENTS: 0.05, RESEARCH_COST: 1.25, INCOME_TAXATION: 1.4, INCOME_PRODUCTION: 0.57, MILITARY_UPKEEP: 1.6, ADMINISTRATION_COST: 1.2, ADMINISTRATION_COST_DISTANCE: 1.2, ADMINISTRATION_COST_CAPITAL: 0.4, COST_OF_MOVE: 2, COST_OF_MOVE_TO_THE_SAME_PROV: 2, COST_OF_MOVE_OWN_PROV: 1, COST_OF_RECRUIT: 40, COST_OF_DISBAND: 12, COST_OF_PLUNDER: 10, DEFENSE_BONUS: 15, CAN_BECOME_CIVILIZED: -1, CIVILIZE_TECH_LEVEL: 2.0f, AVAILABLE_SINCE_AGE_ID: 0, REVOLUTIONARY: false, AI_TYPE: "DEFAULT", R: 112, G: 112, B: 112 }, ], Age_of_Civilizations: Governments }
b63b4597272d6969af9f2366655d7cbd
{ "intermediate": 0.3349548578262329, "beginner": 0.37850216031074524, "expert": 0.28654298186302185 }
32,344
toObject(spectator = false) { return { map_id: this.id, sound_id: this.sound, spectator: spectator, game_mode: this.game_mode, kick_period_ms: 300000, skybox_id: this.skybox_id, invisible_time: 3500, resources: }; } } exports.Map = Map; как сюда добавить mounted_turret, mounted_hull, mounted_paint из const { market_list } = require("./server"); const GarageItem = require("./GarageItem"), Area = require("./Area"), { turrets, hulls, paints, getType } = require("./server"), InventoryItem = require("./InventoryItem"); class Garage extends Area { static fromJSON(data) { if (typeof (data.tank) !== "undefiend") { var garage = new Garage(data.tank); garage.items = Garage.fromItemsObject(data.items); garage.updateMarket(); garage.mounted_turret = data.mounted_turret; garage.mounted_hull = data.mounted_hull; garage.mounted_paint = data.mounted_paint; garage.inventory = null; return garage; } return null; } static fromItemsObject(obj) { var items = []; for (var i in obj.items) { items.push(GarageItem.fromJSON(obj.items[i])); } return items; } constructor(tank) { super(); this.tank = tank; this.items = [GarageItem.get("smoky", 0), GarageItem.get("green", 0), GarageItem.get("holiday", 0), GarageItem.get("wasp", 0), GarageItem.get("health", 0)]; this.updateMarket(); this.mounted_turret = "smoky_m0"; this.mounted_hull = "wasp_m0"; this.mounted_paint = "green_m0"; this.inventory = []; } getPrefix() { return "garage"; } getInventory() { // if (this.inventory !== null) // return this.inventory; var inventory = []; for (var i in this.items) { var item = this.items[i]; if (getType(item.id) === 4) { inventory.push(InventoryItem.fromGarageItem(item)); } } this.inventory = inventory; return inventory; } addGarageItem(id, amount) { var tank = this.tank; var new_item = GarageItem.get(id, 0); if (new_item !== null) { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } return true; } useItem(id) { for (var i in this.items) { if (this.items[i].isInventory && this.items[i].id === id) { if (this.items[i].count <= 0) return false; if (this.items[i].count = 1) { this.deleteItem(this.items[i]) } --this.items[i].count; } } return true; } hasItem(id, m = null) { for (var i in this.items) { if (this.items[i].id === id) { if (this.items[i].type !== 4) { if (m === null) return true; return this.items[i].modificationID >= m; } else if (this.items[i].count > 0) return true; else { this.items.splice(i, 1); } } } return false; } initiate(socket) { this.send(socket, "init_garage_items;" + JSON.stringify({ items: this.items })); this.addPlayer(this.tank); } initMarket(socket) { this.send(socket, "init_market;" + JSON.stringify(this.market)); } initMountedItems(socket) { this.send(socket, "init_mounted_item;" + this.mounted_hull); this.send(socket, "init_mounted_item;" + this.mounted_turret); this.send(socket, "init_mounted_item;" + this.mounted_paint); } getItem(id) { for (var i in this.items) { if (this.items[i].id === id) return this.items[i]; } return null; } getTurret() { return this.getItem(this.mounted_turret.split("_")[0]); } getHull() { return this.getItem(this.mounted_hull.split("_")[0]); } getPaint() { return this.getItem(this.mounted_paint.split("_")[0]); } updateMarket() { this.market = { items: [] }; for (var i in market_list) { if (!this.hasItem(market_list[i]["id"]) && market_list[i]["index"] >= 0) { this.market.items.push(market_list[i]); } this.hasItem(market_list[i]["multicounted"]) } } onData(socket, args) { if (this.tank === null || !this.hasPlayer(this.tank.name)) return; var tank = this.tank; if (args.length === 1) { if (args[0] === "get_garage_data") { this.updateMarket(); setTimeout(() => { this.initMarket(socket); this.initMountedItems(socket); }, 1500); } } else if (args.length === 3) { if (args[0] === "try_buy_item") { var itemStr = args[1]; var arr = itemStr.split("_"); var id = itemStr.replace("_m0", ""); var amount = parseInt(args[2]); var new_item = GarageItem.get(id, 0); if (new_item !== null) { if (tank.crystals >= new_item.price * amount && tank.rank >= new_item.rank) { var obj = {}; obj.itemId = id; obj.multicounted = arr[2]; if (new_item !== null && id !== "1000_scores") { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } tank.crystals -= new_item.price * amount; if (id === "1000_scores") tank.addScore(1000 * amount); if (id === "supplies") { this.addKitItem("health",0,100,tank); this.addKitItem("armor",0,100,tank); this.addKitItem("damage",0,100,tank); this.addKitItem("nitro",0,100,tank); this.addKitItem("mine",0,100,tank); this.send(socket,"reload") } else { this.send(socket, "buy_item;" + itemStr + ";" + JSON.stringify(obj)); } tank.sendCrystals(); } } } } else if (args.length === 2) { if (args[0] === "try_mount_item") { var itemStr = args[1]; var itemStrArr = itemStr.split("_"); if (itemStrArr.length === 2) { var modificationStr = itemStrArr[1]; var item_id = itemStrArr[0]; if (modificationStr.length === 2) { var m = parseInt(modificationStr.charAt(1)); if (!isNaN(m)) { this.mountItem(item_id, m); this.sendMountedItem(socket, itemStr); tank.save(); } } } } else if (args[0] === "try_update_item") { var itemStr = args[1], arr = itemStr.split("_"), modStr = arr.pop(), id = arr.join("_"); if (modStr.length === 2) { var m = parseInt(modStr.charAt(1)); if (!isNaN(m) && m < 3) { if (this.hasItem(id, m) && this.getItem(id).attempt_upgrade(tank)) { this.send(socket, "update_item;" + itemStr); tank.sendCrystals(); } } } } } } addKitItem(item, m, count, tank) { // this.items.push(item); var itemStr = item + "_m" var arr = itemStr.split("_"); var id = itemStr.replace("_m", ""); var amount = parseInt(count); var new_item = GarageItem.get(id, 0); console.log(new_item) if (new_item !== null) { var obj = {}; obj.itemId = id; var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; new_item.modificationID = m; obj.count = amount; obj.multicounted = item.multicounted; this.addItem(new_item); } else { item.count += amount; item.modificationID = m; obj.count = item.count; obj.multicounted = item.multicounted; } } } addItem(item) { this.items.push(item); } deleteItem(item) { delete this.items[item]; } mountItem(item_id, m) { if (this.hasItem(item_id, m)) { var itemStr = item_id + "_m" + m; if (hulls.includes(item_id)) this.mounted_hull = itemStr; else if (turrets.includes(item_id)) this.mounted_turret = itemStr; else if (paints.includes(item_id)) this.mounted_paint = itemStr; } } sendMountedItem(socket, itemStr) { this.send(socket, "mount_item;" + itemStr); } getItemsObject() { var items = []; for (var i in this.items) { items.push(this.items[i].toObject()); } return { items: items }; } toSaveObject() { return { items: this.getItemsObject(), mounted_turret: this.mounted_turret, mounted_hull: this.mounted_hull, mounted_paint: this.mounted_paint }; } } module.exports = Garage;
1b61710484edffecc130d2a5d937004c
{ "intermediate": 0.3561175465583801, "beginner": 0.44245511293411255, "expert": 0.2014273852109909 }
32,345
Write bootstrap code for navbar Upper navbar two selectors at top right lower navbar logo products claims contact us login button It should be mobile responsive
381aec4dd6779ed83d39c6b5f7733913
{ "intermediate": 0.43588611483573914, "beginner": 0.17750923335552216, "expert": 0.3866046071052551 }
32,346
File "<ipython-input-16-da465df87554>", line 12 plt.figure(figsize=(10, 6)) ^ IndentationError: expected an indented block after function definition on line 11
9faf006046906ad93d77339cee5e73b7
{ "intermediate": 0.3749421536922455, "beginner": 0.3820054829120636, "expert": 0.2430523782968521 }
32,347
ai generate using Linear Regression algorithm 6 main numbers and 5 lines with balanced selection of odd and even numbers, as well as a mix of low, mid, and high numbers main numbers 1 to 70 with one extra bonus number 1 to 25 with no duplicate bonus and main numbers on each line very important to exclude from main numbers line only the following numbers 5 12 21 23 49 50 51 60 65 67
5d3602f91c26568836674d28d5bce804
{ "intermediate": 0.1357109695672989, "beginner": 0.060322754085063934, "expert": 0.8039662837982178 }
32,348
XImage *pWindowBuffer = XCreateImage(pDisplay, visual, 24, ZPixmap, 0, pPixels, width, height, 32, 0); XPutImage(pDisplay, window, gc, pWindowBuffer, 0, 0, 0, 0, width, height); pPixels is an array of width * height * 3 uint8_ts. But when the image is displayed, I get the wrong colors. It sort of looks weird, as if it's reading more channels than it should be.
67af55cc4d5bb0c706abeef93fbec137
{ "intermediate": 0.4605601131916046, "beginner": 0.21451541781425476, "expert": 0.324924498796463 }
32,349
how whoosh library handles latex characters
c8ca015bef80e185f21baa64b4bb8a97
{ "intermediate": 0.7843217849731445, "beginner": 0.1271672248840332, "expert": 0.08851103484630585 }
32,350
Hi
5b8f2700936f1dbee61f12574d88297f
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
32,351
python code using BiLSTM encoder and BiLSTM decoder rnn and attention layer to translate English text to Arabic text using train, validate and test data from text files ,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
c4e479dc089e9f2c5daedb2ae44f50e9
{ "intermediate": 0.3748818337917328, "beginner": 0.09119625389575958, "expert": 0.5339218974113464 }
32,352
How do I color icons in layout?
0a5183f2812093568ce11f9cdcc3ad7e
{ "intermediate": 0.3658815920352936, "beginner": 0.355379581451416, "expert": 0.2787388861179352 }
32,353
напиши плагин на майнкрафт спигот 1.12.2, сделай чтобы создавался файл stats.yml в котором записывался бы каждый игрок и его количество strength, сделай чтобы базовое количество strength было 0, сделай чтобы за каждую 1 единицу стренжа у игрока повышался урон на 1% и скинь итоговый код со всеми классами.
b920d7714241600b53d9239f7859cce4
{ "intermediate": 0.3143532872200012, "beginner": 0.3134244680404663, "expert": 0.37222224473953247 }
32,354
import numpy as np from keras.models import Model from keras.layers import Input, LSTM, Bidirectional, Concatenate, Dot,Embedding,Activation,Dense from keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Define hyperparameters max_sequence_length = 100 embedding_dim = 100 latent_dim = 256 # Load train, validate, and test data from text files with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Train.txt', 'r', encoding='utf-8') as f: train_data = f.read().splitlines() with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Validate.txt', 'r', encoding='utf-8') as f: validate_data = f.read().splitlines() with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Test.txt', 'r', encoding='utf-8') as f: test_data = f.read().splitlines() # Tokenize sentences and convert them into numerical representations tokenizer_en = Tokenizer() tokenizer_en.fit_on_texts(train_data) train_data_en = tokenizer_en.texts_to_sequences(train_data) train_data_en = pad_sequences(train_data_en, maxlen=max_sequence_length) tokenizer_ar = Tokenizer() tokenizer_ar.fit_on_texts(train_data) train_data_ar = tokenizer_ar.texts_to_sequences(train_data) train_data_ar = pad_sequences(train_data_ar, maxlen=max_sequence_length) # Define encoder inputs and LSTM layer encoder_inputs = Input(shape=(max_sequence_length,)) encoder_embedding = Embedding(len(tokenizer_en.word_index) + 1, embedding_dim)(encoder_inputs) encoder_lstm = Bidirectional(LSTM(latent_dim, return_sequences=True))(encoder_embedding) # Define decoder inputs and LSTM layer decoder_inputs = Input(shape=(max_sequence_length,)) decoder_embedding = Embedding(len(tokenizer_ar.word_index) + 1, embedding_dim)(decoder_inputs) decoder_lstm = Bidirectional(LSTM(latent_dim, return_sequences=True))(decoder_embedding) # Apply attention mechanism attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) attention = Activation('softmax')(attention) context = Dot(axes=[2, 1])([attention, encoder_lstm]) decoder_combined_context = Concatenate(axis=-1)([context, decoder_lstm]) # Define decoder output layer decoder_dense = Dense(len(tokenizer_ar.word_index) + 1, activation='softmax') decoder_outputs = decoder_dense(decoder_combined_context) # Define the model model = Model([encoder_inputs, decoder_inputs], decoder_outputs) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.summary() # Train the model model.fit([train_data_en, train_data_ar], np.expand_dims(train_data_ar, -1), batch_size=64, epochs=10, validation_split=0.2) # Use test data to evaluate the model with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Test.txt', 'r', encoding='utf-8') as f: test_data = f.read().splitlines() test_data_en = tokenizer_en.texts_to_sequences(test_data) test_data_en = pad_sequences(test_data_en, maxlen=max_sequence_length) predicted_arabic = model.predict(test_data_en) decoded_arabic = tokenizer_ar.sequences_to_texts(np.argmax(predicted_arabic, axis=-1)) # Print example prediction translation from test data print("English sentence: ", test_data[0]) print("Predicted Arabic sentence: ", decoded_arabic[0])
44f65589cb95c287c638560ea367a235
{ "intermediate": 0.27769598364830017, "beginner": 0.3991117477416992, "expert": 0.3231922686100006 }
32,355
How can you write a java program to accept two user inputs
75593d5cb5d2648add1b909bad9aed81
{ "intermediate": 0.47428563237190247, "beginner": 0.17439575493335724, "expert": 0.3513186573982239 }
32,356
A ship leaves a port and sails 26 miles. Then the ship turns and travels another 62 miles due east. The angle between the ship’s path leaving the port and the line of sight from the port to the ship’s current location is 68 degrees. What is the distance, d,d, between the ship’s current location and the port? Round the answer to the nearest mile, if necessary.
7854f083a232afb0f84aa98a32f8cf0c
{ "intermediate": 0.3716689646244049, "beginner": 0.29753053188323975, "expert": 0.33080047369003296 }
32,357
Examine the following two relations which are part of a database for a company selling horse accessories. Product Product No (PK) Description Price P001 Riding Hat £50 P002 Jodhpurs £20 P003 Back Support £60 P004 Riding Boots £100 P005 Jacket £150 Warehouse Warehouse No (PK) City Address W010 London 10 New Road W020 Cambridge 23 Hills Road W015 York 456 Long Road W040 Bedford 45 Old Street W025 Nottingham 56 Bar Hill Assumptions: 1. The products sold by the company are stored in Warehouses. 2. Each warehouse can store many products. 3. Each product can be stored in many warehouses. NOTE: The codes to create the above tables are given in the HorseDB.sql file. Download the file and execute it. You will need the Product and Warehouse tables before you create the Stock table: Task 1: Create a Stock table which links the product table with the warehouse table and contains the attributes given in the table below. You are expected to give each attribute a relevant name and data type, and to correctly define the primary key and foreign keys: Stock Attribute Description Data Type Attribute 1 Code used to uniquely identify the Stock. String – 5 characters Attribute 2 Link to the Product Table. String – 5 characters Attribute 3 Links to the Warehouse Table. String – 5 characters Attribute 4 Stock quantity. Integer Attribute 5 Aisle Number where stock located in warehouse. String – 5 characters Attribute 6 Bin Number where stock is located in aisle. Integer Task 2: Populate the table with at least 5 rows of data. Make sure the data is realistic and the Entity and Referential Integrity Constraint are not violated.   You will be marked on the following GOALs: These GOALs are all individual and worth 1 mark. I9.1. The correct use of the CREATE TABLE statement. I9.2. Relevant attribute names. I9.3 Relevant domain types. I9.4. Correctly defined Primary Key. I9.5 Correctly define the Foreign Keys. I9.6. The correct use of the INSERT INTO statement. I9.7. The correct use of the VALUES statement. I9.8. Relevant data inserted into table. I9.9. Demonstrate that the Entity Integrity constraint is not violated. I9.10. Demonstrate that the Referential Integrity constraint is not violated.
dbffb109dbbef524687dac9fe19a01f6
{ "intermediate": 0.43948739767074585, "beginner": 0.22957926988601685, "expert": 0.3309333920478821 }
32,358
Give me an example of an RRN in javascript.
a2d1290d82f9f39e5b9b9f0f86363809
{ "intermediate": 0.23603542149066925, "beginner": 0.20981433987617493, "expert": 0.5541502833366394 }
32,359
def f_function(stream, key): string = permute(stream, E) for _ in string: string = np.logical_xor(stream, key)
8a3d50726b7f571d1e6c9dc2ed0b28e8
{ "intermediate": 0.25866788625717163, "beginner": 0.4828296899795532, "expert": 0.25850242376327515 }
32,360
ecrire un programme qui calcule la somme d'un tableau initialisée par l'utilisateur de taille 5
4a0988fac26fc3644413a6e5584c7b9c
{ "intermediate": 0.15427526831626892, "beginner": 0.056575093418359756, "expert": 0.7891496419906616 }
32,361
write a java program on a scientific calculator
11c19098f69b8ab6f87e2a39690f3eb2
{ "intermediate": 0.3186849355697632, "beginner": 0.3767813444137573, "expert": 0.3045337200164795 }
32,362
for some reason, it doesn't generate wall tiles? it's only floor tiles: extends TileMap # Initialize noise generators for different map features # Values between -1 and 1 var moisture = FastNoiseLite.new() var temperature = FastNoiseLite.new() var altitude = FastNoiseLite.new() # Dimensions of each generated chunk var width = 64 var height = 64 # Reference to the player character @onready var player = get_tree().current_scene.get_node("Player") # List to keep track of loaded chunks var loaded_chunks = [] func _ready(): # Set random seeds for noise variation moisture.seed = randi() temperature.seed = randi() altitude.seed = randi() # Adjust this value to change the 'smoothness' of the map; lower values mean more smooth noise altitude.frequency = 0.01 func _process(delta): # Convert the player's position to tile coordinates var player_tile_pos = local_to_map(player.position) # Generate the chunk at the player's position generate_chunk(player_tile_pos) # Unload chunks that are too far away. # Note: Not needed for smaller projects but if you are loading a bigger tilemap it's good practice unload_distant_chunks(player_tile_pos) func generate_chunk(pos): for x in range(width): for y in range(height): # Generate noise values for moisture, temperature, and altitude var moist = moisture.get_noise_2d(pos.x - (width/2) + x, pos.y - (height/2) + y) * 10 # Values between -10 and 10 var temp = temperature.get_noise_2d(pos.x - (width/2) + x, pos.y - (height/2) + y) * 10 var alt = altitude.get_noise_2d(pos.x - (width/2) + x, pos.y - (height/2) + y) * 10 # Set the cell based on altitude; adjust for different tile types # Need to evenly distribute -10 -> 10 to 0 -> 4.... This can be done by first adding 10 # Gets values from 0 -> 20... Then we will multiply by 3/20 in order to remap it to 0 -> 3 # vvv if alt < 0: # Arbitrary sea level value (choosing 0 will mean roughly 1/2 the world is ocean) set_cell(0, Vector2i(pos.x - (width/2) + x, pos.y - (height/2) + y), 0, Vector2(3, round(3 * (temp + 10) / 20))) # Change x value where I've wrote three to whatever the x-coord of your oceans are else: # You can add other logic like making beaches by setting x-coord to whatever beach atlas x-coord is when the alt is between 0 and 0.5 or something set_cell(1, Vector2i(pos.x - (width/2) + x, pos.y - (height/2) + y), 0, Vector2(round(3 * (moist + 10) / 20), round(3 * (temp + 10) / 20))) if Vector2i(pos.x, pos.y) not in loaded_chunks: loaded_chunks.append(Vector2i(pos.x, pos.y)) # Function to unload chunks that are too far away func unload_distant_chunks(player_pos): # Set the distance threshold to at least 2 times the width to limit visual glitches # Higher values unload chunks further away var unload_distance_threshold = (width * 2) + 1 for chunk in loaded_chunks: var distance_to_player = get_dist(chunk, player_pos) if distance_to_player > unload_distance_threshold: clear_chunk(chunk) loaded_chunks.erase(chunk) # Function to clear a chunk func clear_chunk(pos): for x in range(width): for y in range(height): set_cell(0, Vector2i(pos.x - (width/2) + x, pos.y - (height/2) + y), -1, Vector2(-1, -1), -1) # Function to calculate distance between two points func get_dist(p1, p2): var resultant = p1 - p2 return sqrt(resultant.x ** 2 + resultant.y ** 2)
fb1b0c42a0782dbedd89f47c3f41f565
{ "intermediate": 0.3055081367492676, "beginner": 0.3642495572566986, "expert": 0.33024224638938904 }
32,363
C# play sound
56adf892290c079c51a2c5ab7dd0c5cb
{ "intermediate": 0.40023958683013916, "beginner": 0.4543338119983673, "expert": 0.14542663097381592 }
32,364
import numpy as np from keras.models import Model from keras.layers import Input, LSTM, Bidirectional, Concatenate, Dot,Embedding,Activation,Dense from keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences # Define hyperparameters max_sequence_length = 100 embedding_dim = 100 latent_dim = 256 # Load train, validate, and test data from text files with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Train.txt', 'r', encoding='utf-8') as f: train_data = f.read().splitlines() with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Validate.txt', 'r', encoding='utf-8') as f: validate_data = f.read().splitlines() with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Test.txt', 'r', encoding='utf-8') as f: test_data = f.read().splitlines() # Tokenize sentences and convert them into numerical representations tokenizer_en = Tokenizer() tokenizer_en.fit_on_texts(train_data) train_data_en = tokenizer_en.texts_to_sequences(train_data) train_data_en = pad_sequences(train_data_en, maxlen=max_sequence_length) tokenizer_ar = Tokenizer() tokenizer_ar.fit_on_texts(train_data) train_data_ar = tokenizer_ar.texts_to_sequences(train_data) train_data_ar = pad_sequences(train_data_ar, maxlen=max_sequence_length) # Define encoder inputs and LSTM layer encoder_inputs = Input(shape=(max_sequence_length,)) encoder_embedding = Embedding(len(tokenizer_en.word_index) + 1, embedding_dim)(encoder_inputs) encoder_lstm = Bidirectional(LSTM(latent_dim, return_sequences=True))(encoder_embedding) # Define decoder inputs and LSTM layer decoder_inputs = Input(shape=(max_sequence_length,)) decoder_embedding = Embedding(len(tokenizer_ar.word_index) + 1, embedding_dim)(decoder_inputs) decoder_lstm = Bidirectional(LSTM(latent_dim, return_sequences=True))(decoder_embedding) # Apply attention mechanism attention = Dot(axes=[2, 2])([decoder_lstm, encoder_lstm]) attention = Activation('softmax')(attention) context = Dot(axes=[2, 1])([attention, encoder_lstm]) decoder_combined_context = Concatenate(axis=-1)([context, decoder_lstm]) # Define decoder output layer decoder_dense = Dense(len(tokenizer_ar.word_index) + 1, activation='softmax') decoder_outputs = decoder_dense(decoder_combined_context) # Define the model model = Model([encoder_inputs, decoder_inputs], decoder_outputs) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() # Train the model model.fit([train_data_en, train_data_ar[:, :-1]], train_data_ar[:, 1:], batch_size=64, epochs=10, validation_split=0.2) # Use test data to evaluate the model with open('D:/PHD Papers/scientific translation/GPT/First Code BiLSTM/NewResult/Test.txt', 'r', encoding='utf-8') as f: test_data = f.read().splitlines() test_data_en = tokenizer_en.texts_to_sequences(test_data) test_data_en = pad_sequences(test_data_en, maxlen=max_sequence_length) predicted_arabic = model.predict([test_data_en, np.zeros((test_data_en.shape[0], max_sequence_length))]) decoded_arabic = tokenizer_ar.sequences_to_texts(np.argmax(predicted_arabic, axis=-1)) # Print example prediction translation from test data print("English sentence: ", test_data[0]) print("Predicted Arabic sentence: ", decoded_arabic[0])
b380518f93eade56cdbb0966efed2006
{ "intermediate": 0.29470062255859375, "beginner": 0.3753960430622101, "expert": 0.3299033045768738 }
32,365
C# soundplayer change volume
311099880d1b72b3812bcf2e77f52637
{ "intermediate": 0.378237783908844, "beginner": 0.3154025077819824, "expert": 0.3063597083091736 }
32,366
csr reply "Thank you for reach out to us! I apologize but we had a hard time tracking your order from the details you provided. We might need to have the last 4 digits of the card and what type of card was used" please enhance this but make it simple,short, and concise
e1f16c0ab6f6f2c80ddc99a0a2181391
{ "intermediate": 0.32384490966796875, "beginner": 0.29298117756843567, "expert": 0.38317394256591797 }
32,367
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Arrow : MonoBehaviour { void Start() { Invoke("Despawn", 3); } void Despawn() { Destroy(gameObject); } } make it so it does 1 damage to an enemy if it collides with it
79ba43191ac00d15a5593fade90515d6
{ "intermediate": 0.3426853120326996, "beginner": 0.5032713413238525, "expert": 0.1540432870388031 }
32,368
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BowAttack : MonoBehaviour { public float arrowSpeed = 1; public GameObject arrowPrefab; Rigidbody2D rigid; void Start() { rigid = GetComponent<Rigidbody2D>(); } void Update() { //Fire when we click the mouse if (Input.GetMouseButtonDown(0)) { //Get the vector from the player to the mouse Vector3 mousePos = Input.mousePosition; mousePos.z = 10; Vector3 worldPos = Camera.main.ScreenToWorldPoint(mousePos); Vector3 p2m = worldPos - transform.position; p2m.Normalize(); //Spawn a bullet GameObject go = Instantiate<GameObject>(arrowPrefab); go.transform.position = transform.position; //Shoot it in that direction Rigidbody2D arrowRigid = go.GetComponent<Rigidbody2D>(); arrowRigid.velocity = p2m * arrowSpeed; } } } make it so that the arrow can only be fired every 1 seconds
c397954ad689e83742731db4cae3ddb1
{ "intermediate": 0.45203542709350586, "beginner": 0.3275100588798523, "expert": 0.22045446932315826 }
32,369
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public float delayTime = 5f; public GameObject bowPrefab; private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { // Generate a random number (between 0 and 1) to determine if bow spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a bow GameObject bow = Instantiate(bowPrefab, collision.transform); bow.transform.localPosition = new Vector3(-0.25f, -0.25f, 0f); bow.transform.localRotation = Quaternion.identity; } // Disable the chest to prevent spawning multiple bows gameObject.SetActive(false); // Enable the chest after a delay Invoke("EnableChest", delayTime); } } private void EnableChest() { gameObject.SetActive(true); } } make it so the bow may only be instantiated once
bee52c7374e2c6b8efd69b5752ead049
{ "intermediate": 0.4746066629886627, "beginner": 0.31191495060920715, "expert": 0.21347838640213013 }
32,370
Your computer might have been infected by a virus! Create a python function that finds the viruses in files and removes them from your computer. Examples remove_virus("PC Files: spotifysetup.exe, virus.exe, dog.jpg") ➞ "PC Files: spotifysetup.exe, dog.jpg" remove_virus("PC Files: antivirus.exe, cat.pdf, lethalmalware.exe, dangerousvirus.exe ") ➞ "PC Files: antivirus.exe, cat.pdf" remove_virus("PC Files: notvirus.exe, funnycat.gif") ➞ "PC Files: notvirus.exe, funnycat.gif") Notes Bad files will contain "virus" or "malware", but "antivirus" and "notvirus" will not be viruses. Return "PC Files: Empty" if there are no files left on the computer.
49abd0ec813edae1370cd0ffe12122fb
{ "intermediate": 0.3072793483734131, "beginner": 0.3511654734611511, "expert": 0.34155523777008057 }
32,371
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public float delayTime = 5f; public GameObject bowPrefab; public GameObject healthPickupPrefab; private bool isBowSpawned = false; private void OnTriggerEnter2D(Collider2D collision) { if (!isHealthPickupSpawned && collision.CompareTag("Player")) { float randomValue2 = Random.value; if (randomValue2 <= 0.3f) { // Spawn a HealthPickup GameObject healthPickup = Instantiate(healthPickupPrefab, collision.transform); healthPickup.tag = "Health"; } } if (!isBowSpawned && collision.CompareTag("Player") && !IsBowAlreadySpawned()) { // Generate a random number (between 0 and 1) to determine if bow spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a bow GameObject bow = Instantiate(bowPrefab, collision.transform); bow.transform.localPosition = new Vector3(-0.25f, -0.25f, 0f); bow.transform.localRotation = Quaternion.identity; bow.tag = "Bow"; // Set the tag for the spawned bow isBowSpawned = true; } // Disable the chest to prevent spawning multiple bows gameObject.SetActive(false); // Enable the chest after a delay Invoke("EnableChest", delayTime); } } private bool IsBowAlreadySpawned() { GameObject[] bows = GameObject.FindGameObjectsWithTag("Bow"); return bows.Length > 0; } private void EnableChest() { gameObject.SetActive(true); isBowSpawned = false; } } isHeatlhPickupSpawned has an error, what is wrong with it?
60796cafb9a2529e3a22fbd6bb2a4b7e
{ "intermediate": 0.5397460460662842, "beginner": 0.2633788287639618, "expert": 0.19687505066394806 }
32,372
Hi
902a2a155ec405507764b43b76c4ea73
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
32,373
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Chest : MonoBehaviour { public float delayTime = 5f; public GameObject bowPrefab; public GameObject healthPickupPrefab; private bool isBowSpawned = false; bool isHealthPickupSpawned = false; private void OnTriggerEnter2D(Collider2D collision) { if (!isHealthPickupSpawned && collision.CompareTag("Player")) { float randomValue2 = Random.value; if (randomValue2 <= 0.3f) { // Spawn a HealthPickup GameObject healthPickup = Instantiate(healthPickupPrefab, collision.transform); healthPickup.transform.localPosition = new Vector3(0f, 0f, 0f); healthPickup.transform.localRotation = Quaternion.identity; healthPickup.tag = "Health"; } } if (!isBowSpawned && collision.CompareTag("Player") && !IsBowAlreadySpawned()) { // Generate a random number (between 0 and 1) to determine if bow spawns or not float randomValue = Random.value; if (randomValue <= 0.5f) { // Spawn a bow GameObject bow = Instantiate(bowPrefab, collision.transform); bow.transform.localPosition = new Vector3(-0.25f, -0.25f, 0f); bow.transform.localRotation = Quaternion.identity; bow.tag = "Bow"; // Set the tag for the spawned bow isBowSpawned = true; } // Disable the chest to prevent spawning multiple bows gameObject.SetActive(false); // Enable the chest after a delay Invoke("EnableChest", delayTime); } } private bool IsBowAlreadySpawned() { GameObject[] bows = GameObject.FindGameObjectsWithTag("Bow"); return bows.Length > 0; } private void EnableChest() { gameObject.SetActive(true); isBowSpawned = false; } } after the bow is spawned, the chest are no longer being temporarily disabled
e6a779d61659ab9e00fca4570a52c23a
{ "intermediate": 0.31629031896591187, "beginner": 0.4791385531425476, "expert": 0.20457112789154053 }
32,374
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Player : MonoBehaviour { public float speed = 5f; // Speed of character movement public int maxHealth = 3; // Maximum player health public int currentHealth; // Current player health private Animator anim; private void Start() { anim = GetComponent<Animator>(); currentHealth = maxHealth; // Set the initial health to maxHealth value } private void Update() { // Move character based on input axes float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // Calculate movement direction Vector2 movement = new Vector2(horizontalInput, verticalInput) * speed * Time.deltaTime; // Apply movement to the character’s position transform.Translate(movement); anim.SetFloat("moveX", movement.x); anim.SetFloat("moveY", movement.y); } private void OnCollisionEnter2D(Collision2D collision) { // Check if the player collides with an enemy if (collision.gameObject.CompareTag("Enemy")) { TakeDamage(1); // Deduct 1 health point if (currentHealth <= 0) { ResetScene(); // Reset the scene if health reaches 0 } } } private void TakeDamage(int amount) { currentHealth -= amount; // Deduct the specified amount from the current health } public void AddHealth(int amount) { currentHealth += amount; // Increase the current health by the specified amount currentHealth = Mathf.Min(currentHealth, maxHealth); // Ensure current health doesn’t exceed max health } private void ResetScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); // Reload the current scene } } make it so that if the player collides with a game object tagged "Health" they will get one health
0be76e283146f175518fa993b665d1a6
{ "intermediate": 0.43714460730552673, "beginner": 0.3057388961315155, "expert": 0.25711652636528015 }
32,375
What is 3x+y=27?
3a5be32d5ce77ed99eb060eedb685c4c
{ "intermediate": 0.25922879576683044, "beginner": 0.2875294089317322, "expert": 0.4532417356967926 }
32,376
Создай класс в html: <input type="submit" name="search" class="btn btn-primary" value="Поиск">
5e4b53be85ea68f2b6491edaceb9d145
{ "intermediate": 0.2798740863800049, "beginner": 0.2893314063549042, "expert": 0.43079447746276855 }
32,377
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossHealth : MonoBehaviour { public int maxHealth = 5; private int currentHealth; private void Start() { currentHealth = maxHealth; } public void TakeDamage(int damageAmount) { currentHealth -= damageAmount; if (currentHealth <= 0) { Die(); } } private void Die() { // Destroy the enemy object when health reaches 0 Destroy(gameObject); } } make it so if the health reaches 0, the scene changes to Level2
c8b2bfa8bea821ac4707fde4655f3a77
{ "intermediate": 0.382095605134964, "beginner": 0.39684534072875977, "expert": 0.22105903923511505 }
32,378
hi
11ba8ca18b5442e214c52754537e49a0
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
32,379
explain why OSPF requires ‘designated routers’
ba1707281bdf4dde969130a80eccb1b2
{ "intermediate": 0.4727025628089905, "beginner": 0.2085961401462555, "expert": 0.31870126724243164 }
32,380
find the longest palindrome sequence using python
52c702109a31a7076ae9a07e03dbed12
{ "intermediate": 0.22822511196136475, "beginner": 0.1622800976037979, "expert": 0.6094948053359985 }
32,381
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Boss : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private void Start() { rb = GetComponent<Rigidbody2D>(); 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); } 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 the boss is only spawned in (at the point (0f, 0f, 0f,) after 10 enemy game objects are destroyed
c01083adeca9d7e547b433c68a9049cc
{ "intermediate": 0.4057077467441559, "beginner": 0.32648083567619324, "expert": 0.2678114175796509 }
32,382
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Player : MonoBehaviour { public float speed = 5f; // Speed of character movement public int maxHealth = 3; // Maximum player health public int currentHealth; // Current player health private Animator anim; private void Start() { anim = GetComponent<Animator>(); currentHealth = maxHealth; // Set the initial health to maxHealth value } private void Update() { // Move character based on input axes float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); // Calculate movement direction Vector2 movement = new Vector2(horizontalInput, verticalInput) * speed * Time.deltaTime; // Apply movement to the character’s position transform.Translate(movement); anim.SetFloat("moveX", movement.x); anim.SetFloat("moveY", movement.y); } private void OnCollisionEnter2D(Collision2D collision) { // Check if the player collides with an enemy if (collision.gameObject.CompareTag("Enemy")) { TakeDamage(1); // Deduct 1 health point if (currentHealth <= 0) { ResetScene(); // Reset the scene if health reaches 0 } } // Check if the player collides with a Boss if (collision.gameObject.CompareTag("Boss")) { TakeDamage(1); // Deduct 1 health point if (currentHealth <= 0) { ResetScene(); // Reset the scene if health reaches 0 } } // Check if the player collides with a health object if (collision.gameObject.CompareTag("Health")) { AddHealth(1); // Increase health by 1 Destroy(collision.gameObject); // Destroy the health object } } private void TakeDamage(int amount) { currentHealth -= amount; // Deduct the specified amount from the current health } public void AddHealth(int amount) { currentHealth += amount; // Increase the current health by the specified amount currentHealth = Mathf.Min(currentHealth, maxHealth); // Ensure current health doesn’t exceed max health } private void ResetScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); // Reload the current scene } } make it so after the player takes damage, he is invincible for 1 second
bb5bb855ff53b67925abda86de6af3a3
{ "intermediate": 0.290312260389328, "beginner": 0.4213525652885437, "expert": 0.2883351445198059 }
32,383
Check this function: fn build_gtf_line( record: &BedRecord, gene_name: &str, gene_type: &str, exon_start: u32, exon_end: u32, frame: u32, exon: i16, file: &mut File, ) { assert!(record.tx_start() < record.tx_end()); let phase = if frame < 0 { "." } else if frame == 0 { "0" } else if frame == 1 { "2" } else { "1" }; let mut gtf_line = format!( "{}\t{}\t{}\t{}\t{}\t.\t{}\t{}\t", record.chrom(), SOURCE, gene_type, exon_start + 1, exon_end, record.strand(), phase, ); gtf_line += &format!("gene_id \"{}\"; ", gene_name); gtf_line += &format!("transcript_id \"{}\";", record.name()); if exon >= 0 { if record.strand() == "-" { gtf_line += &format!(" exon_number \"{}\";", record.exon_count() - exon); gtf_line += &format!( " exon_id \"{}.{}\";", record.name(), record.exon_count() - exon ); } else { gtf_line += &format!(" exon_number \"{}\";", exon + 1); gtf_line += &format!(" exon_id \"{}.{}\";", record.name(), exon + 1); } } gtf_line += "\n"; let _ = file.write_all(gtf_line.as_bytes()); } Review it and correct any error. Re-implement anything you want to make this the most efficient and fastest way. Since you are a Rust expert I believe you will do it perfectly! Some notes to take into account are: the final line will not be written to a file but append it to a vector.
357e5d40485df78ead6d6a4c7669d7ad
{ "intermediate": 0.4590393602848053, "beginner": 0.31552621722221375, "expert": 0.22543449699878693 }
32,384
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Boss : MonoBehaviour { public float speed = 2f; public float chaseRange = 5f; private Transform player; private Vector2 targetPosition; private Rigidbody2D rb; private void Start() { rb = GetComponent<Rigidbody2D>(); 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); } 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 the boss will shoot MagicBullets at the player every 2 seconds
fea8da20f22713dddc15fc69e4583ba7
{ "intermediate": 0.48455101251602173, "beginner": 0.2761479616165161, "expert": 0.23930108547210693 }
32,385
Есть недописанная программа реализации АВЛ-дерева. Допиши её, при следующих условиях: при удалении элемента программа заменяет его на максимальный слева; обход справа налево; добавить в дерево элементы 9, 1, 2, 2, 0, 9, 0, 3, 0, 4 и вывести его. Вот программа: #include <iostream> using namespace std; struct Node { int key, count; Node *left, *right; int balance; }; void search(int x, Node* p, short h) { Node* p1, * p2; if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = false; break; case 0: p->balance = 1; break; case 1: // балансировка p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node* p, short h) { Node* q; if (p == NULL) { cout << "Key is not in tree" << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } Node* tree(int x) { } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->left, h + 1); for (int i = 1; i <= h; i++) { cout << ' '; } cout << t->key << endl; printtree(t->right, h + 1); } } int main() { }
3f58a92c1ebb6a0786d6bddd349763a9
{ "intermediate": 0.3230394124984741, "beginner": 0.5174763798713684, "expert": 0.15948423743247986 }
32,386
You are a Rust expert programmer. For your job interview you are asked this question: "The output of a complex algorithm produces a Vec<Vec<String>> with an estimated size of 10000 vectors. Since this process needs to be the fastest, implement the fastest and more efficient code to write all those vectors to a file.".
07158a39ba38ca5e30865880f3a53895
{ "intermediate": 0.17340117692947388, "beginner": 0.12927384674549103, "expert": 0.6973249912261963 }
32,387
Есть недописанная программа реализации АВЛ-дерева. Допиши её, при следующих условиях: при удалении элемента программа заменяет его на максимальный слева; обход справа налево; добавить в дерево элементы 9, 1, 2, 2, 0, 9, 0, 3, 0, 4 и вывести его. Вот программа: #include<iostream> using namespace std; struct Node { int key, count; Node left, right; int balance; }; void search(int x, Node p, short h) { Node p1, * p2; if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = false; break; case 0: p->balance = 1; break; case 1: // балансировка p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node* p, short h) { Node* q; if (p == NULL) { cout << “Key is not in tree” << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } Node* tree(int x) { } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->left, h + 1); for (int i = 1; i <= h; i++) { cout << ’ '; } cout << t->key << endl; printtree(t->right, h + 1); } } int main() { }
2e8d9db856f52863599fcc22af5b1393
{ "intermediate": 0.2973635792732239, "beginner": 0.4581441879272461, "expert": 0.24449224770069122 }
32,388
Есть недописанная программа реализации АВЛ-дерева. Допиши её, при следующих условиях: при удалении элемента программа заменяет его на максимальный слева; обход справа налево; добавить в дерево элементы 9, 1, 2, 2, 0, 9, 0, 3, 0, 4 и вывести его. Вот программа: #include using namespace std; struct Node { int key, count; Node left, right; int balance; }; void search(int x, Node p, short h) { Node p1, * p2; if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = false; break; case 0: p->balance = 1; break; case 1: // балансировка p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node* p, short h) { Node* q; if (p == NULL) { cout << “Key is not in tree” << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } Node* tree(int x) { } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->left, h + 1); for (int i = 1; i <= h; i++) { cout << ’ '; } cout << t->key << endl; printtree(t->right, h + 1); } } int main() { }
c289485fc32a6ed8be0cf8265d8e33e8
{ "intermediate": 0.33691924810409546, "beginner": 0.4169559180736542, "expert": 0.24612486362457275 }
32,389
Write a for loop statement C program that Validate the Goldbach conjecture: Any sufficiently large even number can be represented by the sum of two prime numbers. For example: 4 = 2 + 2, 6 = 3 + 3, 98 = 19 + 79
d2ae02b6d04790441e49ba1b043d0fb4
{ "intermediate": 0.18315604329109192, "beginner": 0.5486418604850769, "expert": 0.2682020962238312 }
32,390
how to website script download a generate video in steve.ai in chrome browser
40aaaab4ac7e29376c28f4090c4f978f
{ "intermediate": 0.31486746668815613, "beginner": 0.21742109954357147, "expert": 0.4677114486694336 }
32,391
What would be the fastest way to write a Vec<Vec<String>> to a file? You are free to use any algorithm, trick, unsafe code, parallelization, crate, etc
57f5728535232b1ba2f8e5b29625aec8
{ "intermediate": 0.5372718572616577, "beginner": 0.1160067617893219, "expert": 0.346721351146698 }
32,392
Write a simple for loop statement C program that Output the sum of all integers between 200 and 400, divisible by 3 and with a bit number of 7.
3a0b674d5d5766d1e31d6d94e71a08bf
{ "intermediate": 0.0976976603269577, "beginner": 0.7813236117362976, "expert": 0.12097872048616409 }
32,393
What would be the fastest way to write a Vec < Vec< String > > to a file? You are free to use any algorithm, trick, unsafe code, parallelization, crate, etc
860471923462924d23ce379193f152fd
{ "intermediate": 0.542588472366333, "beginner": 0.10325823724269867, "expert": 0.35415324568748474 }
32,394
how to find website script in chrome browser
23791fc5a8b43b8005eba783b95def80
{ "intermediate": 0.3270955979824066, "beginner": 0.4102259576320648, "expert": 0.2626783847808838 }
32,395
Есть недописанная программа реализации АВЛ-дерева. Допиши её, при следующих условиях: при удалении элемента программа заменяет его на максимальный слева; обход справа налево; добавить в дерево элементы 9, 1, 2, 2, 0, 9, 0, 3, 0, 4 и вывести его. Также всё комментируй. Вот программа: #include using namespace std; struct Node { int key, count; Node left, right; int balance; }; void search(int x, Node p, short h) { Node p1, * p2; if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = false; break; case 0: p->balance = 1; break; case 1: // балансировка p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node* p, short h) { Node* q; if (p == NULL) { cout << “Key is not in tree” << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } Node* tree(int x) { } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->left, h + 1); for (int i = 1; i <= h; i++) { cout << ’ '; } cout << t->key << endl; printtree(t->right, h + 1); } } int main() { }
f83615faf52f82d52dd15825e93c76e2
{ "intermediate": 0.3024440407752991, "beginner": 0.46434903144836426, "expert": 0.23320689797401428 }
32,396
{formData.options.map((option, index) => ( <input key={index} name={option${index + 1}} id={option${index + 1}} type="text" value={option.description} onChange={(e) => handleOptionChange(e, index)} required /> ))} estoy usando react tengo errores en esta parte name={option${index + 1}} id={option${index + 1}}
3263a223c1e8564338d21b9c9d8f47d4
{ "intermediate": 0.3678784966468811, "beginner": 0.29907453060150146, "expert": 0.33304697275161743 }
32,397
{formData.options.map((option, index) => ( <input key={index} name={option${index + 1}} id={option${index + 1}} type="text" value={option.description} onChange={(e) => handleOptionChange(e, index)} required /> ))} tengo errores con los index
db142cfb377e0f51c11df244eae2fc3c
{ "intermediate": 0.37783753871917725, "beginner": 0.30243149399757385, "expert": 0.3197309076786041 }
32,398
Есть недописанная программа реализации АВЛ-дерева. Допиши её, при следующих условиях: при удалении элемента программа заменяет его на максимальный слева; обход справа налево; добавить в дерево элементы 9, 1, 2, 2, 0, 9, 0, 3, 0, 4 и вывести его. Также всё комментируй. Вот программа: #include using namespace std; struct Node { int key, count; Node left, right; int balance; }; void search(int x, Node p, short h) { Node p1, * p2; if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = false; break; case 0: p->balance = 1; break; case 1: // балансировка p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node* p, short h) { Node* q; if (p == NULL) { cout << “Key is not in tree” << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } Node* tree(int x) { } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->left, h + 1); for (int i = 1; i <= h; i++) { cout << ’ '; } cout << t->key << endl; printtree(t->right, h + 1); } } int main() { }
0b9bd1e24ef08cb9e111ceb35c50f49f
{ "intermediate": 0.3024440407752991, "beginner": 0.46434903144836426, "expert": 0.23320689797401428 }
32,399
Now we need to know how the length of rental duration of these family-friendly movies compares to the duration that all movies are rented for. Can you provide a table with the movie titles and divide them into 4 levels (first_quarter, second_quarter, third_quarter, and final_quarter) based on the quartiles (25%, 50%, 75%) of the average rental duration(in the number of days) for movies across all categories? Make sure to also indicate the category that these family-friendly movies fall into.
b9a0c49ca0353995838cf085838c322a
{ "intermediate": 0.4153730273246765, "beginner": 0.2669971287250519, "expert": 0.3176298439502716 }
32,400
import pandas as pd from sklearn.manifold import TSNE import matplotlib.pyplot as plt iris = sns.load_dataset(‘iris’) from sklearn.manifold import TSNE tsne = TSNE(n_components=2) tsne_result = tsne.fit_transform(X) tsne_df = pd.DataFrame(data=tsne_result, columns=['t-SNE component 1', 't-SNE component 2']) plt.scatter(tsne_df['t-SNE component 1'], tsne_df['t-SNE component 2']) plt.xlabel('t-SNE Component 1') plt.ylabel('t-SNE Component 2') plt.show() Подкарсь точки таргетом
1b011eab33c83069229120e063b7f907
{ "intermediate": 0.4121319055557251, "beginner": 0.288113534450531, "expert": 0.29975461959838867 }
32,401
fig, ax = plt.subplots() # You can modify the values as per your requirement cax = ax.imshow(cmap='coolwarm', vmin=-1, vmax=1) # Only show the values outside the range ax.set_xticks(np.arange(len(LB))) ax.set_yticks(np.arange(2*len(mode_list))) ax.set_xticklabels([r'$\rho_{st}$', r'$E_b$', r'$E_c$', r'$E_s$', r'$E_t$', r'$E_f$', r'$E_{lb}$', r'$\rho_r$', r'$E_r$', r'$K_{x}$', r'$K_{y}$', r'$K_{z}$', r'$K_{\phi}$', r'$m_{bd}$'], rotation=45, fontsize=10) ax.set_yticklabels([r'$f_1$', r'$f_2$', r'$f_3$', r'$f_4$', r'$f_5$', r'$f_6$', r'$f_7$', r'$MAC_1$', r'$MAC_2$', r'$MAC_3$', r'$MAC_4$', r'$MAC_5$', r'$MAC_6$', r'$MAC_7$']) ax.set_xlabel('Inputs') ax.set_ylabel('Outputs') ax.set_title('Spearman Correlation Coefficient matrix') cbar = fig.colorbar(cax) plt.tight_layout() plt.show() correct this code
4213746cca4df3962c378c31cf1d1250
{ "intermediate": 0.4524705410003662, "beginner": 0.25018438696861267, "expert": 0.29734504222869873 }
32,402
write a javascript bot for bustabit that is counting the loses under 10x and after 20 loses under 10x bet 1 bit till 10x do that 6 times after that bet 10 bits till 10x and do that 4 times
c678d014cbcba8b37d92aed07ffab6b2
{ "intermediate": 0.2832990884780884, "beginner": 0.19098111987113953, "expert": 0.5257197618484497 }
32,403
I have just started creating a python module to load all the images in a path, do some basic processing, load a caption file if one exists(same filename but with the extension .txt or .caption instead, for example, "image205.png" would have a caption file "image205.txt" or "image205.caption", and done in a way to allow further extension types with unique loading to be done) For now, my skeleton code looks like this:
8914cea8a7f13ea7be712c9b7f223d8c
{ "intermediate": 0.5556792616844177, "beginner": 0.16684867441654205, "expert": 0.2774720788002014 }
32,404
Перепиши код umap_result = umap.UMAP(n_components=2).fit_transform(X) umap_df = pd.DataFrame(umap_result, columns=['UMAP component 1', 'UMAP component 2']) plt.scatter(umap_df['UMAP component 1'], umap_df['UMAP component 2']) plt.xlabel('UMAP Component 1') plt.ylabel('UMAP Component 2') plt.show() Что-бы было два графика как тут: tsne = TSNE(n_components=2) tsne_result = tsne.fit_transform(X) tsne_df = pd.DataFrame(data=tsne_result, columns=['t-SNE component 1', 't-SNE component 2']) plt.figure(figsize=(10, 5)) plt.subplot(1, 2, 1) plt.title(f't-SNE Analysis of Iris') plt.scatter(tsne_df['t-SNE component 1'], tsne_df['t-SNE component 2']) plt.xlabel('t-SNE Component 1') plt.ylabel('t-SNE Component 2') # t-SNE with target coloring plt.subplot(1, 2, 2) plt.title(f't-SNE Analysis of Iris with target') plt.scatter(tsne_df['t-SNE component 1'], tsne_df['t-SNE component 2'], c=y) plt.xlabel('t-SNE Component 1') plt.ylabel('t-SNE Component 2') plt.tight_layout() plt.show()
01914c5de1154edc7b199cf07aadde74
{ "intermediate": 0.42045751214027405, "beginner": 0.27109217643737793, "expert": 0.30845028162002563 }
32,405
Для вот этого: k_values = [2, 3, 4, 5 ,6] for k in k_values: kmeans = KMeans(n_clusters=k, n_init=10) kmeans.fit(X) labels = kmeans.labels_ Сделай fig = plt.figure(figsize=(7, 8)) ax = plt.axes(projection=‘3d’) ax.set_xlabel(‘Petal Width’) ax.set_ylabel(‘Petal Length’) ax.set_zlabel(‘Sepal Width’) ax.scatter3D( iris[‘petal_width’], iris[‘petal_length’], iris[‘sepal_width’], c=y ) plt.show()
02439a407870da5f553fe7abd27a9af4
{ "intermediate": 0.3851293921470642, "beginner": 0.27340102195739746, "expert": 0.34146955609321594 }
32,406
in python i have a matrix with dimension 800x14, of my parameters called LHS_matrix (14 input parameters, 800 samples) using latin hypercube sampling. i have a matrix Y, with dimension 800x14, containing 14 outputs for each sampling therefore 800. how to plot the spearman matrix?
7f5ecac27f844551f2755560e43ffa3d
{ "intermediate": 0.45332005620002747, "beginner": 0.20576049387454987, "expert": 0.34091946482658386 }
32,407
I need your help. This is my code: fn to_gtf( bedline: &BedRecord, isoforms: &HashMap<String, String>, track: &HashMap<String, String>, ) -> Vec<String> { let mut result: Vec<String> = Vec::new(); let gene = isoforms.get(&bedline.name).unwrap(); let fcodon = first_codon(bedline).unwrap(); let lcodon = last_codon(bedline).unwrap(); let first_utr_end = bedline.cds_start; let last_utr_start = bedline.cds_end; let frames = bedline.get_frames(); let cds_end: u32 = if bedline.strand == "+" && codon_complete(&lcodon) { move_pos(bedline, lcodon.end, -3) } else { bedline.cds_end }; let cds_start = if bedline.strand == "-" && codon_complete(&fcodon) { move_pos(bedline, fcodon.start, 3) } else { bedline.cds_start }; if track.values().any(|v| *v == bedline.name) { result.push(build_gene_line(gene, bedline)); }; build_gtf_line( bedline, gene, "transcript", bedline.tx_start, bedline.tx_end, 3, -1, &mut result, ); for i in 0..bedline.exon_count as usize { build_gtf_line( bedline, gene, "exon", bedline.exon_start[i], bedline.exon_end[i], 3, i as i16, &mut result, ); if cds_start < cds_end { write_features( i, bedline, gene, first_utr_end, cds_start, cds_end, last_utr_start, frames[i] as u32, &mut result, ); } } if bedline.strand != "-" { if codon_complete(&fcodon) { write_codon(bedline, gene, "start_codon", fcodon, &mut result); } if codon_complete(&lcodon) { write_codon(bedline, gene, "stop_codon", lcodon, &mut result); } } else { if codon_complete(&lcodon) { write_codon(bedline, gene, "start_codon", lcodon, &mut result); } if codon_complete(&fcodon) { write_codon(bedline, gene, "stop_codon", fcodon, &mut result); } } result } I though I was finished but checking the output I found that the coordinates of the "gene" line are actually wrong. The "gene" line coordinates (start, end) should comprise the first start and the last end (spanning all isoforms). Using my implementation I get to only write the "gene" line once, which is correct, but I fail to assign it the correct coordinates, instead I am assigning it the coordinates of one of the isoforms only. I do not what to do right now.
cae6ef8bf89c9eb60dd556d5d7e9d6b3
{ "intermediate": 0.4811726212501526, "beginner": 0.3629131317138672, "expert": 0.15591424703598022 }
32,408
In an earlier session you help implementing this code: isoforms_to_genes: &HashMap<String, String>, transcript_coordinates: &HashMap<String, (String, u32, u32, String)>, ) -> HashMap<String, (String, u32, u32, String)> { isoforms_to_genes .par_iter() .fold( || HashMap::new(), |mut acc: HashMap<String, (String, u32, u32, String)>, (transcript, gene)| { if let Some(&(ref chrom, start, end, ref strand)) = transcript_coordinates.get(transcript) { let entry = acc.entry(gene.clone()).or_insert(( chrom.to_string(), start, end, strand.to_string(), )); entry.1 = entry.1.min(start); // Update min start entry.2 = entry.2.max(end); // Update max end } acc }, ) .reduce( || HashMap::new(), |mut a, b| { for (gene, (chrom, start, end, strand)) in b { let entry = a.entry(gene).or_insert((chrom, start, end, strand)); entry.1 = entry.1.min(start); // Update min start entry.2 = entry.2.max(end); // Update max end } a }, ) } I slightly modified it to suit better for my purposes; however, I want to ask you this: that function returns: “ENSG00000243115.3”: (“chr9”, 12764760, 12765055, “-”), “ENS G00000251834.1”: (“chr9”, 15431898, 15432006, “-”), “ENSG00000163904.13”: (“ chr3”, 185582495, 185633551, “+”), “ENSG00000242766.1”: (“chr2”, 90082634, 9 0083291, “+”)} is it possible to build a "gene" line for each key taking its values? I want to end with a Vec<String> where each String is formatted like this: chr1 bed2gtf gene 11869 14409 . + . gene_id "ENSG00000290825.1"; where bed2gtf, gene, . and . are constants
5503d19314d0d67af5d577001098eb8c
{ "intermediate": 0.3909165859222412, "beginner": 0.3038693964481354, "expert": 0.3052140176296234 }
32,409
Есть программа реализации АВЛ-дерева. Нужно, чтобы при удалении элемента она меняла на максимальный слева. Вот программа: #include <iostream> using namespace std; struct Node { int key, count; Node* left; // указатель на левого потомка Node* right; // указатель на правого потомка int balance; }; void search(int x, Node*& p, short h) { if (p == NULL) // слова нет в дереве; включить его { p = new Node; p->key = x; p->count = 1; p->balance = 0; p->left = NULL; p->right = NULL; } else if (x < p->key) { search(x, p->left, h); if (h != 0) // выросла левая ветвь { switch (p->balance) { case 1: p->balance = 0; h = 0; break; case 0: p->balance = -1; break; case -1: // балансировка Node* p1 = p->left; if (p1->balance == -1) // L-поворот { p->left = p1->right; p1->right = p; p->balance = 0; p = p1; } else // LR-поворот { Node* p2 = p1->right; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (p2->balance == -1) p->balance = 1; else p->balance = 0; if (p2->balance == 1) p1->balance = -1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else if (x > p->key) { search(x, p->right, h); if (h != 0) // выросла правая ветвь { switch (p->balance) { case -1: p->balance = 0; h = 0; break; case 0: p->balance = 1; break; case 1: // балансировка Node* p1 = p->right; if (p1->balance == 1) //R-поворот { p->right = p1->left; p1->left = p; p->balance = 0; p = p1; } else // RL-поворот { Node* p2 = p1->left; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (p2->balance == 1) p->balance = -1; else p->balance = 0; if (p2->balance == -1) p1->balance = 1; else p1->balance = 0; p = p2; } p->balance = 0; h = 0; break; } } } else { p->count += 1; h = 0; } } void balance1(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case -1: p->balance = 0; break; case 0: p->balance = 1; h = 0; break; case 1: // балансировка p1 = p->right; b1 = p1->balance; if (b1 >= 0) // R-поворот { p->right = p1->left; p1->left = p; if (b1 == 0) { p->balance = 1; p1->balance = -1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // RL-поворот { p2 = p1->left; b2 = p2->balance; p1->left = p2->right; p2->right = p1; p->right = p2->left; p2->left = p; if (b2 == 1) p->balance = -1; else p->balance = 0; if (b2 == -1) p1->balance = 1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void balance2(Node* p, short h) { Node* p1, * p2; short b1, b2; switch (p->balance) { case 1: p->balance = 0; break; case 0: p->balance = 0; h = 0; break; case -1: p1 = p->left; b1 = p1->balance; if (b1 <= 0) // L-поворот { p->left = p1->right; p1->right = p; if (b1 == 0) { p->balance = -1; p1->balance = 1; h = 0; } else { p->balance = 0; p1->balance = 0; } p = p1; } else // LR-поворот { p2 = p1->right; b2 = p2->balance; p1->right = p2->left; p2->left = p1; p->left = p2->right; p2->right = p; if (b2 == -1) p->balance = 1; else p->balance = 0; if (b2 == 1) p1->balance = -1; else p1->balance = 0; p = p2; p2->balance = 0; } } } void del(Node* r, Node* q, short h) { if (r->right != NULL) { del(r->right, q, h); if (h != 0) balance2(r, h); } else { q->key = r->key; q->count = r->count; r = r->left; h = 1; } } void delet(int x, Node*& p, short h) { Node* q; if (p == NULL) { cout << "Key is not in tree" << endl; h = 0; } else if (x < p->key) { delet(x, p->left, h); if (h != 0) balance1(p, h); } else if (x > p->key) { delet(x, p->right, h); if (h != 0) balance2(p, h); } else { q = p; if (q->right == NULL) { p = q->left; h = 1; } else if (q->left == NULL) { p = q->right; h = 1; } else { del(q->left, q, h); if (h != 0) balance1(p, h); } } } void printtree(Node* t, short h) { if (t != NULL) { printtree(t->right, h + 1); for (int i = 1; i <= h; i++) { cout << ' '; } cout << t->key << endl; printtree(t->left, h + 1); } } int main() { Node* root = NULL; return 0; }
60ce564d65e390cf47370f029bebbf26
{ "intermediate": 0.3511388897895813, "beginner": 0.5253139138221741, "expert": 0.12354721128940582 }
32,410
<template> <section class="h-100 h-custom min-h-content" > <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col"> <div class="card border-0"> <div class="card-body p-4"> <div class="row"> <div class="col-lg-7"> <h5 class="mb-3"><router-link :to="{name:'Home'}" class="text-body"><i class="fas fa-long-arrow-alt-left me-2"></i>Continue shopping</router-link></h5> <hr> <div class="d-flex justify-content-between align-items-center mb-4"> <div> <p class="mb-0">You have {{ $store.state.cart.length }} items in your cart</p> </div> </div> <div v-for="item in $store.state.cart" class="card mb-3 shadow-sm border-0" :key="item.id"> <div class="card-body"> <div class="d-flex justify-content-between"> <div class="d-flex flex-row align-items-center"> <div> <img :src="item.image" class="img-fluid rounded-3" alt="Shopping item" style="width: 65px;"> </div> <div class="ms-3"> <p>{{ item.name }}</p> </div> </div> <div class="d-flex flex-row align-items-center"> <div > <CartAddRemove :product="item"/> </div> </div> <div class="d-flex flex-row align-items-center"> <div > <h5 class="mb-0"><i class="bi bi-currency-dollar"></i>{{ item.price*item.qty }}</h5> <small v-if="item.hasDiscount" class="text-muted text-decoration-line-through"><i class="bi bi-currency-dollar"></i>{{ item.price}}</small> </div> <a role="button" @click="removeItem(item)" class="ms-4" style="color: #cecece;"><i class="bi bi-trash3 h4"></i></a> </div> </div> </div> </div> </div> <div class="col-lg-5"> <div class="card bg-primary text-white rounded-0 border-0"> <div class="card-body"> <div class="d-flex justify-content-between align-items-center mb-4"> <h5 class="mb-0">Cart details</h5> <i class="bi bi-cart3 h1"></i> </div> <hr class="my-4"> <div class="d-flex justify-content-between"> <p class="mb-2">Subtotal</p> <p class="mb-2"><i class="bi bi-currency-dollar"></i>{{ $store.state.cartTotal }}</p> </div> <div class="d-flex justify-content-between mb-4"> <p class="mb-2">Total</p> <p class="mb-2"><i class="bi bi-currency-dollar"></i>{{ $store.state.cartTotal }}</p> </div> <button type="button" class="btn btn-info btn-block btn-lg"> Checkout </button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> </template> <script lang="ts"> import CartAddRemove from '../components/CartAddRemove.vue'; export default{ components :{CartAddRemove}, methods:{ removeItem(item: any){ this.$store.commit('addRemoveCart',{product:item,toAdd:false}) }, }, mounted(){ } } </script>error: Property '$store' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $props: Partial<{}> & Omit<{} & VNodeProps & AllowedComponentProps & ComponentCustomProps & Readonly<...>, never>; ... 10 more ...; $watch<T extends string | ((...args: any) => any)>(source: T, cb: T extends (...args: any) => infe
2d164b0606b32d74c18fbdb2e92c3223
{ "intermediate": 0.329758882522583, "beginner": 0.6075674295425415, "expert": 0.0626736730337143 }
32,411
How to get all latex symbols with python
c5cbefaac7f2f6348e3ecfba56292817
{ "intermediate": 0.33369600772857666, "beginner": 0.2834489941596985, "expert": 0.38285499811172485 }
32,412
how to convert Arabic alphabets to its modern standard format using python code? example showed below Unicode Isolated Final (End) Medial (Middle) Initial (Beginning) 627 FE8D FE8E ا ﺍ ﺎ 628 FE8F FE90 FE92 FE91 ب ﺏ ﺐ ﺒ ﺑ 062A FE95 FE96 FE98 FE97 ت ﺕ ﺖ ﺘ ﺗ 062B FE99 FE9A FE9C FE9B ث ﺙ ﺚ ﺜ ﺛ 062C FE9D FE9E FEA0 FE9F ج ﺝ ﺞ ﺠ ﺟ 062D FEA1 FEA2 FEA4 FEA3 ح ﺡ ﺢ ﺤ ﺣ 062E FEA5 FEA6 FEA8 FEA7 خ ﺥ ﺦ ﺨ ﺧ 062F FEA9 FEAA د ﺩ ﺪ 630 FEAB FEAC ذ ﺫ ﺬ 631 FEAD FEAE ر ﺭ ﺮ 632 FEAF Feb-00 ز ﺯ ﺰ 633 1-Feb 2-Feb 4-Feb 3-Feb س ﺱ ﺲ ﺴ ﺳ 634 5-Feb 6-Feb 8-Feb 7-Feb ش ﺵ ﺶ ﺸ ﺷ 635 9-Feb FEBA FEBC FEBB ص ﺹ ﺺ ﺼ ﺻ 636 FEBD FEBE FEC0 FEBF ض ﺽ ﺾ ﻀ ﺿ 637 FEC1 FEC2 FEC4 FEC3 ط ﻁ ﻂ ﻄ ﻃ 638 FEC5 FEC6 FEC8 FEC7 ظ ﻅ ﻆ ﻈ ﻇ 639 FEC9 FECA FECC FECB ع ﻉ ﻊ ﻌ ﻋ 063A FECD FECE FED0 FECF غ ﻍ ﻎ ﻐ ﻏ 641 FED1 FED2 FED4 FED3 ف ﻑ ﻒ ﻔ ﻓ 642 FED5 FED6 FED8 FED7 ق ﻕ ﻖ ﻘ ﻗ 643 FED9 FEDA FEDC FEDB ك ﻙ ﻚ ﻜ ﻛ 644 FEDD FEDE FEE0 FEDF ل ﻝ ﻞ ﻠ ﻟ 645 FEE1 FEE2 FEE4 FEE3 م ﻡ ﻢ ﻤ ﻣ 646 FEE5 FEE6 FEE8 FEE7 ن ﻥ ﻦ ﻨ ﻧ 647 FEE9 FEEA FEEC FEEB ه ﻩ ﻪ ﻬ ﻫ 648 FEED FEEE و ﻭ ﻮ 064A FEF1 FEF2 FEF4 FEF3 ي ﻱ ﻲ ﻴ ﻳ 622 FE81 FE82 آ ﺁ ﺂ 629 FE93 FE94 — — ة ﺓ ﺔ 649 FEEF FEF0 — — ى ﻯ ﻰ
ef0418e9f79e572088b7c9a1aefefe75
{ "intermediate": 0.3282982409000397, "beginner": 0.4458399713039398, "expert": 0.22586177289485931 }
32,413
I have this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] exit = [] sell_result = 0.0 buy_result = 0.0 active_signal = None mark_price_data = client.ticker_price(symbol=symbol) mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 # Retrieve depth data depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] highest_bid_price = max(bid_prices) lowest_bid_price = min(bid_prices) b_h = highest_bid_price buy_lowest_price = lowest_bid_price b_l = buy_lowest_price asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] highest_ask_price = max(ask_prices) lowest_ask_price = min(ask_prices) s_h = highest_ask_price s_l = lowest_ask_price buy_qty = round(sum(float(bid[1]) for bid in bids), 0) sell_qty = round(sum(float(ask[1]) for ask in asks), 0) Return this code, and give me code which will print me in [] order prices which higher than mark_price
1fe452da530ea15836d325f2e546d1db
{ "intermediate": 0.35536226630210876, "beginner": 0.3708707392215729, "expert": 0.2737669348716736 }
32,414
A data analyst wants to convert their R Markdown file into another format. What are their options? Select all that apply. HTML, PDF, and Word Slide presentation JPEG, PNG, and GIF Dashboard
bcfed6fe4cbf29aac575fc19d946336d
{ "intermediate": 0.3324187099933624, "beginner": 0.2739475965499878, "expert": 0.3936336934566498 }
32,415
Instead change the require of index.js in C:\xampp\htdocs\web\gulpfile.js to a dynamic import() which is available in all CommonJS modules
d08a64098148c79f96127ddab1af6cbf
{ "intermediate": 0.48922640085220337, "beginner": 0.2517930865287781, "expert": 0.25898048281669617 }
32,416
ai distribute the following numbers for me using Random Chaos Number Generator algorithm 5 numbers 1 2 3 4 5 6 7 9 11 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 28 31 32 33 34 35 36 37 39 40 42 till all are distributed no duplicate lines
85e55c2db70587b46af79b9c8e895353
{ "intermediate": 0.2576308846473694, "beginner": 0.1783575564622879, "expert": 0.5640115737915039 }
32,417
I used this code: depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] bid_prices = [float(bid[0]) for bid in bids] asks = depth_data['asks'] ask_prices = [float(ask[0]) for ask in asks] You need to give me code which will return me highest price bid_price of all bids and most lowest ask price of all asks
95f556cc8c4e19c781531e1bedb00bc5
{ "intermediate": 0.4366626739501953, "beginner": 0.30273765325546265, "expert": 0.2605997323989868 }
32,418
## solver.py import numpy as np from corner_detector.corner_detector import CornerDetector class Solver(object): def __init__(self): self.alg = CornerDetector() def solve(self, image_gray: np.ndarray) -> np.ndarray: result = self.alg.find_corners(image_gray) return result ## corner_detector.corner_detector.corner_detector.py import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B, TIME_MAX ) from services.image_service import ImageService from services.time_service import TimeService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([1, 1], [2, 2], [3, 3]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.time_service.start_time() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if not self.time_service.time_check(): return self.random_answer if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) if not self.time_service.time_check(): return self.random_answer neigh_nums = self.__get_neigh_nums_list(coords) if not self.time_service.time_check(): return self.random_answer sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) if not self.time_service.time_check(): return self.random_answer potential_points = self.__get_potential_points_coords(sorted_neigh_nums) if not self.time_service.time_check(): return self.random_answer best_lines = self.__get_best_lines(potential_points) if not self.time_service.time_check(): return self.random_answer intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_points ПОЛУЧАЮ ОШИБКУ: solver.py import ERROR: 401 Unauthorized: unsupported operand type(s) for |: 'type' and 'type'; Traceback: File "/3divi/estimators/test_estimator.py", line 42, in estimator; module = load_module_python(_vars.entrypoint); File "/3divi/estimators/est_utils.py", line 19, in load_module_python; abort(401, str(e)); File "/usr/local/lib/python3.9/site-packages/werkzeug/exceptions.py", line 881, in abort; _aborter(status, *args, **kwargs); File "/usr/local/lib/python3.9/site-packages/werkzeug/exceptions.py", line 864, in __call__; raise self.mapping[code](*args, **kwargs) ЧТО МОЖЕТ БЫТЬ НЕ ТАК?!
5b98d06a067d0d6bb4275e52099697fb
{ "intermediate": 0.30348730087280273, "beginner": 0.4526437819004059, "expert": 0.243868887424469 }
32,419
Реши задачу и напиши код на python и numpy, строящий решение методом конечных элементов. Область раздели на квадраты одинакового размера. Задача о граничном управлении в круге с дыркой Пусть $\vec{x}=\left(x_1, x_2\right) \in \mathbb{R}^2$, где $x_1, x_2$ - координаты точки в некоторой прямоугольной декартовой системе координат. Рассмотрим также полярную систему координат $(\phi, r)$, такую, что $x_1=r \cos \phi, x_2=r \sin \phi$. В области $\Omega=\left{(\phi, r): R_1<r<R_2, \forall \phi \in[0,2 \pi)\right}$, $0<R_1<R_2<\infty$, рассмотрим следующую систему уравнений: \begin{gathered} U_1 \frac{\partial \Phi}{\partial x_1}+U_2 \frac{\partial \Phi}{\partial x_2}-\mu \frac{\partial^2 \Phi}{\partial x_1^2}-\mu \frac{\partial^2 \Phi}{\partial x_2^2}=f(\vec{x}), \\ U_n^{(-)} \Phi+\mu \operatorname{grad} \Phi \cdot \vec{n}+\gamma\left(\Phi-\Phi_r\right)=u \text { на } \Gamma_{\text {in }}, \\ U_n^{(-)} \Phi+\mu \operatorname{grad} \Phi \cdot \vec{n}+\gamma\left(\Phi-\Phi_r\right)=0 \text { на } \Gamma_{\text {out }}, \end{gathered} с дополнительным условием \Phi=\Phi_{\text {obs }} \quad \text { на } \Gamma_{\text {out }}, где $\Gamma_{\text {in }}=\left{\left(\phi, R_1\right), \forall \phi \in[0,2 \pi)\right}, \Gamma_{\text {out }}=\left{\left(\phi, R_2\right), \forall \phi \in[0,2 \pi)\right}, \vec{U}=\left(U_1, U_2\right)^T$ - вектор скорости, причем $\frac{\partial U_1}{\partial x_1}+\frac{\partial U_2}{\partial x_2}=0, U_n^{(-)}=(|\vec{U} \cdot \vec{n}|-\vec{U} \cdot \vec{n})$ - "входящий поток", $\vec{n}-$ внешняя нормаль к $\Omega, \operatorname{grad}(\Phi)=\left(\frac{\partial \Phi}{\partial x_1}, \frac{\partial \Phi}{\partial x_2}\right)^T, \mu=\mathrm{const}>0, \gamma=$ const $>0 ; f, \Phi_{o b s}, \Phi_r$ - заданные функции. Найти: $\Phi, u$.
479da6288738563602f4c09d4be12e7c
{ "intermediate": 0.33770087361335754, "beginner": 0.4576137959957123, "expert": 0.20468537509441376 }
32,420
import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B, TIME_MAX ) from services.image_service import ImageService from services.time_service import TimeService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([[1, 1], [2, 2], [3, 3]]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ neigh_nums = [] offset = (kernel_size - 1) // 2 for x, y in zip(coords[0], coords[1]): if x < 0 + offset or x > self.image.shape[0] - offset: continue if y < 0 + offset or y > self.image.shape[1] - offset: continue kernel = self.image[x-offset:x+offset+1, y-offset:y+offset+1] step_neigh_num = np.count_nonzero(kernel) - 1 neigh_nums.append([x, y, step_neigh_num]) return neigh_nums @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[ (np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)] np_neigh_nums = np_neigh_nums[ np.argsort(-np_neigh_nums[:, 2])] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if not self.time_service.check_timer(): return self.random_answer if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=3, replace=False) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.time_service.start_timer() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) neigh_nums = self.__get_neigh_nums_list(coords) sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) potential_points = self.__get_potential_points_coords(sorted_neigh_nums) best_lines = self.__get_best_lines(potential_points) intersection_points = np.array([ np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])), np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])), np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]])) ], dtype=np.float32) return intersection_points Етсь алгоритм, который находит углы треугольника, нужно с помощью numpy ускорить его, оставив смысл алгоритма таким же
c63d72d146926fe0879d29ef772e73f3
{ "intermediate": 0.3574940860271454, "beginner": 0.4044358730316162, "expert": 0.2380700409412384 }
32,421
import numpy as np from c_settings import ( ITERATIONS_NUM, IMAGE_THRESHOLD_MIN, IMAGE_THRESHOLD_MAX, NOISE_LESS, POTENTIAL_POINTS_NUM, THRESHOLD_DISTANCE, THRESHOLD_K, THRESHOLD_B, TIME_MAX ) from services.image_service import ImageService from services.time_service import TimeService class CornerDetector(object): """Class for corner detection on image.""" def __init__( self, potential_points_num: int = POTENTIAL_POINTS_NUM, iterations_num: int = ITERATIONS_NUM, threshold_distance: int = THRESHOLD_DISTANCE, threshold_k: float = THRESHOLD_K, threshold_b: int = THRESHOLD_B ): self.potential_points_num = potential_points_num self.iterations_num = iterations_num self.threshold_distance = threshold_distance self.threshold_k = threshold_k self.threshold_b = threshold_b self.image = None self.image_threshold = None self.time_service = TimeService(TIME_MAX) self.random_answer = np.array([[1, 1], [2, 2], [3, 3]]) def __get_coords_by_threshold( self, image: np.ndarray, ) -> tuple: """Gets coordinates with intensity more than 'image_threshold'.""" coords = np.where(image > self.image_threshold) return coords def __get_neigh_nums_list( self, coords: tuple, kernel_size: int = 3 ) -> list: """ Gets list with number of neighborhoods by kernel. Returns list like [[x1, y1, N1], [x2, y2, N2]], Where N - neighborhood's number. """ offset = (kernel_size - 1) // 2 kernel = self.image[coords[0] - offset:coords[0] + offset + 1, coords[1] - offset:coords[1] + offset + 1] step_neigh_nums = np.count_nonzero(kernel, axis=(2, 3)) - 1 neigh_nums = np.concatenate( (np.reshape(coords[0], (-1, 1)), np.reshape(coords[1], (-1, 1)), np.reshape(step_neigh_nums, (-1, 1))), axis=1 ) return list(neigh_nums) @staticmethod def __sort_neigh_nums_by_N( neigh_nums: list ) -> np.ndarray: """ Sort neigh_nums by N parameter. Removes N=-1, N=0 and sorts by N desc. """ np_neigh_nums = np.array(neigh_nums) np_neigh_nums = np_neigh_nums[np_neigh_nums[:, 2] != 0] sorted_indices = np.argsort(-np_neigh_nums[:, 2]) np_neigh_nums = np_neigh_nums[sorted_indices] return np_neigh_nums def __get_potential_points_coords( self, sorted_niegh_nums: np.ndarray ) -> np.ndarray: """ Gets best candidates, potential points coords only. Returns np.ndarray like [[x1, y1], [x2, y2]]. """ sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1) return sorted_neigh_nums[:self.potential_points_num] def __get_best_lines( self, potential_points: np.ndarray ) -> np.ndarray: """ Gets the best combinations of lines by all points. Line y = kx + b. Returns np.ndarray like [[k1, b1], [k2, b2]]. """ remaining_points = 0 best_lines = [] num_lines = 0 while num_lines < 3: if not self.time_service.check_timer(): return self.random_answer if num_lines == 0: remaining_points = np.copy(potential_points) print(f"remaining points: {len(remaining_points)}") best_inlines = [] best_line = None if len(remaining_points) == 0: remaining_points = np.array([[1, 1], [2, 2], [3, 3], [4, 4]]) for i in range(self.iterations_num): sample_indices = np.random.choice( remaining_points.shape[0], size=(self.iterations_num, 3), replace=True) sample_points = remaining_points[sample_indices] sample_x = sample_points[:, 1] sample_y = sample_points[:, 0] coefficients = np.polyfit(sample_x, sample_y, deg=1) distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1) inlines = np.where(distances < self.threshold_distance)[0] is_similar = False for line in best_lines: diff_k = abs(coefficients[0] - line[0]) diff_b = abs(coefficients[1] - line[1]) if diff_k <= self.threshold_k and diff_b <= self.threshold_b: is_similar = True break if not is_similar and len(inlines) > len(best_inlines): best_line = coefficients best_inlines = inlines if best_line is not None: best_lines.append(best_line) remaining_points = np.delete(remaining_points, best_inlines, axis=0) num_lines += 1 return np.array(best_lines) def find_corners(self, image: np.ndarray) -> np.ndarray: """Finding triangle corners on image process.""" self.time_service.start_timer() self.image = image zero_percentage = ImageService.calculate_zero_pixel_percentage(image) if zero_percentage > NOISE_LESS: self.image_threshold = IMAGE_THRESHOLD_MIN else: self.image_threshold = IMAGE_THRESHOLD_MAX # Noise i cannot realise. if zero_percentage < 45: return self.random_answer coords = self.__get_coords_by_threshold(image) if not self.time_service.check_timer(): return self.random_answer neigh_nums = self.__get_neigh_nums_list(coords) if not self.time_service.check_timer(): return self.random_answer sorted_neigh_nums = self.__sort_neigh_nums_by_N(neigh_nums) if not self.time_service.check_timer(): return self.random_answer potential_points = self.__get_potential_points_coords(sorted_neigh_nums) if not self.time_service.check_timer(): return self.random_answer best_lines = self.__get_best_lines(potential_points) if not self.time_service.check_timer(): return self.random_answer intersection_points = np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), [-best_lines[0][1], -best_lines[1][1]]) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), [-best_lines[0][1], -best_lines[2][1]]))) intersection_points = np.vstack((intersection_points, np.linalg.solve( np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), [-best_lines[1][1], -best_lines[2][1]]))) return intersection_points ПОЛУЧАЮ ОШИБКУ: ERROR: only integer scalar arrays can be converted to a scalar index; Traceback: File "/3divi/estimators/test_estimator.py", line 72, in estimator; result = solver.solve(image); File "/tmp/tmpc9w_4bqy/solver.py", line 11, in solve; result = self.alg.find_corners(image_gray); File "/tmp/tmpc9w_4bqy/corner_detector/corner_detector.py", line 171, in find_corners; neigh_nums = self.__get_neigh_nums_list(coords); File "/tmp/tmpc9w_4bqy/corner_detector/corner_detector.py", line 58, in __get_neigh_nums_list; kernel = self.image[coords[0] - offset:coords[0] + offset + 1, В чем дело?!!?
2b531aa6a6ecdbf868f5c0fa00bf857e
{ "intermediate": 0.25524914264678955, "beginner": 0.4547785520553589, "expert": 0.2899723947048187 }