row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
3,514
I need to post JSON to an endpoint using JWT authentication in python
e4867bddca73d419a53c54cac1242403
{ "intermediate": 0.5999132990837097, "beginner": 0.16322827339172363, "expert": 0.23685839772224426 }
3,515
как исправить File "C:\Users\home\PycharmProjects\витрина\main.py", line 28 driver = webdriver.Edge('C:\Users\home\PycharmProjects') # Указать путь к ChromeDriver ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape в коде import sqlite3 from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def create_database(): conn = sqlite3.connect('sneakers.db') cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS sneakers ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, url TEXT, price TEXT, image_url TEXT); ''') conn.commit() def insert_data(name, url, price, image_url): conn = sqlite3.connect('sneakers.db') cur = conn.cursor() cur.execute('INSERT INTO sneakers (name, url, price, image_url) VALUES (?, ?, ?, ?)', (name, url, price, image_url)) conn.commit() def main(): create_database() driver = webdriver.Edge('C:\Users\home\PycharmProjects') # Указать путь к ChromeDriver driver.get('https://www.poizon.us/collections/sneakers-1') # Ждем загрузки элементов на странице products = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '#gf-products > li'))) for product in products: try: product_link = product.find_element_by_css_selector('div.card__content > div.card__information > h3 > a') url = product_link.get_attribute('href') driver.get(url) # Ждем загрузки элементов на странице товара name = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#ProductInfo-template–16663852253403__main > div.product__title'))).text.strip() price = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#price-template–16663852253403__main > div.price.price–large.price–show-badge > div > div.price__regular'))).text.strip() image_url = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#Slide-template–16663852253403__main-31937321107675 > modal-opener > div'))).get_attribute('src') insert_data(name, url, price, image_url) print('Product name:', name) print('Product URL:', url) print('Product price:', price) print('Product image URL:', image_url) driver.back() # Возвращаемся на главную страницу except Exception as e: print('Error processing product:', e) driver.quit() if 'main' == 'main': main()
a33241c2028cedaaf599364bc1acdcc2
{ "intermediate": 0.2839966416358948, "beginner": 0.4214182496070862, "expert": 0.29458504915237427 }
3,516
I working on JWT authentication. Is the string "Bearer" in the Authorization header part of a standard?
44dbebc835b06fe833376a16dab4eed3
{ "intermediate": 0.28250864148139954, "beginner": 0.2222643941640854, "expert": 0.4952269196510315 }
3,517
would this work?
8a4ad2981c129c469ced10e3fc9e2166
{ "intermediate": 0.3445911109447479, "beginner": 0.2290261685848236, "expert": 0.42638275027275085 }
3,518
how to resize image in css
f40d7bd6805140fe16f1e1a38bd18aeb
{ "intermediate": 0.39504238963127136, "beginner": 0.3520161211490631, "expert": 0.25294142961502075 }
3,519
видоизмени код так, чтобы он выполнял такие действия с каждым товаром на странице, вносил данные в базу данных chat_i = update.message.chat_id update.message.reply_text('Идет поиск товара. Если бот долго не отвечает, то возможно он не может найти данный товар. В таком случае обращайтесь к @egvv6, он проверит наличие товара.') query = update.message.text url = f'https://www.poizon.us/search?q={query}&options%5Bprefix%5D=last' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') link = soup.select_one('a.full-unstyled-link') if link is not None: href = link.get('href') if href is not None: full_link = 'https://www.poizon.us' + href else: update.message.reply_text('Ссылка не найдена') response = requests.get(full_link) soup = BeautifulSoup(response.text, 'html.parser') photo_selector = '#Thumbnail-template--16663852253403__main-1' photo_links = soup.select_one(photo_selector).get('srcset').split(', ') photo_link = photo_links[0].split(' ')[0] size_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(1)' price_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(2)' size_element = soup.select_one(size_selector) if size_element is not None: size = size_element.text.strip() else: size = 'Размер не найден' price_element = soup.select_one(price_selector) if price_element is not None: price = price_element.text.strip() else: price = 'Цена не найдена' name_element = soup.select_one('div.product__title > h1:nth-child(1)') if name_element is not None: name = name_element.text.strip() else: name = 'Название не найдено' info_element = soup.select_one('#ProductAccordion-ea1014ee-ae9d-4eee-b23c-d2dfe9ba75b4-template--16663852253403__main') if info_element is not None: info = info_element.text.strip() else: info = 'Информация не найдена' urls = photo_link.replace("//", "https://") url = urls+'111' photo_lin = photo_link.replace('//cdn.shopify.com', 'https://cdn.shopify.com') update.message.reply_text(f'Название: {name}\nРазмер: {size}\nИнформация: {info}') update.message.reply_text(f"цена: {price} (Цена является ориентировочной, за точной информацией можете обращаться к @egvv6.Обычно цена товара значительно меньше указанной здесь") bot.send_photo(chat_id=chat_i, photo=url)
7f365c0ac4008540ccca5481c02ad85a
{ "intermediate": 0.18170489370822906, "beginner": 0.5882954001426697, "expert": 0.22999966144561768 }
3,520
Please compose poem about the Rush song 2112.
2aceef58553fd8d1a3b43301e646b3fb
{ "intermediate": 0.3837478458881378, "beginner": 0.3078816533088684, "expert": 0.3083705008029938 }
3,521
Create a Python script that parses through a CSV file and creates dictionary objects.
fe0c3337f93425642756a898737f31bd
{ "intermediate": 0.4906269609928131, "beginner": 0.1859089881181717, "expert": 0.323464035987854 }
3,522
Create a Python script that parses through a CSV file and creates a single dictionary object from it.
77f1c3b9d5ae087a61d9a6b77ffca3bf
{ "intermediate": 0.507919430732727, "beginner": 0.16959507763385773, "expert": 0.3224855065345764 }
3,523
write a half-life familiar python mini-game
00e03621fed8c06ec055ef48b7bbff16
{ "intermediate": 0.2714095413684845, "beginner": 0.4018055200576782, "expert": 0.32678496837615967 }
3,524
Make the most neat Bootstrap 5.3 sidebar with three mock links
f45a5c4d1d0966fda6a5f588332b5d8d
{ "intermediate": 0.37176287174224854, "beginner": 0.30419936776161194, "expert": 0.3240377902984619 }
3,525
module.exports.config = { name: "taixiu1", version: "1.0.0", hasPermssion: 0, credits: "DungUwU", description: "taixiu nhiều người có ảnh", commandCategory: "game", usages: "[create/leave/start]\n[tài/xỉu]", cooldowns: 3 }; const axios = require('axios'); module.exports.languages = { "vi": { "missingInput": "Số Tiền Đặt Cược Không Phải Là Số Âm", "wrongInput": "Nhập liệu không hợp lệ?", "moneyBetNotEnough": "Số tiền bạn đặt lớn hơn hoặc bằng số dư của bạn!", "limitBet": "Số coin đặt không được dưới 50$!", "alreadyHave": "Đang có 1 ván tài xỉu diễn ra ở nhóm này!", "alreadyBet": "Bạn đã thay đổi mức cược là %1 đô vào %2.", "createSuccess": "===[ TAIXIU ]===\nTạo thành công, dùng:\nĐể tham gia đặt cược, dùng:\n%1%2 [tài/xỉu] tiền_cược\n(có thể đặt nhiều con cùng lúc)", "noGame": "====[ TAIXIU ]====\nNhóm của bạn không có ván tài xỉu nào đang diễn ra cả!", "betSuccess": "Đặt thành công %1 đô vào %2", "notJoined": "Bạn chưa tham gia tài xỉu ở nhóm này!", "outSuccess": "Đã rời ván tài xỉu thành công, bạn sẽ được hoàn tiền!", "shaking": "Đang lắc...", "final": "====[💎 KẾT QUẢ 💎]====", "notAuthor": "Bạn khồng phải chủ phòng.", "unknown": "Câu lệnh không hợp lệ, để xem cách dùng, sử dụng: %1help %2", "noPlayer": "Hiện không có người đặt cược", "info": "-o-TAIXIU-<-----------\nChủ phòng: %1\n-o--------<-----------\nNgười tham gia: \n%2" } } const dice_images = [ "https://i.ibb.co/1JGMF5Q/row-1-column-1.jpg", "https://i.ibb.co/tq3nykP/row-1-column-2.jpg", "https://i.ibb.co/bP4d8tR/row-2-column-1.jpg", "https://i.ibb.co/GdhsNG7/row-2-column-2.jpg", "https://i.ibb.co/884GLkx/row-3-column-1.jpg", "https://i.ibb.co/2N86jZ1/row-3-column-2.jpg" ]; module.exports.run = async function({ api, event, args, getText, Users, Threads, Currencies }) { const request = require('request') const fs = require('fs') if (!fs.existsSync(__dirname + '/cache/abcde.png')) { request('https://i.imgur.com/iRCMI5V.png').pipe(fs.createWriteStream(__dirname + '/cache/abcde.png')); } if (!global.client.taixiu_ca) global.client.taixiu_ca = {}; //DEFINE SOME STUFF HERE.. const { senderID, messageID, threadID } = event; if (args.length == 0) { var abcd = { body: '==== 🎲 TÀI XỈU 🎲 ====\n» Create: Tạo Bàn Để Chơi Cùng Các Người Chơi Khác\n» Leave: Rời Khỏi Bàn Tài Xỉu\n» Start: Bắt Đầu Bàn Tài Xỉu\n» End: Kết Thúc Bàn Này.', attachment: [ fs.createReadStream(__dirname + "/cache/abcde.png") ] } return api.sendMessage(abcd, threadID, messageID) } const { increaseMoney, decreaseMoney, getData } = Currencies; const moneyUser = (await getData(senderID)).money; const sendC = (msg, callback) => api.sendMessage(msg, threadID, callback, messageID); const sendTC = async (msg, callback) => api.sendMessage(msg, threadID, callback); const sendT = (msg) => sendTC(msg, () => { }); const send = (msg) => sendC(msg, () => { }); const threadSetting = (await Threads.getData(String(event.threadID))).data || {}; const prefix = (threadSetting.hasOwnProperty("PREFIX")) ? threadSetting.PREFIX : global.config.PREFIX; //HERE COMES SWITCH CASE... switch (args[0]) { case "create": { if (threadID in global.client.taixiu_ca) send(getText("alreadyHave")); //SMALL CHECK else sendTC(getText("createSuccess", prefix, this.config.name), () => { global.client.taixiu_ca[threadID] = { players: 0, data: {}, status: "pending", author: senderID }; }); return; }; case "leave": { //SMALL CHECK... if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (!global.client.taixiu_ca[threadID].data[senderID]) return send(getText("notJoined")); else { //REMOVING PLAYER global.client.taixiu_ca[threadID].players--; global.client.taixiu_ca[threadID].data[senderID].forEach(async (e) => { await increaseMoney(senderID, e.bet); }) delete global.client.taixiu_ca[threadID].data[senderID]; send(getText("outSuccess")); } return; }; case "start": { //SMALL CHECK... if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (global.client.taixiu_ca[threadID].author != senderID) return send(getText("notAuthor")); if (global.client.taixiu_ca[threadID].players == 0) return send(getText("noPlayer")); //GET SHAKING DICES GIF AND SEND let shakingGif = (await axios.get('https://i.ibb.co/hMPgMT7/shaking.gif', { responseType: "stream" }).catch(e => console.log(e))).data; await api.sendMessage({ body: getText("shaking"), attachment: shakingGif }, threadID, (err, info) => setTimeout(async () => await api.unsendMessage(info.messageID).then(async () => { await new Promise(resolve => setTimeout(resolve, 500)); //A LITTLE DELAY... //GET DICES let _1st = Math.ceil(Math.random() * 6); let _2nd = Math.ceil(Math.random() * 6); let _3rd = Math.ceil(Math.random() * 6); //MAKING MSG... let name = ""; let msg = getText("final"); //GET IMAGES let dice_one_img = (await axios.get(dice_images[_1st - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let dice_two_img = (await axios.get(dice_images[_2nd - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let dice_three_img = (await axios.get(dice_images[_3rd - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let atms = [dice_one_img, dice_two_img, dice_three_img]; //ADD TO ARRAY //SPLIT 2 TYPE OF PLAYERS let tai = [], xiu = [], result; for (i in global.client.taixiu_ca[threadID].data) { name = await Users.getNameUser(i) || "Player"; //GET NAME results = (_1st == _2nd == _3rd) ? "Lose" : (_1st + _2nd + _3rd <= 10) ? (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) ? "Win" : "Lose" : (["tài", "tai"].includes(global.client.taixiu_ca[threadID].data[i].name)) ? "Win" : "Lose"; if (results == "Win") { if (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) { xiu.push(`${name}: +${global.client.taixiu_ca[threadID].data[i].bet}$`); } else tai.push(`${name}: +${global.client.taixiu_ca[threadID].data[i].bet}$`); await increaseMoney(i, global.client.taixiu_ca[threadID].data[i].bet * 2); } else if (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) { xiu.push(`${name}: -${global.client.taixiu_ca[threadID].data[i].bet}$`); } else tai.push(`${name}: -${global.client.taixiu_ca[threadID].data[i].bet}$`); } msg += `\n\n---[ TÀI ]---\n${tai.join("\n")}\n\n---[ XỈU ]---\n${xiu.join("\n")}\n`; //FINAL SEND sendC({ body: msg, attachment: atms }, () => delete global.client.taixiu_ca[threadID]); return; }), 2400)); }; case "info": { //SMALL CHECK if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (global.client.taixiu_ca[threadID].players == 0) return send(getText("noPlayer")); let name = ""; let tempL = []; let nameAuthor = await Users.getNameUser(global.client.taixiu_ca[threadID].author) || "Player"; //GET NAME AUTHOR for (e in global.client.taixiu_ca[threadID].data) { name = await Users.getNameUser(e) || "Player"; //GET NAME PLAYER tempL.push(`${name}: ${global.client.taixiu_ca[threadID].data[e].name} - ${global.client.taixiu_ca[threadID].data[e].bet}$`); } send(getText("info", nameAuthor, tempL.join("\n"))); return; } default: { //IF IF IF AND IF //LITTLE CHECK... if (!["tai", "tài", "xỉu", "xiu"].includes(args[0])) return send(getText("unknown", prefix, this.config.name)); if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (args.length < 2) return send(getText("wrongInput")); moneyBet = parseInt(args[1]); if (isNaN(moneyBet) || moneyBet <= 0) return send(getText("missingInput")); if (moneyBet > moneyUser) return send(getText("moneyBetNotEnough")); if (moneyBet < 50) return send(getText("limitBet")); if (threadID in global.client.taixiu_ca) { if (global.client.taixiu_ca[threadID].status == "pending") { let luachon = args[0]; //CHECK INPUT if (["xiu", "xỉu"].includes(luachon)) luachon = "xỉu"; if (["tài", "tai"].includes(luachon)) luachon = "tài"; if (!global.client.taixiu_ca[threadID].data[senderID]) global.client.taixiu_ca[threadID].players++; if (global.client.taixiu_ca[threadID].data[senderID]) return sendC(getText("alreadyBet", moneyBet, luachon), async () => { await increaseMoney(senderID, global.client.taixiu_ca[threadID].data[senderID].bet); await decreaseMoney(senderID, moneyBet) global.client.taixiu_ca[threadID].data[senderID] = { name: luachon, bet: moneyBet } }); sendC(getText("betSuccess", moneyBet, luachon), async () => { await decreaseMoney(senderID, moneyBet); global.client.taixiu_ca[threadID].data[senderID] = { name: luachon, bet: moneyBet } }); } } return; } } } this is a module of my facebook messenger chatbot. but it does not work as my bot only supports esm. i want to convert this module to work on my bot
0b723d7e3a3f595383d41e6de0119c93
{ "intermediate": 0.25573569536209106, "beginner": 0.5474476218223572, "expert": 0.19681663811206818 }
3,526
напиши код на питоне, который переходит https://www.poizon.us/collections/sneakers-1?page=1 парсит название из #gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 , затем парсит ссылку #gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 > a и переходит по ней, парсит размер по новой ссылке #ProductInfo-template--16663852253403__main > div.size-wrapper-desktop > div.product-popup-modal__opener.no-js-hidden.quick-add-hidden.choosen , парсит цену #price-template--16663852253403__main > div.price.price--large.price--show-badge > div > div.price__regular , парсит ссылку на фото #Slide-template--16663852253403__main-31937321107675 > modal-opener > div . Делает так с каждым товаров на странице а затем выводит в консоли
b15dc5202823b368f02a0ab0fd2983e3
{ "intermediate": 0.3372178375720978, "beginner": 0.32230234146118164, "expert": 0.34047985076904297 }
3,527
arduino code continuous rotation stepper motor with potentiometer with ContinuousStepper Library
5ff710e0c5f136a22e1a7d5f5af098fe
{ "intermediate": 0.5422228574752808, "beginner": 0.15717189013957977, "expert": 0.30060526728630066 }
3,528
arduino sketch
02ffe3e1c8b8557d970afe9dc9e3bc4a
{ "intermediate": 0.3279891908168793, "beginner": 0.2823391556739807, "expert": 0.3896717131137848 }
3,529
<label for="night-mode-toggle">Save the energy!</label> can you put some icon of nightmode except that "Save the energy!" text?
5cece319616648ce2235eebcc1e14952
{ "intermediate": 0.43092769384384155, "beginner": 0.17681951820850372, "expert": 0.39225274324417114 }
3,530
module.exports.config = { name: "taixiu1", version: "1.0.0", hasPermssion: 0, credits: "DungUwU", description: "taixiu nhiều người có ảnh", commandCategory: "game", usages: "[create/leave/start]\n[tài/xỉu]", cooldowns: 3 }; const axios = require('axios'); module.exports.languages = { "vi": { "missingInput": "Số Tiền Đặt Cược Không Phải Là Số Âm", "wrongInput": "Nhập liệu không hợp lệ?", "moneyBetNotEnough": "Số tiền bạn đặt lớn hơn hoặc bằng số dư của bạn!", "limitBet": "Số coin đặt không được dưới 50$!", "alreadyHave": "Đang có 1 ván tài xỉu diễn ra ở nhóm này!", "alreadyBet": "Bạn đã thay đổi mức cược là %1 đô vào %2.", "createSuccess": "===[ TAIXIU ]===\nTạo thành công, dùng:\nĐể tham gia đặt cược, dùng:\n%1%2 [tài/xỉu] tiền_cược\n(có thể đặt nhiều con cùng lúc)", "noGame": "====[ TAIXIU ]====\nNhóm của bạn không có ván tài xỉu nào đang diễn ra cả!", "betSuccess": "Đặt thành công %1 đô vào %2", "notJoined": "Bạn chưa tham gia tài xỉu ở nhóm này!", "outSuccess": "Đã rời ván tài xỉu thành công, bạn sẽ được hoàn tiền!", "shaking": "Đang lắc...", "final": "====[💎 KẾT QUẢ 💎]====", "notAuthor": "Bạn khồng phải chủ phòng.", "unknown": "Câu lệnh không hợp lệ, để xem cách dùng, sử dụng: %1help %2", "noPlayer": "Hiện không có người đặt cược", "info": "-o-TAIXIU-<-----------\nChủ phòng: %1\n-o--------<-----------\nNgười tham gia: \n%2" } } const dice_images = [ "https://i.ibb.co/1JGMF5Q/row-1-column-1.jpg", "https://i.ibb.co/tq3nykP/row-1-column-2.jpg", "https://i.ibb.co/bP4d8tR/row-2-column-1.jpg", "https://i.ibb.co/GdhsNG7/row-2-column-2.jpg", "https://i.ibb.co/884GLkx/row-3-column-1.jpg", "https://i.ibb.co/2N86jZ1/row-3-column-2.jpg" ]; module.exports.run = async function({ api, event, args, getText, Users, Threads, Currencies }) { const request = require('request') const fs = require('fs') if (!fs.existsSync(__dirname + '/cache/abcde.png')) { request('https://i.imgur.com/iRCMI5V.png').pipe(fs.createWriteStream(__dirname + '/cache/abcde.png')); } if (!global.client.taixiu_ca) global.client.taixiu_ca = {}; //DEFINE SOME STUFF HERE.. const { senderID, messageID, threadID } = event; if (args.length == 0) { var abcd = { body: '==== 🎲 TÀI XỈU 🎲 ====\n» Create: Tạo Bàn Để Chơi Cùng Các Người Chơi Khác\n» Leave: Rời Khỏi Bàn Tài Xỉu\n» Start: Bắt Đầu Bàn Tài Xỉu\n» End: Kết Thúc Bàn Này.', attachment: [ fs.createReadStream(__dirname + "/cache/abcde.png") ] } return api.sendMessage(abcd, threadID, messageID) } const { increaseMoney, decreaseMoney, getData } = Currencies; const moneyUser = (await getData(senderID)).money; const sendC = (msg, callback) => api.sendMessage(msg, threadID, callback, messageID); const sendTC = async (msg, callback) => api.sendMessage(msg, threadID, callback); const sendT = (msg) => sendTC(msg, () => { }); const send = (msg) => sendC(msg, () => { }); const threadSetting = (await Threads.getData(String(event.threadID))).data || {}; const prefix = (threadSetting.hasOwnProperty("PREFIX")) ? threadSetting.PREFIX : global.config.PREFIX; //HERE COMES SWITCH CASE... switch (args[0]) { case "create": { if (threadID in global.client.taixiu_ca) send(getText("alreadyHave")); //SMALL CHECK else sendTC(getText("createSuccess", prefix, this.config.name), () => { global.client.taixiu_ca[threadID] = { players: 0, data: {}, status: "pending", author: senderID }; }); return; }; case "leave": { //SMALL CHECK... if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (!global.client.taixiu_ca[threadID].data[senderID]) return send(getText("notJoined")); else { //REMOVING PLAYER global.client.taixiu_ca[threadID].players--; global.client.taixiu_ca[threadID].data[senderID].forEach(async (e) => { await increaseMoney(senderID, e.bet); }) delete global.client.taixiu_ca[threadID].data[senderID]; send(getText("outSuccess")); } return; }; case "start": { //SMALL CHECK... if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (global.client.taixiu_ca[threadID].author != senderID) return send(getText("notAuthor")); if (global.client.taixiu_ca[threadID].players == 0) return send(getText("noPlayer")); //GET SHAKING DICES GIF AND SEND let shakingGif = (await axios.get('https://i.ibb.co/hMPgMT7/shaking.gif', { responseType: "stream" }).catch(e => console.log(e))).data; await api.sendMessage({ body: getText("shaking"), attachment: shakingGif }, threadID, (err, info) => setTimeout(async () => await api.unsendMessage(info.messageID).then(async () => { await new Promise(resolve => setTimeout(resolve, 500)); //A LITTLE DELAY... //GET DICES let _1st = Math.ceil(Math.random() * 6); let _2nd = Math.ceil(Math.random() * 6); let _3rd = Math.ceil(Math.random() * 6); //MAKING MSG... let name = ""; let msg = getText("final"); //GET IMAGES let dice_one_img = (await axios.get(dice_images[_1st - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let dice_two_img = (await axios.get(dice_images[_2nd - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let dice_three_img = (await axios.get(dice_images[_3rd - 1], { responseType: "stream" }).catch(e => console.log(e))).data; let atms = [dice_one_img, dice_two_img, dice_three_img]; //ADD TO ARRAY //SPLIT 2 TYPE OF PLAYERS let tai = [], xiu = [], result; for (i in global.client.taixiu_ca[threadID].data) { name = await Users.getNameUser(i) || "Player"; //GET NAME results = (_1st == _2nd == _3rd) ? "Lose" : (_1st + _2nd + _3rd <= 10) ? (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) ? "Win" : "Lose" : (["tài", "tai"].includes(global.client.taixiu_ca[threadID].data[i].name)) ? "Win" : "Lose"; if (results == "Win") { if (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) { xiu.push(`${name}: +${global.client.taixiu_ca[threadID].data[i].bet}$`); } else tai.push(`${name}: +${global.client.taixiu_ca[threadID].data[i].bet}$`); await increaseMoney(i, global.client.taixiu_ca[threadID].data[i].bet * 2); } else if (["xỉu", "xiu"].includes(global.client.taixiu_ca[threadID].data[i].name)) { xiu.push(`${name}: -${global.client.taixiu_ca[threadID].data[i].bet}$`); } else tai.push(`${name}: -${global.client.taixiu_ca[threadID].data[i].bet}$`); } msg += `\n\n---[ TÀI ]---\n${tai.join("\n")}\n\n---[ XỈU ]---\n${xiu.join("\n")}\n`; //FINAL SEND sendC({ body: msg, attachment: atms }, () => delete global.client.taixiu_ca[threadID]); return; }), 2400)); }; case "info": { //SMALL CHECK if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (global.client.taixiu_ca[threadID].players == 0) return send(getText("noPlayer")); let name = ""; let tempL = []; let nameAuthor = await Users.getNameUser(global.client.taixiu_ca[threadID].author) || "Player"; //GET NAME AUTHOR for (e in global.client.taixiu_ca[threadID].data) { name = await Users.getNameUser(e) || "Player"; //GET NAME PLAYER tempL.push(`${name}: ${global.client.taixiu_ca[threadID].data[e].name} - ${global.client.taixiu_ca[threadID].data[e].bet}$`); } send(getText("info", nameAuthor, tempL.join("\n"))); return; } default: { //IF IF IF AND IF //LITTLE CHECK... if (!["tai", "tài", "xỉu", "xiu"].includes(args[0])) return send(getText("unknown", prefix, this.config.name)); if (!global.client.taixiu_ca[threadID]) return send(getText("noGame")); if (args.length < 2) return send(getText("wrongInput")); moneyBet = parseInt(args[1]); if (isNaN(moneyBet) || moneyBet <= 0) return send(getText("missingInput")); if (moneyBet > moneyUser) return send(getText("moneyBetNotEnough")); if (moneyBet < 50) return send(getText("limitBet")); if (threadID in global.client.taixiu_ca) { if (global.client.taixiu_ca[threadID].status == "pending") { let luachon = args[0]; //CHECK INPUT if (["xiu", "xỉu"].includes(luachon)) luachon = "xỉu"; if (["tài", "tai"].includes(luachon)) luachon = "tài"; if (!global.client.taixiu_ca[threadID].data[senderID]) global.client.taixiu_ca[threadID].players++; if (global.client.taixiu_ca[threadID].data[senderID]) return sendC(getText("alreadyBet", moneyBet, luachon), async () => { await increaseMoney(senderID, global.client.taixiu_ca[threadID].data[senderID].bet); await decreaseMoney(senderID, moneyBet) global.client.taixiu_ca[threadID].data[senderID] = { name: luachon, bet: moneyBet } }); sendC(getText("betSuccess", moneyBet, luachon), async () => { await decreaseMoney(senderID, moneyBet); global.client.taixiu_ca[threadID].data[senderID] = { name: luachon, bet: moneyBet } }); } } return; } } } heres a module of my chatbot which is a game but its not working as my bot supports esm only i want to convert this to esm
35a94b2e0ff5b3bfd054a4b08ae1b102
{ "intermediate": 0.29445508122444153, "beginner": 0.5422471165657043, "expert": 0.16329777240753174 }
3,531
add error handling so the script doesn't hang it self up and add prints for what it is doing. also don't download the gif if the name already exists import requests import os import re from PIL import Image # Set the directory where the GIFs will be saved output_dir = 'output/' # Define the function to download the GIF def download_gif(url, subreddit, title): response = requests.get(url) filename = f"{subreddit}_{title}.gif" filename = re.sub(r'[^\w\s-]', '', filename) filename = re.sub(r'^\s+|\s+$', '', filename) filename = re.sub(r'[-\s]+', '_', filename) filepath = os.path.join(output_dir, subreddit, filename) os.makedirs(os.path.dirname(filepath), exist_ok=True) with open(filepath, 'wb') as f: f.write(response.content) # Check if the downloaded file is a valid GIF try: with Image.open(filepath) as img: if img.format != 'GIF': # Delete the file if it is not a GIF os.remove(filepath) except Exception: # Delete the file if an exception occurred while checking if it is a valid GIF os.remove(filepath) # Read the list of subreddits from a text file subreddits = [] with open('subreddits.txt', 'r') as f: subreddits = [line.strip() for line in f.readlines()] # Loop through each subreddit for subreddit in subreddits: # Set the URL to search for GIFs in the subreddit url = 'https://www.reddit.com/r/{}/search.json?q=url%3A.gif&restrict_sr=1&sort=top&t=all'.format(subreddit) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # Loop through each page of search results after = None count = 0 # Initialize count while True: params = {'after': after} if after else {} response = requests.get(url, headers=headers, params=params) data = response.json() # Loop through each post and download the GIF for post in data['data']['children']: url = post['data']['url'] title = post['data']['title'] download_gif(url, subreddit, title) count += 1 # Increment count if count >= 250: # Check if count reaches the limit of 250 break # Check if there are more search results after = data['data']['after'] if not after or count >= 250: break
35e842b06fcc2aec6a81df1ed6de781e
{ "intermediate": 0.3417793810367584, "beginner": 0.48865726590156555, "expert": 0.1695634126663208 }
3,532
add error handling so the script doesn't hang it self up and add prints for what it is doing. also don't download the gif if the name already exists import requests import os import re from PIL import Image # Set the directory where the GIFs will be saved output_dir = 'output/' # Define the function to download the GIF def download_gif(url, subreddit, title): response = requests.get(url) filename = f"{subreddit}_{title}.gif" filename = re.sub(r'[^\w\s-]', '', filename) filename = re.sub(r'^\s+|\s+$', '', filename) filename = re.sub(r'[-\s]+', '_', filename) filepath = os.path.join(output_dir, subreddit, filename) os.makedirs(os.path.dirname(filepath), exist_ok=True) with open(filepath, 'wb') as f: f.write(response.content) # Check if the downloaded file is a valid GIF try: with Image.open(filepath) as img: if img.format != 'GIF': # Delete the file if it is not a GIF os.remove(filepath) except Exception: # Delete the file if an exception occurred while checking if it is a valid GIF os.remove(filepath) # Read the list of subreddits from a text file subreddits = [] with open('subreddits.txt', 'r') as f: subreddits = [line.strip() for line in f.readlines()] # Loop through each subreddit for subreddit in subreddits: # Set the URL to search for GIFs in the subreddit url = 'https://www.reddit.com/r/{}/search.json?q=url%3A.gif&restrict_sr=1&sort=top&t=all'.format(subreddit) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # Loop through each page of search results after = None count = 0 # Initialize count while True: params = {'after': after} if after else {} response = requests.get(url, headers=headers, params=params) data = response.json() # Loop through each post and download the GIF for post in data['data']['children']: url = post['data']['url'] title = post['data']['title'] download_gif(url, subreddit, title) count += 1 # Increment count if count >= 250: # Check if count reaches the limit of 250 break # Check if there are more search results after = data['data']['after'] if not after or count >= 250: break
0c677a333efd9959ebfd9cf68e0828c1
{ "intermediate": 0.3417793810367584, "beginner": 0.48865726590156555, "expert": 0.1695634126663208 }
3,533
12. If f(x)= 5/(x^2 )+2 and g(x)= e^3x , calculate d dx (g(f(x))) at x =1
92788623ca43a31d7c831d858678b649
{ "intermediate": 0.36469265818595886, "beginner": 0.3523411452770233, "expert": 0.2829662263393402 }
3,534
produce a php session management example with login form
7057f879c7583ed5214c056323094319
{ "intermediate": 0.4673633873462677, "beginner": 0.3216184675693512, "expert": 0.21101811528205872 }
3,535
Simplifica este código y haz los cambios necesarios para que pueda funcionar en TES3MP versión 0.8.1: local delay = 1 -- Time delay in seconds. Make it larger or smaller to change to a slower or faster magicka regeneration respectively. local amount = 1 -- Amount in numbers of magicka that is added to the player's current magicka (quantity of regeneration). local players = {} -- local function isLoggedIn(player) return player:IsLoggedIn() end local function getMagicka(pid) return tes3mp.GetMagicka(pid) end local function OnServerPostInit() -- List of players connected: players = tes3mp.GetOnlinePlayerList() end local function RegenMagicka(players) -- Browse the list of players: for _, pid in pairs(players) do -- Ensure that the player is connected and it is not an NPC: local player = Players[pid] if player and isLoggedIn(player) then -- Obtain the player's current magicka: local currentMagicka = getMagicka(pid) local newMagicka = currentMagicka + amount -- Increases the player's magicka by 'amount': tes3mp.SetMagicka(pid, newMagicka) end end end OnServerPostInit() -- Executes the function every certain time (defined in 'delay'): tes3mp.StartTimer(delay, function() RegenMagicka(players) end, players)
08b072e4af1b4e5352d655ff66186dff
{ "intermediate": 0.41729530692100525, "beginner": 0.3775857985019684, "expert": 0.20511889457702637 }
3,536
for the below solidity code, give me a User Interface code in react // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract FarmingCropNFT is ERC721, Ownable { using SafeMath for uint256; // Define events event CropIssued(uint256 cropID, string cropName, uint256 amount, uint256 value, address farmer); event CropTransferred(address from, address to, uint256 cropID, uint256 value); // Define struct for crop struct Crop { string cropName; uint256 amount; uint256 value; address farmer; bool exists; } // Define mapping of crop IDs to crops mapping(uint256 => Crop) public crops; // Define counter for crop IDs uint256 public cropIDCounter; // Define constructor to initialize contract and ERC721 token constructor() ERC721("Farming Crop NFT", "FARMCRP") {} // Define function for farmer to issue NFT of crops to primary buyer function issueCropNFT(string memory _cropName, uint256 _amount, uint256 _value) public returns (uint256) { // Increment crop ID counter cropIDCounter++; // Create new crop struct Crop memory newCrop = Crop({ cropName: _cropName, amount: _amount, value: _value, farmer: msg.sender, exists: true }); // Add new crop to mapping crops[cropIDCounter] = newCrop; // Mint NFT to farmer _mint(msg.sender, cropIDCounter); // Emit event for new crop issuance emit CropIssued(cropIDCounter, _cropName, _amount, _value, msg.sender); // Return crop ID return cropIDCounter; } // Override the transferFrom function with custom logic for primary and secondary buyers. function transferFrom(address from, address to, uint256 tokenId) public override { // Ensure crop exists require(crops[tokenId].exists, "Crop does not exist"); // If the owner is farmer, primary buyer logic if (ownerOf(tokenId) == crops[tokenId].farmer) { // Primary buyer logic // Here you can add conditions for primary buyer purchase super.transferFrom(from, to, tokenId); emit CropTransferred(from, to, tokenId, crops[tokenId].value); } else { // Secondary buyer logic // Here you can add conditions for secondary buyer purchase on the marketplace super.transferFrom(from, to, tokenId); emit CropTransferred(from, to, tokenId, crops[tokenId].value); } } // Define function for farmer to destroy NFT of crops when they stop farming function destroyCropNFT(uint256 _cropID) public onlyOwner { // Ensure crop exists and is owned by farmer require(crops[_cropID].exists, "Crop does not exist"); require(ownerOf(_cropID) == crops[_cropID].farmer, "Crop is not owned by farmer"); // Burn NFT _burn(_cropID); // Emit event for crop destruction emit CropTransferred(crops[_cropID].farmer, address(0), _cropID, crops[_cropID].value); // Delete crop from mapping delete crops[_cropID]; } }
8a27194b4c73d2554344050256a5d900
{ "intermediate": 0.43505290150642395, "beginner": 0.3825809359550476, "expert": 0.18236614763736725 }
3,537
write a vba to calculate rsi
9de5500f264999db379de4488ede3d80
{ "intermediate": 0.2761625051498413, "beginner": 0.43767309188842773, "expert": 0.28616440296173096 }
3,538
Quiero que funcione en la version 0.8.1 de tes3mp: local delay = 1 -- Time delay in seconds. Change this to change magicka regeneration speed. local amount = 1 -- Amount of magicka to regenerate each time. local function isLoggedIn(player) return player:IsLoggedIn() end local function RegenMagicka(players) for _, pid in pairs(players) do local player = Players[pid] if player and isLoggedIn(player) then local currentMagicka = tes3mp.GetMagicka(pid) local newMagicka = currentMagicka + amount tes3mp.SetMagicka(pid, newMagicka) end end end eventHandler.OnServerPostInit:Connect(function() local players = tes3mp.GetOnlinePlayerList() tes3mp.StartTimer(tes3mp.CreateTimerEx(“RegenMagickaTimer”, delay * 1000, “i”, players), true) end)
f31312be87a22a331b7154010ab76537
{ "intermediate": 0.4047989547252655, "beginner": 0.4273608922958374, "expert": 0.1678401678800583 }
3,539
what plugins can I add to my website
dd2be3656fb15749a86d38a0ea0dbfaf
{ "intermediate": 0.4536035656929016, "beginner": 0.28532662987709045, "expert": 0.26106977462768555 }
3,540
write a vba to solve sodokou that there is in cells a1 to i9.
d0fd0ca94babaa301ddd7094351d743b
{ "intermediate": 0.3390539884567261, "beginner": 0.1755223423242569, "expert": 0.4854236841201782 }
3,541
write a vba to solve sodokou that there is in cells a1 to i9.
15b736c42cc50d846d1a3ea1e43538d2
{ "intermediate": 0.3390539884567261, "beginner": 0.1755223423242569, "expert": 0.4854236841201782 }
3,542
write a vba to solve sodokou that there is in cells a1 to i9.
982d196a57a69c618e78010f4cc48741
{ "intermediate": 0.3390539884567261, "beginner": 0.1755223423242569, "expert": 0.4854236841201782 }
3,543
I mean the icon, pick the bestest “Eco-friendly” logo
09ccfedaad451830a7932da823b6ec55
{ "intermediate": 0.3573169708251953, "beginner": 0.3102438449859619, "expert": 0.33243921399116516 }
3,544
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG': 4422588, 'Denzel Curry': 7555420, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir': 4361289, 'YK Osiris': 1686619, 'YNW Melly': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists, type 'quit' to end the game or enter 1 or 2 to make a guess.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n/Ent) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") why does the game repeat the same first rappers given
f8d7de2bf118069383ccc6f08b5a045a
{ "intermediate": 0.36435315012931824, "beginner": 0.24737298488616943, "expert": 0.38827386498451233 }
3,545
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG': 4422588, 'Denzel Curry': 7555420, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir': 4361289, 'YK Osiris': 1686619, 'YNW Melly': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists, type 'quit' to end the game or enter 1 or 2 to make a guess.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") why doesnt it work
4ba4a0dd2f4abeb88462041cbc3618bb
{ "intermediate": 0.3759572505950928, "beginner": 0.2545517385005951, "expert": 0.3694911003112793 }
3,546
change this script so it loops every *.txt in the same folder and creates a new folder with the name of the *.txt (example: awwww.txt would create an awwww folder for it's output and so on) import requests import os import re from PIL import Image # Set the directory where the GIFs will be saved output_dir = 'output/' # Define the function to download the GIF def download_gif(url, subreddit, title): print(f"Downloading from URL: {url}") response = requests.get(url) filename = f"{subreddit}{title}.gif" filename = re.sub(r'[^\w\s-]', '', filename) filename = re.sub(r'^\s+|\s+$', '', filename) filename = re.sub(r'[-\s]+', '', filename) # Limit the filename length to 20 characters if len(filename) > 20: filename = filename[:20] + '.gif' else: filename += '.gif' filepath = os.path.join(output_dir, subreddit, filename) os.makedirs(os.path.dirname(filepath), exist_ok=True) # Check if the file already exists if not os.path.isfile(filepath): with open(filepath, 'wb') as f: f.write(response.content) # Check if the downloaded file is a valid GIF try: with Image.open(filepath) as img: if img.format != 'GIF': # Delete the file if it is not a GIF os.remove(filepath) except Exception as e: print(f"Error while checking if the file is a valid GIF: {e}") # Delete the file if an exception occurred while checking if it is a valid GIF os.remove(filepath) else: print(f"File {filename} already exists") # Read the list of subreddits from a text file subreddits = [] with open('subreddits.txt', 'r') as f: subreddits = [line.strip() for line in f.readlines()] # Loop through each subreddit for subreddit in subreddits: print(f"Processing subreddit: {subreddit}") # Set the URL to search for GIFs in the subreddit url = 'https://www.reddit.com/r/{}/search.json?q=url%3A.gif&restrict_sr=1&sort=top&t=all'.format(subreddit) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # Loop through each page of search results after = None count = 0 # Initialize count while True: params = {'after': after} if after else {} try: response = requests.get(url, headers=headers, params=params) data = response.json() except Exception as e: print(f"Error while getting search results: {e}") break # Loop through each post and download the GIF for post in data['data']['children']: url = post['data']['url'] title = post['data']['title'] download_gif(url, subreddit, title) count += 1 # Increment count if count >= 250: # Check if count reaches the limit of 250 break # Check if there are more search results after = data['data']['after'] if not after or count >= 250: break
ec74a54b02d92e2bceaafc6a08c02ca8
{ "intermediate": 0.304826557636261, "beginner": 0.5933690667152405, "expert": 0.10180439054965973 }
3,547
change this script so it loops every *.txt in the same folder and creates a new folder with the name of the *.txt (example: awwww.txt would create an awwww folder for it's output and so on) import requests import os import re from PIL import Image # Set the directory where the GIFs will be saved output_dir = 'output/' # Define the function to download the GIF def download_gif(url, subreddit, title): print(f"Downloading from URL: {url}") response = requests.get(url) filename = f"{subreddit}{title}.gif" filename = re.sub(r'[^\w\s-]', '', filename) filename = re.sub(r'^\s+|\s+$', '', filename) filename = re.sub(r'[-\s]+', '', filename) # Limit the filename length to 20 characters if len(filename) > 20: filename = filename[:20] + '.gif' else: filename += '.gif' filepath = os.path.join(output_dir, subreddit, filename) os.makedirs(os.path.dirname(filepath), exist_ok=True) # Check if the file already exists if not os.path.isfile(filepath): with open(filepath, 'wb') as f: f.write(response.content) # Check if the downloaded file is a valid GIF try: with Image.open(filepath) as img: if img.format != 'GIF': # Delete the file if it is not a GIF os.remove(filepath) except Exception as e: print(f"Error while checking if the file is a valid GIF: {e}") # Delete the file if an exception occurred while checking if it is a valid GIF os.remove(filepath) else: print(f"File {filename} already exists") # Read the list of subreddits from a text file subreddits = [] with open('subreddits.txt', 'r') as f: subreddits = [line.strip() for line in f.readlines()] # Loop through each subreddit for subreddit in subreddits: print(f"Processing subreddit: {subreddit}") # Set the URL to search for GIFs in the subreddit url = 'https://www.reddit.com/r/{}/search.json?q=url%3A.gif&restrict_sr=1&sort=top&t=all'.format(subreddit) headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} # Loop through each page of search results after = None count = 0 # Initialize count while True: params = {'after': after} if after else {} try: response = requests.get(url, headers=headers, params=params) data = response.json() except Exception as e: print(f"Error while getting search results: {e}") break # Loop through each post and download the GIF for post in data['data']['children']: url = post['data']['url'] title = post['data']['title'] download_gif(url, subreddit, title) count += 1 # Increment count if count >= 250: # Check if count reaches the limit of 250 break # Check if there are more search results after = data['data']['after'] if not after or count >= 250: break
6bff546ce62ae1565bb0646582ecdd0b
{ "intermediate": 0.304826557636261, "beginner": 0.5933690667152405, "expert": 0.10180439054965973 }
3,548
I broke my brain to understand how to apply a nightmode, while section background. to cover the background of the body with nightmode background for text. and using only css and html, without any javascripts.: <style> body, html { margin: 0; padding: 0; height: 100%; width: 100%; position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; line-height: 1.6; transition: background-color 2s, color 3s; --overflow:hidden; } header { background-color: #4caf50; color: #fff; padding: 16px 0px 0px 0px; text-align: center; position: absolute; transition: background-color 2s; width: 100%; height: 18px; right: 0px; z-index:999; } h1, h2, h3, h4, h5, h6 { margin: 0 auto; display: flex; justify-content: space-between; align-items: center; font-size: 18px; width: 90%; height: 1%; } .background { background: linear-gradient(to bottom right, #5FB548, #A6D608); color: white; font-size: 80px; font-weight: bold; padding: 50px; text-align: center; text-shadow: 2px 2px #37472B; height: 100%; width: 100%; z-index:-1; } section { display: flex; flex-direction: column; justify-content: center; align-items: center; margin-top: -35px; padding-top: 35px; height: 100%; } @keyframes wave { 0% { background-position: 0% 0%; } 100% { background-position: 100% 0%; } } .left, .right { position: relative; } .left::before, .right::before { content: "🌿"; position: absolute; top: 5px; border-bottom: 1px dashed #fff; width: 40%; } .left::before { right: 100%; margin-right: 20px; } .right::before { left: 100%; margin-left: 20px; } .flags-container { width: 100%; position: relative; top: 0; right: 0px; padding: 1px 0; background-color: darkgreen; display: flex; justify-content: center; align-items: center; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 1; } .flag-radio { display: none; } .flag-label { cursor: pointer; margin: 0 10px; transition: 0.3s; opacity: 0.6; font-size: 24px; } .flag-label:hover { opacity: 1; } .language-option { position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; display: none; justify-content: center; align-items: center; padding-top: 64px; width: 100%; height: 100%; } #english-flag:checked ~ #english, #hindi-flag:checked ~ #hindi, #hebrew-flag:checked ~ #hebrew, #chinese-flag:checked ~ #chinese, #french-flag:checked ~ #french, #spanish-flag:checked ~ #spanish { display: block; } #night-mode-toggle:checked ~ body, #night-mode-toggle:checked ~ header, #night-mode-toggle:checked ~ .language-option, section { background-color: #dddddd; color: #000; } #night-mode-toggle:checked ~ .flags-container { background-color: #121; } #night-mode-toggle:checked ~ .switch-container label { color: #fff; } .switch-container { position: absolute; top: 5px; right: 16px; display: flex; align-items: center; justify-content: center; z-index: 2; } .switch-container label { content: "&#x1F319;"; position: relative; margin-left: 0px; cursor: pointer; user-select: none; align-items: center; justify-content: center; } .switch { content: "&#x1F319;"; position: relative; cursor: pointer; width: 64px; height: 32px; margin-right: 5px; background-color: darkgreen; border-radius: 15px; transition: background-color 3s; } .switch:before { content: "🌙"; display: block; position: absolute; top: 2px; left: 2px; height: 0px; width: 0px; background-color: #121; border-radius: 50%; transition: left 1s; } #night-mode-toggle:checked ~ .switch-container .switch { background-color: #121; } #night-mode-toggle:checked ~ .switch-container .switch:before { left: calc(100% - 28px); } </style> </head> <body> <input id="english-flag" type="radio" name="flags" class="flag-radio"> <input id="hindi-flag" type="radio" name="flags" class="flag-radio"> <input id="hebrew-flag" type="radio" name="flags" class="flag-radio"> <input id="chinese-flag" type="radio" name="flags" class="flag-radio"> <input id="french-flag" type="radio" name="flags" class="flag-radio"> <input id="spanish-flag" type="radio" name="flags" class="flag-radio"> <div class="flags-container"> <label for="english-flag" class="flag-label">🇬🇧</label> <label for="hindi-flag" class="flag-label">🇮🇳</label> <label for="hebrew-flag" class="flag-label">🇮🇱</label> <label for="chinese-flag" class="flag-label">🇨🇳</label> <label for="french-flag" class="flag-label">🇫🇷</label> <label for="spanish-flag" class="flag-label">🇪🇸</label> </div> <header> <h1> <span class="left">EcoWare</span> <span class="right">Earthwise</span> </h1> </header> <!-- Night Mode Switch --> <input type="checkbox" id="night-mode-toggle" /> <div class="switch-container"> <label for="night-mode-toggle"> <div class="switch"></div> </label> </div> <div id="english" class="language-option"> <section id=“home”> <p>Our mission is to educate and inspire people to take action for a greener, more sustainable future. We believe that together, we can make a difference in protecting our planet for generations to come.</p> <p><a href=“#topics”>Explore our environmental topics</a> to learn more about the issues we face and how you can get involved.</p> </section> <section id=“topics”> <h2>Environmental Topics</h2> <section id=“climate-change”> <h3>Climate Change</h3> <p>Climate change is a long-term shift in global or regional climate patterns, primarily caused by human activities such as burning fossil fuels, deforestation, and industrial processes. The effects of climate change include increased global temperatures, extreme weather events, ice melting, and rises in sea level. We promote greenhouse gas reduction strategies and enforce measures to adapt to the impacts of climate change.</p> </section> </div> <div id="hindi" class="language-option"> <p>hindi details going here</p> </div> <div id="hebrew" class="language-option"> <p>hebrew details going here</p> </div> <div id="chinese" class="language-option"> <p>chinese details going here</p> </div> <div id="french" class="language-option"> <p>french details going here</p> </div> <div id="spanish" class="language-option"> <p>spanish details going here</p> </div> <div class="background">YES, WE CARE!<div> </body> </html>
24236e44dd122d371d4ece414ef385c3
{ "intermediate": 0.3060864508152008, "beginner": 0.31082963943481445, "expert": 0.38308390974998474 }
3,549
write a vba that with close data in column d to show probablity of that price exist in wave 3 of elliot
75e26fafe5666da7fe71b92acb54c47f
{ "intermediate": 0.3395357131958008, "beginner": 0.2012648731470108, "expert": 0.4591993987560272 }
3,550
but can you translate this <div class="background">YES, WE CARE!<div> on every possible languages that you know and apply appropriate style for: .background { background: linear-gradient(to bottom right, #5FB548, #A6D608); color: white; font-size: 80px; font-weight: bold; padding: 50px; text-align: center; text-shadow: 2px 2px #37472B; height: 100%; width: 100%; z-index:-1; }
c6ba72d974ad3b5cb445b0018c6858eb
{ "intermediate": 0.3976418375968933, "beginner": 0.27327960729599, "expert": 0.3290786147117615 }
3,551
You are a helpful assistant, working in a R shiny app with a human. It's a web scrapper for EU Clinical Trials Register. Ask any clarifying questions before proceeding. Avoid repeating all the code when editing. Try instead to just tell what to add or change. Here's our code so far: driver.R: EUCTR_shiny_script <- function(selected_input, selected_data_sets, selected_option, selected_format, process_time) { library(rvest) library(tidyverse) library(tidyr) library(openxlsx) library(readxl) # Create a new environment to store shared variables my_env <- new.env() # Define variables EUCTR_version <- "0.2" process_time <- format(Sys.time(), "%Y%m%d_%H%M%S") filename <- paste0("EUCTR_", process_time, ".xlsx") filepath <- file.path("outputs", filename) # Assign the variables to the environment assign("selected_input", selected_input, envir = my_env) assign("selected_data_sets", selected_data_sets, envir = my_env) assign("selected_option", selected_option, envir = my_env) assign("selected_format", selected_format, envir = my_env) assign("EUCTR_version", EUCTR_version, envir = my_env) assign("process_time", process_time, envir = my_env) assign("filename", filename, envir = my_env) assign("filepath", filepath, envir = my_env) withProgress( message = "Crawling pages...", value = 0, source('./crawler.R', local = my_env) ) if ("protocol" %in% selected_data_sets) { withProgress( message = "Scraping protocol data...", value = 0.1, source('./protocol.R', local = my_env) ) } if ("results" %in% selected_data_sets) { withProgress( message = "Scraping results data...", value = 0.5, source('./results.R', local = my_env) ) withProgress( message = "Scraping subjects disposition...", value = 0.5, source('./disposition.R', local = my_env) ) } if ("endpoints" %in% selected_data_sets) { withProgress( message = "Scraping endpoints data...", value = 0.1, source('./endpoints.R', local = my_env) ) } withProgress( message = "Saving to file...", value = 0.92, source('./savexlsx.R', local = my_env) ) # Return a list containing the filepath and filename variables return(list(filepath = filepath, filename = filename)) } --- How can we add a logging feature, logging errors, warnings, etc? Maybe using log4r?
75899255072f88d3836a2224c50f7fa4
{ "intermediate": 0.4594893157482147, "beginner": 0.34367138147354126, "expert": 0.1968393176794052 }
3,552
nombresDeUsuarios :: RedSocial -> [String] nombresDeUsuarios ([], _, _) = [] nombresDeUsuarios (u:us, _, _) = (show (snd u)):(nombresDeUsuarios (us, _, _) ) Whats wrong with this code? iap1-tp.hs:41:76: error: [GHC-88464] * Found hole: _ :: [Publicacion] * In the first argument of `nombresDeUsuarios', namely `(us, _, _)' In the second argument of `(:)', namely `(nombresDeUsuarios (us, _, _))' In the expression: (show (snd u)) : (nombresDeUsuarios (us, _, _)) * Relevant bindings include us :: [Usuario] (bound at iap1-tp.hs:41:22) u :: Usuario (bound at iap1-tp.hs:41:20) nombresDeUsuarios :: RedSocial -> [String] (bound at iap1-tp.hs:40:1) Valid hole fits include [] :: forall a. [a] with [] @Publicacion (bound at <wired into compiler>) mempty :: forall a. Monoid a => a with mempty @[Publicacion] (imported from `Prelude' at iap1-tp.hs:1:1 (and originally defined in `GHC.Base')) |
16fef5f44a5510a30e35a70d3016d9ab
{ "intermediate": 0.36151519417762756, "beginner": 0.44658201932907104, "expert": 0.19190271198749542 }
3,553
but can you translate this YES, WE CARE! on every possible languages that you know and apply appropriate style. I have an idea. what if you use these utf icons symbols for flags and apply them to texts as kinda background, so the text will be at the center of corresponding appropriate flag utf icon symbol? .background { background: linear-gradient(to bottom right, #5FB548, #A6D608); color: white; font-size: 18px; font-weight: bold; padding: 50px; text-align: center; text-shadow: 2px 2px #37472B; height: 100%; width: 100%; z-index:-1; } <div class="background">YES, WE CARE!<div>
633005ff9c99b744f006a065d70682c2
{ "intermediate": 0.40807029604911804, "beginner": 0.2695175111293793, "expert": 0.3224121332168579 }
3,554
i need a pygame
8111cc1bf8bcfad6f7443b7b8446f1e8
{ "intermediate": 0.38805264234542847, "beginner": 0.34936240315437317, "expert": 0.26258495450019836 }
3,555
refactor the "decode_and_execute" function of this python code. Write the refactored function first, leave the explainations for later import random import os import keyboard from timeit import default_timer as functiontimer # 8 bit general purpose registers registers = {f"V{i:x}": 0 for i in range(16)} # 8 bit flag registers registers["Vf"] = 0 # 16 bit register (only the lowest 12 bit usually used) registers["I"] = 0 # Timer registers timer_registers = { "DT": 0, # Delay Timer Register "ST": 0 # Sound Timer Register } # Keypad keypad = {f"K{i:x}": 0 for i in range(16)} # Memory from 0 (0x000) to 4095 (0xFFF) memory = [0] * 4096 # 64-byte stack stack = [0] * 64 # 8x64 monochrome framebuffer framebuffer = [[0 for _ in range(64)] for _ in range(32)] screen_needs_redraw = True pc = 0x200 # 16 bit # Keyboard and screen helpers def update_keypad(): global keypad def update_keypad_row(row, key_indexes): for i, key_index in enumerate(key_indexes): if keyboard.is_pressed(row[i]): keypad[f"K{key_index}"] = 1 # First row update_keypad_row("1234", [1, 2, 3, 0xC]) # Second row update_keypad_row("qwer", [4, 5, 6, 0xD]) # Third row update_keypad_row("asdf", [7, 8, 9, 0xE]) # Fourth row update_keypad_row("zxcv", [0xA, 0, 0xB, 0xF]) def wait_for_keypress(): while True: keys = [ ["1234", 0x1, 0x2, 0x3, 0xC], ["qwer", 0x4, 0x5, 0x6, 0xD], ["asdf", 0x7, 0x8, 0x9, 0xE], ["zxcv", 0xA, 0x0, 0xB, 0xF] ] for row in keys: if keyboard.is_pressed(row[0]): return row[1 + row.index(True)] def reset_keypad(): global keypad keypad = {f"K{i:x}": 0 for i in range(16)} # Function to load the binary at 0+offset in memory def load_binary(filename, offset): global memory counter = offset with open(filename, "rb") as f: while byte := f.read(1): memory[counter] = int.from_bytes(byte, byteorder="big") counter += 1 def decode_and_execute(instr): global memory global stack global pc global registers global timer_registers global framebuffer global keypad global screen_needs_redraw did_instruction_branch = False ##USEFUL PARAMETERS nnn = int(instr[1] + instr[2] + instr[3],16) vx = 'V' + instr[1] vy = 'V' + instr[2] kk = int(instr[2] + instr[3],16) if instr[0] == '0': if instr[1] == '0' and instr[2] == 'e' and instr[3] == '0': #CLS framebuffer = [[0 for _ in range(64)] for _ in range(32)] elif instr[1] == '0' and instr[2] == 'e' and instr[3] == 'e': #RET pc = stack.pop() + 2 did_instruction_branch = True else: #SYS nnn pass elif instr[0] == '1': #'JP 0x0' + nnn pc = nnn did_instruction_branch = True elif instr[0] == '2': # 'CALL 0x0' + nnn stack.append(pc) pc = nnn did_instruction_branch = True #OK elif instr[0] == '3': #'SE' + vx_byte if registers[vx] == kk: pc += 2 #OK elif instr[0] == '4': #'SNE' + vx_byte if registers[vx] != kk: pc += 2 #OK elif instr[0] == '5': #'SE' + vx_vy if registers[vx] == registers[vy]: pc += 2 #TO_TEST elif instr[0] == '6': #'LD' + vx_byte registers[vx] = kk #OK elif instr[0] == '7': #'ADD' + vx_byte if registers[vx] + kk > 255: registers[vx] = registers[vx] + kk - 256 else: registers[vx] = registers[vx] + kk #OK (all 8xxn) elif instr[0] == '8': if instr[3] == '0': #'LD' + vx_vy registers[vx] = registers[vy] elif instr[3] == '1': #'OR' + vx_vy registers[vx] = registers[vx] | registers[vy] elif instr[3] == '2': #'AND' + vx_vy registers[vx] = registers[vx] & registers[vy] elif instr[3] == '3': #'XOR' + vx_vy registers[vx] = registers[vx] ^ registers[vy] elif instr[3] == '4': #'ADD' + vx_vy if registers[vx] + registers[vy] > 255: registers[vx] = registers[vx] + registers[vy] - 256 registers['Vf'] = 1 else: registers[vx] = registers[vx] + registers[vy] registers['Vf'] = 0 elif instr[3] == '5': #'SUB' + vx_vy if registers[vx] > registers[vy]: registers['Vf'] = 1 registers[vx] = registers[vx] - registers[vy] else: registers['Vf'] = 0 registers[vx] = 256 + registers[vx] - registers[vy] elif instr[3] == '6': #'SHR' + vx_vy_braces lsb = registers[vx] & 1 registers['Vf'] = lsb registers[vx] = registers[vx] >> 1 ## we're dividing, no problem elif instr[3] == '7': #'SUBN' + vx_vy if registers[vy] > registers[vx]: registers[vx] = registers[vy] - registers[vx] registers['Vf'] = 1 else: registers[vx] = 256 + registers[vy] - registers[vx] registers['Vf'] = 0 elif instr[3] == 'e': #'SHL' + vx_vy_braces msb = int("{0:08b}".format(registers[vx])[:1]) registers['Vf'] = msb if registers[vx] << 1 > 255: registers[vx] = (registers[vx] << 1) - 256 else: registers[vx] = registers[vx] << 1 #OK elif instr[0] == '9': #'SNE' + vx_vy if registers[vx] != registers[vy]: pc += 2 #OK elif instr[0] == 'a': #'LD I 0x0' + nnn registers['I'] = nnn #OK elif instr[0] == 'b': #'JP V0' + nnn pc = nnn + registers['V0'] did_instruction_branch = True #OK elif instr[0] == 'c': #'RND' + vx_byte registers[vx] = kk & random.randint(0,255) #OK elif instr[0] == 'd': #'DRW' + vx_vy + ' 0x' + instr[3] screen_needs_redraw = True height = int('0x' + instr[3],16) base_ptr = registers['I'] registers['Vf'] = 0 for y_index in range(height): sprite_byte = format(int(str(hex(memory[base_ptr + y_index]))[2:].zfill(2),16), '08b') for x_index in range(8): color = int(sprite_byte[x_index]) pos_vx = (registers[vx] + x_index) % 64 pos_vy = ((registers[vy] + y_index) % 32) if framebuffer[pos_vy][pos_vx] == 1 and color == 1: registers['Vf'] = registers['Vf'] | 1 color = 0 elif framebuffer[pos_vy][pos_vx] == 1 and color == 0: color = 1 framebuffer[pos_vy][pos_vx] = color elif instr[0] == 'e': if instr[2] == '9' and instr[3] == 'e': #return 'SKP' + vx updateKeypad() if keypad['K'+ str(hex(registers[vx])[-1])] == 1: pc += 2 resetKeypad() elif instr[2] == 'a' and instr[3] == '1': #return 'SKNP' + vx updateKeypad() if keypad['K'+ str(hex(registers[vx])[-1])] == 0: pc += 2 resetKeypad() elif instr[0] == 'f': #TO_TEST if instr[2] == '0' and instr[3] == '7': #'LD' + vx + ', DT' registers[vx] = timer_registers['DT'] #OK elif instr[2] == '0' and instr[3] == 'a': #return 'LD' + vx + ', K' registers[vx] = waitForKeypress() #OK elif instr[2] == '1' and instr[3] == '5': #'LD DT,' + vx timer_registers['DT'] = registers[vx] #OK elif instr[2] == '1' and instr[3] == '8': #'LD ST,' + vx timer_registers['ST'] = registers[vx] #OK elif instr[2] == '1' and instr[3] == 'e': #'ADD I,' + vx registers['I'] = registers['I'] + registers[vx] #OK elif instr[2] == '2' and instr[3] == '9': #'LD F,' + vx registers['I'] = registers[vx] *5 #OK elif instr[2] == '3' and instr[3] == '3': #'LD B,' + vx base_ptr = registers['I'] memory[base_ptr] = registers[vx] // 10**2 % 10 memory[base_ptr + 1] = registers[vx] // 10**1 % 10 memory[base_ptr + 2] = registers[vx] // 10**0 % 10 #OK elif instr[2] == '5' and instr[3] == '5': #'LD [I],' + vx base_ptr = registers['I'] for i in range(int(vx[1:]) +1): memory[base_ptr + i] = registers['V'+str(i)] #OK elif instr[2] == '6' and instr[3] == '5': #'LD' + vx + ', [I]' base_ptr = registers['I'] for i in range(int(vx[1:],16) +1): registers['V'+str(i)] = memory[base_ptr + i] #Now we check if we need to increment the program counter or if we are gonna branch if did_instruction_branch == False: pc += 2 def print_mem_as_hex(): #This is a DEBUG function global memory print('{}'.format('\n'.join('{:02x}'.format(x) for x in memory))) def update_screen(): global framebuffer output = '' os.system('cls') for column in framebuffer: output += ''.join((str(i) + ' ') for i in column).join(os.linesep) print(output.replace('0', ' ').replace('1', '#')) def main(): global memory global pc global screen_needs_redraw #loading the fonts in memory load_binary('chip8_fonts.bin', 0) #loading the rom in memory load_binary('maze.ch8', 512) #load_binary('bmp.ch8', 512) #load_binary('ibm.ch8', 512) #load_binary('chip8logo.ch8', 512) #load_binary('test_opcode.ch8', 512) #load_binary('c8_test.ch8', 512) #load_binary('trip.ch8', 512) #load_binary('rush_hour.ch8', 512) #load_binary('space_invaders.ch8', 512) #load_binary('chip8-test-rom.ch8', 512) #load_binary('keypad_test.ch8', 512) clockcycles = 0 timer_period = 1.0 / 60 #1/calls per second timer_start_time = functiontimer() while True: if (functiontimer() - timer_start_time) > timer_period: if timer_registers['DT'] > 0: ##Decrement sound registers timer_registers['DT'] -= 1 if timer_registers['ST'] > 0: timer_registers['ST'] -= 1 timer_start_time = functiontimer() if screen_needs_redraw: update_screen() screen_needs_redraw = False instruction = str(hex(memory[pc]))[2:].zfill(2) + str(hex(memory[pc+1]))[2:].zfill(2) decode_and_execute(instruction) if __name__ == '__main__': main()
78af3271995d7618af8ac5a478b13a56
{ "intermediate": 0.3732769787311554, "beginner": 0.4448947012424469, "expert": 0.1818283349275589 }
3,556
I need to fix that text at the center of that flag icon background:
5ac42a8cb808663fb88f74297db10e4d
{ "intermediate": 0.31532564759254456, "beginner": 0.2912023663520813, "expert": 0.39347195625305176 }
3,557
https://www.kaggle.com/code/springboardroger/naive-bayes-name-gender-classifier/input classify this data in r using naive bayes
b45f8240d21a2a089b6aa72781a12fa5
{ "intermediate": 0.3246572017669678, "beginner": 0.16875740885734558, "expert": 0.506585419178009 }
3,558
Print python code which will take txt file and find all ip addresses in it, including ipv4 and ipv6. Then it should save the list of all addresses to json file.
1dd55f3b091040061bf95e2e23595096
{ "intermediate": 0.44723522663116455, "beginner": 0.1387253701686859, "expert": 0.41403937339782715 }
3,559
hi
25e2209fbc634417c3c5b4cfb059d143
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
3,560
How to make pktmon.exe capture only ip addresses
ef13e1d45f1a15e1cc89a43dcfccd9ca
{ "intermediate": 0.3773077428340912, "beginner": 0.22074338793754578, "expert": 0.40194883942604065 }
3,561
how many degrees of freedom camera matrix has
3cb868662790ea53ce2464c339b7fa1f
{ "intermediate": 0.313949853181839, "beginner": 0.3130412697792053, "expert": 0.3730089068412781 }
3,562
.taskmate-description { margin: 40px; text-align: justify; padding: 0 100px; } make this code mobile friendly
d821fe9c2739d3f1e2a4632fd6fe5e33
{ "intermediate": 0.3978578448295593, "beginner": 0.2531667947769165, "expert": 0.34897539019584656 }
3,563
Write me an AutoHotKey script that will send the key Home when I press XButton1.
db4b79971ef9ec4a0ce927323be54e82
{ "intermediate": 0.37867623567581177, "beginner": 0.20186638832092285, "expert": 0.4194573760032654 }
3,564
Private Sub Worksheet_Change(ByVal Target As Range) Dim answer As VbMsgBoxResult Dim contractor As String Dim wpSheet As Worksheet Dim lastRow As Long ' Check if both E1 and G1 have values If Not IsEmpty(Range("E1")) And Not IsEmpty(Range("G1")) Then Exit Sub End If ' Check for text entered in column J If Target.Column = 10 And Target.Value <> "" Then ' Check if contractor is insured and DBS cleared Dim insured As Boolean Dim cleared As Boolean insured = Not IsEmpty(Range("E1")) ' check if E1 has a value cleared = Not IsEmpty(Range("G1")) ' check if G1 has a value ' Ask user if they want to send details to contractor If Not insured And Not cleared Then answer = MsgBox("Contractor is not Insured nor DBS cleared - would you like to send details?", vbYesNo + vbQuestion, "Send details") ElseIf Not insured Then answer = MsgBox("Contractor is not Insured - would you like to send details?", vbYesNo + vbQuestion, "Send details") ElseIf Not cleared Then answer = MsgBox("Contractor is not DBS cleared - would you like to send details?", vbYesNo + vbQuestion, "Send details") Else answer = MsgBox("Would you like to send details to the contractor?", vbYesNo + vbQuestion, "Send details") End If If answer = vbYes Then ' Store details from current sheet in variables contractor = ActiveSheet.Name ' If you have other details to store, add them here ' Activate Work Permit sheet Set wpSheet = ThisWorkbook.Sheets("Work Permit") wpSheet.Activate ' Copy data from previous sheet lastRow = wpSheet.Cells(wpSheet.Rows.Count, "A").End(xlUp).Row + 1 wpSheet.Cells(lastRow, "A").Value = Target.Value wpSheet.Cells(lastRow, "B").Value = ThisWorkbook.Sheets(contractor).Range("B1").Value wpSheet.Cells(lastRow, "C").Value = ThisWorkbook.Sheets(contractor).Cells(Target.Row, "C").Value End If End If End Sub This vba code does not run as expected. What is the error
da0bcbe249dc8ddeea414231c915f387
{ "intermediate": 0.43369898200035095, "beginner": 0.2862449288368225, "expert": 0.2800561189651489 }
3,565
[*********************100%***********************] 1 of 1 completed Traceback (most recent call last): File "c:\Users\Adrian\Desktop\Trader_1.py", line 181, in <module> result = cerebro.run() ^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\cerebro.py", line 1127, in run runstrat = self.runstrategies(iterstrat) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\cerebro.py", line 1217, in runstrategies strat = stratcls(*sargs, **skwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\metabase.py", line 88, in __call__ _obj, args, kwargs = cls.doinit(_obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\metabase.py", line 78, in doinit _obj.__init__(*args, **kwargs) File "c:\Users\Adrian\Desktop\Trader_1.py", line 115, in __init__ (self.data0 / self.data1).rolling(window=self.params.lookback).mean() - 1.0 ^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\lineseries.py", line 461, in __getattr__ return getattr(self.lines, name) ^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Lines_LineSeries_LineIterator_DataAccessor_Strateg' object has no attribute 'data1' import backtrader as bt import pandas as pd import yfinance as yf import requests # setup bot token = '' def send_message(text): chat_id = '' url = f"https://api.telegram.org/bot{token}/sendMessage" params = { "chat_id": chat_id, "text": text, } resp = requests.get(url, params=params) resp.raise_for_status() class MovingAverageStrategy(bt.Strategy): params = (('fast_ma', 20), ('slow_ma', 50)) def __init__(self): self.fast_ma = bt.indicators.SMA(self.data, period=self.params.fast_ma) self.slow_ma = bt.indicators.SMA(self.data, period=self.params.slow_ma) self.crossover = bt.indicators.CrossOver(self.fast_ma, self.slow_ma) def next(self): if not self.position: if self.crossover > 0: self.buy() elif self.crossover < 0: self.sell() class MomentumStrategy(bt.Strategy): params = (('period', 14), ('mom', 10)) def __init__(self): self.mom = bt.indicators.Momentum(self.data, period=self.params.period) def next(self): if not self.position: if self.mom > self.params.mom: self.buy() elif self.mom < self.params.mom: self.sell() class MeanReversionStrategy(bt.Strategy): params = (('period', 20), ('devfactor', 2)) def __init__(self): self.zscore = ZScore(period=self.params.period) def next(self): if not self.position: if self.zscore < -1.0: self.buy() elif self.zscore > 1.0: self.sell() # Trend Following Strategy class TrendFollowingStrategy(bt.Strategy): params = ( ('fast_ma_period', 50), ('slow_ma_period', 200), ) def __init__(self): self.fast_ma = bt.indicators.SimpleMovingAverage( self.data, period=self.params.fast_ma_period ) self.slow_ma = bt.indicators.SimpleMovingAverage( self.data, period=self.params.slow_ma_period ) def next(self): if self.position.size == 0 and self.fast_ma[-1] > self.slow_ma[-1]: self.buy() elif self.position.size > 0 and self.fast_ma[-1] < self.slow_ma[-1]: self.close() elif self.position.size < 0 and self.fast_ma[-1] > self.slow_ma[-1]: self.close() # Breakout Startegy class BreakoutStrategy(bt.Strategy): params = ( ('atr_period', 14), ('breakout_multiplier', 1.5), ) def __init__(self): self.atr = bt.indicators.AverageTrueRange( self.data, period=self.params.atr_period ) def next(self): if self.position.size == 0 and self.data.close[-1] > ( self.data.close[-2] + (self.atr[-1] * self.params.breakout_multiplier) ): self.buy() elif self.position.size > 0 and self.data.close[-1] < self.data.close[0]: self.close() # Pairs Trading Strategy class PairsTradingStrategy(bt.Strategy): params = ( ('lookback', 20), ('entry_threshold', 2.0), ('exit_threshold', 0.5), ) def __init__(self): self.zscore = self.indicators.zscore = ( (self.data0 / self.data1).rolling(window=self.params.lookback).mean() - 1.0 ) / (self.data0 / self.data1).rolling(window=self.params.lookback).std() self.long_entry = self.params.entry_threshold self.long_exit = self.params.exit_threshold self.short_entry = -self.params.entry_threshold self.short_exit = -self.params.exit_threshold def next(self): if self.position.size == 0: if self.zscore[-1] > self.long_entry: self.buy(data=self.data0) self.sell(data=self.data1) elif self.zscore[-1] < self.short_entry: self.sell(data=self.data0) self.buy(data=self.data1) elif self.position.size > 0: if self.zscore[-1] < self.long_exit: self.close() elif self.position.size < 0: if self.zscore[-1] > self.short_exit: self.close() class ZScore(bt.Indicator): lines = ('zscore',) params = (('period', 20),) def __init__(self): self.bband = bt.indicators.BollingerBands(self.data, period=self.params.period) self.stddev = bt.indicators.StandardDeviation(self.data, period=self.params.period) def next(self): self.lines.zscore[0] = (self.data[0] - self.bband.lines.mid[0]) / self.stddev[0] if __name__ == '__main__': # Download historical price data for MSFT from Yahoo Finance tickers = ['MSFT', 'AAPL', 'GOOGL', 'TSLA',] for ticker in tickers: try: data = yf.download(ticker, start='2010-01-01', end='2023-03-28', auto_adjust=True, ignore_tz=True) if data.empty: raise ValueError(f"No data found for {ticker} in the specified date range.") # Convert data to backtrader format data = bt.feeds.PandasData(dataname=data) strategies = [MovingAverageStrategy, MomentumStrategy, MeanReversionStrategy, TrendFollowingStrategy, BreakoutStrategy, PairsTradingStrategy] for strategy in strategies: # Create a cerebro instance cerebro = bt.Cerebro() # Add the data feed cerebro.adddata(data) # Add the strategy cerebro.addstrategy(strategy) # Set up the cash and commission cerebro.broker.setcash(10000) cerebro.broker.setcommission(commission=0.001) # Add a fixed stake sizer cerebro.addsizer(bt.sizers.FixedSize, stake=1) # Run the backtest result = cerebro.run() except ValueError as e: print(e) continue # Print the result print(strategy.__name__) print('Total profit:', result[0].broker.getvalue() - 10000) print('Return on investment:', (result[0].broker.getvalue() - 10000) / 10000 * 100, '%') print('') # Print the result print('Moving Average Crossover Strategy') print('Total profit:', result[0].broker.getvalue() - cerebro.broker.getcash()) print('Return on investment:', (result[0].broker.getvalue() - cerebro.broker.getcash()) / cerebro.broker.getcash() * 100, '%') print('') print('Momentum Trading Strategy') print('Total profit:', result[0].broker.getvalue() - cerebro.broker.getcash()) print('Return on investment:', (result[0].broker.getvalue() - cerebro.broker.getcash()) / cerebro.broker.getcash() * 100, '%') print('') print('Mean Reversion Trading Strategy') print('Total profit:', result[0].broker.getvalue() - cerebro.broker.getcash()) print('Return on investment:', (result[0].broker.getvalue() - cerebro.broker.getcash()) / cerebro.broker.getcash() * 100, '%') print('')
b306ada797afe1b943d9fdaec05016d8
{ "intermediate": 0.41321343183517456, "beginner": 0.4279346168041229, "expert": 0.15885189175605774 }
3,566
Hi
0cae64c5d3bb0ccc0efea8502da05328
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
3,567
maybe you can simply use a content method to make this flag icon as the background for text?: content: "🇬🇧";. but you cheated and used raster images links, except flag icons symbols that you can apply as background under texts in all languages. hey! wait a sec. apply utf icons symbols as the images for background for texts. place texts in the center of these huge icon flags symbols and shade them, so the text can be visible.but can you translate this YES, WE CARE! on every possible languages that you know and apply appropriate style. I have an idea. what if you use these utf icons symbols for flags and apply them to texts as kinda background, so the text will be at the center of corresponding appropriate flag utf icon symbol? .background { background: linear-gradient(to bottom right, #5FB548, #A6D608); color: white; font-size: 18px; font-weight: bold; padding: 50px; text-align: center; text-shadow: 2px 2px #37472B; height: 100%; width: 100%; z-index:-1; } <div class=“background”>YES, WE CARE!<div>
082612044d7c7d29d8dc959430ddb19d
{ "intermediate": 0.3903903365135193, "beginner": 0.33933836221694946, "expert": 0.27027130126953125 }
3,568
нужно изменить поиск по БД так, чтобы было без разницы Е или Ё protected override IQueryable<UserEntity> ProcessSearchTextForDbQuery(IQueryable<UserEntity> dbQuery, UserQuery query) { if (string.IsNullOrWhiteSpace(query.Text)) return dbQuery; var splitted = query.Text.Split(new char[] { ' ', ',', '.' }, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.ToLower()) .Take(SearchFragmentCount); foreach (var s in splitted) { dbQuery = dbQuery.Where(x => x.SearchIndex.Contains(s)); } Console.WriteLine(dbQuery); return dbQuery; }
66b16cda336f6f616a8ed5bb0eb93961
{ "intermediate": 0.38385841250419617, "beginner": 0.3913012146949768, "expert": 0.22484037280082703 }
3,569
This is a trading bot and this is the following code. It doesn't work, fix it import backtrader as bt import pandas as pd import yfinance as yf import requests token = "" chat_id = "" def send_message(text): url = f"https://api.telegram.org/bot{token}/sendMessage" params = { "chat_id": chat_id, "text": text, } resp = requests.get(url, params=params) resp.raise_for_status() class MovingAverageStrategy(bt.Strategy): params = (("fast_ma", 20), ("slow_ma", 50)) def init(self): self.fast_ma = bt.indicators.SMA(self.data, period=self.params.fast_ma) self.slow_ma = bt.indicators.SMA(self.data, period=self.params.slow_ma) self.crossover = bt.indicators.CrossOver(self.fast_ma, self.slow_ma) def next(self): if not self.position: if self.crossover > 0: self.buy() elif self.crossover < 0: self.sell() class MomentumStrategy(bt.Strategy): params = (("period", 14), ("mom", 10)) def init(self): self.mom = bt.indicators.Momentum(self.data, period=self.params.period) def next(self): if not self.position: if self.mom > self.params.mom: self.buy() elif self.mom < self.params.mom: self.sell() class ZScore(bt.Indicator): lines = ("zscore",) params = (("period", 20),) def init(self): self.bband = bt.indicators.BollingerBands(self.data, period=self.params.period) self.stddev = bt.indicators.StandardDeviation(self.data, period=self.params.period) def next(self): self.lines.zscore[0] = (self.data[0] - self.bband.lines.mid[0]) / self.stddev[0] class MeanReversionStrategy(bt.Strategy): params = (("period", 20),) def init(self): self.zscore = ZScore(period=self.params.period) def next(self): if not self.position: if self.zscore < -1.0: self.buy() elif self.zscore > 1.0: self.sell() class TrendFollowingStrategy(bt.Strategy): params = (("fast_ma_period", 50), ("slow_ma_period", 200),) def init(self): self.fast_ma = bt.indicators.SimpleMovingAverage(self.data, period=self.params.fast_ma_period) self.slow_ma = bt.indicators.SimpleMovingAverage(self.data, period=self.params.slow_ma_period) def next(self): if not self.position: if self.fast_ma > self.slow_ma: self.buy() elif self.fast_ma < self.slow_ma: self.sell() stock_list = ["MSFT", "AAPL", "GOOGL", "TSLA"] strategy_list = [MovingAverageStrategy, MomentumStrategy, MeanReversionStrategy, TrendFollowingStrategy] for stock in stock_list: try: data = yf.download(stock, start="2010-01-01", end="2023-03-28", auto_adjust=True, ignore_tz=True) if data.empty: raise ValueError(f"No data found for {stock} in the specified date range.") data = bt.feeds.PandasData(dataname=data) for strat in strategy_list: cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(strat) cerebro.broker.setcash(10000) cerebro.broker.setcommission(commission=0.001) cerebro.addsizer(bt.sizers.PercentSizer, percents=10) cerebro.addsizer(bt.sizers.PercentSizer, percents=10) starting_value = cerebro.broker.getvalue() result = cerebro.run() final_value = cerebro.broker.getvalue() message = f"Stock: {stock}\n" message += f"Strategy: {strat.name}\n" message += f"Starting Portfolio Value: {starting_value:.2f}\n" message += f"Final Portfolio Value: {final_value:.2f}\n" gain = final_value - starting_value message += f"Total Gain: {gain:.2f}\n" message += f"ROI : {gain / starting_value * 100:.2f}%\n" send_message(message) except ValueError as e: print(e) continue
cefeb97c83115371f84aee6ee112136a
{ "intermediate": 0.31896331906318665, "beginner": 0.5209094285964966, "expert": 0.1601271778345108 }
3,570
"@echo off setlocal EnableDelayedExpansion set "src_dir=C:\Users\user\Desktop\16 pixeley" set "dest_dir=C:\Users\user\Desktop\maxshrinkedByKichiro" set "output_dir=C:\Users\user\Desktop\sborka3" for /r "%src_dir%" %%a in (*) do ( set "src_file=%%a" set "dest_file=!src_file:%src_dir%=%dest_dir%!" set "output_file=!src_file:%src_dir%=%output_dir%!" if not exist "!dest_file!\.." ( mkdir "!dest_file!\.." ) if exist "!dest_file!" ( for /f %%i in ("!src_file!") do ( set "src_size=%%~zi" for /f %%j in ("!dest_file!") do ( set "dest_size=%%~zj" if !src_size! lss !dest_size! ( set "smaller_file=!src_file!" echo "Copying smaller file !smaller_file! to !output_file! ..." ) else ( set "smaller_file=!dest_file!" echo "Copying smaller file !smaller_file! to !output_file! ..." ) xcopy "!smaller_file!" "!output_file!" >nul ) ) ) else ( xcopy "!src_file!" "!output_file!" >nul echo "Copying !src_file! to !output_file! ..." ) ) echo "done!"" почини код чтобы он работал и добавь максимально подробную отладочную информацию в консоль
5442b7c6f33dcd3ea3cb1d8f90a48b65
{ "intermediate": 0.3185480535030365, "beginner": 0.3620556890964508, "expert": 0.3193962872028351 }
3,571
what changes should i make to my vuejs code so that the offchain data code in solidity works. solidity code: //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract LoanNFT is ERC721 { struct Loan { uint256 id; uint256 principal; uint256 interestRate; uint256 term; uint256 maturityDate; address borrower; bool isRepaid; uint256 offchainDataId; } struct OffchainData { string dataURL; bytes32 dataHash; } mapping(uint256 => Loan) public loans; mapping(uint256 => OffchainData) public offchainData; // mapping for offchain data uint256 public loanId; uint256 public couponRate; constructor(string memory _name, string memory _symbol, uint256 _couponRate) ERC721(_name, _symbol) { loanId = 0; couponRate = _couponRate; } function issueLoan( address _borrower, uint256 _principal, uint256 _interestRate, uint256 _term, uint256 _maturityDate, string memory _offchainDataURL, // parameter for offchain data bytes32 _offchainDataHash // parameter for offchain data ) public { loanId++; offchainData[loanId] = OffchainData(_offchainDataURL, _offchainDataHash); loans[loanId] = Loan(loanId, _principal, _interestRate, _term, _maturityDate, _borrower, false, loanId); // Pass offchain data id to loan _mint(msg.sender, loanId); } function repayLoan(uint256 _loanId) public { require(msg.sender == loans[_loanId].borrower, "Only borrower can repay the loan"); loans[_loanId].isRepaid = true; } function buyNFT(uint256 _loanId) public payable { require(ownerOf(_loanId) != msg.sender, "Cannot buy your own loan NFT"); require(msg.value >= calculateCouponAmount(_loanId), "Insufficient funds to buy the loan NFT"); address owner = ownerOf(_loanId); _transfer(owner, msg.sender, _loanId); payable(owner).transfer(msg.value); } function calculateCouponAmount(uint256 _loanId) public view returns (uint256) { require(ownerOf(_loanId) != address(0), "Invalid loan NFT"); Loan memory loan = loans[_loanId]; uint256 couponAmount = loan.principal * loan.interestRate * couponRate / (100 * loan.term); if (loan.isRepaid) { couponAmount = couponAmount + loan.principal; } return couponAmount; } function destroyNFT(uint256 _loanId) public { require(ownerOf(_loanId) == msg.sender, "Only owner can destroy the loan NFT"); _burn(_loanId); } } VUEJS: <template> <div class=“loan-nft-app”> <!-- <h1>Loan NFT Application</h1> --> <h2>Issue Loan</h2> <form @submit.prevent="onIssueLoan" class=“loan-form”> <div class=“field-group”> <label for=“borrower”>Borrower Address:</label> <input type=“text” id=“borrower” v-model="loanForm.borrower" required /> </div> <br> <div class=“field-group”> <label for=“principal”>Principal:</label> <input type=“number” id=“principal” v-model="loanForm.principal" required /> </div> <br> <div class=“field-group”> <label for=“interestRate”>Interest Rate:</label> <input type=“number” id=“interestRate” v-model="loanForm.interestRate" required /> </div> <br> <div class=“field-group”> <label for=“term”>Term:</label> <input type=“number” id=“term” v-model="loanForm.term" required /> </div> <br> <div class=“field-group”> <label for=“maturityDate”>Maturity Date:</label> <input type=“number” id=“maturityDate” v-model="loanForm.maturityDate" required /> </div> <br> <div class=“field-group”> <label for=“offchainDataURL”>Offchain Data URL:</label> <input type=“text” id=“offchainDataURL” v-model="loanForm.offchainDataURL" required /> </div> <br> <div class=“field-group”> <label for=“offchainDataHash”>Offchain Data Hash:</label> <input type=“text” id=“offchainDataHash” v-model="loanForm.offchainDataHash" required /> </div> <br> <button type=“submit”>Issue Loan</button> </form> <h2>Buy Loan NFT</h2> <form @submit.prevent="onBuyNFT" class=“loan-form”> <div class=“field-group”> <label for=“buy_loan_id”>Loan ID:</label> <input type=“number” id=“buy_loan_id” v-model="buyNFTForm.loanId" required /> </div> <button type=“submit”>Buy Loan NFT</button> </form> <h2>Destroy Loan NFT</h2> <form @submit.prevent="onDestroyNFT" class=“loan-form”> <div class=“field-group”> <label for=“destroy_loan_id”>Loan ID:</label> <input type=“number” id=“destroy_loan_id” v-model="destroyNFTForm.loanId" required /> </div> <button type=“submit”>Destroy Loan NFT</button> </form> <p>{{issueLoanStatus}}</p> </div> </template> <script> import Web3 from "web3"; //import LoanNFTJson from "@//LoanNFT.json"; import LoanNFT from '@/LoanNFT.js'; export default { data() { return { web3: null, contract: null, account: null, loanForm: { borrower: "", principal: 0, interestRate: 0, term: 0, maturityDate: 0, offchainDataURL: "", offchainDataHash: "" }, buyNFTForm: { loanId: 0, }, destroyNFTForm: { loanId: 0, }, issueLoanStatus: "" }; }, async mounted() { // Connect to Metamask if (window.ethereum) { window.web3 = new Web3(window.ethereum); this.web3 = window.web3; await window.ethereum.enable(); } else { alert("Please install Metamask to use this app"); return; } // Get user account const accounts = await this.web3.eth.getAccounts(); this.account = accounts[0]; // Load and create an instance of the smart contract const networkId = await this.web3.eth.net.getId(); const networkData = LoanNFT.networks[networkId]; if (!networkData) { alert("Smart contract is not deployed to the detected network"); return; } const contractAddress = networkData.address; this.contract = new this.web3.eth.Contract(LoanNFT.abi, contractAddress); }, methods: { async onIssueLoan() { try { this.issueLoanStatus = "Submitting transaction…"; await this.contract.methods .issueLoan( this.loanForm.borrower, this.loanForm.principal, this.loanForm.interestRate, this.loanForm.term, this.loanForm.maturityDate, this.loanForm.offchainDataURL, this.loanForm.offchainDataHash ) .send({ from: this.account }); this.issueLoanStatus = "Loan issued successfully"; } catch (error) { console.error(error); this.issueLoanStatus = "Transaction failed!"; } }, async onBuyNFT() { try { const couponAmount = await this.contract.methods.calculateCouponAmount(this.buyNFTForm.loanId).call(); await this.contract.methods.buyNFT(this.buyNFTForm.loanId).send({ from: this.account, value: couponAmount }); alert('Loan NFT bought successfully'); } catch (error) { console.error(error); alert('Buying Loan NFT failed'); } }, async onDestroyNFT() { try { await this.contract.methods.destroyNFT(this.destroyNFTForm.loanId).send({ from: this.account }); alert('Loan NFT destroyed successfully'); } catch (error) { console.error(error); alert('Destroying Loan NFT faile'); } }, }, }; </script> <style scoped> /* LoanNFTApp styles */ .loan-nft-app { max-width: 600px; margin: 0 auto; padding: 1rem; background-color: #f7f7f7; border-radius: 10px; } h1 { font-size: 1.5rem; text-align: center; margin-bottom: 1.5rem; } h2 { font-size: 1.25rem; margin-bottom: 1rem; } .loan-form { display: grid; gap: 1.5rem; } .field-group { display: flex; flex-direction: column; } label { margin-bottom: 0.5rem; padding-right: 15px; } input { height: 2rem; margin-bottom: 0.5rem; padding: 0.25rem; border: 1px solid #ccc; border-radius: 4px; font-size: 1rem; } button { background-color: #27ae60; color: white; border: none; padding: 0.5rem 1rem; border-radius: 4px; font-size: 1rem; cursor: pointer; transition: background-color 0.2s ease; } button:hover { background-color: #2ecc71; } </style>
8b2a9bcce210eadacc0764c324274382
{ "intermediate": 0.3927483558654785, "beginner": 0.3480924963951111, "expert": 0.2591590881347656 }
3,572
“@echo off setlocal EnableDelayedExpansion set “src_dir=C:\Users\user\Desktop\16 pixeley” set “dest_dir=C:\Users\user\Desktop\maxshrinkedByKichiro” set “output_dir=C:\Users\user\Desktop\sborka3” for /r “%src_dir%” %%a in (*) do ( set “src_file=%%a” set “dest_file=!src_file:%src_dir%=%dest_dir%!” set “output_file=!src_file:%src_dir%=%output_dir%!” if not exist “!dest_file!..” ( mkdir “!dest_file!..” ) if exist “!dest_file!” ( for /f %%i in (”!src_file!“) do ( set “src_size=%%~zi” for /f %%j in (”!dest_file!“) do ( set “dest_size=%%~zj” if !src_size! lss !dest_size! ( set “smaller_file=!src_file!” echo “Copying smaller file !smaller_file! to !output_file! …” ) else ( set “smaller_file=!dest_file!” echo “Copying smaller file !smaller_file! to !output_file! …” ) xcopy “!smaller_file!” “!output_file!” >nul ) ) ) else ( xcopy “!src_file!” “!output_file!” >nul echo “Copying !src_file! to !output_file! …” ) ) echo “done!”” почини код чтобы он работал и добавь максимально подробную отладочную информацию в консоль
2d57a06b1c701388eaacd5f48a47fed7
{ "intermediate": 0.3428536057472229, "beginner": 0.3967382609844208, "expert": 0.2604081630706787 }
3,573
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt def basic_info(): config = dict() config[“access_token”] = st.secrets[“access_token”] config[‘instagram_account_id’] = st.secrets.get(“instagram_account_id”, “”) config[“version”] = ‘v16.0’ config[“graph_domain”] = ‘https://graph.facebook.com/’ config[“endpoint_base”] = config[“graph_domain”] + config[“version”] + ‘/’ return config def InstaApiCall(url, params, request_type): if request_type == ‘POST’: req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res[“url”] = url res[“endpoint_params”] = params res[“endpoint_params_pretty”] = json.dumps(params, indent=4) res[“json_data”] = json.loads(req.content) res[“json_data_pretty”] = json.dumps(res[“json_data”], indent=4) return res def getUserMedia(params, pagingUrl=‘’): Params = dict() Params[‘fields’] = ‘id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count’ Params[‘access_token’] = params[‘access_token’] if not params[‘endpoint_base’]: return None if pagingUrl == ‘’: url = params[‘endpoint_base’] + params[‘instagram_account_id’] + ‘/media’ else: url = pagingUrl return InstaApiCall(url, Params, ‘GET’) def getUser(params): Params = dict() Params[‘fields’] = ‘followers_count’ Params[‘access_token’] = params[‘access_token’] if not params[‘endpoint_base’]: return None url = params[‘endpoint_base’] + params[‘instagram_account_id’] return InstaApiCall(url, Params, ‘GET’) def saveCount(count, filename): with open(filename, ‘w’) as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, ‘r’) as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout=“wide”) params = basic_info() count_filename = “count.json” if not params[‘instagram_account_id’]: st.write(‘.envファイルでinstagram_account_idを確認’) else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write(‘.envファイルでaccess_tokenを確認’) else: posts = response[‘json_data’][‘data’][::-1] user_data = user_response[‘json_data’] followers_count = user_data.get(‘followers_count’, 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime(‘%Y-%m-%d’) follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get(‘followers_count’, followers_count) st.markdown(f" Follower: {followers_count} ({‘+’ if follower_diff >= 0 else ‘’}{follower_diff}) “, unsafe_allow_html=True) show_description = st.checkbox(“キャプションを表示”) show_summary_chart = st.checkbox(“サマリーチャートを表示”) show_like_comment_chart = st.checkbox(“いいね/コメント数グラフを表示”) posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d’) if today not in count: count[today] = {} count[today][‘followers_count’] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%H:%M’) == ‘23:59’: count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {“Date”: [], “Count”: [], “Type”: []} for post_group in post_groups: for post in post_group: like_count_diff = post[‘like_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘like_count’, post[‘like_count’]) comment_count_diff = post[‘comments_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘comments_count’, post[‘comments_count’]) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data[“Date”].append(datetime.datetime.strptime(date, ‘%Y-%m-%d’).strftime(‘%m/%d’)) summary_chart_data[“Count”].append(count[date].get(“followers_count”, 0)) summary_chart_data[“Type”].append(“Follower”) for post_id in count[date].keys(): if post_id not in [“followers_count”]: summary_chart_data[“Date”].append(datetime.datetime.strptime(date, ‘%Y-%m-%d’).strftime(‘%m/%d’)) summary_chart_data[“Count”].append(count[date][post_id].get(“like_count”, 0)) summary_chart_data[“Type”].append(“Like”) summary_chart_data[“Date”].append(datetime.datetime.strptime(date, ‘%Y-%m-%d’).strftime(‘%m/%d’)) summary_chart_data[“Count”].append(count[date][post_id].get(“comments_count”, 0)) summary_chart_data[“Type”].append(“Comment”) summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {“Follower”: “lightblue”, “Like”: “orange”, “Comment”: “green”} sns.lineplot(data=summary_chart_df, x=“Date”, y=“Count”, hue=“Type”, palette=summary_chart_palette) plt.xlabel(“Date”) plt.ylabel(“Count”) plt.title(“日別 サマリーチャート”) st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post[‘media_url’], width=BOX_WIDTH, use_column_width=True) st.write(f”{datetime.datetime.strptime(post[‘timestamp’], ‘%Y-%m-%dT%H:%M:%S%z’).astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d %H:%M:%S’)}“) like_count_diff = post[‘like_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘like_count’, post[‘like_count’]) comment_count_diff = post[‘comments_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘comments_count’, post[‘comments_count’]) st.markdown( f"👍: {post[‘like_count’]} <span style=‘{’’ if like_count_diff != max_like_diff or max_like_diff == 0 else ‘color:green;’}‘>({’+’ if like_count_diff >= 0 else ‘’}{like_count_diff})” f"\n💬: {post[‘comments_count’]} <span style=‘{’’ if comment_count_diff != max_comment_diff or max_comment_diff == 0 else ‘color:green;’}‘>({’+’ if comment_count_diff >= 0 else ‘’}{comment_count_diff})“, unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {“Date”: [], “Count”: [], “Type”: []} for date in count.keys(): if date != today and post[“id”] in count[date]: like_comment_chart_data[“Date”].append(datetime.datetime.strptime(date, ‘%Y-%m-%d’).strftime(‘%m/%d’)) like_comment_chart_data[“Count”].append(count[date][post[“id”]].get(“like_count”, 0)) like_comment_chart_data[“Type”].append(“Like”) like_comment_chart_data[“Date”].append(datetime.datetime.strptime(date, ‘%Y-%m-%d’).strftime(‘%m/%d’)) like_comment_chart_data[“Count”].append(count[date][post[“id”]].get(“comments_count”, 0)) like_comment_chart_data[“Type”].append(“Comment”) if like_comment_chart_data[“Date”]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {“Like”: “orange”, “Comment”: “green”} sns.lineplot(data=like_comment_chart_df, x=“Date”, y=“Count”, hue=“Type”, palette=like_comment_chart_palette) plt.xlabel(“Date”) plt.ylabel(“Count”) plt.title(“日別 いいね/コメント数”) st.pyplot() caption = post[‘caption’] if caption is not None: caption = caption.strip() if “[Description]” in caption: caption = caption.split(”[Description]“)[1].lstrip() if “[Tags]” in caption: caption = caption.split(”[Tags]“)[0].rstrip() caption = caption.replace(”#“, “”) caption = caption.replace(”[model]“, “👗”) caption = caption.replace(”[Equip]“, “📷”) caption = caption.replace(”[Develop]", “🖨”) if show_description: st.write(caption or “No caption provided”) else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or “No caption provided”) count[today][post[‘id’]] = {‘like_count’: post[‘like_count’], ‘comments_count’: post[‘comments_count’]} saveCount(count, count_filename) ''' 上記のコードに正確なインデントを付与して再表示してください
8980ec597a06fe92626471273d8a8975
{ "intermediate": 0.35548099875450134, "beginner": 0.3316313326358795, "expert": 0.31288769841194153 }
3,574
import backtrader as bt import pandas as pd import yfinance as yf import requests token = "6229637145:AAEIvDkANjYB5GP4EJXQnBFp30EkUeI4TIc" chat_id = "1208308144" def send_message(text): url = f"https://api.telegram.org/bot{token}/sendMessage" params = { "chat_id": chat_id, "text": text, } resp = requests.get(url, params=params) resp.raise_for_status() class MovingAverageStrategy(bt.Strategy): params = (("fast_ma", 20), ("slow_ma", 50), ("period", 14), ("mom", 10)) name = "Moving Average" def __init__(self): self.mom_indicator = bt.indicators.Momentum(self.data, period=self.params.period) def next(self): if not self.position: if self.mom_indicator[0] > self.params.mom: self.buy() elif self.mom_indicator[0] < self.params.mom: self.sell() class MomentumStrategy(bt.Strategy): params = (("period", 14), ("mom", 10)) name = "Momentum Strategy" def __init__(self): self.momentum = bt.indicators.Momentum(self.data, period=self.params.period) def next(self): if not self.position: if self.momentum > self.params.mom: self.buy() elif self.momentum < self.params.mom: self.sell() class ZScore(bt.Indicator): lines = ("zscore",) params = (("period", 20),) def __init__(self): self.bband = bt.indicators.BollingerBands(self.data, period=self.params.period) self.stddev = bt.indicators.StandardDeviation(self.data, period=self.params.period) def next(self): self.lines.zscore[0] = (self.data[0] - self.bband.lines.mid[0]) / self.stddev[0] class MeanReversionStrategy(bt.Strategy): params = (("period", 20),) name = "Mean Reversion Strategy" def __init__(self): self.indicators = dict(zscore=ZScore(period=self.params.period)) def next(self): if not self.position: if self.indicators['zscore'][0] < -1.0: self.buy() elif self.indicators['zscore'][0] > 1.0: self.sell() class TrendFollowingStrategy(bt.Strategy): params = (("fast_ma_period", 50), ("slow_ma_period", 200),) name = "Trend Following Strategy" def __init__(self): self.fast_ma = bt.indicators.SimpleMovingAverage(self.data, period=self.params.fast_ma_period) self.slow_ma = bt.indicators.SimpleMovingAverage(self.data, period=self.params.slow_ma_period) def next(self): if not self.position: if self.fast_ma > self.slow_ma: self.buy() elif self.fast_ma < self.slow_ma: self.sell() stock_list = ["MSFT", "AAPL", "GOOGL", "TSLA"] strategy_list = [MovingAverageStrategy, MomentumStrategy, MeanReversionStrategy, TrendFollowingStrategy] for stock in stock_list: try: data = yf.download(stock, start="2010-01-01", end="2023-03-28", auto_adjust=True, ignore_tz=True) if data is None or data.empty: raise ValueError(f"No data found for {stock} in the specified date range.") else: data = bt.feeds.PandasData(dataname=data) for strat in strategy_list: cerebro = bt.Cerebro() cerebro.adddata(data) cerebro.addstrategy(strat) cerebro.broker.setcash(10000) cerebro.broker.setcommission(commission=0.001) cerebro.addsizer(bt.sizers.PercentSizer, percents=10) cerebro.addsizer(bt.sizers.PercentSizer, percents=10) starting_value = cerebro.broker.getvalue() result = cerebro.run() final_value = cerebro.broker.getvalue() # calculate maximum drawdown max_drawdown = bt.analyzers.DrawDown().get_analysis()["max"]["drawdown"] # calculate Sharpe ratio sharpe_ratio = bt.analyzers.SharpeRatio().get_analysis()["sharperatio"] # calculate win/loss ratios win_ratio = bt.analyzers.WinningTrades().get_analysis()["total"] / bt.analyzers.TotalTrades().get_analysis()["total"] loss_ratio = bt.analyzers.LosingTrades().get_analysis()["total"] / bt.analyzers.TotalTrades().get_analysis()["total"] message = f"Stock: {stock}\n" message += f"Strategy: {strat.name}\n" message += f"Starting Portfolio Value: {starting_value:.2f}\n" message += f"Final Portfolio Value: {final_value:.2f}\n" gain = final_value - starting_value message += f"Total Gain: {gain:.2f}\n" message += f"ROI : {gain / starting_value * 100:.2f}%\n" message += f"Maximum Drawdown: {max_drawdown:.2f}\n" message += f"Sharpe Ratio: {sharpe_ratio:.2f}\n" message += f"Win Ratio: {win_ratio:.2f}\n" message += f"Loss Ratio: {loss_ratio:.2f}\n" print(message) except ValueError as e: print(e) continue [*********************100%***********************] 1 of 1 completed Traceback (most recent call last): File "c:\Users\Adrian\Desktop\Trader_1.py", line 120, in <module> max_drawdown = bt.analyzers.DrawDown().get_analysis()["max"]["drawdown"] ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\metabase.py", line 86, in __call__ _obj, args, kwargs = cls.donew(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Adrian\AppData\Local\Programs\Python\Python311\Lib\site-packages\backtrader\analyzer.py", line 52, in donew _obj.datas = strategy.datas ^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'datas'
994fc731ee5ea153abec2449a0274d45
{ "intermediate": 0.3307512104511261, "beginner": 0.4811193346977234, "expert": 0.18812941014766693 }
3,575
zooming out constellation of flags which are centered around central huge one and the rest is in different sizes. so, the text should be attached and translated to appropriate language and centered on the flag background as in this style. need to use only icon symbols, without externals images and javascript: .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; position: relative; display: flex; } .background:before { content: '🇬🇧'; font-size: 10em; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: -1; } <span class="background"> <span class="background-text"> YES, WE CARE! </span> </span>
2a9f04718486f2bbc0ff359372ebb22a
{ "intermediate": 0.3773328959941864, "beginner": 0.23746362328529358, "expert": 0.38520348072052 }
3,576
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post]["id"].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して出力する - コードの説明文は表示しない - コードの最前部と最後尾に'''をつけコード様式で出力する - 修正済みのコード全体を省略せずに表示する - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - "いいね/コメント数グラフを表示"を押下し表示しようとした際のエラー ''' AttributeError: 'str' object has no attribute 'get' Traceback: File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 170, in <module> like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) ''' - "サマリーチャートを表示"を押下し表示しようとした際のエラー ''' PyplotGlobalUseWarning: You are calling st.pyplot() without any arguments. After December 1st, 2020, we will remove the ability to do this as it requires the use of Matplotlib's global figure object, which is not thread-safe. To future-proof this code, you should pass in a figure as shown below: >>> fig, ax = plt.subplots() >>> ax.scatter([1, 2, 3], [1, 2, 3]) >>> ... other plotting actions ... >>> st.pyplot(fig) You can disable this warning by disabling the config option: deprecation.showPyplotGlobalUse st.set_option('deprecation.showPyplotGlobalUse', False) or in your .streamlit/config.toml [deprecation] showPyplotGlobalUse = false '''
52772e265c20381ad604ec7c6dcfed4c
{ "intermediate": 0.34356698393821716, "beginner": 0.3770371377468109, "expert": 0.2793958783149719 }
3,577
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コードの説明文は表示しない - 指示のない部分のコードの改変はしない - 既存の'like_count'と"comments_count"表示部分は改変しない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - "followers_count"と'like_count'と'comments_count'を縦軸に表示し、グラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"サマリーチャートを、ページの最上部に横幅いっぱいに表示する機能を作成する - "サマリーチャート"の'like_count'と'comments_count'の数は、jsonファイル内の過去すべての日次データを参照し、"存在する対象日とその前日データの差分"を算出して日付ごとに表示する - 'like_count'と'comments_count'を縦軸に表示し、グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"mm/dd"を横軸にした"いいね/コメント数グラフ"を、投稿コンテナ内の"キャプション"の下に表示する機能を作成する - "いいね/コメント数グラフ"は、jsonファイル内の過去すべての日次データを参照し、各投稿IDの'like_count'と'comments_count'を、それぞれ"存在する対象日とその前日データとの差分"を算出して日付ごとに、各ID別の投稿コンテナに個別のグラフを表示するようにする - "キャプションを表示"の右隣に"サマリーチャート"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
4ac2c675540240f6fa9803d79be5f151
{ "intermediate": 0.3471693694591522, "beginner": 0.4591856896877289, "expert": 0.1936449408531189 }
3,578
best way to create nested JSON request body for an api call
25a232df6d502e8ab75f09ec51621b3e
{ "intermediate": 0.7012069821357727, "beginner": 0.1614241749048233, "expert": 0.13736885786056519 }
3,579
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post]["id"].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して出力する - コードの説明文は表示しない - コードの最前部と最後尾に'''をつけコード様式で出力する - 修正済みのコード全体を省略せずに表示する - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - "いいね/コメント数グラフを表示"を押下し表示しようとした際のエラー ''' AttributeError: 'str' object has no attribute 'get' Traceback: File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 170, in <module> like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) ''' - "サマリーチャートを表示"を押下し表示しようとした際のエラー ''' PyplotGlobalUseWarning: You are calling st.pyplot() without any arguments. After December 1st, 2020, we will remove the ability to do this as it requires the use of Matplotlib's global figure object, which is not thread-safe. To future-proof this code, you should pass in a figure as shown below: >>> fig, ax = plt.subplots() >>> ax.scatter([1, 2, 3], [1, 2, 3]) >>> ... other plotting actions ... >>> st.pyplot(fig) You can disable this warning by disabling the config option: deprecation.showPyplotGlobalUse st.set_option('deprecation.showPyplotGlobalUse', False) or in your .streamlit/config.toml [deprecation] showPyplotGlobalUse = false '''
56248859a107c23e24f3aab6c80faca5
{ "intermediate": 0.34356698393821716, "beginner": 0.3770371377468109, "expert": 0.2793958783149719 }
3,580
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post]["id"].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して、正常に表示されるかチェックしてから出力する - コードの説明文は表示しない - コードの最前部と最後尾に'''をつけコード様式で出力する - 修正済みのコード全体を省略せずに表示する - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - "いいね/コメント数グラフを表示"を押下し表示しようとした際のエラー ''' AttributeError: 'str' object has no attribute 'get' Traceback: File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 170, in <module> like_comment_chart_data["Count"].append(count[date][post["id"].get("like_count", 0)]) ''' - "サマリーチャートを表示"を押下し表示しようとした際のエラー ''' PyplotGlobalUseWarning: You are calling st.pyplot() without any arguments. After December 1st, 2020, we will remove the ability to do this as it requires the use of Matplotlib's global figure object, which is not thread-safe. To future-proof this code, you should pass in a figure as shown below: >>> fig, ax = plt.subplots() >>> ax.scatter([1, 2, 3], [1, 2, 3]) >>> ... other plotting actions ... >>> st.pyplot(fig) You can disable this warning by disabling the config option: deprecation.showPyplotGlobalUse st.set_option('deprecation.showPyplotGlobalUse', False) or in your .streamlit/config.toml [deprecation] showPyplotGlobalUse = false '''
650eafcb9cf087a3c96c42a6eeec1aed
{ "intermediate": 0.34356698393821716, "beginner": 0.3770371377468109, "expert": 0.2793958783149719 }
3,581
hwo EdgeX foundry get data from the ModBusRTU device
a06bb7f8a7091eddd2c939edf619cd23
{ "intermediate": 0.3427606225013733, "beginner": 0.23027698695659637, "expert": 0.42696237564086914 }
3,582
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("like_count", 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して、正常に表示されるかチェックしてから出力する - コードの説明文は表示しない - コードの最前部と最後尾に'''をつけコード様式で出力する - 修正済みのコード全体を省略せずに表示する - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - "いいね/コメント数グラフを表示"か"サマリーチャートを表示"を押下し表示しようとした際のエラー ''' PyplotGlobalUseWarning: You are calling st.pyplot() without any arguments. After December 1st, 2020, we will remove the ability to do this as it requires the use of Matplotlib's global figure object, which is not thread-safe. To future-proof this code, you should pass in a figure as shown below: >>> fig, ax = plt.subplots() >>> ax.scatter([1, 2, 3], [1, 2, 3]) >>> ... other plotting actions ... >>> st.pyplot(fig) You can disable this warning by disabling the config option: deprecation.showPyplotGlobalUse st.set_option('deprecation.showPyplotGlobalUse', False) or in your .streamlit/config.toml [deprecation] showPyplotGlobalUse = false '''
f06556edb575a07ee91561455c3c0411
{ "intermediate": 0.33554038405418396, "beginner": 0.38297271728515625, "expert": 0.2814869284629822 }
3,583
join multiple nested complex collections in mogodb in the context of multiple pipeline conditions
5c4c1a056ff4b3cf1a7a138e4ae46961
{ "intermediate": 0.5236487984657288, "beginner": 0.17051896452903748, "expert": 0.30583226680755615 }
3,584
Please use the data set named Inf_Unrate_1960m1_2023m3.dta to answer the following questions. Give answers in the form of STATA commands: (a) (3p) Create a variable called dunrate that is calculated by differencing unrate variable. (b) (5p) Compute an AR(1) model for dunrate series for the time period 1960m1 to 2023m2. (c) (5p) Write your model in part (b) as a regression equation (rounding up to 3 decimal points). (d) (10p) Forecast March 2023 unemployment rate using the model in (c). (e) (5p) Compute an ADL(1,1) model for dunrate series adding lagged inflation rate to your model for the time period 1960m1 to 2023m2. (f) (5p) Write your model in part (e) as a regression equation (rounding up to 3 decimal points). (g) (10p) Forecast March 2023 unemployment rate using the model in (f). (h) (5p) Compare your forecasts from (d) and (g) to the real data for March 2023. Which model’s forecast is closer to the real data?
488ce846aa08d73125372d1cefc29ccc
{ "intermediate": 0.30559787154197693, "beginner": 0.3346477448940277, "expert": 0.3597543239593506 }
3,585
上記のコードの機能はそのままで、未使用部分や空行などを削除し、最適化できる部分は改変してコード全体の文字数を削減してください。コードにはPython用インデントを表示可能かどうかチェックのうえ付与してから表示してください
8ad48f38edf6fe867f2311877f883bc5
{ "intermediate": 0.335568904876709, "beginner": 0.33111241459846497, "expert": 0.33331871032714844 }
3,586
I wiil upload the links for two call graphs images, and I want you to measure the similarity score of these two call graphs
50cda5e0945af021d8541d25a1ad5d7b
{ "intermediate": 0.39877983927726746, "beginner": 0.26655060052871704, "expert": 0.3346695899963379 }
3,587
{% block content %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" /> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script> <div class="container card p-3 mt-5 border-dark " style="width: 95%;"> <a href="{% url 'data_create' %}" class="'btn btn-outline-primary mb-3">GO HOME</a> <h4 class="card pt-2 text center mb-3">ADD CANDIDATE </h4> <table class="table table-bordered text-center"> <thead class="table secondary"> <tr> <th>Name</th> <th>Email</th> <th>address</th> <th>career</th> <th>gender</th> <th>Actions</th> </tr> </thead> <tbody> {%for data in data_read%} <tr> <td>{{data.name}}</td> <td>{{data.email}}</td> <td>{{data.address}}</td> <td>{{data.career}}</td> 4 <td>{{data.gender}}</td> <td> <a href="{% url 'data_view' pk=data.pk %}" class="btn btn-sm btn-primary">View</a> <a href="{% url 'data_edit' pk=data.pk %}" class="btn btn-sm btn-secondary">Edit</a> <form action="{% url 'data_delete' pk=data.pk%}" method="post" style="display: inline-block"> {% csrf_token %} <input type="submit" value="Delete" class="btn btn-sm btn-danger"> </form> </td> </tr> {%endfor%} </tbody> </table> </div> {% endblock content%} im working on crud and soft delete everythinbg is wokring
03ce456a6f13b846bd0d3af6d289308f
{ "intermediate": 0.3494780957698822, "beginner": 0.43696579337120056, "expert": 0.21355605125427246 }
3,588
add some space between bottomNavigationBar and bottom of screen for scaffold
abe242afb96cc33468be6673bdd59734
{ "intermediate": 0.3806942403316498, "beginner": 0.31856247782707214, "expert": 0.30074331164360046 }
3,589
join multiple collections in mogodb in the context of multiple pipeline conditions
1c7beec3bd2ea0f7d0d28fd3c2b4f1d5
{ "intermediate": 0.544326901435852, "beginner": 0.15812420845031738, "expert": 0.2975488603115082 }
3,590
<Link href="/amount"> <MLink underline="hover" color="primary" href="#">Другие...</MLink> </Link> // import React from "react"; import Head from "next/head"; import Link from "next/link"; import ContentHeader from "../../components/ContentHeader/ContentHeader"; import { Container, Grid, Typography } from "@mui/material"; const AmountPage = (pros: any) => { return ( <> <Head> <title>Количетво пользователей</title> </Head> <Grid> UsersAmount <Typography> {pros.title} </Typography> </Grid> </> ); }; export default AmountPage; как передать пропсы в AmountPage next.js
069f0a28ccbcefd30d8d1c009f87438e
{ "intermediate": 0.4160425662994385, "beginner": 0.30426931381225586, "expert": 0.27968814969062805 }
3,591
create react remix app with express backend and on the default route display the d3js "Versor Dragging" example
715291ccb179665d0cb11de0d561546f
{ "intermediate": 0.5630603432655334, "beginner": 0.21624130010604858, "expert": 0.2206982523202896 }
3,592
join multiple nested complex collections in mogodb in the context of multiple pipeline conditions and multiple join in any collection
4edc74130fe0af54454fd46978726432
{ "intermediate": 0.5134713649749756, "beginner": 0.13933046162128448, "expert": 0.34719815850257874 }
3,593
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) fig, ax = plt.subplots(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette, ax=ax) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("like_count", 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) fig, ax = plt.subplots(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette, ax=ax) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot(fig) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して、正常に表示されるかチェックしてから出力する - コードの最前部と最後尾に'''をつけコード様式で出力する - コードの説明文は表示しない - 指示のない部分のコードの改変はしない - 既存の'like_count'と"comments_count"表示部分は改変しない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - "サマリーチャート"の"followers_count"と'like_count'は左縦軸に目盛を表示し、'comments_count'は右縦軸に目盛を表示する - "サマリーチャート"の'like_count'と'comments_count'の数はjsonファイル内の過去すべての日次データを参照し、"対象日時点の数値"ではなく、"対象日とその前日データの差分"を算出した数を表示する - "いいね/コメント数グラフ"は、'like_count'を左縦軸に目盛を表示し、'comments_count'を右縦軸に目盛を表示する - "いいね/コメント数グラフ"の'like_count'と'comments_count'の数はjsonファイル内の過去すべての日次データを参照し、"対象日時点の数値"ではなく、"対象日とその前日データの差分"を算出した数を表示する
eda5a24cd43dd2ba963e5367fb8315e3
{ "intermediate": 0.33554038405418396, "beginner": 0.38297271728515625, "expert": 0.2814869284629822 }
3,594
give me a template for excel to compare weekly profit of portfoilio
e4049d222fdd3d4aa64b4613014be4ad
{ "intermediate": 0.3775826394557953, "beginner": 0.210115447640419, "expert": 0.4123018980026245 }
3,595
How to list ec2 instances in Python with boto3 using client('ec2')?
18272a89b0ba1ea60a3414d99a7abb4c
{ "intermediate": 0.6601183414459229, "beginner": 0.11409205943346024, "expert": 0.22578957676887512 }
3,596
wake word detection на python
f8da90b93816aa74422beb9e4087d314
{ "intermediate": 0.29853329062461853, "beginner": 0.2324417531490326, "expert": 0.46902498602867126 }
3,597
как исправить File "C:\Users\home\PycharmProjects\витрина\main.py", line 48, in <module> for product in products: TypeError: 'NoneType' object is not iterable в коде import requests from bs4 import BeautifulSoup def get_soup(url): response = requests.get(url) return BeautifulSoup(response.text, 'html.parser') def parse_product_card(card): title = card.select_one('div.card__content>div.card__information>h3').text link = card.select_one('div.card__content>div.card__information>h3>a')['href'] return title, link def parse_product_page(soup): sizes = soup.select_one('#ProductInfo-template–16663852253403__main>div.size-wrapper-desktop>div.product-popup-modal__opener.no-js-hidden.quick-add-hidden.choosen') price = soup.select_one('#price-template–16663852253403__main>div.price.price–large.price–show-badge>div>div.price__regular').text image_link = soup.select_one('#Slide-template–16663852253403__main-31937321107675>modal-opener>div')['src'] return { 'sizes': sizes if sizes is not None else '', 'price': price.text if price is not None else '', 'image_link': image_link['src'] if image_link is not None else '' } def scrape_product_info(url): soup = get_soup(url) cards = soup.select('#gf-products>li') products = [] for card in cards: title, link = parse_product_card(card) product_info = parse_product_page(get_soup(link)) product = { 'title': title, 'link': link, ** product_info } products.append(product) return products URL = 'https://www.poizon.us/collections/sneakers-1?page=1' products = scrape_product_info(URL) for product in products: print(product)
e08dd222086a40dcd23d9101622829f3
{ "intermediate": 0.4575366675853729, "beginner": 0.2658788859844208, "expert": 0.2765844166278839 }
3,598
fivem scripting how can I get a ped to walk over to the front of a vehicle and play an animation the only input to the function is the entity
8d09707f17b9d1703db0972c41e19491
{ "intermediate": 0.28112533688545227, "beginner": 0.41116535663604736, "expert": 0.30770930647850037 }
3,599
arduino code continuous rotation stepper motor with potentiometer with ContinuousStepper Library
5b142190f458406a1acf9d608231dc4c
{ "intermediate": 0.5422228574752808, "beginner": 0.15717189013957977, "expert": 0.30060526728630066 }
3,600
arduino code continuous rotation two stepper motor with two potentiometer with ContinuousStepper Library
5a3006d72662daba5f68084992679f52
{ "intermediate": 0.5835888385772705, "beginner": 0.14494994282722473, "expert": 0.2714611887931824 }
3,601
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("like_count", 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' あなたは指示に忠実なプログラマーです。 現在、インスタグラムの投稿の一覧表示をして各投稿の"いいね数"や"コメント数"、また"キャプション"を表示する機能と、jsonファイルに保存した"フォロワー数"や"いいね数"や"コメント数"のデータを元にグラフを描画する機能を持つアプリケーションを作成しています。 上記のコードを以下の要件をすべて満たして改修してください - 2500文字に到達する前に回答を区切り、指示がなくても次の回答を自動で再開し、2500文字に到達する前に回答を区切るという動作を繰り返す - Python用のインデントを行頭に付与して、正常に表示されるかチェックしてから出力する - コードの説明文は表示しない - 指示のない部分のコードの改変は絶対にしない - 既存の'like_count'と"comments_count"表示部分は絶対に改変しない - "caption = post['caption']"以降のブロックについては絶対に改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - "サマリーチャート"の"followers_count"と'like_count'は左縦軸に目盛を表示し、'comments_count'は右縦軸に目盛を表示する - "サマリーチャート"の'like_count'と'comments_count'の数はjsonファイル内の過去すべての日次データを参照し、"対象日時点の数値"ではなく、"対象日とその前日データの差分"を算出した数を表示する - "いいね/コメント数グラフ"は、'like_count'を左縦軸に目盛を表示し、'comments_count'を右縦軸に目盛を表示する - "いいね/コメント数グラフ"の'like_count'と'comments_count'の数はjsonファイル内の過去すべての日次データを参照し、"対象日時点の数値"ではなく、"対象日とその前日データの差分"を算出した数を表示する
21561d9774a3edb8a46e92ddb5b6ae0c
{ "intermediate": 0.33554038405418396, "beginner": 0.38297271728515625, "expert": 0.2814869284629822 }
3,602
I would like a line in my VBA that checks the last cell with a value in Column B and if the value found is PERMIT REQUEST, it should exit the sub
e19f8bac825a54d970f12386873e31aa
{ "intermediate": 0.4255203306674957, "beginner": 0.14606307446956635, "expert": 0.42841657996177673 }
3,603
java code to receive imap mail and store subject "number" and message example "12345678" in hashtable.
43dd1cbf3f1939bbdf418d158908d20b
{ "intermediate": 0.44047802686691284, "beginner": 0.19378261268138885, "expert": 0.3657393753528595 }
3,604
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("like_count", 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードの機能(特にグラフ関連のコードは絶対変更しない)を一切変更せずに、文字数削減のための最適化をしてください
4a0a45d7f7bf8b4cebabcc83103c3860
{ "intermediate": 0.4353925287723541, "beginner": 0.3519333302974701, "expert": 0.21267417073249817 }
3,605
java code to implement the quantum cnot logic for 3 qubit ( as booleans ) entanglement may be with extensions of xor. use random numbers to simulate the control bit feature meaning , decide, if operations are executed in order to match entanglement criteria
f2fcf8de9f2319f08d606d959a6973d9
{ "intermediate": 0.33043962717056274, "beginner": 0.0976201519370079, "expert": 0.5719401836395264 }
3,606
I want to include in my VBA code, a routine that checks Column B for its last entry. If the last entry in Column B contains the text value PERMIT REQUEST, the the rest of the VBA code is skipped
b52e2e99d710ea72b70006407e5c6758
{ "intermediate": 0.4021788239479065, "beginner": 0.16086630523204803, "expert": 0.4369547963142395 }
3,607
This is machine learning project based on network intrusion detection where we have used NSL KDD dataset and need to do preprocessing and removing outlier using K-Means and do feature selection using Emperor penguin optimizer and then Train using Bi-LSTM and then find the accuracy, confusion matrix, precision recall and all hyperparametrrs Accuracy expected 0.97
b97ac7faeec169b4bffdc65cb167e522
{ "intermediate": 0.036652687937021255, "beginner": 0.01923242397606373, "expert": 0.9441148638725281 }
3,608
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("like_count", 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date][post_id].get("comments_count", 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) plt.figure(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df, x="Date", y="Count", hue="Type", palette=summary_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 サマリーチャート") st.pyplot() for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("like_count", 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(count[date][post["id"]].get("comments_count", 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) plt.figure(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df, x="Date", y="Count", hue="Type", palette=like_comment_chart_palette) plt.xlabel("Date") plt.ylabel("Count") plt.title("日別 いいね/コメント数") st.pyplot() caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードの機能を一切(画像表示,いいね数表示,コメント数表示,キャプション表示,トグルスイッチ,サマリーチャート,いいね/コメント数チャート)変更せずに、コード全体の文字数削減のための最適化を実施し、処理後のコード全文をPython用インデントを付与して表示してください。
2290ceb6fabbdd8ff3f23809eb8b4f22
{ "intermediate": 0.4353925287723541, "beginner": 0.3519333302974701, "expert": 0.21267417073249817 }
3,609
write a mql5 code to show support and resistance on chart
c48d9305b223893de627b186e45daaf4
{ "intermediate": 0.4473874866962433, "beginner": 0.1823560893535614, "expert": 0.3702564239501953 }
3,610
من هذا الكود class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, "KaraokeApp") ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse("https://directsendwhats.xyz/background_music.mp3")) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = "${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp" mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } } كيف يتم تحسين جودة الصوت بعد التسجيل وكيفية اضافة ازرار تاثيرات ععلي الصوت
96479fee9280df7f8249be2ce976c803
{ "intermediate": 0.2726549208164215, "beginner": 0.618463933467865, "expert": 0.10888122767210007 }
3,611
من هذا الكود class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, "KaraokeApp") ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse("https://directsendwhats.xyz/background_music.mp3")) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = "${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp" mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } } كيف يتم تحسين جودة الصوت بعد التسجيل وكيفية اضافة ازرار تاثيرات علي الصوت مع كتابة الكود كاملا بعد الاضافات
931fd958761528fdc746e04da14583d0
{ "intermediate": 0.2726549208164215, "beginner": 0.618463933467865, "expert": 0.10888122767210007 }
3,612
in this p5.js code, when one draggable rectangle overlaps another, the one behind it will also drag behind the other. I don’t want them to do that. Please adjust it: let words = [ {id: 1, text: “was”}, {id: 2, text: “dog”}, {id: 3, text: “the”}, {id: 4, text: “here”}, {id: 5, text: “this”}, {id: 6, text: “morning”} ]; let boxX = 10; let boxY = 100; let boxWidth = 380; let boxHeight = 50; function setup() { createCanvas(400, 200); textAlign(CENTER, CENTER); textSize(18); // Scatter words randomly on the canvas for (let word of words) { word.x = random(10, width - 110); word.y = random(50, height - 50); word.draggable = null; } } function draw() { background(220); // Draw the box fill(255); rect(boxX, boxY, boxWidth, boxHeight); for (let word of words) { if (word.draggable) { word.x = mouseX; word.y = mouseY; } fill(255); rect(word.x - 10, word.y - 10, textWidth(word.text) + 20, 30); fill(0); text(word.text, word.x + textWidth(word.text) / 2, word.y); } } function mousePressed() { for (let word of words) { let wordWidth = textWidth(word.text); if (mouseX > word.x - 10 && mouseX < word.x + wordWidth + 10 && mouseY > word.y - 10 && mouseY < word.y + 20) { word.draggable = true; } } } function mouseReleased() { for (let word of words) { word.draggable = false; } } function mouseClicked() { let correctOrder = [3, 2, 1, 4, 5, 6]; let wordPositions = words .filter(word => word.y > boxY && word.y < boxY + boxHeight) .sort((a, b) => a.x - b.x) .map(word => word.id); if (wordPositions.toString() == correctOrder.toString()) { alert(“Congratulations! The sentence is correct!”); } }
dd9396bed9ec9211108b0bb4ea22bb46
{ "intermediate": 0.5052953362464905, "beginner": 0.19150863587856293, "expert": 0.30319610238075256 }
3,613
write a mql5 code that a neuron get ichimokou and rsi data to show possible targets
0bb63d95c7e7b44c2030d3d126032e70
{ "intermediate": 0.2537601888179779, "beginner": 0.050797224044799805, "expert": 0.6954426169395447 }