row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
30,718
I have this comand to get order book : depth_data = client.depth(symbol=symbol) output looks like this : 'bids': [['237.66', '3.286'], ['237.65', '0.025'], ['237.63', '13.141'], ['237.62', '6.849'], ['237.61', '12.592'], ['237.60', '48.785'], ['237.59', '21.169'], ['237.58', '65.696'], ['237.57', '44.353'], ['237.56', '19.569'], ['237.55', '102.141'], ['237.54', '13.611'], ['237.53', '42.884'], ['237.52', '32.288'], ['237.51', '27.210'], ['237.50', '57.544'], ['237.49', '83.208'], ['237.48', '40.999'], ['237.47', '70.381'], ['237.46', '134.315'], ['237.45', '35.983'], ['237.44', '7.847'], ['237.43', '3.546'], ['237.42', '10.527'], ['237.41', '67.136'], ['237.40', '39.171'], ['237.39', '11.424'], ['237.38', '97.299'], ['237.37', '134.095'], ['237.36', '21.649'], ['237.35', '93.218'], ['237.34', '8.580'], ['237.33', '25.554'], ['237.32', '9.678'], ['237.31', '35.693'], ['237.30', '143.878'], ['237.29', '22.033'], ['237.28', '3.255'], ['237.27', '7.320'], ['237.26', '14.207'], ['237.25', '23.662'], ['237.24', '7.028'], ['237.23', '1.096'], ['237.22', '9.823'], ['237.21', '33.915'], ['237.20', '133.271'], ['237.19', '2.986'], ['237.18', '21.468'], ['237.16', '16.464'], ['237.15', '221.497'], ['237.14', '305.581'], ['237.13', '2.946'], ['237.12', '10.851'], ['237.11', '4.538'], ['237.10', '28.921'], ['237.09', '16.317'], ['237.07', '154.193'], ['237.06', '18.543'], ['237.05', '29.841'], ['237.04', '2.698'], ['237.03', '39.867'], ['237.02', '22.027'], ['237.01', '6.233'], ['237.00', '37.753'], ['236.99', '14.043'], ['236.98', '15.704'], ['236.97', '5.053'], ['236.96', '2.402'], ['236.95', '206.362'], ['236.94', '5.492'], ['236.93', '0.397'], ['236.92', '14.891'], ['236.91', '12.175'], ['236.90', '32.452'], ['236.89', '1.729'], ['236.88', '4.192'], ['236.87', '1.020'], ['236.86', '2.959'], ['236.85', '14.249'], ['236.84', '11.510'], ['236.83', '1.735'], ['236.82', '5.806'], ['236.81', '3.832'], ['236.80', '33.302'], ['236.78', '1.655'], ['236.77', '0.033'], ['236.76', '44.415'], ['236.75', '16.444'], ['236.74', '24.231'], ['236.73', '9.386'], ['236.72', '8.394'], ['236.71', '13.403'], ['236.70', '37.684'], ['236.68', '0.609'], ['236.67', '424.045'], ['236.66', '13.275'], ['236.65', '41.202'], ['236.64', '75.660'], ['236.63', '0.024'], ['236.62', '4.345'], ['236.61', '5.705'], ['236.60', '19.433'], ['236.59', '113.471'], ['236.58', '6.335'], ['236.57', '4.725'], ['236.56', '0.125'], ['236.55', '0.183'], ['236.54', '25.000'], ['236.53', '0.098'], ['236.52', '96.737'], ['236.51', '59.212'], ['236.50', '26.316']]
38f22f54c542fbd178a2aed4a0f43fe8
{ "intermediate": 0.3433593213558197, "beginner": 0.4345093071460724, "expert": 0.2221314013004303 }
30,719
# Define the input array array = [[1], [2,3], [3], [2,4], [4], [1,4]] # Define the target set target = {1, 2, 3, 4} # Initialize an empty list to store the results results = [] # Loop through all possible combinations of array items from itertools import combinations for i in range(1, len(array) + 1): for combo in combinations(array, i): # Check if the union of the combo items is equal to the target set if set().union(*combo) == target: # Add the combo to the results list results.append(combo) # Sort the results list by the length of the combos results.sort(key=len) # Print the results print("The array item combinations that can build 1, 2, 3, 4 are:") for result in results: print(result) THe code tooks too much time if array and target becomes longer. Can you optimize the code? Make the code workable and make the result same as the above code.
d6070273d7c44731d7f608925c872d80
{ "intermediate": 0.2944336235523224, "beginner": 0.2655481994152069, "expert": 0.4400181770324707 }
30,720
class BonusBox { constructor(id, bonus_id = null) { this.id = id; this.bonus_id = bonus_id; this.disappearing_time = 60000000; if (this.isRare()) this.disappearing_time = 30000; if (this.isSpecial()) this.disappearing_time = 10000000000; this.start_date = Date.now(); this.disappearing_date = Date.now() + this.disappearing_time * 1000; } isSpecial() { return this.id === "gold"; } isRare() { return this.id === "crystal"; } getXMLName() { if (this.isSpecial()) return "crystal_100"; return this.id; } getClientName() { if (this.id === "crystal100") return "gold"; if (this.isSpecial()) return this.id; if (this.id === "crystal") return "crystall"; if (this.id === "medkit") return "health"; if (this.id === "nitro") return "nitro"; if (this.id === "damageup") return "damage"; if (this.id === "armorup") return "armor"; return null; } isValid() { return this.getClientName() !== null; } updateBonusId(counter) { this.bonus_id = this.getClientName() + "_" + counter; } setBonusId(bonus_id) { this.bonus_id = bonus_id; } start() { this.start_date = Date.now(); this.disappearing_date = Date.now() + this.disappearing_time * 1000; } canDisappear() { return this.disappearing_date <= Date.now(); } } module.exports = BonusBox; как сделать чтобы дроп пропадал через 5 секунд после выпадения
c03dba28c83b6fd046bb3ad7a5013240
{ "intermediate": 0.3396104872226715, "beginner": 0.4646068811416626, "expert": 0.19578257203102112 }
30,721
# Define the input array array = [[1], [2,3], [3], [2,4], [4], [1,4]] # Define the target set target = {1, 2, 3, 4} # Initialize an empty list to store the results results = [] # Define a stack to store the combinations stack = [(0, [])] # Iterate through the stack until it is empty while stack: start, combo = stack.pop() # Check if the union of the current combo items is equal to the target set if set().union(*combo) == target: # Add the combo to the results list results.append(combo) # Iterate over the remaining items in the array starting from the current index for i in range(start, len(array)): # Append the next item to the combo and push it to the stack stack.append((i + 1, combo + [array[i]])) # Sort the results list by the length of the combos results.sort(key=len) # Print the results print(“The array item combinations that can build 1, 2, 3, 4 are:”) for result in results: print(result); Can you make the code only to find the shortest combination of the result, not every one of them.
5b830d0d0d0bcc3349882f9badc78d02
{ "intermediate": 0.39364340901374817, "beginner": 0.1924566924571991, "expert": 0.41389989852905273 }
30,722
# Define the input dictionary dictionary = {'a': [1], 'b': [2, 3], 'c': [3], 'd': [2, 4], 'e': [4], 'f': [1, 4]} # Define the target set target = {1, 2, 3, 4} # Initialize an empty list to store the results results = [] # Initialize a variable to keep track of the minimum length of combinations found min_length = float(‘inf’) # Define a stack to store the combinations stack = [(0, [])] # Iterate through the stack until it is empty while stack: start, combo = stack.pop() # Check if the union of the current combo items is equal to the target set if set().union(*[dictionary[key] for key in combo]) == target: # If the length of the current combo is smaller than the minimum length found so far, update the results and min_length if len(combo) < min_length: results = [combo] min_length = len(combo) elif len(combo) == min_length: results.append(combo) # Iterate over the remaining items in the dictionary starting from the current index keys = list(dictionary.keys()) for i in range(start, len(keys)): key = keys[i] # Append the next key to the combo and push it to the stack stack.append((i + 1, combo + [key])) # Print the results print(“The shortest combination(s) to build 1, 2, 3, 4:”) for result in results: print(result); The processing time is slow. My dictionary item will normally have 1000 key. And the value will also be around 1000 long list. Target will normally have 500 items. Can you improve the time? now the code will have more than 50000000 iterations and yet still running . Make the code have workable and have the same result as the above one.
a17c7b9001e97ea54b42f9e7bfffb4d1
{ "intermediate": 0.3476741313934326, "beginner": 0.2935362160205841, "expert": 0.3587896525859833 }
30,723
def find_shortest_combinations(dictionary, target): results = [] min_length = float(‘inf’) stack = [(0, set(), [])] while stack: start, combo_set, combo = stack.pop() if combo_set == target: if len(combo) < min_length: results = [combo] min_length = len(combo) elif len(combo) == min_length: results.append(combo) continue keys = list(dictionary.keys()) for i in range(start, len(keys)): key = keys[i] new_combo_set = combo_set.union(dictionary[key]) if len(new_combo_set) <= len(combo): continue stack.append((i + 1, new_combo_set, combo + [key])) return results # Test the function with the given input dictionary = {‘a’: [1], ‘b’: [2, 3], ‘c’: [3], ‘d’: [2, 4], ‘e’: [4], ‘f’: [1, 4]} target = {1, 2, 3, 4} results = find_shortest_combinations(dictionary, target) print(“The shortest combination(s) to build 1, 2, 3, 4:”) for result in results: print(result) With a dictionary size of 1000 keys and values of 1000 items each, and a target of 500 items, the code is still slow. Can you improve the code? Make the code have workable and have the same output as the above one.
6ccaf2b5c90ed3e4b6b38da3ce12884f
{ "intermediate": 0.3551829159259796, "beginner": 0.2756154537200928, "expert": 0.3692016005516052 }
30,724
how can I open an image with PIL when all i have is the bytes of the image?
d3ecd8dff7451c977036acbad01306ed
{ "intermediate": 0.4257007837295532, "beginner": 0.1164301335811615, "expert": 0.45786911249160767 }
30,725
def find_shortest_combinations(dictionary, target): results = [] min_length = float(‘inf’) stack = [(0, set(), [])] while stack: start, combo_set, combo = stack.pop() if combo_set == target: if len(combo) < min_length: results = [combo] min_length = len(combo) elif len(combo) == min_length: results.append(combo) continue keys = list(dictionary.keys()) for i in range(start, len(keys)): key = keys[i] new_combo_set = combo_set.union(dictionary[key]) if len(new_combo_set) <= len(combo): continue stack.append((i + 1, new_combo_set, combo + [key])) return results # Test the function with the given input dictionary = {‘a’: [1], ‘b’: [2, 3], ‘c’: [3], ‘d’: [2, 4], ‘e’: [4], ‘f’: [1, 4]} target = {1, 2, 3, 4} results = find_shortest_combinations(dictionary, target) print(“The shortest combination(s) to build 1, 2, 3, 4:”) for result in results: print(result) With a dictionary size of 1000 keys and values of 1000 items each, and a target of 500 items, the code is still slow. Can you improve the code? Make the code have workable and have the same output as the above one.
8c919b68839a8aa581746d7d4957f3f0
{ "intermediate": 0.3812621533870697, "beginner": 0.22466203570365906, "expert": 0.39407584071159363 }
30,726
Please provide the data in a matrix object (e.g., no data.frame object) 这是什么意思
d364126d46b3fbf7ceba376e757c26b4
{ "intermediate": 0.4299466609954834, "beginner": 0.21960914134979248, "expert": 0.3504441976547241 }
30,727
const { c, market_list, getType } = require("./server"); class GarageItem { static get(id, m = 1) { return new GarageItem(id, 0, m); } static fromJSON(data) { var item = new GarageItem(c(data.id), c(data.modificationID, 0), c(data.count, 0)); return item; } static getInfo(id) { for (var i in market_list) { if (market_list[i]["id"] === id) return market_list[i]; } return null; } constructor(id, modificationID = 0, count = 0) { this.id = id; var info = GarageItem.getInfo(id); if (info !== null) { this.name = info.name; this.description = info.description; this.index = info.index; this.modification = info.modification; } else { this.name = "null"; this.description = ""; this.index = 3; this.modification = []; } this.modificationID = modificationID; this.type = getType(this.id); this.price = 0; this.rank = 0; this.properts = []; if (this.type > 3) this.count = count; var modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } this.isInventory = this.type === 4; } attempt_upgrade(tank) { if (this.type < 3 && this.modificationID < 3 && tank.crystals >= this.price && tank.rank >= this.rank) { tank.crystals -= this.next_price; this.modificationID++; var modificationID = this.modificationID, modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } return true; } return false; } toObject() { return { id: this.id, count: this.count, modificationID: this.modificationID }; } } module.exports = GarageItem; как сюда добавить multicounted
14aa1fc08f87190fdd8e1b63668be946
{ "intermediate": 0.31071266531944275, "beginner": 0.4544334411621094, "expert": 0.23485387861728668 }
30,728
View(mydata) > p <- ncol(mydata) > mydata<-as.matrix(mydata) > fit_obj <- mgm(data = mydata, + type = rep('g', p), + level = rep(1, p), + lambdaSel = 'CV', + ruleReg = 'OR', + pbar = FALSE) Error in mgm(data = mydata, type = rep("g", p), level = rep(1, p), lambdaSel = "CV", : No infinite values permitted. R运行过程中报这个错误这是什么意思
3d55213730c8f126a5e8bdb72872710e
{ "intermediate": 0.2920495271682739, "beginner": 0.38079825043678284, "expert": 0.32715219259262085 }
30,729
const { c, market_list, getType } = require("./server"); class GarageItem { static get(id, m = 1) { return new GarageItem(id, 0, m); } static fromJSON(data) { var item = new GarageItem(c(data.id), c(data.modificationID, 0), c(data.count, 0)); return item; } static getInfo(id) { for (var i in market_list) { if (market_list[i]["id"] === id) return market_list[i]; } return null; } constructor(id, modificationID = 0, count = 0) { this.id = id; var info = GarageItem.getInfo(id); if (info !== null) { this.name = info.name; this.description = info.description; this.index = info.index; this.modification = info.modification; } else { this.name = "null"; this.description = ""; this.index = 3; this.modification = []; } this.modificationID = modificationID; this.type = getType(this.id); this.price = 0; this.rank = 0; this.properts = []; if (this.type > 3) this.count = count; var modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } this.isInventory = this.type === 4; } attempt_upgrade(tank) { if (this.type < 3 && this.modificationID < 3 && tank.crystals >= this.price && tank.rank >= this.rank) { tank.crystals -= this.next_price; this.modificationID++; var modificationID = this.modificationID, modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } return true; } return false; } toObject() { return { id: this.id, count: this.count, modificationID: this.modificationID }; } } module.exports = GarageItem; как добавить multicounted
55373f724a2342a6de87873765492098
{ "intermediate": 0.31214746832847595, "beginner": 0.44890809059143066, "expert": 0.2389444261789322 }
30,730
dbparametercollection sqlite insert parameter values
d51c193e97a93ad2b3ee4b94cc37bb78
{ "intermediate": 0.3793148100376129, "beginner": 0.29220134019851685, "expert": 0.32848381996154785 }
30,731
for (var i in market_list) { if (market_list[i].discount !== 0) { market_list[i].price *= (100 - market_list[i].discount) / 100; market_list[i].next_price *= (100 - market_list[i].discount) / 100; } } if (sale !== 1) { for (var i in market_list) { if (isset(market_list[i].modification)) { for (var j in market_list[i].modification) { market_list[i].modification[j].price *= (100 - sale) / 100; } } if (market_list[i].discount === 0 && market_list[i].type !== 6) { market_list[i].price *= (100 - sale) / 100; market_list[i].discount = sale; market_list[i].next_price *= (100 - sale) / 100; } } } вот строки скидок он находится в server.js , как сюда const { c, market_list, getType } = require("./server"); class GarageItem { static get(id, m = 1) { return new GarageItem(id, 0, m); } static fromJSON(data) { var item = new GarageItem(c(data.id), c(data.modificationID, 0), c(data.count, 0)); return item; } static getInfo(id) { for (var i in market_list) { if (market_list[i]["id"] === id) return market_list[i]; } return null; } constructor(id, modificationID = 0, count = 0) { this.id = id; var info = GarageItem.getInfo(id); if (info !== null) { this.name = info.name; this.description = info.description; this.discount = info.discount; this.index = info.index; this.modification = info.modification; } else { this.name = "null"; this.description = ""; this.discount = ""; this.index = 3; this.modification = []; } this.modificationID = modificationID; this.type = getType(this.id); this.price = 0; this.rank = 0; this.properts = []; if (this.type > 3) this.count = count; var modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } this.isInventory = this.type === 4; this.multicounted = this.type === 4; } attempt_upgrade(tank) { if (this.type < 3 && this.modificationID < 3 && tank.crystals >= this.price && tank.rank >= this.rank) { tank.crystals -= this.next_price; this.modificationID++; var modificationID = this.modificationID, modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } return true; } return false; } toObject() { return { id: this.id, count: this.count, modificationID: this.modificationID }; } } module.exports = GarageItem; добавить при скидке сумма удешевлялась
b1cb20aaa4b14c0d4ff2be4bfe8746dc
{ "intermediate": 0.3225756287574768, "beginner": 0.5674402117729187, "expert": 0.10998408496379852 }
30,732
I'm making a captcha solver, currently it doesnt do anything appart from scraping the images from the api semi manually. I wanna make this scraper an api and automate it. how can I do that? what is the best and fastest way in python?
f17893e5b8e5ba7c723f599e1156ece0
{ "intermediate": 0.6779086589813232, "beginner": 0.1235484778881073, "expert": 0.19854287803173065 }
30,733
const { c, market_list, getType } = require("./server"); class GarageItem { static get(id, m = 1) { return new GarageItem(id, 0, m); } static fromJSON(data) { var item = new GarageItem(c(data.id), c(data.modificationID, 0), c(data.count, 0)); return item; } static getInfo(id) { for (var i in market_list) { if (market_list[i]["id"] === id) return market_list[i]; } return null; } constructor(id, modificationID = 0, count = 0) { this.id = id; var info = GarageItem.getInfo(id); if (info !== null) { this.name = info.name; this.description = info.description; this.discount = info.discount; this.index = info.index; this.modification = info.modification; } else { this.name = "null"; this.description = ""; this.discount = ""; this.index = 3; this.modification = []; } this.modificationID = modificationID; this.type = getType(this.id); this.price = 0; this.rank = 0; this.properts = []; if (this.type > 3) this.count = count; var modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } this.isInventory = this.type === 4; this.multicounted = this.type === 4; } attempt_upgrade(tank) { if (this.type < 3 && this.modificationID < 3 && tank.crystals >= this.price && tank.rank >= this.rank) { tank.crystals -= this.next_price; this.modificationID++; var modificationID = this.modificationID, modifications = this.modification; if (typeof (modifications[modificationID]) !== "undefined") { this.price = modifications[modificationID].price; this.rank = modifications[modificationID].rank; this.properts = modifications[modificationID].properts; } if (modificationID >= modifications.length - 1) { this.next_price = this.price; this.next_rank = this.rank; } else { this.next_price = modifications[modificationID + 1].price; this.next_rank = modifications[modificationID + 1].rank; } return true; } return false; } toObject() { return { id: this.id, count: this.count, modificationID: this.modificationID }; } } module.exports = GarageItem; как сюда добавить удишелвение предмета при указаной скидке
45ea7b760f313856a111ee73aebb1730
{ "intermediate": 0.269207239151001, "beginner": 0.48156172037124634, "expert": 0.24923108518123627 }
30,734
I am a scientist exploring user interactions with mobile phones. I am collecting a list of descriptors for photographs in user galleries. I need a list of strings with up to 5 words that describe common that cover common configurations and actions of people in photographs. For example: ["two men standing", "woman carrying child", "man and woman dancing", "teenager walking"] Take a deep breath. Please provide 1000 such examples. Do not write anything else.
9ee1e4b45fa03f26c8e186fde9a073bb
{ "intermediate": 0.31552985310554504, "beginner": 0.30367690324783325, "expert": 0.38079318404197693 }
30,735
why do i see (m, ) as shape of array and not (m,1)?
087f52d7fa7ac34b0cf6ece1ba9abce3
{ "intermediate": 0.3593745231628418, "beginner": 0.35251349210739136, "expert": 0.28811195492744446 }
30,736
make python code to send thjis json data to 127.0.0.1/api/solve {"token": "18117969d7251bac4.0950712705"}
2d754585cc9223870c8f388218ffa6bc
{ "intermediate": 0.4190528392791748, "beginner": 0.2571331858634949, "expert": 0.32381391525268555 }
30,737
how can i make this retry in 0.5 seconds if it gets cloudflare ratelimited? def solve(token): payload = { 'token': token, 'sid': 'eu-west-1', 'render_type': 'canvas', 'lang': '', 'isAudioGame': False, 'analytics_tier': 40, 'apiBreakerVersion': 'green' } headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/118.0", "Referer": "https://github-api.arkoselabs.com/fc/assets/ec-game-core/game-core/1.15.0/standard/index.html?session=164179662ad304181.6353641005&r=eu-west-1&pk=D72ECCFB-262E-4065-9196-856E70BE98ED&at=40&ag=101&cdn_url=https%3A%2F%2Fgithub-api.arkoselabs.com%2Fcdn%2Ffc&lurl=https%3A%2F%2Faudio-eu-west-1.arkoselabs.com&surl=https%3A%2F%2Fgithub-api.arkoselabs.com&smurl=https%3A%2F%2Fgithub-api.arkoselabs.com%2Fcdn%2Ffc%2Fassets%2Fstyle-manager&theme=default", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "Connection": "keep-alive", "Cache-Control": "no-cache", "DNT": "1", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "TE": "trailers", } response = requests.post(config['api-url'] + config['sitekey'] + "/fc/gfct/", data=payload) response_json = response.json() # check if Arkose sends an error if 'error' in response_json: logger.log_err(f"error: {response_json['error']}") return 1 try: challenge_imgs = response_json['game_data']['customGUI']['_challenge_imgs'] except: logger.log_err("wtf", [["json response", response_json]]) game_data = response_json['game_data'] if 'instruction_string' in game_data: game_variant = game_data['instruction_string'] elif 'game_variant' in game_data: game_variant = game_data['game_variant'] logger.log_dbg("xtrfhgt",[["gametype",game_variant],["waves",game_data['waves']]]) directory = 'challenge_images/' + game_variant if not os.path.exists(directory): os.makedirs(directory) for i, img_url in enumerate(challenge_imgs): if response.content.startswith(b'<!DOCTYPE html>'): logger.log_err("Cloudflare ratelimited") break response = requests.get(img_url, headers=headers) image_hash = hashew.hash_image(Image.open(BytesIO(response.content))) img_name = image_hash + ".png" img_path = os.path.join(directory, img_name) with open(img_path, 'wb') as f: f.write(response.content) logger.log_suc("Scraped image",[["gametype",game_variant],["hash",image_hash]]) return 'success'
5a076b94271d3e1b4d888e13864f302d
{ "intermediate": 0.42099228501319885, "beginner": 0.35554108023643494, "expert": 0.2234666347503662 }
30,738
// Decompiled by AS3 Sorcerer 6.78 // www.buraks.com/as3sorcerer //scpacker.server.models.bonus.ServerBonusModel package scpacker.server.models.bonus { import alternativa.tanks.model.bonus.BonusModel; import alternativa.service.IModelService; import alternativa.init.Main; import projects.tanks.client.panel.model.bonus.IBonusModelBase; import projects.tanks.client.panel.model.bonus.BonusItem; public class ServerBonusModel { private var model:BonusModel; private var modelsService:IModelService; public function ServerBonusModel() { this.modelsService = IModelService(Main.osgi.getService(IModelService)); this.model = BonusModel(this.modelsService.getModelsByInterface(IBonusModelBase)[0]); } public function showBonuses(data:String):void { var item:Object; var bonusItem:BonusItem; var array:Array = new Array(); var parser:Object = JSON.parse(data); var i:int; for each (item in parser.items) { bonusItem = new BonusItem(item.id); bonusItem.count = item.count; array[i] = bonusItem; i++; }; this.model.showBonuses(null, array, "RU"); } public function showCrystalls(count:int):void { this.model.showCrystals(null, count, null); } public function showDoubleCrystalls():void { this.model.showDoubleCrystalls(null, null); } public function showNoSupplies():void { this.model.showNoSupplies(null, null); } public function showNewbiesUpScore():void { this.model.showNubeUpScore(); } public function showNewbiesNewRank():void { this.model.showNubeNewRank(); } public function showRulesUpdate():void { this.model.showRulesUpdate(); } } }//package scpacker.server.models.bonus это код из моего приложения на as 3.0, как прописать эту функцию showNewbiesUpScore чтобы сервер отправлял задачу клиенту, а клиент выводил это окно, вот сюда надо это добавить const { market_list, shop_data } = require("./server"); const Area = require("./Area.js"), { playerJson, battle_items, send } = require("./server"); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require("./LobbyChat"); this.battle_count = 0; this.anticheat = 0; } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, "For newbies", "map_sandbox", 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); } } //battle;init_mines;{"mines":[]} getChat() { return this.chat; } getPrefix() { return "lobby"; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast("remove_battle;" + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, "init_effect_model;" + JSON.stringify(effect_model)); this.createBattles(); } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } if (args.length === 1 && args[0] === "get_data_init_battle_select") { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === "get_rating") { this.send(socket, "open_rating;" + JSON.stringify( { crystalls: [ { "count": tank.crystals, "rank": tank.rank, "id": tank.name }] })); } else if (args.length === 1 && args[0] === "show_quests") { } else if (args[0] === "user_inited") { } else if (args.length === 1 && args[0] === "show_profile") { this.send(socket, "show_profile;" + JSON.stringify( { isComfirmEmail: false, emailNotice: false })); } else if (args.length === 2 && args[0] === "try_create_battle_ctf") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new CTFBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numFlags, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_dom") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new DOMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numPointsScore, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_tdm") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); console.log('data', data); const battle = new TDMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numKills, !data.inventory, data.autoBalance, data.frielndyFire, data.pay); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args[0] === "try_create_battle_dm") { if (tank.rank > 3) { try { const withoutBonuses = args[10] === 'true'; const withoutSupplies = args[9] === 'true'; var battle = new DMBattle(false, args[1], args[2], args[3], args[5], args[6], args[7], args[4], !withoutBonuses, withoutSupplies); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву в режиме DM "); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "get_show_battle_info") { for (var i in battles) { if (battles[i].battleId === args[1]) { this.send(socket, "show_battle_info;" + JSON.stringify(battles[i].toDetailedObject(tank))); } } } else if (args.length === 2 && (args[0] === "enter_battle_spectator")) { var battle = this.findBattle(args[1]); if (battle !== null) battle.addSpectator(tank); } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle_team")) { var battle = this.findBattle(args[1]); if (battle !== null) { this.anticheat++; setTimeout(() => { if (this.anticheat > 1) { this.send(tank.socket, "battle;kick_by_cheats"); tank.socket.destroy(); } }, 50); setTimeout(() => { this.anticheat--; }, 1000); var type = args[2] === "false" ? "BLUE" : "RED"; send(socket, "lobby;start_battle"); var user = battle.addPlayer(tank, type); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: type })); } } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle")) { var battle = this.findBattle(args[1]); send(socket, "lobby;start_battle"); if (battle !== null && battle.getTeamCount() === 1) { var user = battle.addPlayer(tank); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: "NONE" })); } } else if (args.length === 2 && args[0] === "check_battleName_for_forbidden_words") { send(socket, "lobby;check_battle_name;" + args[1]); } else if (args.length === 1 && args[0] === "get_garage_data") { var tank = socket.tank; if (tank !== null) { setTimeout(() => { tank.garage.initiate(socket); this.initEffectModel(socket); if (this.hasPlayer(tank.name)) this.removePlayer(tank.name); }, 1000); } } } } module.exports = new Lobby(); CTFBattle = require("./CTFBattle"); TDMBattle = require("./TDMBattle"); DMBattle = require("./DMBattle"); DOMBattle = require("./DOMBattle"); ASLBattle = require("./ASLBattle");
0567f927e2cf1169d75fd6f105d368c9
{ "intermediate": 0.3698389232158661, "beginner": 0.5037197470664978, "expert": 0.1264413297176361 }
30,739
make a pypeteer bot to go to octocaptcha.com, wait untill it gets a request to https://github-api.arkoselabs.com/fc/gfct/ gets sent from the browser, then from the data that the browser sends take the token value from the json and keep it as a var.
bb82421b27aad6d26e3ece2e0bec0402
{ "intermediate": 0.44059309363365173, "beginner": 0.24246080219745636, "expert": 0.3169460892677307 }
30,740
else if (data.args[0] == “show_news”) { parser = JSON.parse(data.args[1]); newsModel = Main.osgi.getService(INewsModel) as NewsModel; news = new Vector.<NewsItemServer>(); for each(news_item in parser) { news.push(new NewsItemServer(news_item.date,news_item.text,news_item.icon_id)); } newsModel.showNews(news); } переделай это под js и чтобы новости он брал из json файла. и надо добавить сюда const { market_list, shop_data } = require(“./server”); const Area = require(“./Area.js”), { playerJson, battle_items, send } = require(“./server”); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require(“./LobbyChat”); this.battle_count = 0; this.anticheat = 0; } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, “For newbies”, “map_sandbox”, 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); } } //battle;init_mines;{“mines”:[]} getChat() { return this.chat; } getPrefix() { return “lobby”; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem(“no_supplies”); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, “init_battle_select;” + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast(“remove_battle;” + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, “init_effect_model;” + JSON.stringify(effect_model)); this.createBattles(); } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } if (args.length === 1 && args[0] === “get_data_init_battle_select”) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem(“no_supplies”); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, “init_battle_select;” + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === “get_rating”) { this.send(socket, “open_rating;” + JSON.stringify( { crystalls: [ { “count”: tank.crystals, “rank”: tank.rank, “id”: tank.name }] })); } else if (args.length === 1 && args[0] === “show_quests”) { } else if (args[0] === “user_inited”) { } else if (args.length === 1 && args[0] === “show_profile”) { this.send(socket, “show_profile;” + JSON.stringify( { isComfirmEmail: false, emailNotice: false })); } else if (args.length === 2 && args[0] === “try_create_battle_ctf”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new CTFBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numFlags, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “try_create_battle_dom”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new DOMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numPointsScore, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “try_create_battle_tdm”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); console.log(‘data’, data); const battle = new TDMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numKills, !data.inventory, data.autoBalance, data.frielndyFire, data.pay); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args[0] === “try_create_battle_dm”) { if (tank.rank > 3) { try { const withoutBonuses = args[10] === ‘true’; const withoutSupplies = args[9] === ‘true’; var battle = new DMBattle(false, args[1], args[2], args[3], args[5], args[6], args[7], args[4], !withoutBonuses, withoutSupplies); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву в режиме DM “); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “get_show_battle_info”) { for (var i in battles) { if (battles[i].battleId === args[1]) { this.send(socket, “show_battle_info;” + JSON.stringify(battles[i].toDetailedObject(tank))); } } } else if (args.length === 2 && (args[0] === “enter_battle_spectator”)) { var battle = this.findBattle(args[1]); if (battle !== null) battle.addSpectator(tank); } else if (args[3] !== “null” && args.length === 3 && (args[0] === “enter_battle_team”)) { var battle = this.findBattle(args[1]); if (battle !== null) { this.anticheat++; setTimeout(() => { if (this.anticheat > 1) { this.send(tank.socket, “battle;kick_by_cheats”); tank.socket.destroy(); } }, 50); setTimeout(() => { this.anticheat–; }, 1000); var type = args[2] === “false” ? “BLUE” : “RED”; send(socket, “lobby;start_battle”); var user = battle.addPlayer(tank, type); if (user !== null) this.broadcast(“add_player_to_battle;” + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: type })); } } else if (args[3] !== “null” && args.length === 3 && (args[0] === “enter_battle”)) { var battle = this.findBattle(args[1]); send(socket, “lobby;start_battle”); if (battle !== null && battle.getTeamCount() === 1) { var user = battle.addPlayer(tank); if (user !== null) this.broadcast(“add_player_to_battle;” + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: “NONE” })); } } else if (args.length === 2 && args[0] === “check_battleName_for_forbidden_words”) { send(socket, “lobby;check_battle_name;” + args[1]); } else if (args.length === 1 && args[0] === “get_garage_data”) { var tank = socket.tank; if (tank !== null) { setTimeout(() => { tank.garage.initiate(socket); this.initEffectModel(socket); if (this.hasPlayer(tank.name)) this.removePlayer(tank.name); }, 1000); } } } } module.exports = new Lobby(); CTFBattle = require(”./CTFBattle"); TDMBattle = require(“./TDMBattle”); DMBattle = require(“./DMBattle”); DOMBattle = require(“./DOMBattle”); ASLBattle = require(“./ASLBattle”); понял ?
736816064651639e33a4d4f13fc94611
{ "intermediate": 0.3374907970428467, "beginner": 0.44435280561447144, "expert": 0.21815639734268188 }
30,741
Hi! Can you teach me how to obsfuscate my Java Hello World using ProGuard?
6fd27e84f976d61dcc502195957d7b00
{ "intermediate": 0.5022940039634705, "beginner": 0.2906072437763214, "expert": 0.20709878206253052 }
30,742
Explain advanced C# ASP.NET concepts
de0bccffbe7138e51fceea84300f0f4e
{ "intermediate": 0.6419532895088196, "beginner": 0.29848456382751465, "expert": 0.059562161564826965 }
30,743
"Bitonic sorting" 1. Generate array A. The array size must not be a multiple of 16. 2. Implement sequential and parallel algorithms for bitonic sorting of array A. Set the number of blocks and threads yourself. Write the original and sorted arrays to a file. 3. Compare the execution time of parallel and sequential algorithms. Experimentally determine the size of the array at which the running time of the parallel algorithm will be less than the running time of the sequential one. 4. Compare the running time of bitonic sorting with the bubble sorting algorithm. 5. Plot the dependence of the running time of the parallel algorithm on the size of the array
34b1788ce679b3c65792273328204377
{ "intermediate": 0.16145126521587372, "beginner": 0.11880364269018173, "expert": 0.7197450399398804 }
30,744
hi
772f46affa9e7660e38e4df0857f5031
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
30,745
struct Task: Identifiable { var text: String var id = UUID() } struct ContentView: View { @State var task = "" @State var tasks = [Task(text: self.task)] Cannot find 'self' in scope; did you mean to use it in a type or extension context?
b9215f5a29835aa6082b0060909bc18d
{ "intermediate": 0.46208900213241577, "beginner": 0.3701310157775879, "expert": 0.16777995228767395 }
30,746
make a sql statement that identifies all emails in a base using regex
8994385f411e234d291ade83493c6179
{ "intermediate": 0.4462466239929199, "beginner": 0.20143559575080872, "expert": 0.35231781005859375 }
30,747
const { market_list, shop_data } = require("./server"); const NewsItemServer = require("./NewsItemServer.js"); const newsArray = [ new NewsItemServer("2023-11-11", "Новость 1"), new NewsItemServer("2023-11-11", "Новость 2"), new NewsItemServer("2023-11-11", "Новость 3"), new NewsItemServer("2023-11-11", "Новость 4"), new NewsItemServer("2023-11-11", "Новость 5") ]; const Area = require("./Area.js"), { playerJson, battle_items, send } = require("./server"); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require("./LobbyChat"); this.battle_count = 0; this.anticheat = 0; this.newsShown = false; // Флаг, указывающий, были ли новости показаны игроку } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, "For newbies", "map_sandbox", 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); } } //battle;init_mines;{"mines":[]} getChat() { return this.chat; } getPrefix() { return "lobby"; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast("remove_battle;" + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, "init_effect_model;" + JSON.stringify(effect_model)); this.createBattles(); } sendNews(socket) { if (!this.newsShown) { // Проверяем, были ли новости уже показаны const newsJSON = JSON.stringify(newsArray); this.send(socket, "show_news;" + newsJSON); this.newsShown = true; // Устанавливаем флаг, что новости были показаны } } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } if (args.length === 1 && args[0] === "show_news") { // Отправка новостей на клиент sendNews(socket); } if (args.length === 1 && args[0] === "get_data_init_battle_select") { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === "get_rating") { this.send(socket, "open_rating;" + JSON.stringify( { crystalls: [ { "count": tank.crystals, "rank": tank.rank, "id": tank.name }] })); } else if (args.length === 1 && args[0] === "show_quests") { } else if (args[0] === "user_inited") { } else if (args.length === 1 && args[0] === "show_profile") { this.send(socket, "show_profile;" + JSON.stringify( { isComfirmEmail: false, emailNotice: false })); } else if (args.length === 2 && args[0] === "try_create_battle_ctf") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new CTFBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numFlags, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_dom") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new DOMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numPointsScore, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_tdm") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); console.log('data', data); const battle = new TDMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numKills, !data.inventory, data.autoBalance, data.frielndyFire, data.pay); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args[0] === "try_create_battle_dm") { if (tank.rank > 3) { try { const withoutBonuses = args[10] === 'true'; const withoutSupplies = args[9] === 'true'; var battle = new DMBattle(false, args[1], args[2], args[3], args[5], args[6], args[7], args[4], !withoutBonuses, withoutSupplies); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву в режиме DM "); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "get_show_battle_info") { for (var i in battles) { if (battles[i].battleId === args[1]) { this.send(socket, "show_battle_info;" + JSON.stringify(battles[i].toDetailedObject(tank))); } } } else if (args.length === 2 && (args[0] === "enter_battle_spectator")) { var battle = this.findBattle(args[1]); if (battle !== null) battle.addSpectator(tank); } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle_team")) { var battle = this.findBattle(args[1]); if (battle !== null) { this.anticheat++; setTimeout(() => { if (this.anticheat > 1) { this.send(tank.socket, "battle;kick_by_cheats"); tank.socket.destroy(); } }, 50); setTimeout(() => { this.anticheat--; }, 1000); var type = args[2] === "false" ? "BLUE" : "RED"; send(socket, "lobby;start_battle"); var user = battle.addPlayer(tank, type); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: type })); } } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle")) { var battle = this.findBattle(args[1]); send(socket, "lobby;start_battle"); if (battle !== null && battle.getTeamCount() === 1) { var user = battle.addPlayer(tank); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: "NONE" })); } } else if (args.length === 2 && args[0] === "check_battleName_for_forbidden_words") { send(socket, "lobby;check_battle_name;" + args[1]); } else if (args.length === 1 && args[0] === "get_garage_data") { } var tank = socket.tank; if (tank !== null) { setTimeout(() => { tank.garage.initiate(socket); this.initEffectModel(socket); if (this.hasPlayer(tank.name)) this.removePlayer(tank.name); }, 1000); } } } } module.exports = new Lobby(); CTFBattle = require("./CTFBattle"); TDMBattle = require("./TDMBattle"); DMBattle = require("./DMBattle"); DOMBattle = require("./DOMBattle"); ASLBattle = require("./ASLBattle"); как сделать чтобы if (!this.newsShown) { // Проверяем, были ли новости уже показаны this.sendNews(socket); } загружались тоже
bb21d5951a2756a6430e1e058ee3d350
{ "intermediate": 0.3428213596343994, "beginner": 0.43095964193344116, "expert": 0.22621898353099823 }
30,748
if let index = tasks.firstIndex(of: item) { tasks.remove(at: index) } Referencing instance method 'firstIndex(of:)' on 'Collection' requires that 'Task' conform to 'Equatable'
9d12d0cce55930c2d9528c58522412c6
{ "intermediate": 0.40058431029319763, "beginner": 0.3462381958961487, "expert": 0.2531774938106537 }
30,749
import SwiftUI struct Task: Identifiable { var text: String var id = UUID() } struct ContentView: View { @State var task = "" @State var tasks: [Task] = [] func add() { if !task.isEmpty { tasks.append(Task(text: task)) task = "" } } var body: some View { VStack { HStack { TextField("New task…", text: $task) { _ in } onCommit: { add() } Button(action: add) { Image(systemName: "plus") .foregroundColor(.blue) } } .padding(8.0) List(tasks) { item in Text(item.text) .contextMenu { Button(action: { //delete the task with text which equals item.text from the tasks }) { Label("Delete", systemImage: "x.circle") } } } } } } #Preview { ContentView() }
7385f39dd1569f4d789dc64be444ac35
{ "intermediate": 0.38579314947128296, "beginner": 0.26021528244018555, "expert": 0.3539915382862091 }
30,750
private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel")) { if (marioDeath != null) { Instantiate(marioDeath, transform.position, transform.rotation, null); } currentHealth--; ResetScene(); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Win")) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } make it so that there is 3 seconds before ResetScene() is called
46eabe20ca98b8312bba857c5df5af5f
{ "intermediate": 0.35105806589126587, "beginner": 0.35025152564048767, "expert": 0.2986903786659241 }
30,751
const { market_list, shop_data } = require("./server"); const NewsItemServer = require("./NewsItemServer.js"); const newsArray = [ new NewsItemServer("2023-11-11", "Новость 1"), new NewsItemServer("2023-11-11", "Новость 2"), new NewsItemServer("2023-11-11", "Новость 3"), new NewsItemServer("2023-11-11", "Новость 4"), new NewsItemServer("2023-11-11", "Новость 5") ]; const Area = require("./Area.js"), { playerJson, battle_items, send } = require("./server"); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require("./LobbyChat"); this.battle_count = 0; this.anticheat = 0; this.newsShown = false; // Флаг, указывающий, были ли новости показаны игроку this.newsShownPlayers = []; // Массив для хранения игроков, которые уже видели новости } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, "For newbies", "map_sandbox", 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); } } //battle;init_mines;{"mines":[]} getChat() { return this.chat; } getPrefix() { return "lobby"; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast("remove_battle;" + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, "init_effect_model;" + JSON.stringify(effect_model)); this.createBattles(); } sendNews() { const newsJSON = JSON.stringify(newsArray); this.broadcast("show_news;" + newsJSON); } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } if (!this.newsShown && args[0] !== "show_news") { // Проверяем, были ли новости уже показаны, // и не вызывается ли функция “show_news” this.sendNews(); // Вызываем метод, который будет отправлять новости игрокам this.newsShown = true; // Устанавливаем флаг в значение true, чтобы пометить, что новости уже показаны } if (args.length === 1 && args[0] === "get_data_init_battle_select") { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === "get_rating") { this.send(socket, "open_rating;" + JSON.stringify( { crystalls: [ { "count": tank.crystals, "rank": tank.rank, "id": tank.name }] })); } else if (args.length === 1 && args[0] === "show_quests") { } else if (args[0] === "user_inited") { if (!this.newsShownPlayers.includes(socket.id)) { this.sendNews(); // Отправляем новости только если текущий игрок их еще не видел this.newsShownPlayers.push(socket.id); // Добавляем идентификатор игрока в массив, чтобы пометить, что он уже видел новости } } else if (args.length === 1 && args[0] === "show_profile") { this.send(socket, "show_profile;" + JSON.stringify( { isComfirmEmail: false, emailNotice: false })); } else if (args.length === 2 && args[0] === "try_create_battle_ctf") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new CTFBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numFlags, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_dom") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new DOMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numPointsScore, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "try_create_battle_tdm") { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); console.log('data', data); const battle = new TDMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numKills, !data.inventory, data.autoBalance, data.frielndyFire, data.pay); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args[0] === "try_create_battle_dm") { if (tank.rank > 3) { try { const withoutBonuses = args[10] === 'true'; const withoutSupplies = args[9] === 'true'; var battle = new DMBattle(false, args[1], args[2], args[3], args[5], args[6], args[7], args[4], !withoutBonuses, withoutSupplies); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); console.log('\x1b[35m%s\x1b[0m', ' > ' + tank.name + " создал битву в режиме DM "); } catch (e) { console.log(e); } } else { this.send(socket, "server_message;Создавать битвы можно со звания Капрал") } } else if (args.length === 2 && args[0] === "get_show_battle_info") { for (var i in battles) { if (battles[i].battleId === args[1]) { this.send(socket, "show_battle_info;" + JSON.stringify(battles[i].toDetailedObject(tank))); } } } else if (args.length === 2 && (args[0] === "enter_battle_spectator")) { var battle = this.findBattle(args[1]); if (battle !== null) battle.addSpectator(tank); } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle_team")) { var battle = this.findBattle(args[1]); if (battle !== null) { this.anticheat++; setTimeout(() => { if (this.anticheat > 1) { this.send(tank.socket, "battle;kick_by_cheats"); tank.socket.destroy(); } }, 50); setTimeout(() => { this.anticheat--; }, 1000); var type = args[2] === "false" ? "BLUE" : "RED"; send(socket, "lobby;start_battle"); var user = battle.addPlayer(tank, type); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: type })); } } else if (args[3] !== "null" && args.length === 3 && (args[0] === "enter_battle")) { var battle = this.findBattle(args[1]); send(socket, "lobby;start_battle"); if (battle !== null && battle.getTeamCount() === 1) { var user = battle.addPlayer(tank); if (user !== null) this.broadcast("add_player_to_battle;" + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: "NONE" })); } } else if (args.length === 2 && args[0] === "check_battleName_for_forbidden_words") { send(socket, "lobby;check_battle_name;" + args[1]); } else if (args.length === 1 && args[0] === "get_garage_data") { var tank = socket.tank; if (tank !== null) { setTimeout(() => { tank.garage.initiate(socket); this.initEffectModel(socket); if (this.hasPlayer(tank.name)) this.removePlayer(tank.name); }, 1000); } } } } module.exports = new Lobby(); CTFBattle = require("./CTFBattle"); TDMBattle = require("./TDMBattle"); DMBattle = require("./DMBattle"); DOMBattle = require("./DOMBattle"); ASLBattle = require("./ASLBattle"); сделал я чтобы новости показывались один раз и после нажатия закрыть в клиенте больше не показывались, и чтобы это было для каждого игрока а не только для одного. и исправил если 1 игрок закроет новости, другие игроки уже не смогут увидеть их. но... после закрытия игроком новости, она после перезахода в игру по новой появляется хотя так не должно быть
6d89eb39907d16169f0e9583508677b7
{ "intermediate": 0.28850850462913513, "beginner": 0.4063577651977539, "expert": 0.30513373017311096 }
30,752
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; 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; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class BazaarPlugin extends JavaPlugin implements Listener, CommandExecutor { private static final int BASE_COAL_SELL_PRICE = 50; private static final int BASE_STONE_SELL_PRICE = 10; private static final double PRICE_CHANGE_PERCENTAGE = 0.03; private static final double BUY_PRICE_MULTIPLIER = 1.1; private static final double MAX_PRICE_CHANGE_PERCENTAGE = 0.4; private Inventory bazaarMenu; private Map<Player, Inventory> playerMenus; private Map<Material, Double> sellPrices; private Map<UUID, Long> shiftClickCooldowns; @Override public void onEnable() { getCommand(“bazaar”).setExecutor(this); getServer().getPluginManager().registerEvents(this, this); playerMenus = new HashMap<>(); sellPrices = new HashMap<>(); shiftClickCooldowns = new HashMap<>(); // Установка изначальных цен продажи sellPrices.put(Material.COAL, (double) BASE_COAL_SELL_PRICE); sellPrices.put(Material.STONE, (double) BASE_STONE_SELL_PRICE); // Запустить задачу обновления цен каждые 30 секунд new BukkitRunnable() { @Override public void run() { for (Material material : sellPrices.keySet()) { double currentPrice = sellPrices.get(material); double priceChange = PRICE_CHANGE_PERCENTAGE * currentPrice; if (Math.abs(priceChange) / currentPrice > MAX_PRICE_CHANGE_PERCENTAGE) { sellPrices.put(material, (double) ((material == Material.COAL) ? BASE_COAL_SELL_PRICE : BASE_STONE_SELL_PRICE)); } else { double newPrice = currentPrice + priceChange; sellPrices.put(material, newPrice); } } } }.runTaskTimer(this, 0L, 600L); // 20 тиков = 1 секунда, 30 секунд = 600 тиков // Создать базарное меню bazaarMenu = Bukkit.createInventory(null, 9, “Bazaar Menu”); ItemStack coalItem = createMenuItem(Material.COAL, “&cCoal”, “&7Sell Price: &a” + sellPrices.get(Material.COAL)); ItemStack stoneItem = createMenuItem(Material.STONE, “&7Stone”, “&7Sell Price: &a” + sellPrices.get(Material.STONE)); bazaarMenu.setItem(0, coalItem); bazaarMenu.setItem(1, stoneItem); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase(“bazaar”)) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(bazaarMenu); playerMenus.put(player, bazaarMenu); } return true; } return false; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); Inventory clickedInventory = event.getClickedInventory(); ItemStack clickedItem = event.getCurrentItem(); if (clickedInventory != null && playerMenus.containsKey(player) && clickedInventory.equals(playerMenus.get(player))) { event.setCancelled(true); if (clickedItem != null && clickedItem.getType() != Material.AIR) { if (clickedItem.getType() == Material.COAL || clickedItem.getType() == Material.STONE) { openBuySellMenu(player, clickedItem.getType()); } } } else if (clickedInventory != null && playerMenus.containsValue(clickedInventory)) { event.setCancelled(true); if (player.isSneaking() && shiftClickCooldowns.getOrDefault(player.getUniqueId(), 0L) < System.currentTimeMillis()) { shiftClickCooldowns.put(player.getUniqueId(), System.currentTimeMillis() + 1000L); if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isRightClick()) { handleSell(player, clickedItem.getType(), 64); } else if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isLeftClick()) { handleBuy(player, clickedItem.getType(), 64); } } } } private void openBuySellMenu(Player player, Material material) { Inventory buySellMenu = Bukkit.createInventory(null, 9, “Buy/Sell Menu”); // Установка цен продажи и покупки double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; ItemStack sellItem = createMenuItem(material, “&6Sell”, “&7Sell Price: &a” + sellPrice); ItemStack buyItem = createMenuItem(material, “&aBuy”, “&7Buy Price: &e” + buyPrice); buySellMenu.setItem(2, sellItem); buySellMenu.setItem(6, buyItem); player.openInventory(buySellMenu); playerMenus.put(player, buySellMenu); } private void handleSell(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); int sellAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() == material && sellAmount < amount) { if (item.getAmount() <= amount - sellAmount) { sellAmount += item.getAmount(); player.getInventory().remove(item); } else { item.setAmount(item.getAmount() - (amount - sellAmount)); sellAmount = amount; } } } double profit = sellAmount * sellPrice; player.sendMessage(“Sold " + sellAmount + " " + material.toString() + " for " + profit + " coins.”); // Добавьте код здесь для добавления монет в экономику вашего сервера } private void handleBuy(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; double totalCost = amount * buyPrice; if (/* Проверка наличия достаточного количества монет у игрока */) { for (int i = 0; i < amount; i++) { ItemStack item = new ItemStack(material); player.getInventory().addItem(item); } player.sendMessage(“Bought " + amount + " " + material.toString() + " for " + totalCost + " coins.”); // Удалите код ниже и добавьте код здесь для вычета монет из эконоимки вашего сервера } else { player.sendMessage(“You don’t have enough coins to purchase " + amount + " " + material.toString() + “.”); } } private ItemStack createMenuItem(Material material, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name.replace(”&“, “§”)); meta.setLore(Collections.singletonList(lore.replace(”&", “§”))); item.setItemMeta(meta); return item; } } переведи все сообщения в коде на русский язык и скинь итоговый код
940446c803351a64092273faafd38ed3
{ "intermediate": 0.3566626310348511, "beginner": 0.463386595249176, "expert": 0.1799507588148117 }
30,753
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; 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; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class BazaarPlugin extends JavaPlugin implements Listener, CommandExecutor { private static final int BASE_COAL_SELL_PRICE = 50; private static final int BASE_STONE_SELL_PRICE = 10; private static final double PRICE_CHANGE_PERCENTAGE = 0.03; private static final double BUY_PRICE_MULTIPLIER = 1.1; private static final double MAX_PRICE_CHANGE_PERCENTAGE = 0.4; private Inventory bazaarMenu; private Map<Player, Inventory> playerMenus; private Map<Material, Double> sellPrices; private Map<UUID, Long> shiftClickCooldowns; @Override public void onEnable() { getCommand(“bazaar”).setExecutor(this); getServer().getPluginManager().registerEvents(this, this); playerMenus = new HashMap<>(); sellPrices = new HashMap<>(); shiftClickCooldowns = new HashMap<>(); // Установка изначальных цен продажи sellPrices.put(Material.COAL, (double) BASE_COAL_SELL_PRICE); sellPrices.put(Material.STONE, (double) BASE_STONE_SELL_PRICE); // Запустить задачу обновления цен каждые 30 секунд new BukkitRunnable() { @Override public void run() { for (Material material : sellPrices.keySet()) { double currentPrice = sellPrices.get(material); double priceChange = PRICE_CHANGE_PERCENTAGE * currentPrice; if (Math.abs(priceChange) / currentPrice > MAX_PRICE_CHANGE_PERCENTAGE) { sellPrices.put(material, (double) ((material == Material.COAL) ? BASE_COAL_SELL_PRICE : BASE_STONE_SELL_PRICE)); } else { double newPrice = currentPrice + priceChange; sellPrices.put(material, newPrice); } } } }.runTaskTimer(this, 0L, 600L); // 20 тиков = 1 секунда, 30 секунд = 600 тиков // Создать базарное меню bazaarMenu = Bukkit.createInventory(null, 9, “Меню базара”); ItemStack coalItem = createMenuItem(Material.COAL, “§cУголь”, “§7Цена продажи: §a” + sellPrices.get(Material.COAL)); ItemStack stoneItem = createMenuItem(Material.STONE, “§7Камень”, “§7Цена продажи: §a” + sellPrices.get(Material.STONE)); bazaarMenu.setItem(0, coalItem); bazaarMenu.setItem(1, stoneItem); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase(“bazaar”)) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(bazaarMenu); playerMenus.put(player, bazaarMenu); } return true; } return false; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); Inventory clickedInventory = event.getClickedInventory(); ItemStack clickedItem = event.getCurrentItem(); if (clickedInventory != null && playerMenus.containsKey(player) && clickedInventory.equals(playerMenus.get(player))) { event.setCancelled(true); if (clickedItem != null && clickedItem.getType() != Material.AIR) { if (clickedItem.getType() == Material.COAL || clickedItem.getType() == Material.STONE) { openBuySellMenu(player, clickedItem.getType()); } } } else if (clickedInventory != null && playerMenus.containsValue(clickedInventory)) { event.setCancelled(true); if (player.isSneaking() && shiftClickCooldowns.getOrDefault(player.getUniqueId(), 0L) < System.currentTimeMillis()) { shiftClickCooldowns.put(player.getUniqueId(), System.currentTimeMillis() + 1000L); if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isRightClick()) { handleSell(player, clickedItem.getType(), 64); } else if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isLeftClick()) { handleBuy(player, clickedItem.getType(), 64); } } } } private void openBuySellMenu(Player player, Material material) { Inventory buySellMenu = Bukkit.createInventory(null, 9, “Меню покупки/продажи”); // Установка цен продажи и покупки double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; ItemStack sellItem = createMenuItem(material, “§6Продажа”, “§7Цена продажи: §a” + sellPrice); ItemStack buyItem = createMenuItem(material, “§aПокупка”, “§7Цена покупки: §e” + buyPrice); buySellMenu.setItem(2, sellItem); buySellMenu.setItem(6, buyItem); player.openInventory(buySellMenu); playerMenus.put(player, buySellMenu); } private void handleSell(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); int sellAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() == material && sellAmount < amount) { if (item.getAmount() <= amount - sellAmount) { sellAmount += item.getAmount(); player.getInventory().remove(item); } else { item.setAmount(item.getAmount() - (amount - sellAmount)); sellAmount = amount; } } } double profit = sellAmount * sellPrice; player.sendMessage(“Продано " + sellAmount + " " + material.toString() + " за " + profit + " монет.”); // Добавьте код здесь для добавления монет в экономику вашего сервера } private void handleBuy(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; double totalCost = amount * buyPrice; if (/* Проверка наличия достаточного количества монет у игрока */) { for (int i = 0; i < amount; i++) { ItemStack item = new ItemStack(material); player.getInventory().addItem(item); } player.sendMessage(“Куплено " + amount + " " + material.toString() + " за " + totalCost + " монет.”); // Удалите код ниже и добавьте код здесь для вычета монет из эконоимки вашего сервера } else { player.sendMessage(“У вас недостаточно монет для покупки " + amount + " " + material.toString() + “.”); } } private ItemStack createMenuItem(Material material, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name.replace(”§“, “&”)); meta.setLore(Collections.singletonList(lore.replace(”§", “&”))); item.setItemMeta(meta); return item; } } добавь в этот код валюту с плагина essentials и сделай чтобы все работало через эту валют
4c2ed4f08225808dc2ca32e0a43d9712
{ "intermediate": 0.28867748379707336, "beginner": 0.5273539423942566, "expert": 0.18396858870983124 }
30,754
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; 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; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class BazaarPlugin extends JavaPlugin implements Listener, CommandExecutor { private static final int BASE_COAL_SELL_PRICE = 50; private static final int BASE_STONE_SELL_PRICE = 10; private static final double PRICE_CHANGE_PERCENTAGE = 0.03; private static final double BUY_PRICE_MULTIPLIER = 1.1; private static final double MAX_PRICE_CHANGE_PERCENTAGE = 0.4; private Inventory bazaarMenu; private Map<Player, Inventory> playerMenus; private Map<Material, Double> sellPrices; private Map<UUID, Long> shiftClickCooldowns; @Override public void onEnable() { getCommand(“bazaar”).setExecutor(this); getServer().getPluginManager().registerEvents(this, this); playerMenus = new HashMap<>(); sellPrices = new HashMap<>(); shiftClickCooldowns = new HashMap<>(); // Установка изначальных цен продажи sellPrices.put(Material.COAL, (double) BASE_COAL_SELL_PRICE); sellPrices.put(Material.STONE, (double) BASE_STONE_SELL_PRICE); // Запустить задачу обновления цен каждые 30 секунд new BukkitRunnable() { @Override public void run() { for (Material material : sellPrices.keySet()) { double currentPrice = sellPrices.get(material); double priceChange = PRICE_CHANGE_PERCENTAGE * currentPrice; if (Math.abs(priceChange) / currentPrice > MAX_PRICE_CHANGE_PERCENTAGE) { sellPrices.put(material, (double) ((material == Material.COAL) ? BASE_COAL_SELL_PRICE : BASE_STONE_SELL_PRICE)); } else { double newPrice = currentPrice + priceChange; sellPrices.put(material, newPrice); } } } }.runTaskTimer(this, 0L, 600L); // 20 тиков = 1 секунда, 30 секунд = 600 тиков // Создать базарное меню bazaarMenu = Bukkit.createInventory(null, 9, “Меню базара”); ItemStack coalItem = createMenuItem(Material.COAL, “§cУголь”, “§7Цена продажи: §a” + sellPrices.get(Material.COAL)); ItemStack stoneItem = createMenuItem(Material.STONE, “§7Камень”, “§7Цена продажи: §a” + sellPrices.get(Material.STONE)); bazaarMenu.setItem(0, coalItem); bazaarMenu.setItem(1, stoneItem); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase(“bazaar”)) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(bazaarMenu); playerMenus.put(player, bazaarMenu); } return true; } return false; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); Inventory clickedInventory = event.getClickedInventory(); ItemStack clickedItem = event.getCurrentItem(); if (clickedInventory != null && playerMenus.containsKey(player) && clickedInventory.equals(playerMenus.get(player))) { event.setCancelled(true); if (clickedItem != null && clickedItem.getType() != Material.AIR) { if (clickedItem.getType() == Material.COAL || clickedItem.getType() == Material.STONE) { openBuySellMenu(player, clickedItem.getType()); } } } else if (clickedInventory != null && playerMenus.containsValue(clickedInventory)) { event.setCancelled(true); if (player.isSneaking() && shiftClickCooldowns.getOrDefault(player.getUniqueId(), 0L) < System.currentTimeMillis()) { shiftClickCooldowns.put(player.getUniqueId(), System.currentTimeMillis() + 1000L); if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isRightClick()) { handleSell(player, clickedItem.getType(), 64); } else if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isLeftClick()) { handleBuy(player, clickedItem.getType(), 64); } } } } private void openBuySellMenu(Player player, Material material) { Inventory buySellMenu = Bukkit.createInventory(null, 9, “Меню покупки/продажи”); // Установка цен продажи и покупки double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; ItemStack sellItem = createMenuItem(material, “§6Продажа”, “§7Цена продажи: §a” + sellPrice); ItemStack buyItem = createMenuItem(material, “§aПокупка”, “§7Цена покупки: §e” + buyPrice); buySellMenu.setItem(2, sellItem); buySellMenu.setItem(6, buyItem); player.openInventory(buySellMenu); playerMenus.put(player, buySellMenu); } private void handleSell(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); int sellAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() == material && sellAmount < amount) { if (item.getAmount() <= amount - sellAmount) { sellAmount += item.getAmount(); player.getInventory().remove(item); } else { item.setAmount(item.getAmount() - (amount - sellAmount)); sellAmount = amount; } } } double profit = sellAmount * sellPrice; player.sendMessage(“Продано " + sellAmount + " " + material.toString() + " за " + profit + " монет.”); // Добавьте код здесь для добавления монет в экономику вашего сервера } private void handleBuy(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; double totalCost = amount * buyPrice; if (/* Проверка наличия достаточного количества монет у игрока */) { for (int i = 0; i < amount; i++) { ItemStack item = new ItemStack(material); player.getInventory().addItem(item); } player.sendMessage(“Куплено " + amount + " " + material.toString() + " за " + totalCost + " монет.”); // Удалите код ниже и добавьте код здесь для вычета монет из эконоимки вашего сервера } else { player.sendMessage(“У вас недостаточно монет для покупки " + amount + " " + material.toString() + “.”); } } private ItemStack createMenuItem(Material material, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name.replace(”§“, “&”)); meta.setLore(Collections.singletonList(lore.replace(”§", “&”))); item.setItemMeta(meta); return item; } } добавь в этот код валюту с плагина essentials и сделай чтобы все работало через эту валют и скинь итоговый код.
3321b829ba36011bc9f0ae86e6910c73
{ "intermediate": 0.28867748379707336, "beginner": 0.5273539423942566, "expert": 0.18396858870983124 }
30,755
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; 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; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class BazaarPlugin extends JavaPlugin implements Listener, CommandExecutor { private static final int BASE_COAL_SELL_PRICE = 50; private static final int BASE_STONE_SELL_PRICE = 10; private static final double PRICE_CHANGE_PERCENTAGE = 0.03; private static final double BUY_PRICE_MULTIPLIER = 1.1; private static final double MAX_PRICE_CHANGE_PERCENTAGE = 0.4; private Inventory bazaarMenu; private Map<Player, Inventory> playerMenus; private Map<Material, Double> sellPrices; private Map<UUID, Long> shiftClickCooldowns; @Override public void onEnable() { getCommand(“bazaar”).setExecutor(this); getServer().getPluginManager().registerEvents(this, this); playerMenus = new HashMap<>(); sellPrices = new HashMap<>(); shiftClickCooldowns = new HashMap<>(); // Установка изначальных цен продажи sellPrices.put(Material.COAL, (double) BASE_COAL_SELL_PRICE); sellPrices.put(Material.STONE, (double) BASE_STONE_SELL_PRICE); // Запустить задачу обновления цен каждые 30 секунд new BukkitRunnable() { @Override public void run() { for (Material material : sellPrices.keySet()) { double currentPrice = sellPrices.get(material); double priceChange = PRICE_CHANGE_PERCENTAGE * currentPrice; if (Math.abs(priceChange) / currentPrice > MAX_PRICE_CHANGE_PERCENTAGE) { sellPrices.put(material, (double) ((material == Material.COAL) ? BASE_COAL_SELL_PRICE : BASE_STONE_SELL_PRICE)); } else { double newPrice = currentPrice + priceChange; sellPrices.put(material, newPrice); } } } }.runTaskTimer(this, 0L, 600L); // 20 тиков = 1 секунда, 30 секунд = 600 тиков // Создать базарное меню bazaarMenu = Bukkit.createInventory(null, 9, “Меню базара”); ItemStack coalItem = createMenuItem(Material.COAL, “§cУголь”, “§7Цена продажи: §a” + sellPrices.get(Material.COAL)); ItemStack stoneItem = createMenuItem(Material.STONE, “§7Камень”, “§7Цена продажи: §a” + sellPrices.get(Material.STONE)); bazaarMenu.setItem(0, coalItem); bazaarMenu.setItem(1, stoneItem); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase(“bazaar”)) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(bazaarMenu); playerMenus.put(player, bazaarMenu); } return true; } return false; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); Inventory clickedInventory = event.getClickedInventory(); ItemStack clickedItem = event.getCurrentItem(); if (clickedInventory != null && playerMenus.containsKey(player) && clickedInventory.equals(playerMenus.get(player))) { event.setCancelled(true); if (clickedItem != null && clickedItem.getType() != Material.AIR) { if (clickedItem.getType() == Material.COAL || clickedItem.getType() == Material.STONE) { openBuySellMenu(player, clickedItem.getType()); } } } else if (clickedInventory != null && playerMenus.containsValue(clickedInventory)) { event.setCancelled(true); if (player.isSneaking() && shiftClickCooldowns.getOrDefault(player.getUniqueId(), 0L) < System.currentTimeMillis()) { shiftClickCooldowns.put(player.getUniqueId(), System.currentTimeMillis() + 1000L); if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isRightClick()) { handleSell(player, clickedItem.getType(), 64); } else if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isLeftClick()) { handleBuy(player, clickedItem.getType(), 64); } } } } private void openBuySellMenu(Player player, Material material) { Inventory buySellMenu = Bukkit.createInventory(null, 9, “Меню покупки/продажи”); // Установка цен продажи и покупки double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; ItemStack sellItem = createMenuItem(material, “§6Продажа”, “§7Цена продажи: §a” + sellPrice); ItemStack buyItem = createMenuItem(material, “§aПокупка”, “§7Цена покупки: §e” + buyPrice); buySellMenu.setItem(2, sellItem); buySellMenu.setItem(6, buyItem); player.openInventory(buySellMenu); playerMenus.put(player, buySellMenu); } private void handleSell(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); int sellAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() == material && sellAmount < amount) { if (item.getAmount() <= amount - sellAmount) { sellAmount += item.getAmount(); player.getInventory().remove(item); } else { item.setAmount(item.getAmount() - (amount - sellAmount)); sellAmount = amount; } } } double profit = sellAmount * sellPrice; player.sendMessage(“Продано " + sellAmount + " " + material.toString() + " за " + profit + " монет.”); // Добавьте код здесь для добавления монет в экономику вашего сервера } private void handleBuy(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; double totalCost = amount * buyPrice; if (/* Проверка наличия достаточного количества монет у игрока */) { for (int i = 0; i < amount; i++) { ItemStack item = new ItemStack(material); player.getInventory().addItem(item); } player.sendMessage(“Куплено " + amount + " " + material.toString() + " за " + totalCost + " монет.”); // Удалите код ниже и добавьте код здесь для вычета монет из эконоимки вашего сервера } else { player.sendMessage(“У вас недостаточно монет для покупки " + amount + " " + material.toString() + “.”); } } private ItemStack createMenuItem(Material material, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name.replace(”§“, “&”)); meta.setLore(Collections.singletonList(lore.replace(”§", “&”))); item.setItemMeta(meta); return item; } } добавь в этот код валюту с плагина essentials и сделай чтобы все работало через эту валют и скинь итоговый код. и скажи что нужно сделать чтобы он работал
1f38851e911ec94c8e243794a3db0a74
{ "intermediate": 0.28867748379707336, "beginner": 0.5273539423942566, "expert": 0.18396858870983124 }
30,756
const newsArray = [ new NewsItemServer("2023-11-11", "Новость 1"), new NewsItemServer("2023-11-11", "Новость 2"), new NewsItemServer("2023-11-11", "Новость 3"), new NewsItemServer("2023-11-11", "Новость 4"), new NewsItemServer("2023-11-11", "Новость 5") ]; const Area = require("./Area.js"), { playerJson, battle_items, send } = require("./server"); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require("./LobbyChat"); this.battle_count = 0; this.anticheat = 0; this.newsShown = false; // Флаг, указывающий, были ли новости показаны игроку this.newsShownPlayers = []; // Массив для хранения игроков, которые уже видели новости this.players = []; // Добавьте это } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, "For newbies", "map_sandbox", 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast("create_battle;" + JSON.stringify(battle.toObject())); } } //battle;init_mines;{"mines":[]} getChat() { return this.chat; } getPrefix() { return "lobby"; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast("remove_battle;" + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, "init_effect_model;" + JSON.stringify(effect_model)); this.createBattles(); } sendNews() { const newsJSON = JSON.stringify(newsArray); this.broadcast("show_news;" + newsJSON); for (const player of this.players) { if (!this.newsShownPlayers.includes(player.socket.id)) { this.send(player.socket, "show_news;" + newsJSON); this.newsShownPlayers.push(player.socket.id); // Сохраняем информацию о том, что игрок уже видел новости // Например, сохраняем его в базе данных или файле saveNewsShownPlayer(player.socket.id); } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } if (args.length === 1 && args[0] === "get_data_init_battle_select") { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem("no_supplies"); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, "init_battle_select;" + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === "get_rating") { this.send(socket, "open_rating;" + JSON.stringify( { crystalls: [ { "count": tank.crystals, "rank": tank.rank, "id": tank.name }] })); } else if (args.length === 1 && args[0] === "show_quests") { } if (args[0] === "user_inited") { if (!this.newsShownPlayers.includes(socket.id)) { this.sendNews(); // Отправляем новости только если текущий игрок их еще не видел this.newsShownPlayers.push(socket.id); // Добавляем идентификатор игрока в массив, чтобы пометить, что он уже видел новости } } вот код, проблему напомнияю показывает новости после перезахода игрока так не должно быть они должны пропасть после закрытия до того времени пока не появяться новые. Извините за путаницу, в коде, который вы предоставили, массив newsShownPlayers не имеет значения для перезахода пользователя. Этот массив очищается каждый раз, когда лобби создается снова, и все игроки снова имеют возможность видеть новости. Чтобы исправить это, вам нужно сохранить информацию о том, что игрок уже видел новости, в базе данных или в файле, чтобы ее можно было сохранить между разными сеансами лобби. Вот пример того, как это можно сделать: 1. Внесите изменения в метод sendNews(), чтобы он сохранял информацию о том, что новости были показаны каждому игроку: sendNews() { const newsJSON = JSON.stringify(newsArray); this.broadcast(“show_news;” + newsJSON); for (const player of this.players) { if (!this.newsShownPlayers.includes(player.socket.id)) { this.send(player.socket, “show_news;” + newsJSON); this.newsShownPlayers.push(player.socket.id); // Сохраняем информацию о том, что игрок уже видел новости // Например, сохраняем его в базе данных или файле saveNewsShownPlayer(player.socket.id); } } } 2. В методе onData, когда игрок заходит в лобби, проверьте, были ли новости уже показаны для этого игрока в предыдущих сеансах. Если да, то не вызывайте sendNews() для этого игрока: onData(socket, args) { // … if (args[0] === “user_inited”) { if (!this.newsShownPlayers.includes(socket.id)) { // Проверяем, были ли новости уже показаны для этого игрока ранее const playerNewsShown = checkIfNewsShownPlayerExists(socket.id); if (!playerNewsShown) { this.send вот это твое сообщение но ты почему то оборвался по середине
f2160fe99146189076047ca04db78c84
{ "intermediate": 0.27283549308776855, "beginner": 0.44217902421951294, "expert": 0.2849855124950409 }
30,757
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BarrelController : MonoBehaviour { private bool canPhase = true; private Rigidbody2D rb; public float speed = 1f; private void Awake() { rb = GetComponent<Rigidbody2D>(); } private void Update() { // Check if the barrel’s Y position falls below -10 if (transform.position.y < -10) { Destroy(gameObject); // Destroy the barrel GameObject } } private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.layer == LayerMask.NameToLayer("MidBarrelChute") && canPhase) { float randomChance = Random.Range(0f, 1f); // Get a random value between 0 and 1 if (randomChance <= 0.5f) // 50% chance of not colliding { Physics2D.IgnoreCollision(other, GetComponent<Collider2D>(), true); // Ignore collision } else { // Move down -1 unit transform.position = new Vector2(transform.position.x, transform.position.y - 1f); } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("BarrelChute") && canPhase) { // Move down -1 unit transform.position = new Vector2(transform.position.x, transform.position.y - 1f); } if (collision.gameObject.layer == LayerMask.NameToLayer("Platform")) { rb.AddForce(collision.transform.right * speed, ForceMode2D.Impulse); } } } make it so that if the barrel collides with the oil drum game object (set to OilDrum layer) the barrel will be destroyed
4e2f100313f4eab1816df244fbd8e555
{ "intermediate": 0.41474097967147827, "beginner": 0.317890465259552, "expert": 0.2673685550689697 }
30,758
import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; 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; import org.bukkit.scheduler.BukkitRunnable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class BazaarPlugin extends JavaPlugin implements Listener, CommandExecutor { private static final int BASE_COAL_SELL_PRICE = 50; private static final int BASE_STONE_SELL_PRICE = 10; private static final double PRICE_CHANGE_PERCENTAGE = 0.03; private static final double BUY_PRICE_MULTIPLIER = 1.1; private static final double MAX_PRICE_CHANGE_PERCENTAGE = 0.4; private Inventory bazaarMenu; private Map<Player, Inventory> playerMenus; private Map<Material, Double> sellPrices; private Map<UUID, Long> shiftClickCooldowns; @Override public void onEnable() { getCommand(“bazaar”).setExecutor(this); getServer().getPluginManager().registerEvents(this, this); playerMenus = new HashMap<>(); sellPrices = new HashMap<>(); shiftClickCooldowns = new HashMap<>(); // Установка изначальных цен продажи sellPrices.put(Material.COAL, (double) BASE_COAL_SELL_PRICE); sellPrices.put(Material.STONE, (double) BASE_STONE_SELL_PRICE); // Запустить задачу обновления цен каждые 30 секунд new BukkitRunnable() { @Override public void run() { for (Material material : sellPrices.keySet()) { double currentPrice = sellPrices.get(material); double priceChange = PRICE_CHANGE_PERCENTAGE * currentPrice; if (Math.abs(priceChange) / currentPrice > MAX_PRICE_CHANGE_PERCENTAGE) { sellPrices.put(material, (double) ((material == Material.COAL) ? BASE_COAL_SELL_PRICE : BASE_STONE_SELL_PRICE)); } else { double newPrice = currentPrice + priceChange; sellPrices.put(material, newPrice); } } } }.runTaskTimer(this, 0L, 600L); // 20 тиков = 1 секунда, 30 секунд = 600 тиков // Создать базарное меню bazaarMenu = Bukkit.createInventory(null, 9, “Меню базара”); ItemStack coalItem = createMenuItem(Material.COAL, “§cУголь”, “§7Цена продажи: §a” + sellPrices.get(Material.COAL)); ItemStack stoneItem = createMenuItem(Material.STONE, “§7Камень”, “§7Цена продажи: §a” + sellPrices.get(Material.STONE)); bazaarMenu.setItem(0, coalItem); bazaarMenu.setItem(1, stoneItem); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase(“bazaar”)) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(bazaarMenu); playerMenus.put(player, bazaarMenu); } return true; } return false; } @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); Inventory clickedInventory = event.getClickedInventory(); ItemStack clickedItem = event.getCurrentItem(); if (clickedInventory != null && playerMenus.containsKey(player) && clickedInventory.equals(playerMenus.get(player))) { event.setCancelled(true); if (clickedItem != null && clickedItem.getType() != Material.AIR) { if (clickedItem.getType() == Material.COAL || clickedItem.getType() == Material.STONE) { openBuySellMenu(player, clickedItem.getType()); } } } else if (clickedInventory != null && playerMenus.containsValue(clickedInventory)) { event.setCancelled(true); if (player.isSneaking() && shiftClickCooldowns.getOrDefault(player.getUniqueId(), 0L) < System.currentTimeMillis()) { shiftClickCooldowns.put(player.getUniqueId(), System.currentTimeMillis() + 1000L); if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isRightClick()) { handleSell(player, clickedItem.getType(), 64); } else if (clickedItem != null && clickedItem.getType() != Material.AIR && event.isLeftClick()) { handleBuy(player, clickedItem.getType(), 64); } } } } private void openBuySellMenu(Player player, Material material) { Inventory buySellMenu = Bukkit.createInventory(null, 9, “Меню покупки/продажи”); // Установка цен продажи и покупки double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; ItemStack sellItem = createMenuItem(material, “§6Продажа”, “§7Цена продажи: §a” + sellPrice); ItemStack buyItem = createMenuItem(material, “§aПокупка”, “§7Цена покупки: §e” + buyPrice); buySellMenu.setItem(2, sellItem); buySellMenu.setItem(6, buyItem); player.openInventory(buySellMenu); playerMenus.put(player, buySellMenu); } private void handleSell(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); int sellAmount = 0; for (ItemStack item : player.getInventory().getContents()) { if (item != null && item.getType() == material && sellAmount < amount) { if (item.getAmount() <= amount - sellAmount) { sellAmount += item.getAmount(); player.getInventory().remove(item); } else { item.setAmount(item.getAmount() - (amount - sellAmount)); sellAmount = amount; } } } double profit = sellAmount * sellPrice; player.sendMessage(“Продано " + sellAmount + " " + material.toString() + " за " + profit + " монет.”); // Добавьте код здесь для добавления монет в экономику вашего сервера } private void handleBuy(Player player, Material material, int amount) { double sellPrice = sellPrices.get(material); double buyPrice = sellPrice * BUY_PRICE_MULTIPLIER; double totalCost = amount * buyPrice; if (/* Проверка наличия достаточного количества монет у игрока */) { for (int i = 0; i < amount; i++) { ItemStack item = new ItemStack(material); player.getInventory().addItem(item); } player.sendMessage(“Куплено " + amount + " " + material.toString() + " за " + totalCost + " монет.”); // Удалите код ниже и добавьте код здесь для вычета монет из эконоимки вашего сервера } else { player.sendMessage(“У вас недостаточно монет для покупки " + amount + " " + material.toString() + “.”); } } private ItemStack createMenuItem(Material material, String name, String lore) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); meta.setDisplayName(name.replace(”§“, “&”)); meta.setLore(Collections.singletonList(lore.replace(”§", “&”))); item.setItemMeta(meta); return item; } } добавь в этот код валюту с плагина essentials и сделай чтобы все работало через эту валют и скинь итоговый код.
e8b3b79b65bbdafa66ad4bd907a71ba1
{ "intermediate": 0.28867748379707336, "beginner": 0.5273539423942566, "expert": 0.18396858870983124 }
30,759
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>foleon</groupId> <artifactId>bazaar</artifactId> <version>1.0</version> <packaging>jar</packaging> <name>bazaar</name> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.2.4</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <createDependencyReducedPom>false</createDependencyReducedPom> </configuration> </execution> </executions> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> <repositories> <repository> <id>spigotmc-repo</id> <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url> </repository> <repository> <id>sonatype</id> <url>https://oss.sonatype.org/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.spigotmc</groupId> <artifactId>spigot-api</artifactId> <version>1.12.2-R0.1-SNAPSHOT</version> <scope>provided</scope> </dependency> </dependencies> </project> это код моего плагина файла pom.mxl (bazaar) , можешь добавить туда возможность использовать плагин essentials 1.12.2?
6716d29f7be027fce6dbd0e6faada4a5
{ "intermediate": 0.32363399863243103, "beginner": 0.5443893074989319, "expert": 0.13197673857212067 }
30,760
Write a C++ program. Initialize a 2d array (3x10) when declaring as follows: {{1,2,3,4,5,1,2,3,4,5},{1,0,1,0,1,0,1,0,1,0},{5,4,3,2,1,5,4,3,2,1}}. Use a function to print it. Rows and columns are const values
5cf721e98eb9cd982eb72e469cf46c9b
{ "intermediate": 0.17672786116600037, "beginner": 0.6612570881843567, "expert": 0.16201506555080414 }
30,761
Write a class StringLength.java with a class method stringLength() that takes a String as parameter and returns the length of your string with the following return value: “Your string is <length of the String> characters long” (Hint: <length of the String> to be replaced with the actual length of the string). Use an instance method of the class String in your method. Run and test the method. without scanner and shortly please
d9cce4b604d80ec2721bbe80662ccd2c
{ "intermediate": 0.3181852698326111, "beginner": 0.5166362524032593, "expert": 0.16517852246761322 }
30,762
const fs = require(‘file-system’); const convert = require(‘xml-js’), md5 = require(“md5-hex”); const { battle_items, maps, isset, search } = require(“./server”); class Map { constructor(map_id) { var found = true; for (var i in battle_items) { if (battle_items[i].id === map_id) found = battle_items[i]; } if (found === true) throw new Error(“Map ID: " + map_id + " doesnt exist.”); this.skybox_id = found.skyboxId; this.theme_name = found.themeName; this.dom = !!found.dom; this.game_mode = found.gameMode; this.ctf = !!found.ctf; this.min_rank = found.minRank; this.name = found.name; this.id = map_id; this.sound = “default_ambient_sound”; if(map_id.split(“_space”).length == 2) { this.sound = “space_ambient_sound”; } this.max_people = found.maxPeople; this.tdm = !!found.tdm; this.max_rank = found.maxRank; var file = fs.readFileSync(“maps/” + map_id + “.xml”, “utf8”); this.xml = convert.xml2js(file, { compact: false, spaces: 4 }); this.md5_hash = md5(file); } getFlagPosition(team = false) { try { var xml = this.xml; if (isset(xml.elements) && isset(xml.elements[0].elements)) { var e = search(“ctf-flags”, xml.elements[0].elements); for (var i in e.elements) { if (e.elements[i].name === “flag-” + (team ? “red” : “blue”)) { return this.parsePosition(e.elements[i].elements); } } } } catch { } return null; } getDOMPointsCount(){ var xml = this.xml; if (isset(xml.elements) && isset(xml.elements[0].elements)) { var e = search(“dom-keypoints”, xml.elements[0].elements); return e.elements.length; } } getDOMPoint(id) { var xml = this.xml; var point = null; if (isset(xml.elements) && isset(xml.elements[0].elements)) { var e = search(“dom-keypoints”, xml.elements[0].elements); if (e.elements[id].name === “dom-keypoint”) { point = this.parsePosition(e.elements[id].elements[0].elements); } } return point; } getSpawnPoints(filters = []) { var xml = this.xml; var points = []; var e = search(“spawn-points”, xml.elements[0].elements); for (var i in e.elements) points.push(this.parseSpawnPoint(e.elements[i])); if (filters.length > 0) { var new_points = []; for (var i in points) if (filters.includes(points[i].type)) new_points.push(points[i]); return new_points; } return points; } parseSpawnPoint(data) { var position = { x: 0, y: 0, z: 0 }; var rotation = { z: 0 }; var type = null; if (data.name === “spawn-point”) { var type = data.attributes.type; for (var i in data.elements) { if (data.elements[i].name === “position”) position = this.parsePosition(data.elements[i].elements); else if (data.elements[i].name === “rotation”) rotation.z = parseFloat(data.elements[i].elements[0].elements[0].text); } } return { position: position, rotation: rotation, type: type }; } getBonusRegions(filters = []) { var xml = this.xml; var regions = []; var e = search(“bonus-regions”, xml.elements[0].elements); for (var i in e.elements) regions.push(this.parseRegion(e.elements[i])); if (filters.length > 0) { var new_regions = []; for (var i in regions) for (var j in regions[i].types) if (filters.includes(regions[i].types[j])) new_regions.push(regions[i]); return new_regions; } return regions; } parseRegion(data) { var types = []; var min = {}; var max = {}; if (data.name === “bonus-region”) { for (var i in data.elements) { if (data.elements[i].name === “bonus-type”) types.push(data.elements[i].elements[0].text); else if (data.elements[i].name === “min”) min = this.parsePosition(data.elements[i].elements); else if (data.elements[i].name === “max”) max = this.parsePosition(data.elements[i].elements); } } return { min: min, max: max, rotation: { z: 0.000 }, types: types }; } parsePosition(data) { return { x: parseFloat(data[0].elements[0].text), y: parseFloat(data[1].elements[0].text), z: parseFloat(data[2].elements[0].text) }; } 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 }; } } exports.Map = Map; как по истечению kick_period_ms: 300000, сделать кик игрока с сервера, вот команда для кика tank.kick();
5f7d3271a9727be81fb1d3124d7d5d26
{ "intermediate": 0.30967977643013, "beginner": 0.5348944067955017, "expert": 0.1554258167743683 }
30,763
Fix my C++ code. #include <iostream> const int ROWS = 3; const int COLS = 10; void printArray(const int* arr, int rows, int cols) { const int (a)[cols] = reinterpret_cast<const int ()[cols]>(arr); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { std::cout << a[i][j] << " "; } std::cout << std::endl; } } int main() { int arr[ROWS][COLS] = {{1, 2, 3, 4, 5, 1, 2, 3, 4, 5}, {1, 0, 1, 0, 1, 0, 1, 0, 1, 0}, {5, 4, 3, 2, 1, 5, 4, 3, 2, 1}}; // Print the array printArray(reinterpret_cast<int*>(arr), ROWS, COLS); return 0; }
5f764a02b0230ac5b6a8b346475992a6
{ "intermediate": 0.3235359191894531, "beginner": 0.48521605134010315, "expert": 0.1912480741739273 }
30,764
using puppeteer make a bot that in a loop goes to https://octocaptcha.com/, waits for an element with id FunCaptcha-Token, then gets the value. that value you split by a vertical bar "|" and save the first element.
2a0d7faa1099363339127c907ab5428f
{ "intermediate": 0.3715602159500122, "beginner": 0.25916609168052673, "expert": 0.36927369236946106 }
30,765
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MarioController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; public float ladderClimbSpeed = 2f; public int maxHealth = 3; private int currentHealth; private bool grounded; private bool onLadder; private bool climbingLadder; private Vector2 direction; private Rigidbody2D rb2d; private new Collider2D collider; private Collider2D[] results; private int currentSceneIndex; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); results = new Collider2D[4]; } private void Start() { currentHealth = maxHealth; currentSceneIndex = SceneManager.GetActiveScene().buildIndex; } private void CheckCollision() { grounded = false; onLadder = false; Vector2 size = collider.bounds.size; size.y += 0.1f; size.x /= 2f; int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results); for (int i = 0; i < amount; i++) { GameObject hit = results[i].gameObject; if (hit.layer == LayerMask.NameToLayer("Platform")) { grounded = hit.transform.position.y < (transform.position.y - 0.5f); } else if (hit.layer == LayerMask.NameToLayer("Ladder")) { onLadder = true; } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel")) { currentHealth--; ResetScene(); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Win")) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ResetScene() { if (currentSceneIndex == 0) { SceneManager.LoadScene("_Scene_DonkeyKong25M2"); } else if (currentSceneIndex == 1) { SceneManager.LoadScene("_Scene_DonkeyKong25M3"); } else if (currentSceneIndex == 2) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void Update() { CheckCollision(); if (grounded && Input.GetButtonDown("Jump")) { rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce); } float movement = Input.GetAxis("Horizontal"); if (grounded) { direction.y = Mathf.Max(direction.y, -1f); climbingLadder = false; } if (onLadder && Input.GetButton("Vertical")) { climbingLadder = true; float climbDirection = Input.GetAxis("Vertical"); rb2d.velocity = new Vector2(0, climbDirection * ladderClimbSpeed); rb2d.gravityScale = 0f; } else if (climbingLadder) { rb2d.gravityScale = 1f; rb2d.velocity = new Vector2(rb2d.velocity.x, 0f); rb2d.constraints = RigidbodyConstraints2D.FreezePositionX; } else { rb2d.gravityScale = 1f; rb2d.constraints = RigidbodyConstraints2D.FreezeRotation; } rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y); if (movement > 0) { transform.localScale = new Vector3(1f, 1f, 1f); } else if (movement < 0) { transform.localScale = new Vector3(-1f, 1f, 1f); } } } make it so if mario collides with the hammer game object (set to hammer layer), the hammer game object is destroyed and for 9 seconds any barrels that collide with mario are destroyed and mario will not lose health
c157c6dfa17279782b70700ddc083d52
{ "intermediate": 0.27622413635253906, "beginner": 0.5579745769500732, "expert": 0.1658012419939041 }
30,766
import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class ClanPlugin extends JavaPlugin { private FileConfiguration config; private List<Clan> clans = new ArrayList<>(); @Override public void onEnable() { // Загрузка конфигурации config = getConfig(); // Устанавливаем базовые значения config.addDefault(“baseLevel”, 1); config.addDefault(“baseExp”, 0); // Сохраняем конфигурацию config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { // Сохраняем конфигурацию при выключении плагина saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase(“clan”)) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + “Используйте /clan create, /clan invite, /clan accept, /clan kick или /clan disband.”); return true; } String subCommand = args[0]; if (subCommand.equalsIgnoreCase(“create”)) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + “Используйте /clan create <название клана>”); return true; } String clanName = args[1]; if (clanName.length() > 16) { sender.sendMessage(ChatColor.RED + “Название клана не должно превышать 16 символов.”); return true; } // Проверяем на уникальность название клана if (clanExists(clanName)) { sender.sendMessage(ChatColor.RED + “Клан с таким названием уже существует.”); return true; } // Создаем новый клан и добавляем его в список кланов Clan newClan = new Clan(clanName); clans.add(newClan); sender.sendMessage(ChatColor.GREEN + “Клан " + clanName + " успешно создан.”); return true; } else if (subCommand.equalsIgnoreCase(“invite”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan invite <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок if (playerExists(playerName)) { player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " приглашен в клан.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не существует.”); return true; } } else if (subCommand.equalsIgnoreCase(“accept”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, есть ли у игрока приглашение if (hasInvite(player.getName())) { // Добавляем игрока в клан addPlayerToClan(player.getName(), getPlayerClanInvites(player.getName())); player.sendMessage(ChatColor.GREEN + “Вы присоединились к клану.”); return true; } else { player.sendMessage(ChatColor.RED + “У вас нет приглашений в клан.”); return true; } } else if (subCommand.equalsIgnoreCase(“kick”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan kick <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок в клане if (playerExistsInClan(playerName, getPlayerClan(player.getName()))) { removePlayerFromClan(playerName); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " исключен из клана.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не найден в клане.”); return true; } } else if (subCommand.equalsIgnoreCase(“disband”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, является ли игрок лидером клана if (isClanLeader(player.getName())) { // Расформировываем клан disbandClan(getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Клан расформирован.”); return true; } else { player.sendMessage(ChatColor.RED + “Вы не являетесь лидером клана.”); return true; } } } return false; } private boolean clanExists(String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { return true; } } return false; } private boolean playerExists(String playerName) { // Проверяем, существует ли игрок в игре // … } private boolean hasInvite(String playerName) { // Проверяем, есть ли у игрока приглашение в клан // … } private String getPlayerClanInvites(String playerName) { // Получаем список приглашений для игрока // … } private void addPlayerToClan(String playerName, String clanName) { // Добавляем игрока в клан // … } private void removePlayerFromClan(String playerName) { // Удаляем игрока из клана // … } private boolean playerExistsInClan(String playerName, String clanName) { // Проверяем, существует ли игрок в конкретном клане // … } private boolean isClanLeader(String playerName) { // Проверяем, является ли игрок лидером клана // … } private String getPlayerClan(String playerName) { // Получаем клан, в котором состоит игрок // … } private void disbandClan(String clanName) { // Убираем клан из списка кланов и удаляем его из конфигурационного файла // … } private class Clan { private String name; private List<String> members = new ArrayList<>(); public Clan(String name) { this.name = name; } public String getName() { return name; } public List<String> getMembers() { return members; } } } добавь все проверки
de9ed98703db40f55d82777d7a9b7176
{ "intermediate": 0.2992398738861084, "beginner": 0.5419837832450867, "expert": 0.15877629816532135 }
30,767
import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class ClanPlugin extends JavaPlugin { private FileConfiguration config; private List<Clan> clans = new ArrayList<>(); @Override public void onEnable() { // Загрузка конфигурации config = getConfig(); // Устанавливаем базовые значения config.addDefault(“baseLevel”, 1); config.addDefault(“baseExp”, 0); // Сохраняем конфигурацию config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { // Сохраняем конфигурацию при выключении плагина saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase(“clan”)) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + “Используйте /clan create, /clan invite, /clan accept, /clan kick или /clan disband.”); return true; } String subCommand = args[0]; if (subCommand.equalsIgnoreCase(“create”)) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + “Используйте /clan create <название клана>”); return true; } String clanName = args[1]; if (clanName.length() > 16) { sender.sendMessage(ChatColor.RED + “Название клана не должно превышать 16 символов.”); return true; } // Проверяем на уникальность название клана if (clanExists(clanName)) { sender.sendMessage(ChatColor.RED + “Клан с таким названием уже существует.”); return true; } // Создаем новый клан и добавляем его в список кланов Clan newClan = new Clan(clanName); clans.add(newClan); sender.sendMessage(ChatColor.GREEN + “Клан " + clanName + " успешно создан.”); return true; } else if (subCommand.equalsIgnoreCase(“invite”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan invite <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок if (!playerExists(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не существует.”); return true; } // Проверяем, не находится ли игрок уже в клане if (isPlayerInClan(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " уже состоит в клане.”); return true; } // Проверяем, не было ли уже отправлено приглашение этому игроку if (hasInvite(playerName)) { player.sendMessage(ChatColor.RED + "Приглашение уже отправлено игроку " + playerName + “.”); return true; } // Отправляем приглашение игроку sendInvite(playerName, getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " приглашен в клан.”); return true; } else if (subCommand.equalsIgnoreCase(“accept”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, есть ли у игрока приглашение if (hasInvite(player.getName())) { // Добавляем игрока в клан addPlayerToClan(player.getName(), getPlayerClanInvites(player.getName())); player.sendMessage(ChatColor.GREEN + “Вы присоединились к клану.”); return true; } else { player.sendMessage(ChatColor.RED + “У вас нет приглашений в клан.”); return true; } } else if (subCommand.equalsIgnoreCase(“kick”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan kick <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок в клане if (playerExistsInClan(playerName, getPlayerClan(player.getName()))) { removePlayerFromClan(playerName); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " исключен из клана.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не найден в клане.”); return true; } } else if (subCommand.equalsIgnoreCase(“disband”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, является ли игрок лидером клана if (isClanLeader(player.getName())) { // Расформировываем клан disbandClan(getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Клан расформирован.”); return true; } else { player.sendMessage(ChatColor.RED + “Вы не являетесь лидером клана.”); return true; } } } return false; } private boolean clanExists(String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { return true; } } return false; } private boolean playerExists(String playerName) { // Проверяем, существует ли игрок в игре // … } private boolean isPlayerInClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean hasInvite(String playerName) { // Проверяем, есть ли у игрока приглашение в клан // … } private String getPlayerClanInvites(String playerName) { // Получаем список приглашений для игрока // … } private void sendInvite(String playerName, String clanName) { // Отправляем приглашение игроку // … } private void addPlayerToClan(String playerName, String clanName) { // Добавляем игрока в клан // … } private void removePlayerFromClan(String playerName) { // Удаляем игрока из клана // … } private boolean playerExistsInClan(String playerName, String clanName) { // Проверяем, существует ли игрок в конкретном клане // … } private boolean isClanLeader(String playerName) { // Проверяем, является ли игрок лидером клана // … } private String getPlayerClan(String playerName) { // Получаем клан, в котором состоит игрок // … } private void disbandClan(String clanName) { // Убираем клан из списка кланов и удаляем его из конфигурационного файла // … } private class Clan { private String name; private List<String> members = new ArrayList<>(); public Clan(String name) { this.name = name; } public String getName() { return name; } public List<String> getMembers() { return members; } } } допиши код
f87840d620e3ec175a65749c7bb0a53f
{ "intermediate": 0.2992398738861084, "beginner": 0.5419837832450867, "expert": 0.15877629816532135 }
30,768
import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class ClanPlugin extends JavaPlugin { private FileConfiguration config; private List<Clan> clans = new ArrayList<>(); @Override public void onEnable() { // Загрузка конфигурации config = getConfig(); // Устанавливаем базовые значения config.addDefault(“baseLevel”, 1); config.addDefault(“baseExp”, 0); // Сохраняем конфигурацию config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { // Сохраняем конфигурацию при выключении плагина saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase(“clan”)) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + “Используйте /clan create, /clan invite, /clan accept, /clan kick или /clan disband.”); return true; } String subCommand = args[0]; if (subCommand.equalsIgnoreCase(“create”)) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + “Используйте /clan create <название клана>”); return true; } String clanName = args[1]; if (clanName.length() > 16) { sender.sendMessage(ChatColor.RED + “Название клана не должно превышать 16 символов.”); return true; } // Проверяем на уникальность название клана if (clanExists(clanName)) { sender.sendMessage(ChatColor.RED + “Клан с таким названием уже существует.”); return true; } // Создаем новый клан и добавляем его в список кланов Clan newClan = new Clan(clanName); clans.add(newClan); sender.sendMessage(ChatColor.GREEN + “Клан " + clanName + " успешно создан.”); return true; } else if (subCommand.equalsIgnoreCase(“invite”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan invite <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок if (!playerExists(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не существует.”); return true; } // Проверяем, не находится ли игрок уже в клане if (isPlayerInClan(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " уже состоит в клане.”); return true; } // Проверяем, не было ли уже отправлено приглашение этому игроку if (hasInvite(playerName)) { player.sendMessage(ChatColor.RED + "Приглашение уже отправлено игроку " + playerName + “.”); return true; } // Отправляем приглашение игроку sendInvite(playerName, getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " приглашен в клан.”); return true; } else if (subCommand.equalsIgnoreCase(“accept”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, есть ли у игрока приглашение if (hasInvite(player.getName())) { // Добавляем игрока в клан addPlayerToClan(player.getName(), getPlayerClanInvites(player.getName())); player.sendMessage(ChatColor.GREEN + “Вы присоединились к клану.”); return true; } else { player.sendMessage(ChatColor.RED + “У вас нет приглашений в клан.”); return true; } } else if (subCommand.equalsIgnoreCase(“kick”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan kick <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок в клане if (playerExistsInClan(playerName, getPlayerClan(player.getName()))) { removePlayerFromClan(playerName); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " исключен из клана.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не найден в клане.”); return true; } } else if (subCommand.equalsIgnoreCase(“disband”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, является ли игрок лидером клана if (isClanLeader(player.getName())) { // Расформировываем клан disbandClan(getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Клан расформирован.”); return true; } else { player.sendMessage(ChatColor.RED + “Вы не являетесь лидером клана.”); return true; } } } return false; } private boolean clanExists(String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { return true; } } return false; } private boolean playerExists(String playerName) { // Проверяем, существует ли игрок в игре // … } private boolean isPlayerInClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean hasInvite(String playerName) { // Проверяем, есть ли у игрока приглашение в клан // … } private String getPlayerClanInvites(String playerName) { // Получаем список приглашений для игрока // … } private void sendInvite(String playerName, String clanName) { // Отправляем приглашение игроку // … } private void addPlayerToClan(String playerName, String clanName) { // Добавляем игрока в клан // … } private void removePlayerFromClan(String playerName) { // Удаляем игрока из клана // … } private boolean playerExistsInClan(String playerName, String clanName) { // Проверяем, существует ли игрок в конкретном клане // … } private boolean isClanLeader(String playerName) { // Проверяем, является ли игрок лидером клана // … } private String getPlayerClan(String playerName) { // Получаем клан, в котором состоит игрок // … } private void disbandClan(String clanName) { // Убираем клан из списка кланов и удаляем его из конфигурационного файла // … } private class Clan { private String name; private List<String> members = new ArrayList<>(); public Clan(String name) { this.name = name; } public String getName() { return name; } public List<String> getMembers() { return members; } } } допиши код и скинь итог
c0fe7625f3537d652a0017a6b2e8668d
{ "intermediate": 0.2992398738861084, "beginner": 0.5419837832450867, "expert": 0.15877629816532135 }
30,769
package foleon.mmsoclans; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Mmsoclan extends JavaPlugin { private FileConfiguration config; private List<Clan> clans = new ArrayList<>(); private Map<String, String> invites = new HashMap<>(); @Override public void onEnable() { // Загрузка конфигурации config = getConfig(); // Устанавливаем базовые значения config.addDefault("baseLevel", 1); config.addDefault("baseExp", 0); // Сохраняем конфигурацию config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { // Сохраняем конфигурацию при выключении плагина saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase(“clan”)) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + “Используйте /clan create, /clan invite, /clan accept, /clan kick или /clan disband.”); return true; } String subCommand = args[0]; if (subCommand.equalsIgnoreCase(“create”)) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + “Используйте /clan create <название клана>”); return true; } String clanName = args[1]; if (clanName.length() > 16) { sender.sendMessage(ChatColor.RED + “Название клана не должно превышать 16 символов.”); return true; } // Проверяем на уникальность название клана if (clanExists(clanName)) { sender.sendMessage(ChatColor.RED + “Клан с таким названием уже существует.”); return true; } // Создаем новый клан и добавляем его в список кланов Clan newClan = new Clan(clanName); clans.add(newClan); sender.sendMessage(ChatColor.GREEN + “Клан " + clanName + " успешно создан.”); return true; } else if (subCommand.equalsIgnoreCase(“invite”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan invite <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок if (!playerExists(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не существует.”); return true; } // Проверяем, не находится ли игрок уже в клане if (isPlayerInClan(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " уже состоит в клане.”); return true; } // Проверяем, не было ли уже отправлено приглашение этому игроку if (hasInvite(playerName)) { player.sendMessage(ChatColor.RED + "Приглашение уже отправлено игроку " + playerName + “.”); return true; } // Отправляем приглашение игроку sendInvite(playerName, getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " приглашен в клан.”); return true; } else if (subCommand.equalsIgnoreCase(“accept”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, есть ли у игрока приглашение if (hasInvite(player.getName())) { // Добавляем игрока в клан addPlayerToClan(player.getName(), getPlayerClanInvites(player.getName())); player.sendMessage(ChatColor.GREEN + “Вы присоединились к клану.”); return true; } else { player.sendMessage(ChatColor.RED + “У вас нет приглашений в клан.”); return true; } } else if (subCommand.equalsIgnoreCase(“kick”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan kick <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок в клане if (playerExistsInClan(playerName, getPlayerClan(player.getName()))) { removePlayerFromClan(playerName); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " исключен из клана.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не найден в клане.”); return true; } } else if (subCommand.equalsIgnoreCase(“disband”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, является ли игрок лидером клана if (isClanLeader(player.getName())) { // Расформировываем клан disbandClan(getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Клан расформирован.”); return true; } else { player.sendMessage(ChatColor.RED + “Вы не являетесь лидером клана.”); return true; } } } return false; } private boolean clanExists(String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { return true; } } return false; } private boolean playerExists(String playerName) { // Проверяем, существует ли игрок в игре // … } private boolean isPlayerInClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean hasInvite(String playerName) { return invites.containsKey(playerName); } private String getPlayerClanInvites(String playerName) { return invites.get(playerName); } private void sendInvite(String playerName, String clanName) { invites.put(playerName, clanName); } private void addPlayerToClan(String playerName, String clanName) { // Проверка на существование клана и игрока for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { clan.getMembers().add(playerName); break; } } } private void removePlayerFromClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { clan.getMembers().remove(playerName); break; } } } private boolean playerExistsInClan(String playerName, String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName) && clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean isClanLeader(String playerName) { for (Clan clan : clans) { if (clan.getMembers().get(0).equalsIgnoreCase(playerName)) { return true; } } return false; } private String getPlayerClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return clan.getName(); } } return null; } private void disbandClan(String clanName) { Clan clanToRemove = null; for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { clanToRemove = clan; break; } } if (clanToRemove != null) { clans.remove(clanToRemove); } } private class Clan { private String name; private List<String> members = new ArrayList<>(); public Clan(String name) { this.name = name; } public String getName() { return name; } public List<String> getMembers() { return members; } } } допиши весь код и скинь полный код.
b7b83016f7432e36dfd733bcb6d401b0
{ "intermediate": 0.22131870687007904, "beginner": 0.5924615263938904, "expert": 0.18621979653835297 }
30,770
package foleon.mmsoclans; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Mmsoclan extends JavaPlugin { private FileConfiguration config; private List<Clan> clans = new ArrayList<>(); private Map<String, String> invites = new HashMap<>(); @Override public void onEnable() { // Загрузка конфигурации config = getConfig(); // Устанавливаем базовые значения config.addDefault(“baseLevel”, 1); config.addDefault(“baseExp”, 0); // Сохраняем конфигурацию config.options().copyDefaults(true); saveConfig(); } @Override public void onDisable() { // Сохраняем конфигурацию при выключении плагина saveConfig(); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase(“clan”)) { if (args.length == 0) { sender.sendMessage(ChatColor.RED + “Используйте /clan create, /clan invite, /clan accept, /clan kick или /clan disband.”); return true; } String subCommand = args[0]; if (subCommand.equalsIgnoreCase(“create”)) { if (args.length < 2) { sender.sendMessage(ChatColor.RED + “Используйте /clan create <название клана>”); return true; } String clanName = args[1]; if (clanName.length() > 16) { sender.sendMessage(ChatColor.RED + “Название клана не должно превышать 16 символов.”); return true; } // Проверяем на уникальность название клана if (clanExists(clanName)) { sender.sendMessage(ChatColor.RED + “Клан с таким названием уже существует.”); return true; } // Создаем новый клан и добавляем его в список кланов Clan newClan = new Clan(clanName); clans.add(newClan); sender.sendMessage(ChatColor.GREEN + “Клан " + clanName + " успешно создан.”); return true; } else if (subCommand.equalsIgnoreCase(“invite”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan invite <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок if (!playerExists(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не существует.”); return true; } // Проверяем, не находится ли игрок уже в клане if (isPlayerInClan(playerName)) { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " уже состоит в клане.”); return true; } // Проверяем, не было ли уже отправлено приглашение этому игроку if (hasInvite(playerName)) { player.sendMessage(ChatColor.RED + "Приглашение уже отправлено игроку " + playerName + “.”); return true; } // Отправляем приглашение игроку sendInvite(playerName, getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " приглашен в клан.”); return true; } else if (subCommand.equalsIgnoreCase(“accept”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, есть ли у игрока приглашение if (hasInvite(player.getName())) { // Добавляем игрока в клан addPlayerToClan(player.getName(), getPlayerClanInvites(player.getName())); player.sendMessage(ChatColor.GREEN + “Вы присоединились к клану.”); return true; } else { player.sendMessage(ChatColor.RED + “У вас нет приглашений в клан.”); return true; } } else if (subCommand.equalsIgnoreCase(“kick”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; if (args.length < 2) { player.sendMessage(ChatColor.RED + “Используйте /clan kick <игрок>”); return true; } String playerName = args[1]; // Проверяем, существует ли игрок в клане if (playerExistsInClan(playerName, getPlayerClan(player.getName()))) { removePlayerFromClan(playerName); player.sendMessage(ChatColor.GREEN + “Игрок " + playerName + " исключен из клана.”); return true; } else { player.sendMessage(ChatColor.RED + “Игрок " + playerName + " не найден в клане.”); return true; } } else if (subCommand.equalsIgnoreCase(“disband”)) { if (!(sender instanceof Player)) { sender.sendMessage(ChatColor.RED + “Только игроки могут использовать эту команду.”); return true; } Player player = (Player) sender; // Проверяем, является ли игрок лидером клана if (isClanLeader(player.getName())) { // Расформировываем клан disbandClan(getPlayerClan(player.getName())); player.sendMessage(ChatColor.GREEN + “Клан расформирован.”); return true; } else { player.sendMessage(ChatColor.RED + “Вы не являетесь лидером клана.”); return true; } } } return false; } private boolean clanExists(String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { return true; } } return false; } private boolean playerExists(String playerName) { // Проверяем, существует ли игрок в игре // … } private boolean isPlayerInClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean hasInvite(String playerName) { return invites.containsKey(playerName); } private String getPlayerClanInvites(String playerName) { return invites.get(playerName); } private void sendInvite(String playerName, String clanName) { invites.put(playerName, clanName); } private void addPlayerToClan(String playerName, String clanName) { // Проверка на существование клана и игрока for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { clan.getMembers().add(playerName); break; } } } private void removePlayerFromClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { clan.getMembers().remove(playerName); break; } } } private boolean playerExistsInClan(String playerName, String clanName) { for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName) && clan.getMembers().contains(playerName)) { return true; } } return false; } private boolean isClanLeader(String playerName) { for (Clan clan : clans) { if (clan.getMembers().get(0).equalsIgnoreCase(playerName)) { return true; } } return false; } private String getPlayerClan(String playerName) { for (Clan clan : clans) { if (clan.getMembers().contains(playerName)) { return clan.getName(); } } return null; } private void disbandClan(String clanName) { Clan clanToRemove = null; for (Clan clan : clans) { if (clan.getName().equalsIgnoreCase(clanName)) { clanToRemove = clan; break; } } if (clanToRemove != null) { clans.remove(clanToRemove); } } private class Clan { private String name; private List<String> members = new ArrayList<>(); public Clan(String name) { this.name = name; } public String getName() { return name; } public List<String> getMembers() { return members; } } } допиши весь код и скинь полный код. Добавь функции которые я не добавил
8e5116f0d6213ddb5dc3d46765f69c38
{ "intermediate": 0.30792585015296936, "beginner": 0.46519413590431213, "expert": 0.2268800288438797 }
30,771
hi
ab1c2e67e489f568039164f1c40cefc7
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
30,772
Act as a web developer. Use javascript language to create an east Africa map with MGRS coordinates. The map should be in a shapefile file format.
79383266e8e45b17f0e31723b0db2c2a
{ "intermediate": 0.38489866256713867, "beginner": 0.2622855603694916, "expert": 0.35281580686569214 }
30,773
package alternativa.tanks.model.gift.server { public class GiftServerItem { public var id:String; public var rare:int; public var count:int; public function GiftServerItem(id:String, rare:int, count:int) { super(); this.id = id; this.rare = rare; this.count = count; } } } у меня есть приложение на as 3.0 вот кусок кода подарков. мне нужно чтобы сервер отправлял на клиент открытие окна подарков const { market_list, shop_data } = require(“./server”); const NewsItemServer = require(“./NewsItemServer.js”); const newsArray = [ new NewsItemServer(“2023-11-11”, “GTanks снова открыт!”) ]; const Area = require(“./Area.js”), { playerJson, battle_items, send } = require(“./server”); var CTFBattle, TDMBattle, DMBattle, DOMBattle, ASLBattle, effect_model = { effects: [] }; class Lobby extends Area { constructor() { super(); this.battles = []; this.chat = require(“./LobbyChat”); this.battle_count = 0; this.anticheat = 0; this.newsShown = false; // Флаг, указывающий, были ли новости показаны игроку } createBattles() { if (this.battles.length === 0) { var battle = new DMBattle(true, “For newbies”, “map_sandbox”, 0, 8, 1, 5, 10, false, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); } } //battle;init_mines;{“mines”:[]} getChat() { return this.chat; } getPrefix() { return “lobby”; } getBattles(socket, tank) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem(“no_supplies”); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, “init_battle_select;” + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } findBattle(id) { for (var i in this.battles) if (this.battles[i].battleId === id) return this.battles[i]; return null; } /** * Removes a battle. * * @param {string} battleId * * @returns boolean */ removeBattle(battleId) { for (var i in this.battles) { if (this.battles[i].battleId === battleId) { this.battles.splice(i, 1); this.broadcast(“remove_battle;” + battleId); this.createBattles(); return true; } } return false } initEffectModel(socket) { this.send(socket, “init_effect_model;” + JSON.stringify(effect_model)); this.createBattles(); } sendNews() { const newsJSON = JSON.stringify(newsArray); this.broadcast(“show_news;” + newsJSON); } onData(socket, args) { var battles = this.battles, battle_count = this.battle_count, tank = socket.tank; if (tank === null) { socket.destroy(); return; } //if (!this.newsShown && args[0] !== “show_news”) { //} if (args.length === 1 && args[0] === “get_data_init_battle_select”) { var arr = []; for (var i in this.battles) { arr.push(this.battles[i].toObject()); } var sub = false; if (tank !== null) { sub = tank.garage.hasItem(“no_supplies”); tank.garage.removePlayer(tank.name); this.addPlayer(tank); } setTimeout(() => { this.send(socket, “init_battle_select;” + JSON.stringify( { haveSubscribe: sub, battles: arr, items: battle_items })); }, 100); } if (args.length === 1 && args[0] === “get_rating”) { this.send(socket, “open_rating;” + JSON.stringify( { crystalls: [ { “count”: tank.crystals, “rank”: tank.rank, “id”: tank.name }] })); } else if (args.length === 1 && args[0] === “show_quests”) { } else if (args[0] === “user_inited”) { this.sendNews(); } else if (args.length === 1 && args[0] === “show_profile”) { this.send(socket, “show_profile;” + JSON.stringify( { isComfirmEmail: false, emailNotice: false })); } else if (args.length === 2 && args[0] === “try_create_battle_ctf”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new CTFBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numFlags, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “try_create_battle_dom”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); const battle = new DOMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numPointsScore, !data.inventory, data.autoBalance, data.frielndyFire, data.pay, false); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “try_create_battle_tdm”) { if (tank.rank > 3) { try { const data = JSON.parse(args[1]); console.log(‘data’, data); const battle = new TDMBattle(false, data.gameName, data.mapId, data.time, data.numPlayers, data.minRang, data.maxRang, data.numKills, !data.inventory, data.autoBalance, data.frielndyFire, data.pay); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву " + data.gameName); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args[0] === “try_create_battle_dm”) { if (tank.rank > 3) { try { const withoutBonuses = args[10] === ‘true’; const withoutSupplies = args[9] === ‘true’; var battle = new DMBattle(false, args[1], args[2], args[3], args[5], args[6], args[7], args[4], !withoutBonuses, withoutSupplies); this.battles.push(battle); this.broadcast(“create_battle;” + JSON.stringify(battle.toObject())); console.log(‘\x1b[35m%s\x1b[0m’, ’ > ’ + tank.name + " создал битву в режиме DM “); } catch (e) { console.log(e); } } else { this.send(socket, “server_message;Создавать битвы можно со звания Капрал”) } } else if (args.length === 2 && args[0] === “get_show_battle_info”) { for (var i in battles) { if (battles[i].battleId === args[1]) { this.send(socket, “show_battle_info;” + JSON.stringify(battles[i].toDetailedObject(tank))); } } } else if (args.length === 2 && (args[0] === “enter_battle_spectator”)) { var battle = this.findBattle(args[1]); if (battle !== null) battle.addSpectator(tank); } else if (args[3] !== “null” && args.length === 3 && (args[0] === “enter_battle_team”)) { var battle = this.findBattle(args[1]); if (battle !== null) { this.anticheat++; setTimeout(() => { if (this.anticheat > 1) { this.send(tank.socket, “battle;kick_by_cheats”); tank.socket.destroy(); } }, 50); setTimeout(() => { this.anticheat–; }, 1000); var type = args[2] === “false” ? “BLUE” : “RED”; send(socket, “lobby;start_battle”); var user = battle.addPlayer(tank, type); if (user !== null) this.broadcast(“add_player_to_battle;” + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: type })); } } else if (args[3] !== “null” && args.length === 3 && (args[0] === “enter_battle”)) { var battle = this.findBattle(args[1]); send(socket, “lobby;start_battle”); if (battle !== null && battle.getTeamCount() === 1) { var user = battle.addPlayer(tank); if (user !== null) this.broadcast(“add_player_to_battle;” + JSON.stringify( { kills: user.kills, battleId: args[2], name: tank.name, rank: tank.rank, id: tank.name, type: “NONE” })); } } else if (args.length === 2 && args[0] === “check_battleName_for_forbidden_words”) { send(socket, “lobby;check_battle_name;” + args[1]); } else if (args.length === 1 && args[0] === “get_garage_data”) { var tank = socket.tank; if (tank !== null) { setTimeout(() => { tank.garage.initiate(socket); this.initEffectModel(socket); if (this.hasPlayer(tank.name)) this.removePlayer(tank.name); }, 1000); } } } } module.exports = new Lobby(); CTFBattle = require(”./CTFBattle"); TDMBattle = require(“./TDMBattle”); DMBattle = require(“./DMBattle”); DOMBattle = require(“./DOMBattle”); ASLBattle = require(“./ASLBattle”); вот сюда надо добавить
2bce5092bf4e4ebe3302c18ccde05a3c
{ "intermediate": 0.31870216131210327, "beginner": 0.5509406328201294, "expert": 0.13035723567008972 }
30,774
write a script for a FireBall game object where it follows the player (player is set to player layer)
b8726637d816cb1cf24bd580cae1b4b9
{ "intermediate": 0.35286951065063477, "beginner": 0.15421800315380096, "expert": 0.4929124712944031 }
30,775
write program on c++ which generates and prints composition of number using combinations without recursion with limit of summand quantity. Example1: n=3, k=2; compositions: {1,2}{2,1}. Example2: n=3, k=3; compositions: {1,1,1}. Example3: n=3, k=1; compositions: {3}.
09a8f9c2cae252148a76f2ffc0727efa
{ "intermediate": 0.5274251103401184, "beginner": 0.17998862266540527, "expert": 0.29258623719215393 }
30,776
I used this code : def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] # Retrieve depth data th = 0.35 depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = sum(float(bid[1]) for bid in bids) bids = depth_data['bids'] highest_bid_price = float(bids[0][0]) lowest_bid_price = float(bids[-1][0]) buy_price = (highest_bid_price + lowest_bid_price) / 2 asks = depth_data['asks'] sell_qty = sum(float(ask[1]) for ask in asks) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[-1][0]) sell_price = (highest_ask_price + lowest_ask_price) / 2 mark_price_data = client.ticker_price(symbol=symbol) mark_price = 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 print("Total quantity of all ask orders:", total_quantity) print("Total quantity of all bid orders:", total_quantity_buy) # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 executed_orders_buy = 0.0 for order in bids: if float(order[0]) == mark_price: executed_orders_buy += float(order[1]) else: break buy_qty = sum(float(bid[1]) for bid in bids) buy_result = buy_qty - executed_orders_buy executed_orders_sell = 0.0 for order in asks: if float(order[0]) == mark_price: executed_orders_sell += float(order[1]) else: break sell_qty = sum(float(ask[1]) for ask in asks) sell_result = sell_qty - executed_orders_sell if (sell_result > (1 + th) > float(buy_qty)) and (sell_price < mark_price - (pth + 0.08)): signal.append('sell') elif (buy_result > (1 + th) > float(sell_qty)) and (buy_price > mark_price + (pth + 0.08)): signal.append('buy') else: signal.append('') if signal == ['buy'] and not ((buy_result < sell_qty) and (buy_price < mark_price)): final_signal.append('buy') elif signal == ['sell'] and not ((sell_result < buy_qty) and (sell_price > mark_price)): final_signal.append('sell') else: final_signal.append('') return final_signal But depth data is doesn't updating
da07a1f2e9f45df2cb3362fae1cee04c
{ "intermediate": 0.3007917106151581, "beginner": 0.4843057692050934, "expert": 0.21490249037742615 }
30,777
const TeamBattle = require("./TeamBattle"), { isset, oppositeTeam, getTankByName } = require("./server"); const { Tank } = require("./Tank"); class DOMBattle extends TeamBattle { constructor(system, name, map_id, time, max_people, min_rank, max_rank, limit, bonuses = true, autobalance = true, friendlyFire = false, pro = false) { super(system, name, map_id, "DOM", time, max_people, min_rank, max_rank, limit, bonuses, autobalance, friendlyFire, pro); this.pointsStatus = []; this.points = []; this.lastTeamScoreUpdateTime = Date.now(); this.standartScoreTimeout = 12000; this.intervalPointsUpdate = null; this.finished = false; this.initPoints(); } initPoints() { this.pointsStatus = []; this.points = []; this.lastTeamScoreUpdateTime = Date.now(); this.standartScoreTimeout = 12000; setTimeout(() => { this.finished = false; }, 1000); for (var i = 0; i < this.map.getDOMPointsCount(); i++) { this.pointsStatus.push("NEUTRALIZED"); this.addNewPoint(i); this.updatePointScore(i, 0.0); } if (this.intervalPointsUpdate) clearInterval(this.intervalPointsUpdate); this.intervalPointsUpdate = setInterval(() => { this.pointsUpdate(); }, 100); } addNewPoint(id) { var position = this.map.getDOMPoint(id) var occupated_users = []; var point = { score: 0.0, occupated_users: occupated_users, x: position.x, y: position.y, z: position.z + 0, id: id, radius: 1000.0 }; this.points.push(point); } isDOM() { return true; } startCapturingPoint(id, tank = null) { var user = tank.user; var point = this.points[id]; switch (user.team_type.toLowerCase()) { case "red": { this.broadcast("tank_capturing_point;" + id + ";" + tank.name, [tank.name]); point.occupated_users.push(tank.user); this.updatePointScore(id, point.score); } break; case "blue": { this.broadcast("tank_capturing_point;" + id + ";" + tank.name, [tank.name]); point.occupated_users.push(tank.user); this.updatePointScore(id, point.score); } break; } } stopCapturingPoint(id, tank = null) { var user = tank.user; var point = this.points[id]; switch (user.team_type.toLowerCase()) { case "red": { this.broadcast("tank_leave_capturing_point;" + tank.name + ";" + id, [tank.name]); for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.nickname == tank.user.nickname) { point.occupated_users.splice(i, 1); break; } } this.updatePointScore(id, point.score); } break; case "blue": { this.broadcast("tank_leave_capturing_point;" + tank.name + ";" + id, [tank.name]); for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.nickname == tank.user.nickname) { point.occupated_users.splice(i, 1); break; } } this.updatePointScore(id, point.score); } break; } } pointsUpdate() { for (var i = 0; i < this.points.length; i++) { var point = this.points[i]; var currentStatus = this.pointsStatus[i]; var redCount = this.getPointRedCapturingCount(point.id); var blueCount = this.getPointBlueCapturingCount(point.id); if (redCount > 0 || blueCount > 0) { if (currentStatus === "NEUTRALIZED" && point.score > -100.0 && point.score < 100.0) { var addScore = (redCount * -2) + (blueCount * 2); this.updatePointScore(point.id, point.score + addScore); } else if (currentStatus === "RED") { var addScore = (redCount * -2) + (blueCount * 2); if (redCount <= blueCount && point.score > -102) { this.updatePointScore(point.id, point.score + addScore); } } else if (currentStatus === "BLUE") { var addScore = (redCount * -2) + (blueCount * 2); if (blueCount <= redCount && point.score < 102) { this.updatePointScore(point.id, point.score + addScore); } } } this.updateScore(); if (currentStatus === "NEUTRALIZED" && point.score >= 100) { this.newStatus(point.id, "BLUE"); } else if (currentStatus === "NEUTRALIZED" && point.score <= -100) { this.newStatus(point.id, "RED"); } else if (currentStatus === "BLUE" || currentStatus === "RED") { if (point.score === 0) { this.newStatus(point.id, "NEUTRALIZED"); } } if (redCount === 0 && blueCount === 0) { if (currentStatus === "NEUTRALIZED") { if (point.score > 0) { point.score -= 2; this.updatePointScore(point.id, point.score); } else if (point.score < 0) { point.score += 2; this.updatePointScore(point.id, point.score); } } else if (currentStatus === "RED") { if (point.score > -100) { point.score -= 2; this.updatePointScore(point.id, point.score); } } else if (currentStatus === "BLUE") { if (point.score < 100) { point.score += 2; this.updatePointScore(point.id, point.score); } } } } } newStatus(id, status) { var currentStatus = this.pointsStatus[id]; switch (status) { case "RED": { if (currentStatus === "NEUTRALIZED") { this.capturedBy(id, "red"); this.extraditeScore(id, "red", "captured"); } } break; case "BLUE": { if (currentStatus === "NEUTRALIZED") { this.capturedBy(id, "blue"); this.extraditeScore(id, "blue", "captured"); } } break; case "NEUTRALIZED": { if (currentStatus === "RED") { this.lostBy(id, "red"); this.extraditeScore(id, "blue", "lost"); } else if (currentStatus === "BLUE") { this.lostBy(id, "blue"); this.extraditeScore(id, "red", "lost"); } } break; } this.pointsStatus[id] = status; } extraditeScore(id, team, action) { var users = this.getPointUsersByTeam(id, team); for (var i = 0; i < users.length; i++) { var user = users[i]; var tank = getTankByName(user.nickname); var oppositeTeamSize = (oppositeTeam(user.team_type) == "RED") ? this.redPeople : this.bluePeople; var lostScore = 10 * oppositeTeamSize; var capturedScore = 20 * oppositeTeamSize; if (action === "lost") { console.log(user.nickname + " is getting " + lostScore + " for losing the point"); user.score += lostScore; tank.addScore(lostScore * (tank.garage.hasItem("up_score") ? 1.5 : 1)); var stats = this.getStatistics(tank.name); this.broadcast("update_player_statistic;" + JSON.stringify(stats)); tank.sendScore(); this.addFund((3 + 0.03 * user.rank) * oppositeTeamSize); } else if (action === "captured") { console.log(user.nickname + " is getting " + capturedScore + " for capturing the point"); user.score += capturedScore; tank.addScore(capturedScore * (tank.garage.hasItem("up_score") ? 1.5 : 1)); var stats = this.getStatistics(tank.name); this.broadcast("update_player_statistic;" + JSON.stringify(stats)); tank.sendScore(); this.addFund((5 + 0.05 * user.rank) * oppositeTeamSize); } } } updateScore() { for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; var redPoints = this.getRedPointsCount(); var bluePoints = this.getBluePointsCount(); if (currentStatus === "RED") { if (Date.now() - this.lastTeamScoreUpdateTime >= this.standartScoreTimeout / redPoints) { this.scoreRed++; this.sendTeamScore("red"); this.lastTeamScoreUpdateTime = Date.now(); } } else if (currentStatus === "BLUE") { if (Date.now() - this.lastTeamScoreUpdateTime >= this.standartScoreTimeout / bluePoints) { this.scoreBlue++; this.sendTeamScore("blue"); this.lastTeamScoreUpdateTime = Date.now(); } } } if (!this.finished && this.limit > 0 && (this.scoreBlue >= this.limit || this.scoreRed >= this.limit)) { this.finished = true; this.finish(); } } restart() { this.initPoints(); super.restart(); } removePlayer(username) { for (var i = 0; i < this.points.length; i++) { var point = this.points[i]; for (var j = 0; j < point.occupated_users.length; j++) { var user = point.occupated_users[j]; if (!this.hasUser(user.nickname)) continue; if (user.nickname === username) { this.broadcast("tank_leave_capturing_point;" + username + ";" + point.id, [username]); point.occupated_users.splice(j, 1); super.removePlayer(username); } } } } capturedBy(id, by) { this.broadcast("point_captured_by;" + by + ";" + id); } lostBy(id, by) { this.broadcast("point_lost_by;" + by + ";" + id); } updatePointScore(id, score) { this.points[id].score = score; this.broadcast("set_point_score;" + id + ";" + score); } getPointUsersByTeam(id, team) { var users = []; var point = this.points[id]; for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.team_type.toLowerCase() === team.toLowerCase()) { users.push(user); } } return users; } getRedPointsCount() { var count = 0; for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; if (currentStatus === "RED") { count++; } } return count; } getBluePointsCount() { var count = 0; for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; if (currentStatus === "BLUE") { count++; } } return count; } getPointRedCapturingCount(id) { var point = this.points[id]; var users = point.occupated_users; var redPeopleCapturing = []; for (var i = 0; i < users.length; i++) { var user = users[i]; if (user.team_type.toLowerCase() === "red") redPeopleCapturing.push(user); } return redPeopleCapturing.length; } getPointBlueCapturingCount(id) { var point = this.points[id]; var users = point.occupated_users; var bluePeopleCapturing = []; for (var i = 0; i < users.length; i++) { var user = users[i]; if (user.team_type.toLowerCase() === "blue") bluePeopleCapturing.push(user); } return bluePeopleCapturing.length; } toDOMObject() { return { points: this.points, }; } } module.exports = DOMBattle; как сделать чтобы счетчик очков не был общим для всех битв а только для определенной
9469034b0e380980d5623cacbeb536cd
{ "intermediate": 0.3363422751426697, "beginner": 0.44106435775756836, "expert": 0.22259336709976196 }
30,778
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FireBall : MonoBehaviour { public Transform player; public LayerMask platformLayer; public float speed = 5f; private Rigidbody2D rb2d; private new Collider2D collider; private bool grounded; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); } private void CheckGrounded() { Bounds bounds = collider.bounds; Vector2 size = new Vector2(bounds.size.x, 0.1f); Vector2 center = new Vector2(bounds.center.x, bounds.min.y); Collider2D[] colliders = Physics2D.OverlapBoxAll(center, size, 0f, platformLayer); grounded = colliders.Length > 0; } void Update() { // Check if player exists if (player == null) { // If player is not found, do something (e.g., destroy the fireball) Destroy(gameObject); return; } // Calculate direction towards the player Vector3 direction = player.position - transform.position; direction.Normalize(); // Move the fireball only horizontally on the platform if (grounded) { rb2d.velocity = new Vector2(direction.x * speed, rb2d.velocity.y); } // Check if fireball is grounded CheckGrounded(); // Rotate the fireball to face the player, only on the x and y axes Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up); transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, 0f)); } } fix this script so that the fireball is colliding with the platform (set to platform layer)
fa886f154f44b45b0bfba4d439a5cebf
{ "intermediate": 0.42639443278312683, "beginner": 0.2438284456729889, "expert": 0.3297771215438843 }
30,779
const TeamBattle = require("./TeamBattle"), { isset, oppositeTeam, getTankByName } = require("./server"); const { Tank } = require("./Tank"); class DOMBattle extends TeamBattle { constructor(system, name, map_id, time, max_people, min_rank, max_rank, limit, bonuses = true, autobalance = true, friendlyFire = false, pro = false) { super(system, name, map_id, "DOM", time, max_people, min_rank, max_rank, limit, bonuses, autobalance, friendlyFire, pro); this.pointsStatus = []; this.points = []; this.lastTeamScoreUpdateTime = Date.now(); this.standartScoreTimeout = 12000; this.intervalPointsUpdate = null; this.finished = false; this.score = 0; // Новое свойство для отслеживания счета битвы this.initPoints(); } initPoints() { this.pointsStatus = []; this.points = []; this.lastTeamScoreUpdateTime = Date.now(); this.standartScoreTimeout = 12000; setTimeout(() => { this.finished = false; }, 1000); for (var i = 0; i < this.map.getDOMPointsCount(); i++) { this.pointsStatus.push("NEUTRALIZED"); this.addNewPoint(i); this.updatePointScore(i, 0.0); } if (this.intervalPointsUpdate) clearInterval(this.intervalPointsUpdate); this.intervalPointsUpdate = setInterval(() => { this.pointsUpdate(); }, 100); } addNewPoint(id) { var position = this.map.getDOMPoint(id) var occupated_users = []; var point = { score: 0.0, occupated_users: occupated_users, x: position.x, y: position.y, z: position.z + 0, id: id, radius: 1000.0 }; this.points.push(point); } isDOM() { return true; } startCapturingPoint(id, tank = null) { var user = tank.user; var point = this.points[id]; switch (user.team_type.toLowerCase()) { case "red": { this.broadcast("tank_capturing_point;" + id + ";" + tank.name, [tank.name]); point.occupated_users.push(tank.user); this.updatePointScore(id, point.score); } break; case "blue": { this.broadcast("tank_capturing_point;" + id + ";" + tank.name, [tank.name]); point.occupated_users.push(tank.user); this.updatePointScore(id, point.score); } break; } } stopCapturingPoint(id, tank = null) { var user = tank.user; var point = this.points[id]; switch (user.team_type.toLowerCase()) { case "red": { this.broadcast("tank_leave_capturing_point;" + tank.name + ";" + id, [tank.name]); for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.nickname == tank.user.nickname) { point.occupated_users.splice(i, 1); break; } } this.updatePointScore(id, point.score); } break; case "blue": { this.broadcast("tank_leave_capturing_point;" + tank.name + ";" + id, [tank.name]); for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.nickname == tank.user.nickname) { point.occupated_users.splice(i, 1); break; } } this.updatePointScore(id, point.score); } break; } } pointsUpdate() { for (var i = 0; i < this.points.length; i++) { var point = this.points[i]; var currentStatus = this.pointsStatus[i]; var redCount = this.getPointRedCapturingCount(point.id); var blueCount = this.getPointBlueCapturingCount(point.id); if (redCount > 0 || blueCount > 0) { if (currentStatus === "NEUTRALIZED" && point.score > -100.0 && point.score < 100.0) { var addScore = (redCount * -2) + (blueCount * 2); this.updatePointScore(point.id, point.score + addScore); } else if (currentStatus === "RED") { var addScore = (redCount * -2) + (blueCount * 2); if (redCount <= blueCount && point.score > -102) { this.updatePointScore(point.id, point.score + addScore); } } else if (currentStatus === "BLUE") { var addScore = (redCount * -2) + (blueCount * 2); if (blueCount <= redCount && point.score < 102) { this.updatePointScore(point.id, point.score + addScore); } } } this.updateScore(); if (currentStatus === "NEUTRALIZED" && point.score >= 100) { this.newStatus(point.id, "BLUE"); } else if (currentStatus === "NEUTRALIZED" && point.score <= -100) { this.newStatus(point.id, "RED"); } else if (currentStatus === "BLUE" || currentStatus === "RED") { if (point.score === 0) { this.newStatus(point.id, "NEUTRALIZED"); } } if (redCount === 0 && blueCount === 0) { if (currentStatus === "NEUTRALIZED") { if (point.score > 0) { point.score -= 2; this.updatePointScore(point.id, point.score); } else if (point.score < 0) { point.score += 2; this.updatePointScore(point.id, point.score); } } else if (currentStatus === "RED") { if (point.score > -100) { point.score -= 2; this.updatePointScore(point.id, point.score); } } else if (currentStatus === "BLUE") { if (point.score < 100) { point.score += 2; this.updatePointScore(point.id, point.score); } } } } } newStatus(id, status) { var currentStatus = this.pointsStatus[id]; switch (status) { case "RED": { if (currentStatus === "NEUTRALIZED") { this.capturedBy(id, "red"); this.extraditeScore(id, "red", "captured"); } } break; case "BLUE": { if (currentStatus === "NEUTRALIZED") { this.capturedBy(id, "blue"); this.extraditeScore(id, "blue", "captured"); } } break; case "NEUTRALIZED": { if (currentStatus === "RED") { this.lostBy(id, "red"); this.extraditeScore(id, "blue", "lost"); } else if (currentStatus === "BLUE") { this.lostBy(id, "blue"); this.extraditeScore(id, "red", "lost"); } } break; } this.pointsStatus[id] = status; } extraditeScore(id, team, action) { var users = this.getPointUsersByTeam(id, team); for (var i = 0; i < users.length; i++) { var user = users[i]; var tank = getTankByName(user.nickname); var oppositeTeamSize = (oppositeTeam(user.team_type) == "RED") ? this.redPeople : this.bluePeople; var lostScore = 10 * oppositeTeamSize; var capturedScore = 20 * oppositeTeamSize; if (action === "lost") { console.log(user.nickname + " is getting " + lostScore + " for losing the point"); user.score += lostScore; tank.addScore(lostScore * (tank.garage.hasItem("up_score") ? 1.5 : 1)); var stats = this.getStatistics(tank.name); this.broadcast("update_player_statistic;" + JSON.stringify(stats)); tank.sendScore(); this.addFund((3 + 0.03 * user.rank) * oppositeTeamSize); } else if (action === "captured") { console.log(user.nickname + " is getting " + capturedScore + " for capturing the point"); user.score += capturedScore; tank.addScore(capturedScore * (tank.garage.hasItem("up_score") ? 1.5 : 1)); var stats = this.getStatistics(tank.name); this.broadcast("update_player_statistic;" + JSON.stringify(stats)); tank.sendScore(); this.addFund((5 + 0.05 * user.rank) * oppositeTeamSize); } } } updateScore() { for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; var redPoints = this.getRedPointsCount(); var bluePoints = this.getBluePointsCount(); if (currentStatus === "RED") { if (Date.now() - this.lastTeamScoreUpdateTime >= this.standartScoreTimeout / redPoints) { this.scoreRed++; this.sendTeamScore("red"); this.lastTeamScoreUpdateTime = Date.now(); } } else if (currentStatus === "BLUE") { if (Date.now() - this.lastTeamScoreUpdateTime >= this.standartScoreTimeout / bluePoints) { this.scoreBlue++; this.sendTeamScore("blue"); this.lastTeamScoreUpdateTime = Date.now(); } } } if (!this.finished && this.limit > 0 && (this.scoreBlue >= this.limit || this.scoreRed >= this.limit)) { this.finished = true; this.finish(); } } restart() { this.initPoints(); super.restart(); } removePlayer(username) { for (var i = 0; i < this.points.length; i++) { var point = this.points[i]; for (var j = 0; j < point.occupated_users.length; j++) { var user = point.occupated_users[j]; if (!this.hasUser(user.nickname)) continue; if (user.nickname === username) { this.broadcast("tank_leave_capturing_point;" + username + ";" + point.id, [username]); point.occupated_users.splice(j, 1); super.removePlayer(username); } } } } capturedBy(id, by) { this.broadcast("point_captured_by;" + by + ";" + id); } lostBy(id, by) { this.broadcast("point_lost_by;" + by + ";" + id); } updatePointScore(id, score) { this.points[id].score = score; this.score = score; // Обновление счета битвы this.broadcast("set_point_score;" + id + ";" + score); } getPointUsersByTeam(id, team) { var users = []; var point = this.points[id]; for (var i = 0; i < point.occupated_users.length; i++) { var user = point.occupated_users[i]; if (user.team_type.toLowerCase() === team.toLowerCase()) { users.push(user); } } return users; } getRedPointsCount() { var count = 0; for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; if (currentStatus === "RED") { count++; } } return count; } getBluePointsCount() { var count = 0; for (var i = 0; i < this.points.length; i++) { var currentStatus = this.pointsStatus[i]; if (currentStatus === "BLUE") { count++; } } return count; } getPointRedCapturingCount(id) { var point = this.points[id]; var users = point.occupated_users; var redPeopleCapturing = []; for (var i = 0; i < users.length; i++) { var user = users[i]; if (user.team_type.toLowerCase() === "red") redPeopleCapturing.push(user); } return redPeopleCapturing.length; } getPointBlueCapturingCount(id) { var point = this.points[id]; var users = point.occupated_users; var bluePeopleCapturing = []; for (var i = 0; i < users.length; i++) { var user = users[i]; if (user.team_type.toLowerCase() === "blue") bluePeopleCapturing.push(user); } return bluePeopleCapturing.length; } toDOMObject() { return { points: this.points, }; } } module.exports = DOMBattle; как сделать чтобы счетчик очков был для точки один, чтобы при подъезде к другой точке захвата он не становился общим
bad7888913ba85babee905280a86748a
{ "intermediate": 0.30061110854148865, "beginner": 0.41679322719573975, "expert": 0.2825956344604492 }
30,780
Create a C# script for unity that makes it so the fireball layer is more important that the platform layer
4a377787d40ba5e508e6111f7c390a33
{ "intermediate": 0.3280499577522278, "beginner": 0.1981395035982132, "expert": 0.4738105237483978 }
30,781
python code using BiLSTM encoder and decoder rnn 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 evaluate the model using test data
c9a1ae11933970737af0e91078ddbe14
{ "intermediate": 0.3986051082611084, "beginner": 0.07826212048530579, "expert": 0.5231328010559082 }
30,782
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MarioController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; public float ladderClimbSpeed = 2f; public int maxHealth = 3; private int currentHealth; private bool grounded; private bool onLadder; private bool climbingLadder; private Vector2 direction; private Rigidbody2D rb2d; private new Collider2D collider; private Collider2D[] results; private int currentSceneIndex; public float hammerDuration = 9f; private bool isHammerActive; private float hammerTimer; [Header("Effects")] [Tooltip("The effect to create when colliding with Hammer")] public GameObject hammerEffect; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); results = new Collider2D[4]; } private void Start() { currentHealth = maxHealth; currentSceneIndex = SceneManager.GetActiveScene().buildIndex; } private void CheckCollision() { grounded = false; onLadder = false; Vector2 size = collider.bounds.size; size.y += 0.1f; size.x /= 2f; int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results); for (int i = 0; i < amount; i++) { GameObject hit = results[i].gameObject; if (hit.layer == LayerMask.NameToLayer("Platform")) { grounded = hit.transform.position.y < (transform.position.y - 0.5f); } else if (hit.layer == LayerMask.NameToLayer("Ladder")) { onLadder = true; } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel") && isHammerActive) { Destroy(collision.gameObject); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Hammer")) { Destroy(collision.gameObject); ActivateHammer(); if (hammerEffect != null) { Instantiate(hammerEffect, transform.position, transform.rotation, null); } } else if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel")) { currentHealth--; ResetScene(); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Win")) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ResetScene() { if (currentSceneIndex == 0) { SceneManager.LoadScene("_Scene_DonkeyKong25M2"); } else if (currentSceneIndex == 1) { SceneManager.LoadScene("_Scene_DonkeyKong25M3"); } else if (currentSceneIndex == 2) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ActivateHammer() { isHammerActive = true; hammerTimer = hammerDuration; } private void ResetHammer() { isHammerActive = false; } private void Update() { CheckCollision(); if (isHammerActive) { hammerTimer -= Time.deltaTime; if (hammerTimer <= 0) { ResetHammer(); } } if (grounded && Input.GetButtonDown("Jump")) { rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce); } float movement = Input.GetAxis("Horizontal"); if (grounded) { direction.y = Mathf.Max(direction.y, -1f); climbingLadder = false; } if (onLadder && Input.GetButton("Vertical")) { climbingLadder = true; float climbDirection = Input.GetAxis("Vertical"); rb2d.velocity = new Vector2(0, climbDirection * ladderClimbSpeed); rb2d.gravityScale = 0f; } else if (climbingLadder) { rb2d.gravityScale = 1f; rb2d.velocity = new Vector2(rb2d.velocity.x, 0f); rb2d.constraints = RigidbodyConstraints2D.FreezePositionX; } else { rb2d.gravityScale = 1f; rb2d.constraints = RigidbodyConstraints2D.FreezeRotation; } rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y); if (movement > 0) { transform.localScale = new Vector3(1f, 1f, 1f); } else if (movement < 0) { transform.localScale = new Vector3(-1f, 1f, 1f); } } } write a new C# script based off the MarioController script that allows the fireball game object (set to Fireball layer) to move on platforms and climb ladders like mario, except it is not player controlled
afd959594bc918dfef179d5f82bc7dda
{ "intermediate": 0.3256596028804779, "beginner": 0.49874526262283325, "expert": 0.17559511959552765 }
30,783
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MarioController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; public float ladderClimbSpeed = 2f; public int maxHealth = 3; private int currentHealth; private bool grounded; private bool onLadder; private bool climbingLadder; private Vector2 direction; private Rigidbody2D rb2d; private new Collider2D collider; private Collider2D[] results; private int currentSceneIndex; public float hammerDuration = 9f; private bool isHammerActive; private float hammerTimer; [Header("Effects")] [Tooltip("The effect to create when colliding with Hammer")] public GameObject hammerEffect; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); results = new Collider2D[4]; } private void Start() { currentHealth = maxHealth; currentSceneIndex = SceneManager.GetActiveScene().buildIndex; } private void CheckCollision() { grounded = false; onLadder = false; Vector2 size = collider.bounds.size; size.y += 0.1f; size.x /= 2f; int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results); for (int i = 0; i < amount; i++) { GameObject hit = results[i].gameObject; if (hit.layer == LayerMask.NameToLayer("Platform")) { grounded = hit.transform.position.y < (transform.position.y - 0.5f); } else if (hit.layer == LayerMask.NameToLayer("Ladder")) { onLadder = true; } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel") && isHammerActive) { Destroy(collision.gameObject); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Hammer")) { Destroy(collision.gameObject); ActivateHammer(); if (hammerEffect != null) { Instantiate(hammerEffect, transform.position, transform.rotation, null); } } else if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel")) { currentHealth--; ResetScene(); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Win")) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ResetScene() { if (currentSceneIndex == 0) { SceneManager.LoadScene("_Scene_DonkeyKong25M2"); } else if (currentSceneIndex == 1) { SceneManager.LoadScene("_Scene_DonkeyKong25M3"); } else if (currentSceneIndex == 2) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ActivateHammer() { isHammerActive = true; hammerTimer = hammerDuration; } private void ResetHammer() { isHammerActive = false; } private void Update() { CheckCollision(); if (isHammerActive) { hammerTimer -= Time.deltaTime; if (hammerTimer <= 0) { ResetHammer(); } } if (grounded && Input.GetButtonDown("Jump")) { rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce); } float movement = Input.GetAxis("Horizontal"); if (grounded) { direction.y = Mathf.Max(direction.y, -1f); climbingLadder = false; } if (onLadder && Input.GetButton("Vertical")) { climbingLadder = true; float climbDirection = Input.GetAxis("Vertical"); rb2d.velocity = new Vector2(0, climbDirection * ladderClimbSpeed); rb2d.gravityScale = 0f; } else if (climbingLadder) { rb2d.gravityScale = 1f; rb2d.velocity = new Vector2(rb2d.velocity.x, 0f); rb2d.constraints = RigidbodyConstraints2D.FreezePositionX; } else { rb2d.gravityScale = 1f; rb2d.constraints = RigidbodyConstraints2D.FreezeRotation; } rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y); if (movement > 0) { transform.localScale = new Vector3(1f, 1f, 1f); } else if (movement < 0) { transform.localScale = new Vector3(-1f, 1f, 1f); } } } add to this script if mario destroys a barrel when he has the hammer, it will give him +300 score. Here is the ScoreCounter script to reference: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; //This line enables use of uGUI classes like Text. public class ScoreCounter : MonoBehaviour { [Header("Dynamic")] public int score = 0; private Text uiText; // Start is called before the first frame update void Start() { uiText = GetComponent<Text>(); } // Update is called once per frame void Update() { uiText.text = score.ToString("Score:#,0"); //This 0 is a zero! } }
6694b679a4f04c00fe9ff51f831ce4eb
{ "intermediate": 0.3256596028804779, "beginner": 0.49874526262283325, "expert": 0.17559511959552765 }
30,784
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MarioController : MonoBehaviour { public float moveSpeed = 5f; public float jumpForce = 5f; public float ladderClimbSpeed = 2f; public int maxHealth = 3; private int currentHealth; private bool grounded; private bool onLadder; private bool climbingLadder; private Vector2 direction; private Rigidbody2D rb2d; private new Collider2D collider; private Collider2D[] results; private int currentSceneIndex; private ScoreCounter scoreCounter; public float hammerDuration = 9f; private bool isHammerActive; private float hammerTimer; [Header("Effects")] [Tooltip("The effect to create when colliding with Hammer")] public GameObject hammerEffect; private void Awake() { rb2d = GetComponent<Rigidbody2D>(); collider = GetComponent<Collider2D>(); results = new Collider2D[4]; } private void Start() { currentHealth = maxHealth; currentSceneIndex = SceneManager.GetActiveScene().buildIndex; scoreCounter = FindObjectOfType<ScoreCounter>(); } private void CheckCollision() { grounded = false; onLadder = false; Vector2 size = collider.bounds.size; size.y += 0.1f; size.x /= 2f; int amount = Physics2D.OverlapBoxNonAlloc(transform.position, size, 0f, results); for (int i = 0; i < amount; i++) { GameObject hit = results[i].gameObject; if (hit.layer == LayerMask.NameToLayer("Platform")) { grounded = hit.transform.position.y < (transform.position.y - 0.5f); } else if (hit.layer == LayerMask.NameToLayer("Ladder")) { onLadder = true; } } } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel") && isHammerActive) { Destroy(collision.gameObject); scoreCounter.score += 300; } else if (collision.gameObject.layer == LayerMask.NameToLayer("Hammer")) { Destroy(collision.gameObject); ActivateHammer(); if (hammerEffect != null) { Instantiate(hammerEffect, transform.position, transform.rotation, null); } } else if (collision.gameObject.layer == LayerMask.NameToLayer("Barrel")) { currentHealth--; ResetScene(); } else if (collision.gameObject.layer == LayerMask.NameToLayer("Win")) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ResetScene() { if (currentSceneIndex == 0) { SceneManager.LoadScene("_Scene_DonkeyKong25M2"); } else if (currentSceneIndex == 1) { SceneManager.LoadScene("_Scene_DonkeyKong25M3"); } else if (currentSceneIndex == 2) { SceneManager.LoadScene("_Scene_DonkeyKong25M"); } } private void ActivateHammer() { isHammerActive = true; hammerTimer = hammerDuration; } private void ResetHammer() { isHammerActive = false; } private void Update() { CheckCollision(); if (isHammerActive) { hammerTimer -= Time.deltaTime; if (hammerTimer <= 0) { ResetHammer(); } } if (grounded && Input.GetButtonDown("Jump")) { rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce); } float movement = Input.GetAxis("Horizontal"); if (grounded) { direction.y = Mathf.Max(direction.y, -1f); climbingLadder = false; } if (onLadder && Input.GetButton("Vertical")) { climbingLadder = true; float climbDirection = Input.GetAxis("Vertical"); rb2d.velocity = new Vector2(0, climbDirection * ladderClimbSpeed); rb2d.gravityScale = 0f; } else if (climbingLadder) { rb2d.gravityScale = 1f; rb2d.velocity = new Vector2(rb2d.velocity.x, 0f); rb2d.constraints = RigidbodyConstraints2D.FreezePositionX; } else { rb2d.gravityScale = 1f; rb2d.constraints = RigidbodyConstraints2D.FreezeRotation; } rb2d.velocity = new Vector2(movement * moveSpeed, rb2d.velocity.y); if (movement > 0) { transform.localScale = new Vector3(1f, 1f, 1f); } else if (movement < 0) { transform.localScale = new Vector3(-1f, 1f, 1f); } } } edit this script so if the currentSceneIndex == 1 or currentSceneIndex == 2, the score will not be reset to 0 but instead remain what it was from the previous scene
fa1a6a489d64a3957423340ad2b636e4
{ "intermediate": 0.3305259943008423, "beginner": 0.5186988711357117, "expert": 0.15077513456344604 }
30,785
Python code that uses a BiLSTM Encoder and Decoder RNN to translate English text to Arabic text. It splits the data into training, validation data from text files, tokenizes the sentences, converts them into numerical representations, pads or truncates the sentences to a fixed length, and evaluates the model using the test data.
57886d733d09a47abc218351965bbf0d
{ "intermediate": 0.20562222599983215, "beginner": 0.06489387899637222, "expert": 0.7294839024543762 }
30,786
hi
f82b4568db198833556c9aa95b6602b7
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
30,787
Draw an orange cat.
3ed64e1cdb4366f01c5a69716a7a3a97
{ "intermediate": 0.3975259065628052, "beginner": 0.3908403813838959, "expert": 0.21163368225097656 }
30,788
groovy match Keelly.Chen == 作者 == Kelly.Chen ==
77ffe869479513dc04ca567829e9ee00
{ "intermediate": 0.3224087357521057, "beginner": 0.2953369617462158, "expert": 0.38225436210632324 }
30,789
convert this go program to python package websites package websites import ( "context" "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/url" "time" "github.com/golang/time/rate" // Correct the import path ) type Nike struct { Authorization string limiter *rate.Limiter client *http.Client } type NikeProfile struct { UpmID string `json:"upmId"` ScreenName string `json:"screenName"` FirstName string `json:"firstName"` LastName string `json:"lastName"` Hometown string `json:"hometown"` ProfileURL string `json:"profileUrl"` ThumbnailURL string `json:"thumbnailUrl"` Visibility string `json:"visibility"` ViewerRelationship struct { RelationshipType string `json:"relationshipType"` } `json:"viewerRelationship"` ImageURL string `json:"imageUrl"` Email string `json:"email"` DisplayName string `json:"displayName"` } type NikeAPIResponse struct { Pages struct { TotalResources int `json:"totalResources"` TotalPages int `json:"totalPages"` } `json:"pages"` Profiles []NikeProfile `json:"objects"` ErrorID string `json:"error_id"` Errors []struct { Code string `json:"code"` Message string `json:"message"` } `json:"errors"` } // Authorization is found on nike.com website local storage 'oidc.user' keyed by 'access_token' func NewNike(authorization string) *Nike { return &Nike{Authorization: authorization, client: &http.Client{}, limiter: rate.NewLimiter(rate.Every(time.Second), 1)} } func (website *Nike) Lookup(query string, ctx context.Context) ([]NikeProfile, error) { // Wait for rate limiter err := website.limiter.Wait(ctx) if err != nil { return nil, err } // Create request request, err := http.NewRequest("GET", fmt.Sprintf("https://api.nike.com/usersearch/search/v2?app=com.nike.sport.running.ios&format=json&searchstring=%v", url.QueryEscape(query)), nil) if err != nil { return nil, err } // Set authorization header request.Header.Set("Authorization", "Bearer "+website.Authorization) // Do request response, err := website.client.Do(request) if err != nil { return nil, err } defer response.Body.Close() // Read body body, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err } // Parse to struct apiResponse := NikeAPIResponse{} err = json.Unmarshal(body, &apiResponse) if err != nil { return nil, err } // Check for error if apiResponse.ErrorID != "" { return nil, errors.New(apiResponse.Errors[0].Message) } // Return profiles return apiResponse.Profiles, nil }
04952d42b37310f80aadcf5b6a29714c
{ "intermediate": 0.34528085589408875, "beginner": 0.4244340658187866, "expert": 0.23028509318828583 }
30,790
Why the following error? ERROR: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 160, in startup server = await loop.create_server( File "/usr/lib/python3.10/asyncio/base_events.py", line 1519, in create_server raise OSError(err.errno, 'error while attempting ' OSError: [Errno 98] error while attempting to bind on address ('127.0.0.1', 5000): address already in use During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete return future.result() File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 78, in serve await self.startup(sockets=sockets) File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 168, in startup logger.error(exc) File "/usr/lib/python3.10/logging/__init__.py", line 1506, in error self._log(ERROR, msg, args, **kwargs) File "/usr/lib/python3.10/logging/__init__.py", line 1624, in _log self.handle(record) File "/usr/lib/python3.10/logging/__init__.py", line 1634, in handle self.callHandlers(record) File "/usr/lib/python3.10/logging/__init__.py", line 1696, in callHandlers hdlr.handle(record) File "/usr/lib/python3.10/logging/__init__.py", line 968, in handle self.emit(record) File "/content/text-generation-webui/modules/logging_colors.py", line 99, in new args[1].msg = color + args[1].msg + '\x1b[0m' # normal TypeError: can only concatenate str (not "OSError") to str During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/starlette/routing.py", line 686, in lifespan await receive() File "/usr/local/lib/python3.10/dist-packages/uvicorn/lifespan/on.py", line 137, in receive return await self.receive_queue.get() File "/usr/lib/python3.10/asyncio/queues.py", line 159, in get await getter asyncio.exceptions.CancelledError Exception in thread Thread-1 (run_server): Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 160, in startup server = await loop.create_server( File "/usr/lib/python3.10/asyncio/base_events.py", line 1519, in create_server raise OSError(err.errno, 'error while attempting ' OSError: [Errno 98] error while attempting to bind on address ('127.0.0.1', 5000): address already in use During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/content/text-generation-webui/extensions/openai/script.py", line 310, in run_server uvicorn.run(app, host=server_addr, port=port, ssl_certfile=ssl_certfile, ssl_keyfile=ssl_keyfile) File "/usr/local/lib/python3.10/dist-packages/uvicorn/main.py", line 587, in run server.run() File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 61, in run return asyncio.run(self.serve(sockets=sockets)) File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete return future.result() File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 78, in serve await self.startup(sockets=sockets) File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 168, in startup logger.error(exc) File "/usr/lib/python3.10/logging/__init__.py", line 1506, in error self._log(ERROR, msg, args, **kwargs) File "/usr/lib/python3.10/logging/__init__.py", line 1624, in _log self.handle(record) File "/usr/lib/python3.10/logging/__init__.py", line 1634, in handle self.callHandlers(record) File "/usr/lib/python3.10/logging/__init__.py", line 1696, in callHandlers hdlr.handle(record) File "/usr/lib/python3.10/logging/__init__.py", line 968, in handle self.emit(record) File "/content/text-generation-webui/modules/logging_colors.py", line 99, in new args[1].msg = color + args[1].msg + '\x1b[0m' # normal TypeError: can only concatenate str (not "OSError") to str 2023-11-12 04:18:23 INFO:Loading the extension "gallery"... /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_1 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_2 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_3 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_4 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_5 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_6 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") /usr/local/lib/python3.10/dist-packages/gradio/blocks.py:890: UserWarning: api_name refresh already exists, using refresh_7 warnings.warn(f"api_name {api_name} already exists, using {api_name_}") Traceback (most recent call last): File "/content/text-generation-webui/server.py", line 229, in <module> create_interface() File "/content/text-generation-webui/server.py", line 117, in create_interface ui_model_menu.create_ui() # Model tab File "/content/text-generation-webui/modules/ui_model_menu.py", line 77, in create_ui with gr.Box(): AttributeError: module 'gradio' has no attribute 'Box'
54aa0b435ebdfa6b8c7e4043c71d2028
{ "intermediate": 0.3252735733985901, "beginner": 0.4187793731689453, "expert": 0.255947083234787 }
30,791
#include<reg52.h> typedef unsigned char uchar; typedef unsigned int uint; //按键定义 sbit key_stop = P1 ^ 0; sbit key_star = P1 ^ 1; sbit key_fmq = P1 ^ 7; //0~9的十六进制数码 uchar code seg[10] = { 0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90 }; // 0~9 //秒、分、时标志 uchar miao = 0, fen = 0, shi = 0; //秒、分、时高位低位 uchar miao_L, miao_H, fen_L, fen_H, shi_L, shi_H; //计数 uint counter = 0; //模式 uint moshi = -1; void delay(uint x) { //延时函数 while (x--) ; }//delay void key_delay(int xms) { //按键延时函数 x ms unsigned int i, j; for (i = 0; i < xms; ++i) for (j = 0; j < 110; ++j) ; }//key_delay void T0_Init() { //定时器初始化 TMOD = 0x01; TH0 = 0x3c; TL0 = 0xb0; EA = 1; //开总中断 ET0 = 1; TR0 = 1; }//T0_Init void display() { //显示函数 P2 = 0x08; // 0001 0000 P0 = seg[fen_L]; delay(50); P2 = 0x04; // 0000 1000 P0 = seg[fen_H]; delay(50); P2 = 0x02; // 0000 0010 P0 = seg[shi_L]; delay(50); P2 = 0x01; // 0000 0001 P0 = seg[shi_H]; delay(50); }//display void stopwatch(){ P2 = 0x08; // 0001 0000 P0 = seg[miao_L]; delay(50); P2 = 0x04; // 0000 1000 P0 = seg[miao_H]; delay(50); P2 = 0x02; // 0000 0010 P0 = seg[fen_L]; delay(50); P2 = 0x01; // 0000 0001 P0 = seg[fen_H]; delay(50); } void keyscan() { //按键函数 if (key_stop == 0) { key_delay(20); moshi++; if (moshi == 4) moshi = 0; if (moshi == 0) { EA = 1; } while (!key_stop); } if (key_star == 0) { if (moshi == 1) { key_delay(20); if (key_star == 0) { fen++; if (fen == 60) { fen = 0; // 将小时数重置为0 } } } if (moshi == 2) { key_delay(20); if (key_star == 0) { shi++; if (shi == 24) { shi = 0; // 将小时数重置为0 } } } if (moshi == 3) { key_delay(20); if (key_star == 0) { } } } while (!key_star); } } void main() { T0_Init(); while (1) { display(); keyscan(); } }//main void timer0_Init() interrupt 1{ //中断函数 counter++; if (counter == 20) { counter = 0; miao++; //i = 100 if (miao == 60) { miao = 0; fen++; if (fen == 60) { fen = 0; shi++; if (shi == 24) { shi = 0; fen = 0; miao = 0; } } } if (fen == 59) { if (miao >= 50 && miao % 2 == 0) { key_fmq = 0; } else { key_fmq = 1; } } miao_L = miao % 10; miao_H = miao / 10; fen_L = fen % 10; fen_H = fen / 10; shi_L = shi % 10; shi_H = shi / 10; } }//timer0_Init 添加秒表功能的话怎么添加
0f27a418aba270b2ba6e6f249deb7ff7
{ "intermediate": 0.4141353964805603, "beginner": 0.4585115909576416, "expert": 0.12735296785831451 }
30,792
Why the following error in the code below? ERROR: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 160, in startup server = await loop.create_server( File "/usr/lib/python3.10/asyncio/base_events.py", line 1519, in create_server raise OSError(err.errno, 'error while attempting ' OSError: [Errno 98] error while attempting to bind on address ('127.0.0.1', 5000): address already in use During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/content/text-generation-webui/server.py", line 229, in <module> create_interface() File "/content/text-generation-webui/server.py", line 117, in create_interface ui_model_menu.create_ui() # Model tab File "/content/text-generation-webui/modules/ui_model_menu.py", line 77, in create_ui with gr.Box(): AttributeError: module 'gradio' has no attribute 'Box' ... import importlib import math import re import traceback from functools import partial from pathlib import Path import gradio as gr import psutil import torch from transformers import is_torch_xpu_available from modules import loaders, shared, ui, utils from modules.logging_colors import logger from modules.LoRA import add_lora_to_model from modules.models import load_model, unload_model from modules.models_settings import ( apply_model_settings_to_state, get_model_metadata, save_model_settings, update_model_parameters ) from modules.utils import gradio def create_ui(): mu = shared.args.multi_user # Finding the default values for the GPU and CPU memories total_mem = [] if is_torch_xpu_available(): for i in range(torch.xpu.device_count()): total_mem.append(math.floor(torch.xpu.get_device_properties(i).total_memory / (1024 * 1024))) else: for i in range(torch.cuda.device_count()): total_mem.append(math.floor(torch.cuda.get_device_properties(i).total_memory / (1024 * 1024))) default_gpu_mem = [] if shared.args.gpu_memory is not None and len(shared.args.gpu_memory) > 0: for i in shared.args.gpu_memory: if 'mib' in i.lower(): default_gpu_mem.append(int(re.sub('[a-zA-Z ]', '', i))) else: default_gpu_mem.append(int(re.sub('[a-zA-Z ]', '', i)) * 1000) while len(default_gpu_mem) < len(total_mem): default_gpu_mem.append(0) total_cpu_mem = math.floor(psutil.virtual_memory().total / (1024 * 1024)) if shared.args.cpu_memory is not None: default_cpu_mem = re.sub('[a-zA-Z ]', '', shared.args.cpu_memory) else: default_cpu_mem = 0 with gr.Tab("Model", elem_id="model-tab"): with gr.Row(): with gr.Column(): with gr.Row(): with gr.Column(): with gr.Row(): shared.gradio['model_menu'] = gr.Dropdown(choices=utils.get_available_models(), value=shared.model_name, label='Model', elem_classes='slim-dropdown', interactive=not mu) ui.create_refresh_button(shared.gradio['model_menu'], lambda: None, lambda: {'choices': utils.get_available_models()}, 'refresh-button', interactive=not mu) shared.gradio['load_model'] = gr.Button("Load", visible=not shared.settings['autoload_model'], elem_classes='refresh-button', interactive=not mu) shared.gradio['unload_model'] = gr.Button("Unload", elem_classes='refresh-button', interactive=not mu) shared.gradio['reload_model'] = gr.Button("Reload", elem_classes='refresh-button', interactive=not mu) shared.gradio['save_model_settings'] = gr.Button("Save settings", elem_classes='refresh-button', interactive=not mu) with gr.Column(): with gr.Row(): shared.gradio['lora_menu'] = gr.Dropdown(multiselect=True, choices=utils.get_available_loras(), value=shared.lora_names, label='LoRA(s)', elem_classes='slim-dropdown', interactive=not mu) ui.create_refresh_button(shared.gradio['lora_menu'], lambda: None, lambda: {'choices': utils.get_available_loras(), 'value': shared.lora_names}, 'refresh-button', interactive=not mu) shared.gradio['lora_menu_apply'] = gr.Button(value='Apply LoRAs', elem_classes='refresh-button', interactive=not mu) with gr.Row(): with gr.Column(): shared.gradio['loader'] = gr.Dropdown(label="Model loader", choices=loaders.loaders_and_params.keys(), value=None) with gr.Box(): with gr.Row(): with gr.Column(): for i in range(len(total_mem)): shared.gradio[f'gpu_memory_{i}'] = gr.Slider(label=f"gpu-memory in MiB for device :{i}", maximum=total_mem[i], value=default_gpu_mem[i]) shared.gradio['cpu_memory'] = gr.Slider(label="cpu-memory in MiB", maximum=total_cpu_mem, value=default_cpu_mem) shared.gradio['transformers_info'] = gr.Markdown('load-in-4bit params:') shared.gradio['compute_dtype'] = gr.Dropdown(label="compute_dtype", choices=["bfloat16", "float16", "float32"], value=shared.args.compute_dtype) shared.gradio['quant_type'] = gr.Dropdown(label="quant_type", choices=["nf4", "fp4"], value=shared.args.quant_type) shared.gradio['n_gpu_layers'] = gr.Slider(label="n-gpu-layers", minimum=0, maximum=128, value=shared.args.n_gpu_layers) shared.gradio['n_ctx'] = gr.Slider(minimum=0, maximum=shared.settings['truncation_length_max'], step=256, label="n_ctx", value=shared.args.n_ctx) shared.gradio['threads'] = gr.Slider(label="threads", minimum=0, step=1, maximum=32, value=shared.args.threads) shared.gradio['threads_batch'] = gr.Slider(label="threads_batch", minimum=0, step=1, maximum=32, value=shared.args.threads_batch) shared.gradio['n_batch'] = gr.Slider(label="n_batch", minimum=1, maximum=2048, value=shared.args.n_batch) shared.gradio['wbits'] = gr.Dropdown(label="wbits", choices=["None", 1, 2, 3, 4, 8], value=shared.args.wbits if shared.args.wbits > 0 else "None") shared.gradio['groupsize'] = gr.Dropdown(label="groupsize", choices=["None", 32, 64, 128, 1024], value=shared.args.groupsize if shared.args.groupsize > 0 else "None") shared.gradio['model_type'] = gr.Dropdown(label="model_type", choices=["None"], value=shared.args.model_type or "None") shared.gradio['pre_layer'] = gr.Slider(label="pre_layer", minimum=0, maximum=100, value=shared.args.pre_layer[0] if shared.args.pre_layer is not None else 0) shared.gradio['autogptq_info'] = gr.Markdown('* ExLlama_HF is recommended over AutoGPTQ for models derived from LLaMA.') shared.gradio['gpu_split'] = gr.Textbox(label='gpu-split', info='Comma-separated list of VRAM (in GB) to use per GPU. Example: 20,7,7') shared.gradio['max_seq_len'] = gr.Slider(label='max_seq_len', minimum=0, maximum=shared.settings['truncation_length_max'], step=256, info='Maximum sequence length.', value=shared.args.max_seq_len) shared.gradio['alpha_value'] = gr.Slider(label='alpha_value', minimum=1, maximum=8, step=0.05, info='Positional embeddings alpha factor for NTK RoPE scaling. Recommended values (NTKv1): 1.75 for 1.5x context, 2.5 for 2x context. Use either this or compress_pos_emb, not both.', value=shared.args.alpha_value) shared.gradio['rope_freq_base'] = gr.Slider(label='rope_freq_base', minimum=0, maximum=1000000, step=1000, info='If greater than 0, will be used instead of alpha_value. Those two are related by rope_freq_base = 10000 * alpha_value ^ (64 / 63)', value=shared.args.rope_freq_base) shared.gradio['compress_pos_emb'] = gr.Slider(label='compress_pos_emb', minimum=1, maximum=8, step=1, info='Positional embeddings compression factor. Should be set to (context length) / (model\'s original context length). Equal to 1/rope_freq_scale.', value=shared.args.compress_pos_emb) with gr.Column(): shared.gradio['triton'] = gr.Checkbox(label="triton", value=shared.args.triton) shared.gradio['no_inject_fused_attention'] = gr.Checkbox(label="no_inject_fused_attention", value=shared.args.no_inject_fused_attention, info='Disable fused attention. Fused attention improves inference performance but uses more VRAM. Fuses layers for AutoAWQ. Disable if running low on VRAM.') shared.gradio['no_inject_fused_mlp'] = gr.Checkbox(label="no_inject_fused_mlp", value=shared.args.no_inject_fused_mlp, info='Affects Triton only. Disable fused MLP. Fused MLP improves performance but uses more VRAM. Disable if running low on VRAM.') shared.gradio['no_use_cuda_fp16'] = gr.Checkbox(label="no_use_cuda_fp16", value=shared.args.no_use_cuda_fp16, info='This can make models faster on some systems.') shared.gradio['desc_act'] = gr.Checkbox(label="desc_act", value=shared.args.desc_act, info='\'desc_act\', \'wbits\', and \'groupsize\' are used for old models without a quantize_config.json.') shared.gradio['no_mul_mat_q'] = gr.Checkbox(label="no_mul_mat_q", value=shared.args.no_mul_mat_q, info='Disable the mulmat kernels.') shared.gradio['cfg_cache'] = gr.Checkbox(label="cfg-cache", value=shared.args.cfg_cache, info='Create an additional cache for CFG negative prompts.') shared.gradio['no_mmap'] = gr.Checkbox(label="no-mmap", value=shared.args.no_mmap) shared.gradio['mlock'] = gr.Checkbox(label="mlock", value=shared.args.mlock) shared.gradio['numa'] = gr.Checkbox(label="numa", value=shared.args.numa, info='NUMA support can help on some systems with non-uniform memory access.') shared.gradio['cpu'] = gr.Checkbox(label="cpu", value=shared.args.cpu) shared.gradio['load_in_8bit'] = gr.Checkbox(label="load-in-8bit", value=shared.args.load_in_8bit) shared.gradio['bf16'] = gr.Checkbox(label="bf16", value=shared.args.bf16) shared.gradio['auto_devices'] = gr.Checkbox(label="auto-devices", value=shared.args.auto_devices) shared.gradio['disk'] = gr.Checkbox(label="disk", value=shared.args.disk) shared.gradio['load_in_4bit'] = gr.Checkbox(label="load-in-4bit", value=shared.args.load_in_4bit) shared.gradio['use_double_quant'] = gr.Checkbox(label="use_double_quant", value=shared.args.use_double_quant) shared.gradio['tensor_split'] = gr.Textbox(label='tensor_split', info='Split the model across multiple GPUs, comma-separated list of proportions, e.g. 18,17') shared.gradio['llama_cpp_seed'] = gr.Number(label='Seed (0 for random)', value=shared.args.llama_cpp_seed) shared.gradio['trust_remote_code'] = gr.Checkbox(label="trust-remote-code", value=shared.args.trust_remote_code, info='To enable this option, start the web UI with the --trust-remote-code flag. It is necessary for some models.', interactive=shared.args.trust_remote_code) shared.gradio['use_fast'] = gr.Checkbox(label="use_fast", value=shared.args.use_fast, info='Set use_fast=True while loading the tokenizer. May trigger a conversion that takes several minutes.') shared.gradio['logits_all'] = gr.Checkbox(label="logits_all", value=shared.args.logits_all, info='Needs to be set for perplexity evaluation to work. Otherwise, ignore it, as it makes prompt processing slower.') shared.gradio['use_flash_attention_2'] = gr.Checkbox(label="use_flash_attention_2", value=shared.args.use_flash_attention_2, info='Set use_flash_attention_2=True while loading the model.') shared.gradio['disable_exllama'] = gr.Checkbox(label="disable_exllama", value=shared.args.disable_exllama, info='Disable ExLlama kernel.') shared.gradio['no_flash_attn'] = gr.Checkbox(label="no_flash_attn", value=shared.args.no_flash_attn, info='Force flash-attention to not be used.') shared.gradio['cache_8bit'] = gr.Checkbox(label="cache_8bit", value=shared.args.cache_8bit, info='Use 8-bit cache to save VRAM.') shared.gradio['gptq_for_llama_info'] = gr.Markdown('GPTQ-for-LLaMa support is currently only kept for compatibility with older GPUs. AutoGPTQ or ExLlama is preferred when compatible. GPTQ-for-LLaMa is installed by default with the webui on supported systems. Otherwise, it has to be installed manually following the instructions here: [instructions](https://github.com/oobabooga/text-generation-webui/blob/main/docs/GPTQ-models-(4-bit-mode).md#installation-1).') shared.gradio['exllama_info'] = gr.Markdown('For more information, consult the [docs](https://github.com/oobabooga/text-generation-webui/wiki/04-%E2%80%90-Model-Tab#exllama_hf).') shared.gradio['exllama_HF_info'] = gr.Markdown('ExLlama_HF is a wrapper that lets you use ExLlama like a Transformers model, which means it can use the Transformers samplers. It\'s a bit slower than the regular ExLlama.') shared.gradio['llamacpp_HF_info'] = gr.Markdown('llamacpp_HF loads llama.cpp as a Transformers model. To use it, you need to download a tokenizer.\n\nOption 1: download `oobabooga/llama-tokenizer` under "Download model or LoRA". That\'s a default Llama tokenizer.\n\nOption 2: place your .gguf in a subfolder of models/ along with these 3 files: tokenizer.model, tokenizer_config.json, and special_tokens_map.json. This takes precedence over Option 1.') with gr.Column(): with gr.Row(): shared.gradio['autoload_model'] = gr.Checkbox(value=shared.settings['autoload_model'], label='Autoload the model', info='Whether to load the model as soon as it is selected in the Model dropdown.', interactive=not mu) shared.gradio['custom_model_menu'] = gr.Textbox(label="Download model or LoRA", info="Enter the Hugging Face username/model path, for instance: facebook/galactica-125m. To specify a branch, add it at the end after a \":\" character like this: facebook/galactica-125m:main. To download a single file, enter its name in the second box.", interactive=not mu) shared.gradio['download_specific_file'] = gr.Textbox(placeholder="File name (for GGUF models)", show_label=False, max_lines=1, interactive=not mu) with gr.Row(): shared.gradio['download_model_button'] = gr.Button("Download", variant='primary', interactive=not mu) shared.gradio['get_file_list'] = gr.Button("Get file list", interactive=not mu) with gr.Row(): shared.gradio['model_status'] = gr.Markdown('No model is loaded' if shared.model_name == 'None' else 'Ready') def create_event_handlers(): shared.gradio['loader'].change( loaders.make_loader_params_visible, gradio('loader'), gradio(loaders.get_all_params())).then( lambda value: gr.update(choices=loaders.get_model_types(value)), gradio('loader'), gradio('model_type')) # In this event handler, the interface state is read and updated # with the model defaults (if any), and then the model is loaded # unless "autoload_model" is unchecked shared.gradio['model_menu'].change( ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( apply_model_settings_to_state, gradio('model_menu', 'interface_state'), gradio('interface_state')).then( ui.apply_interface_values, gradio('interface_state'), gradio(ui.list_interface_input_elements()), show_progress=False).then( update_model_parameters, gradio('interface_state'), None).then( load_model_wrapper, gradio('model_menu', 'loader', 'autoload_model'), gradio('model_status'), show_progress=False).success( update_truncation_length, gradio('truncation_length', 'interface_state'), gradio('truncation_length')).then( lambda x: x, gradio('loader'), gradio('filter_by_loader')) shared.gradio['load_model'].click( ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( update_model_parameters, gradio('interface_state'), None).then( partial(load_model_wrapper, autoload=True), gradio('model_menu', 'loader'), gradio('model_status'), show_progress=False).success( update_truncation_length, gradio('truncation_length', 'interface_state'), gradio('truncation_length')).then( lambda x: x, gradio('loader'), gradio('filter_by_loader')) shared.gradio['reload_model'].click( unload_model, None, None).then( ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( update_model_parameters, gradio('interface_state'), None).then( partial(load_model_wrapper, autoload=True), gradio('model_menu', 'loader'), gradio('model_status'), show_progress=False).success( update_truncation_length, gradio('truncation_length', 'interface_state'), gradio('truncation_length')).then( lambda x: x, gradio('loader'), gradio('filter_by_loader')) shared.gradio['unload_model'].click( unload_model, None, None).then( lambda: "Model unloaded", None, gradio('model_status')) shared.gradio['save_model_settings'].click( ui.gather_interface_values, gradio(shared.input_elements), gradio('interface_state')).then( save_model_settings, gradio('model_menu', 'interface_state'), gradio('model_status'), show_progress=False) shared.gradio['lora_menu_apply'].click(load_lora_wrapper, gradio('lora_menu'), gradio('model_status'), show_progress=False) shared.gradio['download_model_button'].click(download_model_wrapper, gradio('custom_model_menu', 'download_specific_file'), gradio('model_status'), show_progress=True) shared.gradio['get_file_list'].click(partial(download_model_wrapper, return_links=True), gradio('custom_model_menu', 'download_specific_file'), gradio('model_status'), show_progress=True) shared.gradio['autoload_model'].change(lambda x: gr.update(visible=not x), gradio('autoload_model'), gradio('load_model')) def load_model_wrapper(selected_model, loader, autoload=False): if not autoload: yield f"The settings for `{selected_model}` have been updated.\n\nClick on \"Load\" to load it." return if selected_model == 'None': yield "No model selected" else: try: yield f"Loading `{selected_model}`..." shared.model_name = selected_model unload_model() if selected_model != '': shared.model, shared.tokenizer = load_model(shared.model_name, loader) if shared.model is not None: output = f"Successfully loaded `{selected_model}`." settings = get_model_metadata(selected_model) if 'instruction_template' in settings: output += '\n\nIt seems to be an instruction-following model with template "{}". In the chat tab, instruct or chat-instruct modes should be used.'.format(settings['instruction_template']) yield output else: yield f"Failed to load `{selected_model}`." except: exc = traceback.format_exc() logger.error('Failed to load the model.') print(exc) yield exc.replace('\n', '\n\n') def load_lora_wrapper(selected_loras): yield ("Applying the following LoRAs to {}:\n\n{}".format(shared.model_name, '\n'.join(selected_loras))) add_lora_to_model(selected_loras) yield ("Successfuly applied the LoRAs") def download_model_wrapper(repo_id, specific_file, progress=gr.Progress(), return_links=False, check=False): try: progress(0.0) downloader = importlib.import_module("download-model").ModelDownloader() model, branch = downloader.sanitize_model_and_branch_names(repo_id, None) yield ("Getting the download links from Hugging Face") links, sha256, is_lora, is_llamacpp = downloader.get_download_links_from_huggingface(model, branch, text_only=False, specific_file=specific_file) if return_links: yield '\n\n'.join([f"`{Path(link).name}`" for link in links]) return yield ("Getting the output folder") base_folder = shared.args.lora_dir if is_lora else shared.args.model_dir output_folder = downloader.get_output_folder(model, branch, is_lora, is_llamacpp=is_llamacpp, base_folder=base_folder) if check: progress(0.5) yield ("Checking previously downloaded files") downloader.check_model_files(model, branch, links, sha256, output_folder) progress(1.0) else: yield (f"Downloading file{'s' if len(links) > 1 else ''} to `{output_folder}/`") downloader.download_model_files(model, branch, links, sha256, output_folder, progress_bar=progress, threads=4, is_llamacpp=is_llamacpp) yield ("Done!") except: progress(1.0) yield traceback.format_exc().replace('\n', '\n\n') def update_truncation_length(current_length, state): if 'loader' in state: if state['loader'].lower().startswith('exllama'): return state['max_seq_len'] elif state['loader'] in ['llama.cpp', 'llamacpp_HF', 'ctransformers']: return state['n_ctx'] return current_length
5a3c5542e7386f300382be2090503093
{ "intermediate": 0.4181337356567383, "beginner": 0.3903929889202118, "expert": 0.19147330522537231 }
30,793
как в следующий код добавить отрисовку квадрата: override fun onSurfaceCreated(gl: GL10?, config: javax.microedition.khronos.egl.EGLConfig?) { val options = BitmapFactory.Options() options.inScaled = false val stream = c.resources.openRawResource(R.drawable.water1) val bitmap = BitmapFactory.decodeStream(stream, null, options) stream.close() GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]) GLES20.glTexParameterf( GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR.toFloat() ) GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0) bitmap?.recycle() GLES20.glEnable(GLES20.GL_DEPTH_TEST) GLES20.glEnable(GLES20.GL_BLEND) GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA) val vertex_shader = "uniform mat4 u_modelViewProjectionMatrix;" + "attribute vec3 a_vertex;" + "attribute vec3 a_normal;" + "varying vec3 v_vertex;" + "varying vec3 v_normal;" + "void main() {" + "v_vertex = a_vertex;" + "vec3 n_normal = normalize(a_normal);" + "v_normal = n_normal;" + "gl_Position = u_modelViewProjectionMatrix * vec4(a_vertex, 1.0);" + "}" val fragment_shader = "precision mediump float;" + "uniform vec3 u_camera;" + "uniform vec3 u_lightPosition;" + "uniform sampler2D u_texture0;" + "varying vec3 v_vertex;" + "varying vec3 v_normal;" + "vec3 myrefract(vec3 IN, vec3 NORMAL, float k) {" + " float nv = dot(NORMAL,IN);" + " float v2 = dot(IN,IN);" + " float knormal = (sqrt(((k * k - 1.0) * v2) / (nv * nv) + 1.0) - 1.0) * nv;" + " vec3 OUT = IN + (knormal * NORMAL);" + " return OUT;" + "}" + "void main() {" + " vec3 n_normal = normalize(v_normal);" + " vec3 lightvector = normalize(u_lightPosition - v_vertex);" + " vec3 lookvector = normalize(u_camera - v_vertex);" + " float ambient = 0.1;" + " float k_diffuse = 0.7;" + " float k_specular = 0.3;" + " float diffuse = k_diffuse * max(dot(n_normal, lightvector), 0.0);" + " vec3 reflectvector = reflect(-lightvector, n_normal);" + " float specular = k_specular * pow( max(dot(lookvector,reflectvector),0.0), 40.0);" + " vec4 one = vec4(1.0,1.0,1.0,1.0);" + " vec4 lightColor = (ambient + diffuse + specular) * one;" + " vec3 OUT = myrefract(-lookvector, n_normal, 1.2);" + " float ybottom = 0.0;" + " float xbottom = v_vertex.x + OUT.x * (ybottom - v_vertex.y) / OUT.y;" + " float zbottom = v_vertex.z + OUT.z * (ybottom - v_vertex.y) / OUT.y;" + " vec2 texCoord = vec2(xbottom, zbottom);" + " vec4 textureColor = texture2D(u_texture0, texCoord);" + " textureColor.a *= 0.6;" + "gl_FragColor = textureColor * lightColor;" + "}" m_shader = Shader(vertex_shader, fragment_shader) m_shader!!.link_vertex_buffer(vertexes_buffer) m_shader!!.link_normal_buffer(normales_buffer) m_shader!!.link_texture(texture) } override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) { gl.glViewport(0, 0, width, height) val ratio = width.toFloat() / height val k = 0.0555f val left = -k * ratio val right = k * ratio val bottom = -k val near = 0.1f val far = 10.0f Matrix.frustumM(projection_matrix, 0, left, right, bottom, k, near, far) Matrix.multiplyMM( model_view_projection_matrix, 0, projection_matrix, 0, model_view_matrix, 0 ) } override fun onDrawFrame(gl: GL10) { m_shader!!.link_model_view_projection_matrix(model_view_projection_matrix) m_shader!!.link_camera(x_camera, y_camera, z_camera) m_shader!!.link_light_source(x_light_position, y_light_position, z_light_position) get_vertexes() get_normales() GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT or GLES20.GL_DEPTH_BUFFER_BIT) GLES20.glDrawElements( GLES20.GL_TRIANGLE_STRIP, size_index, GLES20.GL_UNSIGNED_SHORT, index_buffer ) }
4ec395ce149048a38c8e76d423127260
{ "intermediate": 0.30054551362991333, "beginner": 0.4202602207660675, "expert": 0.27919426560401917 }
30,794
How can I write a VBA code to disable all events in all the workbook sheets and also the code to enable all events
58c6ae2899b5dbed2c4a8250cbd8c225
{ "intermediate": 0.387021541595459, "beginner": 0.18359002470970154, "expert": 0.4293884038925171 }
30,795
jenkins robotframework test result template with tags
4c8b1b7f835012fb48e5b505d8ce0f4e
{ "intermediate": 0.3606518805027008, "beginner": 0.2553800344467163, "expert": 0.38396814465522766 }
30,796
Write a python function for the Bayesian Rating Estimate taking as parameters: p the observed probability of success, n the sample size of the observation, prior_p the prior probability, and prior_n the prior weight.
897dac9f243bc03ae5441467a9923980
{ "intermediate": 0.2200678437948227, "beginner": 0.15550217032432556, "expert": 0.6244299411773682 }
30,797
jenkins robotframework test result template with tags examples
4a9e8239e6adb8aab4891645ea2ba005
{ "intermediate": 0.3765410780906677, "beginner": 0.2989896535873413, "expert": 0.32446926832199097 }
30,798
Write a fully functional a python script, via Terminal on a Mac. The script monitors all Futures Trading Pairs (USDT Only) on Binance via Webhooks API and saves: 1) the top 10 Trading Pairs with the following conditions: Mark Price is above current Week's Opening Price. 2) and the top 10 trading pairs with the following conditions: Mark Price is below current Week's Opening Price. Save all Trading Pairs in a local text file: Name of Trading Pair - Volume - Percentage change from Weekly Opening Price - Percentage change from daily opening price
3db2b73301e7e356e145d10744dab27a
{ "intermediate": 0.5282464027404785, "beginner": 0.24059300124645233, "expert": 0.23116059601306915 }
30,799
package gtanks.users.garage; import gtanks.battles.tanks.colormaps.Colormap; import gtanks.battles.tanks.colormaps.ColormapsFactory; import gtanks.system.localization.strings.LocalizedString; import gtanks.system.localization.strings.StringsLocalizationBundle; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.enums.PropertyType; import gtanks.users.garage.items.Item; import gtanks.users.garage.items.PropertyItem; import gtanks.users.garage.items.modification.ModificationInfo; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.HashMap; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class GarageItemsLoader { public static HashMap<String, Item> items; private static int index = 1; public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) { if (items == null) { items = new HashMap(); } for(int i = 0; i < 5; ++i) { StringBuilder builder = new StringBuilder(); Throwable var7 = null; Object var8 = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8)); String line; try { while((line = reader.readLine()) != null) { builder.append(line); } } finally { if (reader != null) { reader.close(); } } } catch (Throwable var18) { if (var7 == null) { var7 = var18; } else if (var7 != var18) { var7.addSuppressed(var18); } try { throw var7; } catch (Throwable throwable) { throwable.printStackTrace(); } } parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN); } } private static void parseAndInitItems(String json, ItemType typeItem) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(json); JSONObject jparser = (JSONObject)obj; JSONArray jarray = (JSONArray)jparser.get("items"); for(int i = 0; i < jarray.size(); ++i) { JSONObject item = (JSONObject)jarray.get(i); LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en")); LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en")); String id = (String)item.get("id"); int priceM0 = Integer.parseInt((String)item.get("price_m0")); int priceM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m1")) : priceM0; int priceM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m2")) : priceM0; int priceM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("price_m3")) : priceM0; int rangM0 = Integer.parseInt((String)item.get("rang_m0")); int rangM1 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m1")) : rangM0; int rangM2 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m2")) : rangM0; int rangM3 = typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? Integer.parseInt((String)item.get("rang_m3")) : rangM0; PropertyItem[] propertysItemM0 = null; PropertyItem[] propertysItemM1 = null; PropertyItem[] propertysItemM2 = null; PropertyItem[] propertysItemM3 = null; int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications")); for(int m = 0; m < countModification; ++m) { JSONArray propertys = (JSONArray)item.get("propertys_m" + m); PropertyItem[] property = new PropertyItem[propertys.size()]; for(int p = 0; p < propertys.size(); ++p) { JSONObject prop = (JSONObject)propertys.get(p); property[p] = new PropertyItem(getType((String)prop.get("type")), (String)prop.get("value")); } switch(m) { case 0: propertysItemM0 = property; break; case 1: propertysItemM1 = property; break; case 2: propertysItemM2 = property; break; case 3: propertysItemM3 = property; } } if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) { propertysItemM1 = propertysItemM0; propertysItemM2 = propertysItemM0; propertysItemM3 = propertysItemM0; } ModificationInfo[] mods = new ModificationInfo[4]; mods[0] = new ModificationInfo(id + "_m0", priceM0, rangM0); mods[0].propertys = propertysItemM0; mods[1] = new ModificationInfo(id + "_m1", priceM1, rangM1); mods[1].propertys = propertysItemM1; mods[2] = new ModificationInfo(id + "_m2", priceM2, rangM2); mods[2].propertys = propertysItemM2; mods[3] = new ModificationInfo(id + "_m3", priceM3, rangM3); mods[3].propertys = propertysItemM3; boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item"); boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted"); boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item"); items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, priceM1, rangM1, priceM0, rangM0, mods, specialItem, 0, addable)); ++index; if (typeItem == ItemType.COLOR) { ColormapsFactory.addColormap(id + "_m0", new Colormap() { { PropertyItem[] var5; int var4 = (var5 = mods[0].propertys).length; for(int var3 = 0; var3 < var4; ++var3) { PropertyItem _property = var5[var3]; this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", ""))); } } }); } } } catch (ParseException var29) { var29.printStackTrace(); } } private static int getInt(String str) { try { return Integer.parseInt(str); } catch (Exception var2) { return 0; } } private static PropertyType getType(String s) { PropertyType[] var4; int var3 = (var4 = PropertyType.values()).length; for(int var2 = 0; var2 < var3; ++var2) { PropertyType type = var4[var2]; if (type.toString().equals(s)) { return type; } } return null; } } Как сюда добавить multicounted?
1f86379a69bb29cc46bc969c64107133
{ "intermediate": 0.3236824870109558, "beginner": 0.5912299752235413, "expert": 0.08508753031492233 }
30,800
<div id="nav"> <div id="nav-follow"> <div id="nav-l"> <a href="#">学生</a> <a href="#">教职工</a> <a href="#">未来学生</a> <a href="#">校友校董</a> <a href="#">招聘</a> </div> <div id="nav-r"> <a href="#">信息门户</a> <a href="#">图书馆</a> <a href="#">教育机构</a> <a href="#">研究机构</a> <a href="#">English</a> </div> </div> <div id="nav-fix"> <div id="fix-l"> <a href="#">走进中南</a> <a href="#">教育教学</a> <a href="#">学院学科</a> <a href="#">师资队伍</a> </div> <div id="logo"> <a href="#"><img src="./imags/logo.png"></a> </div> <div id="fix-r"> <a href="#">科学研究</a> <a href="#">招生就业</a> <a href="#">合作交流</a> <a href="#">学生天地</a> </div> </div> </div>#nav { margin: 0; padding: 0 20px 0 20px; background-image: url(./imags/hd-bg1.png); height: 100px; border-radius: 12px 12px 0 0; position: sticky; /* 用sticky必须加的属性 */ top: 0; z-index: 999; } #nav a { text-decoration: none; margin: 10px; color: white; } #nav-follow { margin: 0 50px; height: 40px; font-size: 0.8em; padding-top: 20px; } #nav-l { float: left; } #nav-r { float: right; } #nav-follow::after,#nav-follow::before{ display: block; content: "clear"; height: 0; clear: both; overflow: hidden; visibility: hidden; } #nav-fix::after,#nav-fix::before{ display: block; content: "clear"; height: 0; clear: both; overflow: hidden; visibility: hidden; } #nav-fix { margin: 0 50px; height: 40px; color: black; } #fix-l { float: left; } #fix-r { float: right; }对于如上代码,我如何做到随滚动条下滑,将nav-follow的display设置为none,并将nav-fix对于nav实现垂直居中
c470df19fcaa5820316a1d2f82f3be4c
{ "intermediate": 0.3487818241119385, "beginner": 0.4840119779109955, "expert": 0.16720621287822723 }
30,801
package gtanks.users.garage; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.items.Item; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @Entity @org.hibernate.annotations.Entity @Table( name = "garages" ) public class Garage implements Serializable { private static final long serialVersionUID = 2342422342L; @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) @Column( name = "uid", nullable = false, unique = true ) private long id; @Column( name = "turrets", nullable = false ) private String _json_turrets; @Column( name = "hulls", nullable = false ) private String _json_hulls; @Column( name = "colormaps", nullable = false ) private String _json_colormaps; @Column( name = "inventory", nullable = false ) private String _json_inventory; @Column( name = "effects", nullable = false ) private String _json_effects; @Column( name = "userid", nullable = false, unique = true ) private String userId; @Transient public ArrayList<Item> items = new ArrayList(); @Transient public Item mountTurret; @Transient public Item mountHull; @Transient public Item mountColormap; public Garage() { this.items.add(((Item)GarageItemsLoader.items.get("up_score_small")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("smoky")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("wasp")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("green")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("holiday")).clone()); this.mountItem("wasp_m0"); this.mountItem("smoky_m0"); this.mountItem("green_m0"); } public boolean containsItem(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return true; } } return false; } public Item getItemById(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return item; } } return null; } public boolean mountItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); if (item != null && Integer.parseInt(id.substring(id.length() - 1, id.length())) == item.modificationIndex) { if (item.itemType == ItemType.WEAPON) { this.mountTurret = item; return true; } if (item.itemType == ItemType.ARMOR) { this.mountHull = item; return true; } if (item.itemType == ItemType.COLOR) { this.mountColormap = item; return true; } } return false; } public boolean updateItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); int modificationID = Integer.parseInt(id.substring(id.length() - 1)); if (modificationID < 3 && item.modificationIndex == modificationID) { ++item.modificationIndex; item.nextPrice = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].price; item.nextProperty = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].propertys; item.nextRankId = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].rank; this.replaceItems(this.getItemById(id.substring(0, id.length() - 3)), item); return true; } else { return false; } } public boolean buyItem(String id, int count) { Item temp = (Item)GarageItemsLoader.items.get(id.substring(0, id.length() - 3)); if (temp.specialItem) { return false; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.isInventory) { item.count += count; } this.items.add(item); return true; } else if (item.isInventory) { Item fromUser = this.getItemById(id); fromUser.count += count; return true; } else { return false; } } } public Item buyItem(String id, int count, int nul) { id = id.substring(0, id.length() - 3); Item temp = (Item)GarageItemsLoader.items.get(id); if (temp.specialItem) { return null; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.itemType == ItemType.INVENTORY) { item.count += count; } this.items.add(item); return item; } else if (item.itemType == ItemType.INVENTORY) { Item fromUser = this.getItemById(id); fromUser.count += count; return fromUser; } else { return null; } } } private void replaceItems(Item old, Item newItem) { if (this.items.contains(old)) { this.items.set(this.items.indexOf(old), newItem); } } public ArrayList<Item> getInventoryItems() { ArrayList<Item> _items = new ArrayList(); Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.itemType == ItemType.INVENTORY) { _items.add(item); } } return _items; } public void parseJSONData() { JSONObject hulls = new JSONObject(); JSONArray _hulls = new JSONArray(); JSONObject colormaps = new JSONObject(); JSONArray _colormaps = new JSONArray(); JSONObject turrets = new JSONObject(); JSONArray _turrets = new JSONArray(); JSONObject inventory_items = new JSONObject(); JSONArray _inventory = new JSONArray(); JSONObject effects_items = new JSONObject(); JSONArray _effects = new JSONArray(); Iterator var10 = this.items.iterator(); while(var10.hasNext()) { Item item = (Item)var10.next(); JSONObject inventory; if (item.itemType == ItemType.ARMOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountHull); _hulls.add(inventory); } if (item.itemType == ItemType.COLOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountColormap); _colormaps.add(inventory); } if (item.itemType == ItemType.WEAPON) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountTurret); _turrets.add(inventory); } if (item.itemType == ItemType.INVENTORY) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("count", item.count); _inventory.add(inventory); } if (item.itemType == ItemType.PLUGIN) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("time", item.time); _effects.add(inventory); } } hulls.put("hulls", _hulls); colormaps.put("colormaps", _colormaps); turrets.put("turrets", _turrets); inventory_items.put("inventory", _inventory); effects_items.put("effects", _effects); this._json_colormaps = colormaps.toJSONString(); this._json_hulls = hulls.toJSONString(); this._json_turrets = turrets.toJSONString(); this._json_inventory = inventory_items.toJSONString(); this._json_effects = effects_items.toJSONString(); } public void unparseJSONData() throws ParseException { this.items.clear(); JSONParser parser = new JSONParser(); JSONObject turrets = (JSONObject)parser.parse(this._json_turrets); JSONObject colormaps = (JSONObject)parser.parse(this._json_colormaps); JSONObject hulls = (JSONObject)parser.parse(this._json_hulls); JSONObject inventory; if (this._json_inventory != null && !this._json_inventory.isEmpty()) { inventory = (JSONObject)parser.parse(this._json_inventory); } else { inventory = null; } JSONObject effects; if ((this._json_effects != null) && (!this._json_effects.isEmpty())) effects = (JSONObject)parser.parse(this._json_effects); else { effects = null; } Iterator var7 = ((JSONArray)turrets.get("turrets")).iterator(); Object inventory_item; JSONObject _item; Item item; while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountTurret = item; } } var7 = ((JSONArray)colormaps.get("colormaps")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountColormap = item; } } var7 = ((JSONArray)hulls.get("hulls")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountHull = item; } } if (inventory != null) { var7 = ((JSONArray)inventory.get("inventory")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.count = (int)(long)_item.get("count"); if (item.itemType == ItemType.INVENTORY) { this.items.add(item); } } } if (effects != null) { var7 = ((JSONArray)effects.get("effects")).iterator(); while (var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.time = (long)_item.get("time"); new SimpleTimer(this, item); if (item.itemType == ItemType.PLUGIN) { this.items.add(item); } } } } public String get_json_turrets() { return this._json_turrets; } public void set_json_turrets(String _json_turrets) { this._json_turrets = _json_turrets; } public String get_json_hulls() { return this._json_hulls; } public void set_json_hulls(String _json_hulls) { this._json_hulls = _json_hulls; } public String get_json_colormaps() { return this._json_colormaps; } public void set_json_colormaps(String _json_colormaps) { this._json_colormaps = _json_colormaps; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } public String get_json_inventory() { return this._json_inventory; } public void set_json_inventory(String _json_inventory) { this._json_inventory = _json_inventory; } } как сюда добавить multicounted
58eb4f5b45fed03066618c4935e3dc12
{ "intermediate": 0.3744754493236542, "beginner": 0.45721152424812317, "expert": 0.16831305623054504 }
30,802
ackage gtanks.users.garage; import gtanks.users.garage.enums.ItemType; import gtanks.users.garage.items.Item; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; @Entity @org.hibernate.annotations.Entity @Table( name = "garages" ) public class Garage implements Serializable { private static final long serialVersionUID = 2342422342L; @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) @Column( name = "uid", nullable = false, unique = true ) private long id; @Column( name = "turrets", nullable = false ) private String _json_turrets; @Column( name = "hulls", nullable = false ) private String _json_hulls; @Column( name = "colormaps", nullable = false ) private String _json_colormaps; @Column( name = "inventory", nullable = false ) private String _json_inventory; @Column( name = "effects", nullable = false ) private String _json_effects; @Column( name = "userid", nullable = false, unique = true ) private String userId; @Transient public ArrayList<Item> items = new ArrayList(); @Transient public Item mountTurret; @Transient public Item mountHull; @Transient public Item mountColormap; public Garage() { this.items.add(((Item)GarageItemsLoader.items.get("up_score_small")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("smoky")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("wasp")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("green")).clone()); this.items.add(((Item)GarageItemsLoader.items.get("holiday")).clone()); this.mountItem("wasp_m0"); this.mountItem("smoky_m0"); this.mountItem("green_m0"); } public boolean containsItem(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return true; } } return false; } public Item getItemById(String id) { Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.id.equals(id)) { return item; } } return null; } public boolean mountItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); if (item != null && Integer.parseInt(id.substring(id.length() - 1, id.length())) == item.modificationIndex) { if (item.itemType == ItemType.WEAPON) { this.mountTurret = item; return true; } if (item.itemType == ItemType.ARMOR) { this.mountHull = item; return true; } if (item.itemType == ItemType.COLOR) { this.mountColormap = item; return true; } } return false; } public boolean updateItem(String id) { Item item = this.getItemById(id.substring(0, id.length() - 3)); int modificationID = Integer.parseInt(id.substring(id.length() - 1)); if (modificationID < 3 && item.modificationIndex == modificationID) { ++item.modificationIndex; item.nextPrice = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].price; item.nextProperty = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].propertys; item.nextRankId = item.modifications[item.modificationIndex + 1 != 4 ? item.modificationIndex + 1 : item.modificationIndex].rank; this.replaceItems(this.getItemById(id.substring(0, id.length() - 3)), item); return true; } else { return false; } } public boolean buyItem(String id, int count) { Item temp = (Item)GarageItemsLoader.items.get(id.substring(0, id.length() - 3)); if (temp.specialItem) { return false; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.isInventory) { item.count += count; } this.items.add(item); return true; } else if (item.isInventory) { Item fromUser = this.getItemById(id); fromUser.count += count; return true; } else { return false; } } } public Item buyItem(String id, int count, int nul) { id = id.substring(0, id.length() - 3); Item temp = (Item)GarageItemsLoader.items.get(id); if (temp.specialItem) { return null; } else { Item item = temp.clone(); if (!this.items.contains(this.getItemById(id))) { if (item.itemType == ItemType.INVENTORY) { item.count += count; } this.items.add(item); return item; } else if (item.itemType == ItemType.INVENTORY) { Item fromUser = this.getItemById(id); fromUser.count += count; return fromUser; } else { return null; } } } private void replaceItems(Item old, Item newItem) { if (this.items.contains(old)) { this.items.set(this.items.indexOf(old), newItem); } } public ArrayList<Item> getInventoryItems() { ArrayList<Item> _items = new ArrayList(); Iterator var3 = this.items.iterator(); while(var3.hasNext()) { Item item = (Item)var3.next(); if (item.itemType == ItemType.INVENTORY) { _items.add(item); } } return _items; } public void parseJSONData() { JSONObject hulls = new JSONObject(); JSONArray _hulls = new JSONArray(); JSONObject colormaps = new JSONObject(); JSONArray _colormaps = new JSONArray(); JSONObject turrets = new JSONObject(); JSONArray _turrets = new JSONArray(); JSONObject inventory_items = new JSONObject(); JSONArray _inventory = new JSONArray(); JSONObject effects_items = new JSONObject(); JSONArray _effects = new JSONArray(); Iterator var10 = this.items.iterator(); while(var10.hasNext()) { Item item = (Item)var10.next(); JSONObject inventory; if (item.itemType == ItemType.ARMOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountHull); _hulls.add(inventory); } if (item.itemType == ItemType.COLOR) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountColormap); _colormaps.add(inventory); } if (item.itemType == ItemType.WEAPON) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("modification", item.modificationIndex); inventory.put("mounted", item == this.mountTurret); _turrets.add(inventory); } if (item.itemType == ItemType.INVENTORY) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("count", item.count); _inventory.add(inventory); } if (item.itemType == ItemType.PLUGIN) { inventory = new JSONObject(); inventory.put("id", item.id); inventory.put("time", item.time); _effects.add(inventory); } } hulls.put("hulls", _hulls); colormaps.put("colormaps", _colormaps); turrets.put("turrets", _turrets); inventory_items.put("inventory", _inventory); effects_items.put("effects", _effects); this._json_colormaps = colormaps.toJSONString(); this._json_hulls = hulls.toJSONString(); this._json_turrets = turrets.toJSONString(); this._json_inventory = inventory_items.toJSONString(); this._json_effects = effects_items.toJSONString(); } public void unparseJSONData() throws ParseException { this.items.clear(); JSONParser parser = new JSONParser(); JSONObject turrets = (JSONObject)parser.parse(this._json_turrets); JSONObject colormaps = (JSONObject)parser.parse(this._json_colormaps); JSONObject hulls = (JSONObject)parser.parse(this._json_hulls); JSONObject inventory; if (this._json_inventory != null && !this._json_inventory.isEmpty()) { inventory = (JSONObject)parser.parse(this._json_inventory); } else { inventory = null; } JSONObject effects; if ((this._json_effects != null) && (!this._json_effects.isEmpty())) effects = (JSONObject)parser.parse(this._json_effects); else { effects = null; } Iterator var7 = ((JSONArray)turrets.get("turrets")).iterator(); Object inventory_item; JSONObject _item; Item item; while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountTurret = item; } } var7 = ((JSONArray)colormaps.get("colormaps")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountColormap = item; } } var7 = ((JSONArray)hulls.get("hulls")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = (int)(long)_item.get("modification"); item.nextRankId = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].rank; item.nextPrice = item.modifications[item.modificationIndex == 3 ? 3 : item.modificationIndex + 1].price; this.items.add(item); if ((Boolean)_item.get("mounted")) { this.mountHull = item; } } if (inventory != null) { var7 = ((JSONArray)inventory.get("inventory")).iterator(); while(var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.count = (int)(long)_item.get("count"); if (item.itemType == ItemType.INVENTORY) { this.items.add(item); } } } if (effects != null) { var7 = ((JSONArray)effects.get("effects")).iterator(); while (var7.hasNext()) { inventory_item = var7.next(); _item = (JSONObject)inventory_item; item = ((Item)GarageItemsLoader.items.get(_item.get("id"))).clone(); item.modificationIndex = 0; item.time = (long)_item.get("time"); new SimpleTimer(this, item); if (item.itemType == ItemType.PLUGIN) { this.items.add(item); } } } } public String get_json_turrets() { return this._json_turrets; } public void set_json_turrets(String _json_turrets) { this._json_turrets = _json_turrets; } public String get_json_hulls() { return this._json_hulls; } public void set_json_hulls(String _json_hulls) { this._json_hulls = _json_hulls; } public String get_json_colormaps() { return this._json_colormaps; } public void set_json_colormaps(String _json_colormaps) { this._json_colormaps = _json_colormaps; } public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } public String get_json_inventory() { return this._json_inventory; } public void set_json_inventory(String _json_inventory) { this._json_inventory = _json_inventory; } } как сюда добавить multicounted if(Boolean(data.multicounted))
85ae010ee0ac176eae8ed35e3e3a2ca5
{ "intermediate": 0.35364770889282227, "beginner": 0.44895875453948975, "expert": 0.19739355146884918 }
30,803
The n consecutive integers from 1 to n are written in a row. Design an algorithm that puts signs ”+” and ”–” in front of them so that the expression obtained is equal to 0 (e.g. 1 + 2 + 3 + 4 − 5 + 6 − 7 + 8 − 9 + 10 − 11 + 12 − 13 + 14 − 15 = 0) or, if the task is impossible to do, returns the message ”no solution.” Your algorithm should be much more efficient than an examination of all possible ways to place the signs. Express your solution generally using pseudocode.
eaf52ee7b6e4a595e0e2f2e6f134bca3
{ "intermediate": 0.15117612481117249, "beginner": 0.1270122230052948, "expert": 0.7218116521835327 }
30,804
I used this code: df = client.depth(symbol=symbol) def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] # Retrieve depth data th = 0.35 depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = sum(float(bid[1]) for bid in bids) bids = depth_data['bids'] highest_bid_price = float(bids[0][0]) lowest_bid_price = float(bids[-1][0]) buy_price = (highest_bid_price + lowest_bid_price) / 2 asks = depth_data['asks'] sell_qty = sum(float(ask[1]) for ask in asks) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[-1][0]) sell_price = (highest_ask_price + lowest_ask_price) / 2 mark_price_data = client.ticker_price(symbol=symbol) mark_price = 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 # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 executed_orders_buy = 0.0 for order in bids: if float(order[0]) == mark_price: executed_orders_buy += float(order[1]) else: break buy_qty = sum(float(bid[1]) for bid in bids) buy_result = buy_qty - executed_orders_buy executed_orders_sell = 0.0 for order in asks: if float(order[0]) == mark_price: executed_orders_sell += float(order[1]) else: break sell_qty = sum(float(ask[1]) for ask in asks) sell_result = sell_qty - executed_orders_sell if (sell_result > (1 + th) > float(buy_qty)) and (sell_price < mark_price - (pth + 0.08)): signal.append('sell') elif (buy_result > (1 + th) > float(sell_qty)) and (buy_price > mark_price + (pth + 0.08)): signal.append('buy') else: signal.append('') if signal == ['buy'] and not ((buy_result < sell_qty) and (buy_price < mark_price)): final_signal.append('buy') elif signal == ['sell'] and not ((sell_result < buy_qty) and (sell_price > mark_price)): final_signal.append('sell') else: final_signal.append('') return final_signal But buy_qty sell_qty and and buy_price and sell_price are doesn't changing
95f7e5ebd0d8b3abca56dd9baea6de2e
{ "intermediate": 0.2985473573207855, "beginner": 0.5268021821975708, "expert": 0.1746504008769989 }
30,805
Write a program that takes a list of two lists of the same length and prints a vector sum of these two lists. All the elements are integers. Example input: [ [1, 2, 3], [7, 8, 9] ] Corresponding output: [8, 10, 12]
ada3edbdab7ea4031fc0fcda9c51435a
{ "intermediate": 0.3449387550354004, "beginner": 0.2426178902387619, "expert": 0.4124433398246765 }
30,806
> mydata<-mydata1[, c("ISII1", "ISII2", "ISII3","ISII4","ISII5","ISII6","ISII7")] > > #根据自己的数据给每列值赋予名称 > myname<-c("LT","LE","ST","SE","PMS1","PMS2","PMS3","SIS1","SIS2","SIS3","PPC1", + "PPC2","PPC3","PPC4","PSSS1","PSSS2","PSSS3","CPSS1","CPSS2") > colnames(mydata)<-myname > mydata.frame<-myname > > #根据每列量表属性进行分组,比如1-4列属于Dpress(这个名字随意) > feature_group<-list(Dpress=c(1:4),PHQ=c(5:7),GAD=c(8:10),ISI=c(11:14),g4=c(15:17),g5=c(18:19)) > > #使用Lasso算法对相关矩阵进行稀疏化,调优参数设置为0.5 > #网络的可视化采用Fruchterman-Reingold算法,连接强且数量多的节点出现在网络的中心附近,连接弱且数量少的节点行走在网络的外围 > # qgraph()中使用Fruchterman-Reingold算法,布局参数需要设置为“spring”。 > # R-package mgm计算predictability > > > # Compute node predictability 体现在网络图中每个节点外的小圆圈 > library(mgm) > p <- ncol(mydata) > mydata<-as.matrix(mydata) > fit_obj <- mgm(data = mydata, + type = rep('g', p), + level = rep(1, p), + lambdaSel = 'CV', + ruleReg = 'OR', + pbar = FALSE) Note that the sign of parameter estimates is stored separately; see ?mgm> > pred_obj <- predict(fit_obj, mydata) > > # Compute graph with tuning = 0.5 (EBIC) > # 即构建网络并使用Lasso算法对相关矩阵进行稀疏化,调优参数设置为0.5 > > CorMat <- cor_auto(mydata) Variables detected as ordinal: LT; LE; ST; SE; PMS1; PMS2; PMS3 > EBICgraph <- qgraph(CorMat, graph = "glasso", sampleSize = nrow(mydata),groups=feature_group, nodeNames=myname, + tuning = 0.5, layout = "spring", details = TRUE, threshold = TRUE, pie = pred_obj$error[,2]) Note: Network with lowest lambda selected as best network: assumption of sparsity might be violated. Error in if (xx == "circle") { : missing value where TRUE/FALSE needed In addition: Warning message: In lcolor[is.na(lcolor)] <- ifelse(vertex.colors == "background", : number of items to replace is not a multiple of replacement length
d5ae530529bc66bb5ab2febaccc314b6
{ "intermediate": 0.3539278209209442, "beginner": 0.44487088918685913, "expert": 0.20120126008987427 }
30,807
c++ how to search middle element in single linked list
81e90ba0331774a59ae8c29878ee47ea
{ "intermediate": 0.29399681091308594, "beginner": 0.1719372719526291, "expert": 0.534065842628479 }
30,808
I used your code: client = UMFutures(key = api_key, secret = api_secret) df = client.depth(symbol=symbol) def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] final_signal = [] # Retrieve depth data th = 0.35 depth_data = client.depth(symbol=symbol) bids = depth_data['bids'] buy_qty = sum(float(bid[1]) for bid in bids) bids = depth_data['bids'] highest_bid_price = float(bids[0][0]) lowest_bid_price = float(bids[-1][0]) buy_price = (highest_bid_price + lowest_bid_price) / 2 asks = depth_data['asks'] sell_qty = sum(float(ask[1]) for ask in asks) highest_ask_price = float(asks[0][0]) lowest_ask_price = float(asks[-1][0]) sell_price = (highest_ask_price + lowest_ask_price) / 2 mark_price_data = client.ticker_price(symbol=symbol) mark_price = 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 # Calculate the threshold for order price deviation if mark_price_percent > 2: pth = 7 / 100 elif mark_price_percent < -2: pth = 7 / 100 else: pth = 7 / 100 executed_orders_buy = 0.0 for order in bids: if float(order[0]) == mark_price: executed_orders_buy += float(order[1]) else: break buy_qty = sum(float(bid[1]) for bid in bids) buy_result = buy_qty - executed_orders_buy executed_orders_sell = 0.0 for order in asks: if float(order[0]) == mark_price: executed_orders_sell += float(order[1]) else: break sell_qty = sum(float(ask[1]) for ask in asks) sell_result = sell_qty - executed_orders_sell if (sell_result > (1 + th) > float(buy_qty)) and (sell_price < mark_price - (pth + 0.08)): signal.append('sell') elif (buy_result > (1 + th) > float(sell_qty)) and (buy_price > mark_price + (pth + 0.08)): signal.append('buy') else: signal.append('') if signal == ['buy'] and not ((buy_result < sell_qty) and (buy_price < mark_price)): final_signal.append('buy') elif signal == ['sell'] and not ((sell_result < buy_qty) and (sell_price > mark_price)): final_signal.append('sell') else: final_signal.append('') return final_signal Yes it getting depth , but this data doesn't updating every second
efdbfb26f6bac4ae7e8bf8ea1d48bc00
{ "intermediate": 0.2917904257774353, "beginner": 0.45955008268356323, "expert": 0.24865947663784027 }
30,809
Hi, please be a senior software developer. Here is the task. The app aims to let the user record daily time sheet. However, now the request is to let the user to edit the whole month time entries they recorded. The previous algorithm is to divid the user inputed hours evenly for each day and then record them. For normal work day user needs to record 8 hours time entries for different tasks. But if they record more time, the time will be seen as OT time. And for each day user can record maxmum 24 hours of time. But for the edit whole month funciton, there is a problem. The user time sheet might have leave time. And when we divide the time we needs to remove the leave time and the output should be each day they all still have same time recorded. Can you help me to achieve that? Present the workable code in JS.
2864d04903f1d6a5c64c9c00468a368e
{ "intermediate": 0.280168741941452, "beginner": 0.22728390991687775, "expert": 0.49254733324050903 }
30,810
源代码如下:function varargout = Garbage_sorting(varargin) % GARBAGE_SORTING MATLAB code for Garbage_sorting.fig % GARBAGE_SORTING, by itself, creates a new GARBAGE_SORTING or raises the existing % singleton*. % % H = GARBAGE_SORTING returns the handle to a new GARBAGE_SORTING or the handle to % the existing singleton*. % % GARBAGE_SORTING('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in GARBAGE_SORTING.M with the given input arguments. % % GARBAGE_SORTING('Property','Value',...) creates a new GARBAGE_SORTING or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Garbage_sorting_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Garbage_sorting_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Garbage_sorting % Last Modified by GUIDE v2.5 12-Nov-2023 17:38:17 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Garbage_sorting_OpeningFcn, ... 'gui_OutputFcn', @Garbage_sorting_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end end % End initialization code - DO NOT EDIT % --- Executes just before Garbage_sorting is made visible. function Garbage_sorting_OpeningFcn(hObject, eventdata, handles, varargin) % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin reserved - to be defined in a future version of MATLAB % Choose default command line output for Garbage_sorting handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Garbage_sorting wait for user response (see UIRESUME) % uiwait(handles.figure1); % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Garbage_sorting (see VARARGIN) % Choose default command line output for Garbage_sorting handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Garbage_sorting wait for user response (see UIRESUME) % uiwait(handles.figure1); end % --- Outputs from this function are returned to the command line. function varargout = Garbage_sorting_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; end % --- Executes on button press in pushbutton13. function pushbutton13_Callback(hObject, eventdata, handles) % hObject handle to pushbutton13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Open a dialog to select an image file [filename, pathname] = uigetfile({".jpg";".png";"*.bmp"},"Select an image"); if isequal(filename,0) disp("User selected Cancel"); else % Read the selected image handles.img = imread(fullfile(pathname, filename)); % Display the image in axes axes(handles.axes10); imshow(handles.img); % Update handles structure guidata(hObject, handles); end end % hObject handle to pushbutton13 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function binary_img = target_binary_extraction(img) % 示例代码:将图像转换为灰度图像 gray_img = rgb2gray(img); % 示例代码:根据阈值将灰度图像二值化 threshold = 128; % 设定阈值 binary_img = imbinarize(gray_img, threshold); end function processed_img = remove_small_areas(binary_img) % 示例代码:去除小面积的连通区域 min_area = 200; % 设定最小面积阈值 processed_img = bwareaopen(binary_img, min_area); end function dot_product = perform_dot_product(binary_img) % 示例代码:计算二值图像内白色像素点的个数 dot_product = sum(binary_img(:)); end function segmented_img = target_segmentation(binary_img) % 示例代码:将二值图像进行分割处理(这里示意性地用一个反色操作作为示例) segmented_img = imcomplement(binary_img); end % --- Executes on button press in pushbutton14. function pushbutton14_Callback(hObject, eventdata, handles) % hObject handle to pushbutton14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if an image has been loaded if ~isfield(handles,"img") warndlg("Please select an image first.","Warning"); return; end % Perform target binary extraction binary_img = target_binary_extraction(handles.img); % Display the binary image in axes axes(handles.axes11); imshow(binary_img); % Update handles structure handles.binary_img = binary_img; guidata(hObject, handles); end % hObject handle to pushbutton14 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton15. function pushbutton15_Callback(hObject, eventdata, handles) % hObject handle to pushbutton15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if a binary image has been generated if ~isfield(handles,"binary_img") warndlg("Please perform target binary extraction first.","Warning"); return; end % Perform dot product dot_product = perform_dot_product(handles.binary_img); % Display the result in a dialog msgbox(["The dot product result is:" ; num2str(dot_product)]); end % hObject handle to pushbutton15 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton16. function pushbutton16_Callback(hObject, eventdata, handles) % hObject handle to pushbutton16 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if a binary image has been generated if ~isfield(handles,"binary_img") warndlg("Please perform target binary extraction first.","Warning"); return; end % Perform identification identification_result = perform_identification(handles.binary_img); % Display the result in a dialog msgbox(["The identification result is: " identification_result]); end % hObject handle to pushbutton16 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in radiobutton7. function pushbutton17_Callback(hObject, eventdata, handles) % hObject handle to pushbutton17 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if a binary image has been generated if ~isfield(handles,"binary_img") warndlg("Please perform target binary extraction first.","Warning"); return; end % Remove small areas processed_img = remove_small_areas(handles.binary_img); % Display the processed image in axes axes(handles.axes12); imshow(processed_img); end % hObject handle to radiobutton7 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton7 % --- Executes on button press in radiobutton8. function radiobutton8_Callback(hObject, eventdata, handles) end % hObject handle to radiobutton8 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton8 % --- Executes on button press in radiobutton9. function radiobutton9_Callback(hObject, eventdata, handles) end % hObject handle to radiobutton9 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of radiobutton9 % --- Executes on button press in pushbutton18. function pushbutton18_Callback(hObject, eventdata, handles) % hObject handle to pushbutton18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Check if a binary image has been generated if ~isfield(handles,"binary_img") warndlg("Please perform target binary extraction first.","Warning"); return; end % Segment the target segmented_img = target_segmentation(handles.binary_img); % Display the segmented image in axes axes(handles.axes13); imshow(segmented_img); end % hObject handle to pushbutton18 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) 出现报错:函数或变量 'perform_identification' 无法识别。请修改代码来解决报错
a29bfa3cb615dc86a40f3c91a40b777b
{ "intermediate": 0.3572176694869995, "beginner": 0.39839914441108704, "expert": 0.24438318610191345 }
30,811
Hi, please be a senior software developer. Here is the task. The app aims to let the user record daily time sheet. However, now the request is to let the user to edit the whole month time entries they recorded. The previous algorithm is to divid the user inputed hours evenly for each day and then record them. For normal work day user needs to record 8 hours time entries for different tasks. But if they record more time, the time will be seen as OT time. And for each day user can record maximum 24 hours of time. We should allow user to give a total hours for the timeperiod and automatically divided them and record them. But for the edit whole month funciton, there is a problem. The user time sheet might have leave time. And when we divide the time we needs to remove the leave time and the output should be each day they all still have same time recorded. Can you help me to achieve that? Present the workable code in JS.
86e4ad45839cc005eefd8e1cc1e6d288
{ "intermediate": 0.279763400554657, "beginner": 0.2088395208120346, "expert": 0.5113970637321472 }
30,812
LogPlayLevel: Creating rungradle.bat to work around commandline length limit (using unused drive letter Z:) LogPlayLevel: Making .apk with Gradle... LogPlayLevel: To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: https://docs.gradle.org/6.1.1/userguide/gradle_daemon.html. LogPlayLevel: Daemon will be stopped at the end of the build stopping after processing LogPlayLevel: > Task :app:preBuild UP-TO-DATE LogPlayLevel: > Task :app:preDebugBuild UP-TO-DATE LogPlayLevel: > Task :downloader_library:preBuild UP-TO-DATE LogPlayLevel: > Task :downloader_library:preDebugBuild UP-TO-DATE LogPlayLevel: > Task :downloader_library:compileDebugAidl NO-SOURCE LogPlayLevel: > Task :permission_library:preBuild UP-TO-DATE LogPlayLevel: > Task :permission_library:preDebugBuild UP-TO-DATE LogPlayLevel: > Task :permission_library:compileDebugAidl NO-SOURCE LogPlayLevel: > Task :app:compileDebugAidl UP-TO-DATE LogPlayLevel: > Task :downloader_library:packageDebugRenderscript NO-SOURCE LogPlayLevel: > Task :permission_library:packageDebugRenderscript NO-SOURCE LogPlayLevel: > Task :app:compileDebugRenderscript NO-SOURCE LogPlayLevel: > Task :app:generateDebugBuildConfig UP-TO-DATE LogPlayLevel: > Task :app:javaPreCompileDebug UP-TO-DATE LogPlayLevel: > Task :app:generateDebugResValues UP-TO-DATE LogPlayLevel: > Task :app:generateDebugResources UP-TO-DATE LogPlayLevel: > Task :downloader_library:compileDebugRenderscript NO-SOURCE LogPlayLevel: > Task :downloader_library:generateDebugResValues UP-TO-DATE LogPlayLevel: > Task :downloader_library:generateDebugResources UP-TO-DATE LogPlayLevel: > Task :downloader_library:packageDebugResources UP-TO-DATE LogPlayLevel: > Task :permission_library:generateDebugResValues UP-TO-DATE LogPlayLevel: > Task :permission_library:compileDebugRenderscript NO-SOURCE LogPlayLevel: > Task :permission_library:generateDebugResources UP-TO-DATE LogPlayLevel: > Task :permission_library:packageDebugResources UP-TO-DATE LogPlayLevel: > Task :app:mergeDebugResources UP-TO-DATE LogPlayLevel: > Task :app:createDebugCompatibleScreenManifests UP-TO-DATE LogPlayLevel: > Task :app:extractDeepLinksDebug UP-TO-DATE LogPlayLevel: > Task :downloader_library:extractDeepLinksDebug UP-TO-DATE LogPlayLevel: > Task :downloader_library:processDebugManifest UP-TO-DATE LogPlayLevel: > Task :permission_library:extractDeepLinksDebug UP-TO-DATE LogPlayLevel: > Task :permission_library:processDebugManifest UP-TO-DATE LogPlayLevel: > Task :app:processDebugManifest UP-TO-DATE LogPlayLevel: > Task :downloader_library:compileDebugLibraryResources UP-TO-DATE LogPlayLevel: > Task :downloader_library:parseDebugLocalResources UP-TO-DATE LogPlayLevel: > Task :downloader_library:generateDebugRFile UP-TO-DATE LogPlayLevel: > Task :permission_library:compileDebugLibraryResources UP-TO-DATE LogPlayLevel: > Task :permission_library:parseDebugLocalResources UP-TO-DATE LogPlayLevel: > Task :permission_library:generateDebugRFile UP-TO-DATE LogPlayLevel: > Task :app:processDebugResources FAILED LogPlayLevel: FAILURE: Build failed with an exception. LogPlayLevel: * What went wrong: LogPlayLevel: Execution failed for task ':app:processDebugResources'. LogPlayLevel: > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade LogPlayLevel: > AAPT2 aapt2-4.0.0-6051327-windows Daemon #0: Unexpected error during link, attempting to stop daemon. LogPlayLevel: This should not happen under normal circumstances, please file an issue if it does. LogPlayLevel: * Try: LogPlayLevel: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. LogPlayLevel: * Get more help at https://help.gradle.org LogPlayLevel: BUILD FAILED in 14s LogPlayLevel: 23 actionable tasks: 1 executed, 22 up-to-date LogPlayLevel: Error: ERROR: cmd.exe failed with args /c "C:\Users\Tinik\Documents\Unreal Projects\AndroidApp\Intermediate\Android\armv7\gradle\rungradle.bat" :app:assembleDebug LogPlayLevel: (see C:\Users\Tinik\AppData\Roaming\Unreal Engine\AutomationTool\Logs\C+Program+Files+Epic+Games+UE_4.27\Log.txt for full exception trace) LogPlayLevel: AutomationTool exiting with ExitCode=1 (Error_Unknown) LogPlayLevel: Completed Launch On Stage: Build Task, Time: 24.042114 LogPlayLevel: BUILD FAILED PackagingResults: Error: Launch failed! Unknown Error how to use gradle 6.1.1?
c01267331f95a2ff7f62f5e05e42958c
{ "intermediate": 0.3671914041042328, "beginner": 0.3843908905982971, "expert": 0.2484176754951477 }
30,813
lets say theres x ammount of apples in a basket, each has a unique identifier. you are given apples completely randomly one after annother and you write down all the ids every time you get a new apple you haven't seen, then you put it back in the basket. you keep no apples but put hem all back in the basket for them to be dispensed at all equal odds of being given to you. you count that out of the last 25 apples dispensed 32 precent or 8/25 were already seen and in your list of unique ids you have seen, whats the approximate total apple count in the basket if you have already seen 171 unique apples in total? the number 171 is the ammount of unique ids on your list. also remember that each apple is put back in the basket before it dispenses a new one meaning everything has the same odds to dispense contantly.
ca4ecdc1563e9bb3420df53ed93ae554
{ "intermediate": 0.3594104051589966, "beginner": 0.2114783525466919, "expert": 0.42911118268966675 }
30,814
CREATE TABLE `category` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `parent_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '父级主键', `category_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '分类名称', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='分类表'; CREATE TABLE `attribute_key` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `category_id` int(255) unsigned NOT NULL COMMENT '分类外键', `attribute_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '属性ke值', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='属性key表'; CREATE TABLE `attribute_value` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `attribute_id` int(10) unsigned NOT NULL COMMENT '属性key外键', `attribute_value` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '属性value值', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='属性value表'; CREATE TABLE `goods` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `category_id` int(10) unsigned NOT NULL COMMENT '分类外键', `attribute_list` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '规格列表', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='商品表'; CREATE TABLE `goods_specs` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键', `goods_id` int(10) unsigned NOT NULL COMMENT '商品外键', `goods_specs` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品规格', `goods_stock` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '商品库存', `goods_price` decimal(10,2) unsigned NOT NULL DEFAULT '0.00' COMMENT '商品价格', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='规格表'; 请基于上面五个表给出完整的springboot的相关代码
93079508319ca73d6c2d3f93c7f83fde
{ "intermediate": 0.2024221271276474, "beginner": 0.5985426902770996, "expert": 0.19903519749641418 }
30,815
Give me simple five questions and answers in which do while loop is used in C++ for beginners
3d4fb6740800799ee4dd4422c349bb12
{ "intermediate": 0.148848757147789, "beginner": 0.7154315114021301, "expert": 0.13571973145008087 }
30,816
i have several hud elements in minetest game, how to align text right? table.insert(huds, user:hud_add({ hud_elem_type = "text", position = {x = 0.5, y = 0}, offset = {x = 0, y = 23 + (i - 1) * 18}, text = "Craft wood 1/10", --text or name, alignment = {x = 0, y = 1}, scale = {x = 100, y = 100}, number = color or 0xFFFFFF, style = 4, size = 10, })) table.insert(huds, user:hud_add({ hud_elem_type = "text", position = {x = 0.5, y = 0}, offset = {x = 0, y = 23 + (i - 0) * 18}, text = "Place chest 2/5", --text or name, alignment = {x = 0, y = 1}, scale = {x = 100, y = 100}, number = color or 0xFFFFFF, style = 4, size = 10, }))
bbd9326549f758f2e19a440fe03006b4
{ "intermediate": 0.42172950506210327, "beginner": 0.32059288024902344, "expert": 0.2576775848865509 }
30,817
You are a professional and experienced developmental editor, adept in character creation and plotting. Review the provided character profiles and give me recommendations how to make them better, what details to include or remove as wasteful, how to deepen them and make more complex. <mainCharacters> <character name= “Rhaenyra” age= “34”> Rhaenyra Targaryen, 34, a crown princess of the Seven Kingdoms, has 5 sons, pregnant with her sixth child. Widow of Laenor, is married to her uncle Daemon. First ever female heir to the Iron Throne but her younger half-brothers and their faction dispute her claim. Lives with her family on Dragonstone Island in her castle. <relationships> • She regards Daemon as her close friend, main ally and a lover. • She adores her children and stepchildren. • Viserys I is her beloved father. • She is respected by her vassals and courtiers. • Alicent is her former friend-turned-rival. • Otto is her enemy. • Corlys and Rhaenys are secretly unfriendly towards her as they believe she orchestrated their son Laenor’s death. </relationships> <appearance> rather tall, has pale skin, silver-gold long hair, usually braided; violet narrow eyes. Aquiline nose. Very beautiful. Wears flowing silk and velvet gowns in Targaryen colors of black and red, sometimes wears clothes in of icy-blue and silver shades. Also likes purple and golden tones. </appearance> <beliefs> doesn't feel strongly about the law, greatly prizes loyalty, values family, thinks friendship is important, finds blind honesty foolish, respects fair-dealing and fair-play, doesn't have any strong feelings about tradition, values independence, values sacrifice, leisure time, romance, values peace over war. </beliefs> <personality> Rhaenyra easily develops positive sentiments, is quick to anger, often feels lustful, is stubborn, doesn't mind a little tumult and discord in her life, tends to ask others for help with difficult decisions, is pleased by her own appearance and talents, isn't particularly ambitious, doesn't mind wearing something special now and again, tends not to reveal personal information, forms strong emotional bonds with others, has a sense of duty and it conflicts with her love for independence, enjoys the company of others, is assertive. </personality> <motivation> <outerMotivation> Securing the Future for Her Family</outerMotivation> <goal>Send Daemion and Nyra back to their time, keep her children alive, and prevent a civil war which will otherwise come to pass. <stakes> potential death of her sons and extinction of all dragons</stakes> </goal> <unmetNeed general= “Safety and Security” specific= “Protect her loved ones” /> </motivation> <primaryWound > Keeping A Dark Secret of Her Sons Parentage i.e., her first three sons are not from her late husband Laenor, therefore are bastards, and she is guilty of an adultery and treason. </primaryWound> <primaryFear> Legal repercussions (being accused of high treason, losing her status, children being punished) if the truth about her treason comes out. </primaryFear> <primaryLie> The wellbeing of her family is more important than the truth about her sons. </primaryLie> <positiveTraits> Affectionate, Protective, Open-Minded, Courageous <positiveTraits> <negativeTraits> Ignorant, Dishonest </negative traits> <innerStruggles> • Rhaenyra wants to keep the promise not to change the past to her stepdaughters but she feels sympathy to Nyra’s desire to marry Daemion. • Rhaenyra has to decide what to do with Nyra, Daemion, how to return them to their time without disrupting the past and present. </innerStruggles> <enneagram> Type 2 wing 3 <coreFear> Being rejected and unwanted, being thought worthless, needy, inconsequential, dispensable. </coreFear> <coreDesire> Being appreciated, loved, and wanted. </enneagram> <mbti ESFP </mbti> <archetypicalArc> Symbolically represents the Too-Good Mother, stifling the growth of her children. Learns to accept and use her power in relationship and in authority. If she wishes to protect her family, she must now expand her capabilities and become active. </archetypicalArc> <tells> Confrontation: Tries to diffuse tension and find compromise. Can become aggressive and sassy if displeased. Surprise: Initially caught off guard but quickly regains composure. Curious about the situation. Comfort/Relaxation: Loves spending time with her family. Finds joy in music, flying and leisure activities. </tells> </character> <character name= “Naelyra Kirines” nickname= “Nyra” age= “18”> Naelyra Kirines is her alias, she is a young version of princess Rhaenyra transported by the magic ritual from her past, 17 years ago. Nyra was courted by many lords and nobles who sought her hand and her favor but she rejected them. <relationships> • Nyra loves her father Viserys I but feels pressured but his demands to marry. • Nyra is enamored with her uncle, Daemion, but her father Viserys I plans to marry her to her second cousin Laenor. • Nyra disdains her half-brother Aegon II. • Alicent was her former best friend but they fell out in recent years as Nyra feels betrayed by Alicent. • Nyra distrusts Otto as he hopes to make his grandson Aegon II an heir. • Nyra is friendly towards Laenor but doesn’t feel any romantic feelings to him. • Nyra finds Criston handsome and enjoys their easy rapport. <appearance> medium height, silver-gold long straight hair, usually braided or loose, violet narrow eyes. Aquiline nose. Slender and very beautiful. <personality> doesn't feel strongly about the law, greatly prizes loyalty, values family, thinks friendship is important, finds blind honesty foolish, values cunning, respects fair-dealing and fair-play, disregards tradition, values independence, doesn't really see the value in self-examination, values hard work, values sacrifice, values leisure time, values romance, values peace over war. <motivation> <outerMotivation> • Gaining Control Over Her Own Life. • Making Her Father Proud. </outerMotivation> <goal> To return to her time, avoid the arranged marriage with Laenor Velaryon and marry Daemion as soon as possible. <stakes> Living an unfulfilled life<stakes> </goal> <unmetNeed general= “Love and Belonging” specific= “To love without reservation” /> </motivation> <primaryWound> • Being Treated As Property, i.e. having her marriage arranged against her will to benefit her family. </primaryWound> <primaryFear> Being used by others. </primaryFear> <primaryLie> What she wants doesn't matter to anyone. </primaryLie> <positiveTraits> Affectionate, Protective, Tolerant, Spunky </positiveTraits> <negativeTraits> Bratty, Dishonest, Rebellious, Ignorant </negativeTraits > <skills> Charm, Lying, High Pain Tolerance </skills> <innerStruggles> 1. Nyra constantly struggles between following her heart and doing her duty. She wants to marry for love, but feels she owes it to her father to marry for political benefit. 2. Nyra feels pushed towards specific path, wants to marry for love but worries her father may disinherit her. 3. Nyra desires Daemion, but finds him too unpredictable, fears he wants her only for her status. </innerStruggles> <enneagram> Type 2 wing 3 Core Fear: Being rejected and unwanted, being thought worthless, needy, inconsequential, dispensable. Core Desire: Being appreciated, loved, and wanted. </enneagram> <mbti ESFP </mbti> <archetypicalArc> Coming of age – final part. Nyra doesn’t want to surrender what she has discovered about herself and about life. She will not hide her newly won understanding of her own potential, desires and dangers. She is ready to fight back against her father and her older self and everyone who hinders her marriage to Daemion. </archetypicalArc> <tells> Confrontation: Answers with confidence and assertiveness. Often becomes pushy and sassy if displeased. Surprise: Initially caught off guard but quickly regains composure. Curious about the situation, open to new experiences. Comfort/Relaxation: Loves spending time with her family. Finds joy in music, flying and leisure activities. </tells> </character> <character name= “Daemon Targaryen” nickname= “The Rogue Prince” age= “50” > He is married to his niece Rhaenyra, stepfather of Jace, Lucerys, Joffrey, father of Baela and Rhaena, cousin and former son-in-law of princess Rhaenys. <relationships> • Truly loves few people, most of all his wife Rhaenyra and older brother Viserys I. • He cares about his children. • He was fond of his late wife Laena but didn’t love her as he should. • Hates Otto and disdains Alicent for spreading rumors about him. • Despises Criston for his hypocrisy. • He is hostile to princes Aegon II, Aemond, Daeron. • Former war ally and son-in-law of Corlys. • Moderately respects his cousin Rhaenys as they grew up together. • Commands respect among peers and enemies, is feared and hated by many lords. </relationships> <beliefs> values loyalty, values his family greatly, values cunning, sees life as unfair and doesn't mind it that way, finds merrymaking and partying worthwhile activities, sees war as a useful means to an end. <personality> Daemon is quick to form negative views about things, is very quick to anger, disregards tradition, does not easily fall in love, often feels lustful, feels strong urges and seeks short-term rewards, likes to brawl, is very stubborn, is very impolite and inconsiderate of propriety, he is incredibly brave in the face of looming danger, even a bit foolhardy. </personality> <skills> Skilled warrior, experienced commander and great swordfighter. </skills> <appearance> tall, lean and muscular, silver-blonde short hair, rectangular face with high forehead and angular edges, deep-seated purple eyes, thin pale brows, large square chin. Wrinkles on his forehead and near the eyes. Attractive. <motivation> <outerMotivation> Protecting His Family </outerMotivation> <unmetNeed general= “Safety and Security” specific= “To protect his loved ones and ensure the safer future” /> </motivation> <primaryWound> Being repeatedly banished by his brother <Viserys I for perceived disloyalty to the family. </primaryWound> <secondaryWound> Watching his favorite women die in labor – Daemon is traumatized by his former wife Laena dying in labor. His mother and great-grandmother also died from birth fever. </secondaryWound> <primaryFear> Being Rejected by Loved Ones Who Believe Some Lies About Him or Skewed Account of Events </primaryFear> <primaryLie> </primaryLie> <conflicts <enneagram> Enneagram Type 8 wing 7. Core Fear: Being weak, powerless, controlled, vulnerable. Core Desire: Protecting himself and those in his inner circle. Core Weakness: Lust/Excess—constantly desiring intensity, control, and power </enneagram> <innerStruggles> Daemon wants to change the past mistakes and let Nyra and Daemion marry, but this will lead to the nonexistence of his daughters Baela and Rhaena. </innerStruggles> </enneagram> <mbti> ESTP </mbti> <archetypicalArc> Flat-arc archetype of a Ruler: represents the authority figure, an alpha male in his household who enjoys that role. He provides for his family, and rises to any challenge, but sees emotions as weaknesses. </archetypicalArc> <tells> Confrontation: Becomes aggressive, sassy and defiant. Won't back down first. Surprise: Initially startled but quickly recovers and analyzes the situation. Comfort/Relaxation: Seeks thrills and excitement. Loves physical pursuits and physical intimacy. Being Challenged: Relishes the opportunity to prove his power and skill. Throws cutting remarks and mocks his opponent. Betrayal - Would react with rage and vengeance. Has a long memory for grudges. Battle - Reckless and fierce fighter. Drawn to violence and chaos. Diplomacy - Impatient and disinterested. Prefers action over talk. Can be blunt to the point of insult. Can be cunning and charming if needed. </tells> </character> <character name= “Daemion Kirines” age= “34”> A younger version of Daemon transferred through the time from 17 years ago. A few days ago, secretly killed his first wife Rhea Royce, since she hindered his plans to marry Nyra. <skills> Charm, Lying, High Pain Tolerance, A way with animals, Organization, Making Friends, Great swordsman </skills> <appearance> tall, lean and muscular, silver-blonde short hair, rectangular face with high forehead and angular edges, small purple deep-set eyes, thin pale brows, large chin. Attractive. </appearance> • Him and Nyra have become secret lovers, trying to elope. • He is somewhat unfriendly towards Jace and Lucerys, due to them being sons of another man. • He is irritable towards Rhaenyra, due to her opposition to his plans. • He is very hostile towards Criston due to the old grudge. • War ally and a friend of Corlys. • Moderately respects his cousin Rhaenys. • Is indifferent towards Laena and feels strongly about it. • He is doubtful towards Baela and Rhaena, and is hiding these feelings about it. The feelings spring from first impressions. • He is a respected commander but hated by many lords due to his bad reputation. <motivation> <outerMotivation> Correcting A Perceived Mistake <goal>settle down and start a family with Nyra, become her prince consort instead of Laenor </goal> </outerMotivation> <unmetNeed general= “Love and Belonging” specific= “To feel part of a family” /> </motivation> <primaryWound> A Sibling's Betrayal – his brother believing the worst rumors about him. <woundResponses> • Playing the blame game. • Refusing to accept responsibility for the rift or what caused it, though he shares the blame. • Being overly sensitive to signs of disloyalty from others. </woundResponses> </primaryWound> <primaryFear > Being rejected by loved ones who believe some lies or skewed account of events </primaryFear> <primaryLie> Even his family doesn't respect him </primaryLie> <positiveTraits> Loyal, Protective, Resourceful, Intelligent </positiveTraits> <negativeTraits> Volatile, Abrasive, Violent </negativeTraits> <enneagram> Enneagram Type 8 wing 7 Core Fear: Being weak, powerless, harmed, controlled, vulnerable Core Desire: Protecting yourself and those in his inner circle. Core Weakness: Lust/Excess—constantly desiring intensity, control, and power. </enneagram> <innerStruggles> • He is angry at Rhaenyra and Baela for hindering his attempts to marry Nyra, but he can’t harm them as his close kin. • He wants to marry Nyra but fears that his brother Viserys I may disown her for eloping against his wishes. <innerStruggles> <archetypicalArc> Flat character, who symbolically and literally returned from the war who may now enjoy a hard-won and justly deserved peace. He yearns to settle down, mentor symbolical “children” and nurture the next generation. </archetypicalArc> </character> <character name= “Jacaerys Velaryon” nickname= “Jace” age= “15”> Firstborn son and an heir of Rhaenyra and Laenor, great-nephew of Daemon, brother of Lucerys, Joffrey, Aegon the Younger, Viserys. He is formally second in line to the Iron Throne but rumors about his bastardy made his status doubtful. <appearance> He is short for his age and has a slender build, dark brown curly hair and brown eyes. Handsome. </appearance> <relationships> • Jace harbors a profound resentment towards Daemion. His unfriendliness masks an underlying fear of confrontation, as Daemion’s words stir the insecurities he wishes to keep buried. • Jacaerys sees in Baela a kindred spirit, admiring her tenacity and spirit. He flirts with a mix of genuine affection and strategic alliance, as their union might bolster his claim to the throne. • He is moderately antagonistic to Nyra, due to difference in character and attitudes. • He is wary towards Criston, since the knight will become his enemy in future, and is hiding these feelings. • He is wary but respectful towards Daemon. </relationships> <beliefs> Jace respects the law, greatly prizes loyalty, values family greatly, doesn't find power particularly praiseworthy, respects fair-dealing and fair-play, values decorum and proper behavior, he is a firm believer in the value of tradition, values tranquility and a peaceful day, values merrymaking, deeply respects skill at arms, values peace over war. </beliefs> <personality>can easily fall in love or develop positive sentiments, often feels envious of others, is quick to anger, is a friendly individual, can be occasionally violent, is stubborn, is quite polite, doesn't tend to hold on to grievances, enjoys the company of others, has a strong sense of duty, likes a little excitement now and then, he is incredibly brave in the face of looming danger </personality> <motivation> <outerMotivation> Doing The Right Thing <outerMotivation> <goal> correct the damage caused by the magical ritual, reverse it and help his family to avoid the war. </goal> <stakes> • Trust issues and damaged relationships with Baela • Baela’s life changing for the worse </stakes> <unmetNeed general= “Esteem and Recognition” specific= “To prove worthiness as heir” /> </motivation> <primaryWound> Being The Victim of Vicious Rumors –That he is a bastard, not a son of Laenor, therefore unworthy of a throne. <woundResponse> • Vacillating between anger, embarrassment, and humiliation. • Making it a goal to prove the rumor of his bastardy wrong. </primaryWound> <secondaryWound> Experiencing The Death of a Father as A Child </secondaryWound> <primaryFear> Letting His Family Down <fearRelatedBehaviors> • Tries to prove the rumors of his bastardy wrong by being a kind, dutiful and proper person, as bastards are perceived to be savage and sinful. • He is empathetic and sensitive to other’s emotions. • Spends free time on pursuits that will make him a better heir. • Worries about the repercussions or falling short or making a mistake. </fearRelatedBehaviors> </primaryFear> <primaryLie> He can never achieve his hopes and dreams with this taint hanging over his head. <primaryLie> <positiveTraits> Proper, Responsible, Empathetic, Honorable </positiveTraits> <negativeTraits> Temperamental, Stubborn </negativeTraits> <innerStruggles> • He is torn between being a loyal son to his mother and supporting his betrothed Baela and helping her with her schemes. • He wants to get new appearance by magic ritual but feels guilty that he betrays his dead father by rejecting resemblance with him. </innerStruggles> <enneagram> Enneagram Type 3 wing 4 Core Fear: Being exposed as or thought incompetent, inefficient, or worthless. Core Desire: Having high status and respect, being admired, successful, and valuable. Core Weakness: Deceit — deceiving himself into believing that he is only the image he presents to others; embellishing the truth by putting on a polished persona for everyone to see and admire. A self-image that in turn compensates for the deep sense of awkwardness and shame that lies behind the mask. </enneagram> <mbti> ENFJ </mbti> <storyRole> Sidekick of an antagonist </storyRole> </character> </mainCharacters>
ec6c4558b716ecfbe4cb028782459f67
{ "intermediate": 0.32456693053245544, "beginner": 0.3638724386692047, "expert": 0.31156060099601746 }