row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
22,203
Write a flutter code to login page
d14d3c27f6e3d47e9de07437228c4f5f
{ "intermediate": 0.3350977301597595, "beginner": 0.24950909614562988, "expert": 0.4153931736946106 }
22,204
how to make glua function that will search for entities "gmod_nail" in owner eye hitpos in radius 15
fa15ed194cc4a604585e45451ffabfac
{ "intermediate": 0.32154831290245056, "beginner": 0.12112554162740707, "expert": 0.5573261380195618 }
22,205
make a C program to send a udp packet
55881cc7c7b7e825b0b1b8414fbdcd16
{ "intermediate": 0.2625855803489685, "beginner": 0.433833509683609, "expert": 0.3035809397697449 }
22,206
from surprise import KNNWithMeans, KNNBasic from surprise import Dataset from surprise import accuracy from surprise import Reader from surprise.model_selection import train_test_split import pandas as pd dataset = pd.DataFrame({ 'uid': movies_with_ratings.userId, 'iid': movies_with_ratings.title, 'rating': movies_with_ratings.rating }) reader = Reader(rating_scale=(0.5, 5.0)) data = Dataset.load_from_df(dataset, reader) trainset, testset = train_test_split(data, test_size=0.2, random_state=1) algo = KNNWithMeans(k=50, sim_options={ 'name': 'cosine', 'user_based': True # compute similarities between users }) algo.fit(trainset) Как исправить с помощью sim_options = { 'k': [10,15, 20, 25,30], "name": ["msd", "cosine"], "min_support": [2, 3], "user_based": [False, True], } Как использовать этот код с GridSearchCV( ) param_grid = {"sim_options": sim_options, "n_epochs": [15], "lr_all": [0.002, 0.005], "reg_all": [0.2, 0.4] } gs = GridSearchCV( ?
1de37d8a6987cceed2b38a412a7372fa
{ "intermediate": 0.3935333788394928, "beginner": 0.17560230195522308, "expert": 0.43086424469947815 }
22,207
Write a python script to download all youtube videos from a channel
d1d624d4fe4511fd93bc0a622730358c
{ "intermediate": 0.30775317549705505, "beginner": 0.2248111069202423, "expert": 0.46743571758270264 }
22,208
Code up the jigsaw SSL for the downstream task of image classification on CIFAR 10.
56a27958cae41ad899a8e60fb0610da9
{ "intermediate": 0.29055631160736084, "beginner": 0.10413587838411331, "expert": 0.6053078174591064 }
22,209
How to use LanguageAnalyzer without the stop words
afd525bd971da10362bc3ee84d05ef77
{ "intermediate": 0.23204955458641052, "beginner": 0.4851904511451721, "expert": 0.2827599346637726 }
22,210
vgh xv
990d0a5154f80e744985cf20dda54631
{ "intermediate": 0.3234238624572754, "beginner": 0.31753137707710266, "expert": 0.35904479026794434 }
22,211
I used this code : depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = buy_price executed_orders = order_price == mark_price for buy_price, buy_qty in bid_depth: if buy_price == mark_price: order = buy_qty executed_orders_qty = order # Subtract executed order quantity from buy_qty buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 result = buy_qty - executed_orders_qty buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 print(f"{result} |{buy_qty}") But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 187, in <module> signals = signal_generator(df) ^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 115, in signal_generator buy_result = buy_qty - executed_orders_buy ^^^^^^^ UnboundLocalError: cannot access local variable 'executed_orders_buy' where it is not associated with a value
381241fa494d1fa8397ff31f97e78c66
{ "intermediate": 0.39159682393074036, "beginner": 0.3626466691493988, "expert": 0.24575647711753845 }
22,212
how to test the following useeffect using react testing library useEffect(() => { if (gridData && gridData.length > 0) { setLoading(false); } }, [ gridData ]); where gridData is const [ gridData, setGridData ] = useState<Pogrid[]>([]); and Pogrid export interface Pogrid { id: number, crushrate: number, uptime: number, totalproduction: number, beanprotein: number, beanmoisture: number, beanfat: number, mealprofit: number, oilprofit: number, hullprofit: number, line: number, reqid: string, mealprotein: number, mealmoisture: number, mealfiber: number, profitperperiod: number, oilyield: number, mealyield: number, powercost: number, heatcost: number, seedcost: number, lastupdate: Date, timestamp: Date, heatprimary: number, profitperday: number, powerprimary: number, wmf: number, grossmargin: number, allowances: number }
90c9d5d200e77cc8c13eab45cab0de14
{ "intermediate": 0.7979580163955688, "beginner": 0.1456158608198166, "expert": 0.05642617493867874 }
22,213
M = 10; %子脉冲数 dfs = 7e6; %脉内跳频间隔 Bs = 5e6; %子脉冲带宽 tp = 4e-6; %子脉冲脉宽 k = Bs/tp; %调频率 fs = 80e6; %采样率 Ts=1/fs; %采样间隔 N = 1; %脉冲数 f0 = 14e9; %信号载频 df = 80e6; %脉间跳频间隔 Tr = 100e-6; %脉冲重复间隔 c = 3e8; lambda = c/f0; %目标参数 Targetnum = 1; Trange =10e3; Tvelocity = 400; %干扰参数 Jrange =10e3-600; Jvelocity = 400; JSR = 20; %信干比 %% 发射信号仿真 N1 = round(tp/Ts); %一个子脉冲对应的采样点 N2 = round(Tr/Ts); %脉冲重复间隔对应的采样点 sr=[]; sr_echo=[]; a = randperm(100)-1; %脉间编码,0~63随机排序 for m = 1 : N b = randperm(M)-1;%脉内编码,0~3随机排序 % b=[1,0,2,3]; for i = 1 : M t1 =((i-1)*N1:N1-1+(i-1)*N1)*Ts; %t=(0:N1-1)*Ts; xt = exp(1i*pi*k*(t1-(i-1)*tp).^2).*exp(1i*2*pi*b(i)*dfs*t1); % .*exp(1i*2*pi*(f0+a(m)*df)*(t1+(m-1)*Tr)); % xt = cos(pi*k*t1.^2).*cos(2*pi*b(i)*dfs*t1).*cos(2*pi*(f0+a(m)*df)*(t1+(m-1)*Tr)); NR = round((2*Trange/c)/Ts); sr_echo(:,NR+(i-1)*N1:NR+i*N1-1) = xt; sr = [sr xt]; end sr = [sr zeros(1,2*N2-N1)]; sr_echo= [sr_echo zeros(1,2*N2-length(sr_echo))]; end figure;plot(real(sr));title("发射信号"); hold on;plot(imag(sr)) figure;plot(real(sr));title("发射信号实部"); figure;plot(imag(sr));title("发射信号虚部"); figure;plot(real(sr_echo));title("无干扰回波信号"); hold on;plot(imag(sr_echo)) figure;plot(real(sr_echo));title("无干扰回波信号实部"); figure;plot(imag(sr_echo));title("无干扰回波信号虚部"); %% 回波信号 % % % 回波时频图 window = N1/2; [s,f,t] = stft(sr_echo,fs,'Window',hamming(window),'OverlapLength',window-1,'FFTLength',2048); %[s,f,t] = spectrogram(sr,hamming(window),window-1,2048,fs); figure;imagesc(t*1e6,f*1e-6,abs(s)); xlabel("t/us");ylabel("f/MHz"); title("无干扰无噪声时频图",'FontSize',12,'FontWeight','bold'); set(gca,'YDir','normal');xlim([40,120]); set(gca,'Fontsize',12);set(gca,'FontWeight','bold');这个matlab代码显示出的时间频率图有负分量,我该怎么设置让他的值均为正
68a3673e8c8aea4e3d47bcc82a13ec8a
{ "intermediate": 0.25682467222213745, "beginner": 0.4411121904850006, "expert": 0.3020630478858948 }
22,214
hi
76e25c03e67dd348967f21bb76b75c54
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
22,215
In Python, how can we create a local server? Local host host flask None of the above
3cc5f5bf72502cfb2163ebfde102e5ef
{ "intermediate": 0.4133565425872803, "beginner": 0.3531554341316223, "expert": 0.2334880381822586 }
22,216
hello
485d14017fe2854f3ee3df0eb03cb176
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
22,217
write a go code to store LUKS headers in a basic http server for backup
5095dfeedb43fbf7235e2cd9f0649cc5
{ "intermediate": 0.4379972517490387, "beginner": 0.1919317990541458, "expert": 0.3700709640979767 }
22,218
write a go code to send LUKS headers to a basic http server for backup
30fe4b25a298bc1693663bfd3536dffd
{ "intermediate": 0.3862476348876953, "beginner": 0.1959802210330963, "expert": 0.41777217388153076 }
22,219
write python code to shutdown pc and wipe memory if mouse click is detected to prevent unautohrized access
c642b56cca23aab006bb7d5cbf420d4f
{ "intermediate": 0.43263837695121765, "beginner": 0.16288483142852783, "expert": 0.4044767916202545 }
22,220
use secrets instead of random in this code: import os import platform import sys import random from threading import Thread from pynput.mouse import Listener from pynput.keyboard import Listener as KeyboardListener # Path to the file to be executed upon shutdown (optional) shutdown_file = “path_to_shutdown_file.sh" # Password for preventing shutdown password = “password123" # Global variable to track password entry entered_password = “" def overwrite_memory(): # Get the size of the system memory total_memory = os.sysconf(‘SC_PAGE_SIZE’) * os.sysconf(‘SC_PHYS_PAGES’) # Generate random data to fill memory random_data = bytearray(random.getrandbits(8) for _ in range(total_memory)) # Overwrite memory for i in range(0, total_memory, 4096): sys.byteorder = ‘little’ data = bytes(random_data[i:i+4096]) ctypes.memmove(i, data, 4096) sys.byteorder = ‘big’ def on_press(key): global entered_password try: # Add key to entered_password string entered_password += key.char except AttributeError: pass def on_release(key): global entered_password if key == Key.enter: # Check if entered password is correct if entered_password == password: print(“Correct password entered. Shutdown preventing and script closing.") # Stop listening for keyboard inputs return False else: print(“Incorrect password entered.") entered_password = “" def on_click(x, y, button, pressed): global entered_password if pressed: # Wipe memory here by overwriting sensitive data overwrite_memory() # Shut down the PC based on the detected OS os_name = platform.system() if os_name == “Windows": os.system(“shutdown /s /t 0") elif os_name == “Darwin" or os_name == “Linux": os.system(“shutdown now") # Run a script or file before shutting down (optional) if shutdown_file: os.system(shutdown_file) # Stop listening for mouse clicks return False def listen_for_mouse_click(): with Listener(on_click=on_click) as listener: listener.join() def listen_for_keyboard_input(): with KeyboardListener(on_press=on_press, on_release=on_release) as listener: listener.join() if name == “main": # Start listening for mouse clicks in a separate thread mouse_listener_thread = Thread(target=listen_for_mouse_click) mouse_listener_thread.start() # Start listening for keyboard input in a separate thread keyboard_listener_thread = Thread(target=listen_for_keyboard_input) keyboard_listener_thread.start() # Your main code can continue running here print(“Listening for mouse clicks and keyboard input…") # Join the mouse listener thread and keyboard listener thread to the main thread mouse_listener_thread.join() keyboard_listener_thread.join() # Once the mouse click or correct password is detected, the code will continue execution here print(“Shutdown prevented or correct password entered. Script closing.")
2854d885f4b7148958a377be0ef06b72
{ "intermediate": 0.3118528723716736, "beginner": 0.4678106904029846, "expert": 0.22033639252185822 }
22,221
improve this emergency shutdown code: import os import platform import sys import secrets from threading import Thread, Event from pynput.mouse import Listener from pynput.keyboard import Listener as KeyboardListener, Key # Path to the file to be executed upon shutdown (optional) shutdown_file = "path_to_shutdown_file.sh" # Password for preventing shutdown password = "password123" # Global variable to track password entry entered_password = "" # Event to signal shutdown prevention shutdown_prevented = Event() def overwrite_memory(): # Get the size of the system memory total_memory = os.sysconf(‘SC_PAGE_SIZE’) * os.sysconf(‘SC_PHYS_PAGES’) # Generate random data to fill memory random_data = secrets.token_bytes(total_memory) # Overwrite memory with open(‘/dev/mem’, ‘wb’) as mem: for i in range(0, total_memory, 4096): data = bytes(random_data[i:i+4096]) mem.seek(i) mem.write(data) def on_press(key): global entered_password try: # Add key to entered_password string entered_password += key.char except AttributeError: pass def on_release(key): global entered_password if key == Key.enter: # Check if entered password is correct if entered_password == password: print("Correct password entered. Shutdown preventing and script closing.") # Signal shutdown prevention shutdown_prevented.set() else: print("Incorrect password entered.") entered_password = "" def on_click(x, y, button, pressed): if pressed: # Wipe memory here by overwriting sensitive data overwrite_memory() # Shut down the PC based on the detected OS os_name = platform.system() if os_name == "Windows": os.system("shutdown /s /t 0") elif os_name == "Darwin" or os_name == "Linux": os.system("shutdown -h now") # Run a script or file before shutting down (optional) if shutdown_file: os.system(shutdown_file) # Signal shutdown prevention shutdown_prevented.set() def listen_for_mouse_click(): with Listener(on_click=on_click) as listener: listener.join() def listen_for_keyboard_input(): with KeyboardListener(on_press=on_press, on_release=on_release) as listener: listener.join() if name == "main": # Start listening for mouse clicks in a separate thread mouse_listener_thread = Thread(target=listen_for_mouse_click) mouse_listener_thread.start() # Start listening for keyboard input in a separate thread keyboard_listener_thread = Thread(target=listen_for_keyboard_input) keyboard_listener_thread.start() # Your main code can continue running here print("Listening for mouse clicks and keyboard input…") # Wait for shutdown prevention signal or keyboard interrupt (Ctrl+C) try: shutdown_prevented.wait() except KeyboardInterrupt: pass # Join the mouse listener thread and keyboard listener thread to the main thread mouse_listener_thread.join() keyboard_listener_thread.join() # Once the shutdown prevention signal is received or keyboard interrupt occurs, # the code will continue execution here print("Shutdown prevented or correct password entered. Script closing.")
bf59eb372300badf2d8298c87a860e69
{ "intermediate": 0.3461364209651947, "beginner": 0.43076688051223755, "expert": 0.22309674322605133 }
22,222
improve this code: import os import platform import sys import secrets from threading import Thread, Event from pynput.mouse import Listener from pynput.keyboard import Listener as KeyboardListener, Key # Path to the file to be executed upon shutdown (optional) shutdown_file = "path_to_shutdown_file.sh" # Password for preventing shutdown password = "password123" # Global variable to track password entry entered_password = "" # Event to signal shutdown prevention shutdown_prevented = Event() def overwrite_memory(): # Get the size of the system memory total_memory = os.sysconf(‘SC_PAGE_SIZE’) * os.sysconf(‘SC_PHYS_PAGES’) # Generate random data to fill memory random_data = secrets.token_bytes(total_memory) # Overwrite memory with open(‘/dev/mem’, ‘wb’) as mem: for i in range(0, total_memory, 4096): data = bytes(random_data[i:i+4096]) mem.seek(i) mem.write(data) def on_press(key): global entered_password try: # Add key to entered_password string entered_password += key.char except AttributeError: pass def on_release(key): global entered_password if key == Key.enter: # Check if entered password is correct if entered_password == password: print("Correct password entered. Shutdown preventing and script closing.") # Signal shutdown prevention shutdown_prevented.set() else: print("Incorrect password entered.") entered_password = "" def on_click(x, y, button, pressed): if pressed: # Wipe memory here by overwriting sensitive data overwrite_memory() # Shut down the PC based on the detected OS os_name = platform.system() if os_name == "Windows": os.system("shutdown /s /t 0") elif os_name == "Darwin" or os_name == "Linux": os.system("shutdown -h now") # Run a script or file before shutting down (optional) if shutdown_file: os.system(shutdown_file) # Signal shutdown prevention shutdown_prevented.set() def listen_for_mouse_click(): with Listener(on_click=on_click) as listener: listener.join() def listen_for_keyboard_input(): with KeyboardListener(on_press=on_press, on_release=on_release) as listener: listener.join() if name == "main": # Start listening for mouse clicks in a separate thread mouse_listener_thread = Thread(target=listen_for_mouse_click) mouse_listener_thread.start() # Start listening for keyboard input in a separate thread keyboard_listener_thread = Thread(target=listen_for_keyboard_input) keyboard_listener_thread.start() # Your main code can continue running here print("Listening for mouse clicks and keyboard input…") # Wait for shutdown prevention signal or keyboard interrupt (Ctrl+C) try: shutdown_prevented.wait() except KeyboardInterrupt: pass # Join the mouse listener thread and keyboard listener thread to the main thread mouse_listener_thread.join() keyboard_listener_thread.join() # Once the shutdown prevention signal is received or keyboard interrupt occurs, # the code will continue execution here print("Shutdown prevented or correct password entered. Script closing.")
0d43bd1f9584f9c433a9a9d3fc21731f
{ "intermediate": 0.3347923755645752, "beginner": 0.45008978247642517, "expert": 0.21511781215667725 }
22,223
function hcyl(bottom, height, radius, id) { let radsq = radius * radius let innerRadsq = (radius - 1.2) * (radius - 1.2) height += bottom for (let x = -radius; x <= radius; x++) { for (let y = bottom; y < height; y++) { for (let z = -radius; z <= radius; z++) { let d = x * x + z * z if (d < radsq && d >= innerRadsq) { world.setBlock(p2.x + x, p2.y + y, p2.z + z, id) } } } } } function cyl(bottom, height, radius, id) { let radsq = radius * radius height += bottom for (let x = -radius; x <= radius; x++) { for (let y = bottom; y < height; y++) { for (let z = -radius; z <= radius; z++) { let d = x * x + z * z if (d < radsq) { world.setBlock(p2.x + x, p2.y + y, p2.z + z, id) } } } } } function cube(bottom, height, radius, id) { let radsq = radius * radius height += bottom for (let x = -radius; x <= radius; x++) { for (let y = bottom; y < height; y++) { for (let z = -radius; z <= radius; z++) { let d = x + z if (d < radsq) { world.setBlock(p2.x + x, p2.y + y, p2.z + z, id) } } } } } function sphereoid(w, h, d, id) { let w2 = w * w let h2 = h * h let d2 = d * d let w3 = (w - 1.5) * (w - 1.5) let h3 = (h - 1.5) * (h - 1.5) let d3 = (d - 1.5) * (d - 1.5) for (let y = -h; y < h; y++) { for (let x = -w; x <= w; x++) { for (let z = -d; z <= d; z++) { let n = x * x / w2 + y * y / h2 + z * z / d2 let n2 = x * x / w3 + y * y / h3 + z * z / d3 if (n < 1 && n2 >= 1) { world.setBlock(p2.x + x, p2.y + y, p2.z + z, id) } } } } } function sleep(ms) { return new Promise(resolve => setTimeout(() => resolve(), ms)) } async function asphereoid(w, h, d, id) { let px = p2.x let py = p2.y let pz = p2.z let w2 = w * w let h2 = h * h let d2 = d * d let w3 = (w - 1.5) * (w - 1.5) let h3 = (h - 1.5) * (h - 1.5) let d3 = (d - 1.5) * (d - 1.5) for (let y = -h; y < h; y++) { for (let x = -w; x <= w; x++) { for (let z = -d; z <= d; z++) { let n = x * x / w2 + y * y / h2 + z * z / d2 let n2 = x * x / w3 + y * y / h3 + z * z / d3 if (n < 1 && n2 >= 1) { world.setBlock(px + x, py + y, pz + z, id) await sleep(10) } } } } } function line(x1, y1, z1, x2, y2, z2, id) { let dx = Math.abs(x2 - x1); let dy = Math.abs(y2 - y1); let dz = Math.abs(z2 - z1); let sx = (x1 < x2) ? 1 : -1; let sy = (y1 < y2) ? 1 : -1; let sz = (z1 < z2) ? 1 : -1; let err1 = dx - dy; let err2 = dx - dz; let err3 = dy - dz; while (true) { world.setBlock(x1, y1, z1, id); if (x1 === x2 && y1 === y2 && z1 === z2) break; let e2 = 2 * err1; let e3 = 2 * err2; let e4 = 2 * err3; if (e2 > -dy) { err1 -= dy; err2 -= dz; x1 += sx; } if (e2 < dx) { err1 += dx; err3 -= dz; y1 += sy; } if (e3 > -dz) { err2 += dy; err3 += dx; z1 += sz; } } } function cloneBlock(sx, sy, sz, dx, dy, dz, w, h, l) { for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { let block = world.getBlock(sx + x, sy + y, sz + z); world.setBlock(dx + x, dy + y, dz + z, block); } } } } function duplicateBlock(sx, sy, sz, dx, dy, dz, w, h, l, offsetX, offsetY, offsetZ, num) { for (let i = 0; i < num; i++) { cloneBlock(sx, sy, sz, dx + offsetX * i, dy + offsetY * i, dz + offsetZ * i, w, h, l); } } function rotateBlock(sx, sy, sz, dx, dy, dz, w, h, l, angle) { let rad = angle * (Math.PI / 180); let sin = Math.sin(rad); let cos = Math.cos(rad); for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { let nx = Math.round(x * cos - z * sin); let nz = Math.round(x * sin + z * cos); let block = world.getBlock(sx + x, sy + y, sz + z); world.setBlock(dx + nx, dy + y, dz + nz, block); } } } } function fillBlock(sx, sy, sz, dx, dy, dz, id) { let w = Math.abs(dx - sx) + 1; let h = Math.abs(dy - sy) + 1; let l = Math.abs(dz - sz) + 1; let startX = Math.min(sx, dx); let startY = Math.min(sy, dy); let startZ = Math.min(sz, dz); for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { world.setBlock(startX + x, startY + y, startZ + z, id); } } } } function moveBlock(sx, sy, sz, dx, dy, dz, w, h, l) { cloneBlock(sx, sy, sz, dx, dy, dz, w, h, l); fillBlock(sx, sy, sz, sx + w - 1, sy + h - 1, sz + l - 1, 0); } function paintBlock(sx, sy, sz, dx, dy, dz, w, h, l, colorId) { cloneBlock(sx, sy, sz, dx, dy, dz, w, h, l); for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { world.setBlock(dx + x, dy + y, dz + z, colorId); } } } } function replaceBlock(sx, sy, sz, dx, dy, dz, id, newId) { let w = Math.abs(dx - sx) + 1; let h = Math.abs(dy - sy) + 1; let l = Math.abs(dz - sz) + 1; let startX = Math.min(sx, dx); let startY = Math.min(sy, dy); let startZ = Math.min(sz, dz); for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { if (world.getBlock(startX + x, startY + y, startZ + z) === id) { world.setBlock(startX + x, startY + y, startZ + z, newId); } } } } } function mirrorBlock(sx, sy, sz, dx, dy, dz, w, h, l, axis) { if (axis === "x") { for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { let block = world.getBlock(sx + x, sy + y, sz + z); world.setBlock(dx + w - x - 1, dy + y, dz + z, block); } } } } else if (axis === "y") { for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { let block = world.getBlock(sx + x, sy + y, sz + z); world.setBlock(dx + x, dy + h - y - 1, dz + z, block); } } } } else if (axis === "z") { for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) { for (let z = 0; z < l; z++) { let block = world.getBlock(sx + x, sy + y, sz + z); world.setBlock(dx + x, dy + y, dz + l - z - 1, block); } } } } } function pathBlock(sx, sy, sz, dx, dy, dz, id, weight) {
defe2a599d10ebc8a58b65dbf594be56
{ "intermediate": 0.2089826762676239, "beginner": 0.5734841227531433, "expert": 0.2175331860780716 }
22,224
create a python script using datadog-client-api to push python logs and create eventattributes from the logs. please give me an example like you are talking to a 5 year old. Please datadog-client-api python library - https://pypi.org/project/datadog-api-client/
91aeb5d11c2127a47ea5c9590f0fbd65
{ "intermediate": 0.8930909633636475, "beginner": 0.0487179309129715, "expert": 0.058191098272800446 }
22,225
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct BstNode { int data; struct BstNode* lchild; struct BstNode* rchild; } BstNode; BstNode* root = NULL; BstNode* GetNewNode(int data) { BstNode* newNode = (BstNode*)malloc(sizeof(BstNode)); newNode->data = data; newNode->lchild = NULL; newNode->rchild = NULL; return newNode; } BstNode* Insert(BstNode* root, int data) { if (root == NULL) { root = GetNewNode(data); } else if (data <= root->data) { root->lchild = Insert(root->lchild, data); } else { root->rchild = Insert(root->rchild, data); } return root; } int max(int a, int b) { return (a > b) ? a : b; } int FindHeight(BstNode* root) { if (root == NULL) { return -1; } else { int leftHeight = FindHeight(root->lchild); int rightHeight = FindHeight(root->rchild); return max(leftHeight, rightHeight) + 1; } } typedef struct QNode { BstNode* data; struct QNode* next; } QNode; typedef struct { QNode* front; QNode* rear; int n; } BiTQueue; BiTQueue* InitQueue() { BiTQueue* newqueue = (BiTQueue*)malloc(sizeof(BiTQueue)); newqueue->front = NULL; newqueue->rear = NULL; newqueue->n = 0; return newqueue; } void Push(BiTQueue* Q, BstNode* T) { QNode* node = (QNode*)malloc(sizeof(QNode)); node->data = T; node->next = NULL; if (Q->rear == NULL) { Q->front = node; Q->rear = node; } else { Q->rear->next = node; Q->rear = node; } Q->n++; } BstNode* Pop(BiTQueue* Q) { if (Q->front == NULL) { return NULL; } BstNode* T = Q->front->data; QNode* temp = Q->front; if (Q->front == Q->rear) { Q->front = NULL; Q->rear = NULL; } else { Q->front = Q->front->next; } Q->n--; free(temp); return T; } void LeveOrderTraverse(BstNode* T, int level) { if (T == NULL) { return; } BiTQueue* Q = InitQueue(); BstNode* p = NULL; int currentLevel = 0; Push(Q, T); while (Q->n > 0) { int nodesAtCurrentLevel = Q->n; while (nodesAtCurrentLevel > 0) { p = Pop(Q); if (currentLevel == level) { printf("%d,", p->data); } if (p->lchild != NULL) { Push(Q, p->lchild); } if (p->rchild != NULL) { Push(Q, p->rchild); } nodesAtCurrentLevel--; } currentLevel++; if (currentLevel > level) { break; } } } int main() { int cnt,level,a; scanf("%d",&cnt); for (int i=0;i<cnt;i++){ scanf("%d",&a); root=Insert(root,a); getchar(); } scanf("%d",&level); LeveOrderTraverse(root,level); return 0; }
2b2b7b136b16943561d87d1db964aa2d
{ "intermediate": 0.31049296259880066, "beginner": 0.3847227096557617, "expert": 0.3047843277454376 }
22,226
voici la fonction à tester : "function withdraw(uint256 _gameId, address _currentPlayer, uint256 _amount) public payable { require(_currentPlayer == games[_gameId].player1 || _currentPlayer == games[_gameId].player2, "You re not a player"); require(!(_currentPlayer == games[_gameId].player1 && games[_gameId].player1HasWithdrawn) && !(_currentPlayer == games[_gameId].player2 && games[_gameId].player2HasWithdrawn), "withdrawn balance"); uint256 balance = playerBalances[_gameId][_currentPlayer].balance; require(balance >= _amount, "Insufficient balance"); if (_currentPlayer == winner){ playerBalances[_gameId][_currentPlayer].balance = balance - _amount; (bool success, ) = payable(_currentPlayer).call{value: _amount}(""); require(success, "The withdrawal failed"); } if (_currentPlayer == games[_gameId].player1) { games[_gameId].player1HasWithdrawn = true; } else { games[_gameId].player2HasWithdrawn = true; } emit Withdraw(_gameId); }" voici le test " context ("FONCTION POUR LE RETRAIT - PERDANT", () => { before(async function() { penduelInstance = await Penduel.new(subId); const letterToGuess = "i"; const wordToGuess = "instable"; const value = web3.utils.toWei("1", "ether"); await penduelInstance.createGame({ from: player1 }); await penduelInstance.joinGame({ from: player2 }); await penduelInstance.deposit({ from: player1, value: value }); await penduelInstance.deposit({ from: player2, value: value }); await penduelInstance.updateStateFirstLetter(); const gameId = 1; await penduelInstance.proposeLetter(gameId, letterToGuess, wordToGuess, {from: player2}); const currentPlayer = player2; await penduelInstance.proposeWord(gameId, "instable", currentPlayer); await penduelInstance.playersSwitched(gameId, { from: currentPlayer }); }); describe ("Vérifie la fonction withdraw avec le perdant", () => { it("ne devrait pas permettre à un joueur non gagnant de retirer", async () => { const gameId = 1; const newActivePlayer = await penduelInstance.getActivePlayer(gameId); assert.equal(newActivePlayer, player1, "Le nouveau joueur actif devrait être player1"); const letterToGuess = "i"; const wordToGuess = "inerte"; await penduelInstance.updateStateFirstLetter(); await penduelInstance.proposeLetter(gameId, letterToGuess, wordToGuess, {from: player1}); const initialGameState = await penduelInstance.state(); assert.equal(initialGameState, 5, "L'état initial devrait être inProgress"); const currentPlayer = player1; await penduelInstance.proposeWord(gameId, wordToGuess, currentPlayer); const initialBalance = await penduelInstance.getBalance({from: currentPlayer}); const amount = 2; const receipt = await penduelInstance.withdraw(gameId, currentPlayer, amount, { from: currentPlayer }); const finalBalance = await penduelInstance.getBalance({from: currentPlayer}); assert.equal(finalBalance, initialBalance, "Le solde du joueur non gagnant ne devrait pas changer"); const withdrawalEvents = await penduelInstance.getPastEvents("Withdraw", { fromBlock: receipt.receipt.blockNumber, toBlock: "latest" }); assert.equal(withdrawalEvents.length, 0, "Aucun événement Withdraw ne devrait être émis"); }); });" il y a t-il une erreur dans le test " context ("FONCTION POUR LE RETRAIT - PERDANT", () => { before(async function() { penduelInstance = await Penduel.new(subId); const letterToGuess = "i"; const wordToGuess = "instable"; const value = web3.utils.toWei("1", "ether"); await penduelInstance.createGame({ from: player1 }); await penduelInstance.joinGame({ from: player2 }); await penduelInstance.deposit({ from: player1, value: value }); await penduelInstance.deposit({ from: player2, value: value }); await penduelInstance.updateStateFirstLetter(); const gameId = 1; await penduelInstance.proposeLetter(gameId, letterToGuess, wordToGuess, {from: player2}); const currentPlayer = player2; await penduelInstance.proposeWord(gameId, "instable", currentPlayer); await penduelInstance.playersSwitched(gameId, { from: currentPlayer }); }); describe ("Vérifie la fonction withdraw avec le perdant", () => { it("ne devrait pas permettre à un joueur non gagnant de retirer", async () => { const gameId = 1; const newActivePlayer = await penduelInstance.getActivePlayer(gameId); assert.equal(newActivePlayer, player1, "Le nouveau joueur actif devrait être player1"); const letterToGuess = "i"; const wordToGuess = "inerte"; await penduelInstance.updateStateFirstLetter(); await penduelInstance.proposeLetter(gameId, letterToGuess, wordToGuess, {from: player1}); const initialGameState = await penduelInstance.state(); assert.equal(initialGameState, 5, "L'état initial devrait être inProgress"); const currentPlayer = player1; await penduelInstance.proposeWord(gameId, wordToGuess, currentPlayer); const initialBalance = await penduelInstance.getBalance({from: currentPlayer}); const amount = 2; const receipt = await penduelInstance.withdraw(gameId, currentPlayer, amount, { from: currentPlayer }); const finalBalance = await penduelInstance.getBalance({from: currentPlayer}); assert.equal(finalBalance, initialBalance, "Le solde du joueur non gagnant ne devrait pas changer"); const withdrawalEvents = await penduelInstance.getPastEvents("Withdraw", { fromBlock: receipt.receipt.blockNumber, toBlock: "latest" }); assert.equal(withdrawalEvents.length, 0, "Aucun événement Withdraw ne devrait être émis"); }); }); il y a t-il une erreur dans le test ?
31aa00348562caf55cbbd1b254b0dd01
{ "intermediate": 0.3865699768066406, "beginner": 0.4494614899158478, "expert": 0.16396859288215637 }
22,227
как правильно установить и настроить для приложения ruby on rails https://github.com/helloextend/salesforce-commerce-cloud
82eaa3fc50013f52b5d5c04fc6825962
{ "intermediate": 0.5020304918289185, "beginner": 0.30064114928245544, "expert": 0.1973283737897873 }
22,228
帮我写一段blender 运行脚本,建立1000个边长为100mm的立方体,按照10*10*10的方式排列,并且每个立方体都会运动
3781401705f1d95292166cb60871a7eb
{ "intermediate": 0.26051461696624756, "beginner": 0.323716402053833, "expert": 0.41576895117759705 }
22,229
I used this code: def signal_generator(df): if df is None or len(df) < 2: return '' signal = [] # Retrieve depth data threshold = 0.35 depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol) mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 # Calculate the threshold for order price deviation if mark_price_percent > 2: price_threshold = 5 / 100 elif mark_price_percent < -2: price_threshold = 5 / 100 else: price_threshold = 4 / 100 executed_orders_buy = 0.0 for buy_price, buy_qty in bid_depth: if buy_price == mark_price: order_buy = buy_qty executed_orders_buy = order_buy # Subtract executed order quantity from buy_qty buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 buy_result = buy_qty - executed_orders_buy buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 executed_orders_sell = 0.0 for sell_price, sell_qty in ask_depth: if sell_price == mark_price: order_sell = sell_qty executed_orders_sell = order_sell # Subtract executed order quantity from buy_qty buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_result = sell_qty - executed_orders_sell buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 if (sell_result > (1 + threshold) > float(buy_qty)) and (sell_price < mark_price - price_threshold): signal.append('sell') elif (buy_result > (1 + threshold) > float(sell_qty)) and (buy_price > mark_price + price_threshold): signal.append('buy') else: signal.append('') return signal But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 192, in <module> signals = signal_generator(df) ^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 134, in signal_generator sell_result = sell_qty - executed_orders_sell ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ TypeError: unsupported operand type(s) for -: 'str' and 'float'
53c05bbdcc1e5b8caf00253ed1e922da
{ "intermediate": 0.31045448780059814, "beginner": 0.41250553727149963, "expert": 0.2770399749279022 }
22,230
In imagemagick, I want to concatenate images as close to a square as possible and with a black gap between them.
43476a48dc03aacfb106235cf1ee0380
{ "intermediate": 0.40565720200538635, "beginner": 0.2878458797931671, "expert": 0.3064969480037689 }
22,231
using System.Collections.Generic; using System.Globalization; using UnityEngine; using System.Linq; using TMPro; public class CanvasKdTree : MonoBehaviour { [SerializeField] private Material circleMaterial; [SerializeField] private Transform quadPointPrefab; [SerializeField] private Transform circlePointPrefab; [SerializeField] private bool startWithStart; [SerializeField] private TextAsset dataFile; [SerializeField] private Color colorClass1; [SerializeField] private Color colorClass2; [SerializeField] private Color unKnownColor; [SerializeField] private List<Vector2> parsedPointsType1 = new List<Vector2>{}; [SerializeField] private List<Vector2> parsedPointsType2 = new List<Vector2>{}; [SerializeField] private List<Transform> pointsType1 = new List<Transform>(); [SerializeField] private List<Transform> pointsType2 = new List<Transform>(); [SerializeField] private bool useRangeForScheme; [SerializeField] private int rangeCreatorPointMinX; [SerializeField] private int rangeCreatorPointMaxX; [SerializeField] private int rangeCreatorPointMinY; [SerializeField] private int rangeCreatorPointMaxY; [SerializeField] [Range(000, 500)] private int coefficientMultiplier; [SerializeField] private bool useRandomUnKnownPoint; [SerializeField] private Vector2 unKnownPointPosition; [SerializeField] private Transform unKnownPointTransform; private void OnDrawGizmos() { } private void Start() { if (!startWithStart) { return; } ParseData(); MultiplyValues(); CreatePoints(); CalculatePointRanges(); CreateUnKnownPoint(); //DrawScheme(); } private void ParseData() { string[] lines = dataFile.text.Split('\n'); string[] xCoords = lines[1].Split(','); List<float> xValues = xCoords.Skip(1).Select(x => float.Parse(x, CultureInfo.InvariantCulture)).ToList(); string[] yCoords = lines[2].Split(','); List<float> yValues = yCoords.Skip(1).Select(y => float.Parse(y, CultureInfo.InvariantCulture)).ToList(); string[] pointTypes = lines[3].Split(','); List<int> typeValues = pointTypes.Skip(1).Select(pointType => int.Parse(pointType, NumberStyles.Float, CultureInfo.InvariantCulture)).ToList(); for (int i = 0; i < xValues.Count; i++) { Vector2 point = new Vector2(xValues[i], yValues[i]); int pointType = typeValues[i]; switch (pointType) { case 0: parsedPointsType1.Add(point); break; case 1: parsedPointsType2.Add(point); break; case 2: if ((i % 2) == 0) { parsedPointsType1.Add(point); } else { parsedPointsType2.Add(point); } break; default: Debug.LogError("Unsupported point type: " + pointType); break; } } } private void MultiplyValues() { List<List<Vector2>> all = new List<List<Vector2>>() {parsedPointsType1, parsedPointsType2}; for (int i = 0; i < all.Count; i++) { for (int j = 0; j < all[i].Count; j++) { Vector2 originalValue = all[i][j]; Vector2 multipliedValue = originalValue * coefficientMultiplier; all[i][j] = multipliedValue; } } } private void CreatePoints() { pointsType1 = PointCreator(parsedPointsType1, colorClass1).ToList(); pointsType2 = PointCreator(parsedPointsType2, colorClass2).ToList(); } private void CalculatePointRanges() { if (!useRangeForScheme) { return; } if (parsedPointsType1.Count > 0 && parsedPointsType2.Count > 0) { float minX = float.MaxValue; float maxX = float.MinValue; float minY = float.MaxValue; float maxY = float.MinValue; foreach (Vector2 point in parsedPointsType1) { minX = Mathf.Min(minX, point.x); maxX = Mathf.Max(maxX, point.x); minY = Mathf.Min(minY, point.y); maxY = Mathf.Max(maxY, point.y); } foreach (Vector2 point in parsedPointsType2) { minX = Mathf.Min(minX, point.x); maxX = Mathf.Max(maxX, point.x); minY = Mathf.Min(minY, point.y); maxY = Mathf.Max(maxY, point.y); } rangeCreatorPointMinX = Mathf.FloorToInt(minX); rangeCreatorPointMaxX = Mathf.CeilToInt(maxX); rangeCreatorPointMinY = Mathf.FloorToInt(minY); rangeCreatorPointMaxY = Mathf.CeilToInt(maxY); } else { Debug.LogError("There are no points for calculating boundaries"); } } private void CreateUnKnownPoint() { if (useRandomUnKnownPoint) { unKnownPointPosition = new Vector2(Random.Range(rangeCreatorPointMinX, rangeCreatorPointMaxX), Random.Range(rangeCreatorPointMinY, rangeCreatorPointMaxY)); unKnownPointTransform = PointCreator(new List<Vector2>(1){unKnownPointPosition}, unKnownColor).First(); } else { unKnownPointTransform = PointCreator(new List<Vector2>(1){unKnownPointPosition}, unKnownColor).First(); } } private Transform[] PointCreator(List<Vector2> points, Color typeColor) { Transform[] transforms = new Transform[points.Count]; for (int i = 0; i < points.Count; i++) { Transform pointTr = Instantiate(circlePointPrefab, transform); pointTr.localPosition = new Vector3(points[i].x, points[i].y); transforms[i] = pointTr; pointTr.GetComponentInChildren<TextMeshProUGUI>().color = typeColor; Vector2 pointPos = pointTr.GetComponent<RectTransform>().anchoredPosition; pointTr.name = "Pont. Class1. " + " X: " + FormatNumber((int)pointPos.x, 3) + " Y: " + FormatNumber((int)pointPos.y, 3); } return transforms; } private static string FormatNumber(int number, int digits) { string format = "D" + digits.ToString(); return number.ToString(format); } } У меня есть вот такой код на C# для unity. Он уже правильно и корректно строит координаты. Напиши мне дополнительно методы, которые я вставлю себе в скрипт. Этот скрипт будет строить KD мерное дерево.
756e9cf8c9df582c4447b019f0a55616
{ "intermediate": 0.3239680528640747, "beginner": 0.44249945878982544, "expert": 0.23353250324726105 }
22,232
I used this code: depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = sell_price executed_orders = order_price == mark_price for sell_price, sell_qty in ask_depth: if sell_price == mark_price: order = sell_qty executed_orders_sell = order sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 sell_result = sell_qty - executed_orders_sell But I getting ERROR : Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 307, in <module> executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 ^^^^^^^^^^^^^^^^^^^^ NameError: name 'executed_orders_sell' is not defined. Did you mean: 'executed_orders_buy'?
8dc1332b541b8ce7a9832fcee828de26
{ "intermediate": 0.37075090408325195, "beginner": 0.36538875102996826, "expert": 0.2638602554798126 }
22,233
The Incident Response Team at Aurora Pharmaceuticals recently recovered this file from a user’s computer. The artifacts indicate it was accessed by what they believe to be multiple DEADFACE members. The program appears to have set up the user’s workstation as a dead drop for DEADFACE members to convert a secret numerical code into a password string for further target access. Our decoding attempts have been unsuccessful, but the script appears to contain a recovery code that may be a good starting point. Submit the flag as flag{the password} exactly how print_password() returns it. code: # Password recovery: # buA9kvZ=T_A}b[J8l:@ob_tviPZtb_<olOpxkvZ=T_=xju]olOpxkvZ=T_bxlu]olOpxkvZ=QIEE arr = ['empty', 'interest', 'current', 'valuable', 'influence', 'from', 'scolded', 'would', 'got', 'key', 'facility', 'run', 'great', 'tack', 'scent', 'close', 'are', 'a', 'plan', 'counter', 'earth', 'self', 'we', 'sick', 'return', 'admit', 'bear', 'cache', 'to', 'grab', 'domination', 'feedback', 'especially', 'motivate', 'tool', 'world', 'phase', 'semblance', 'tone', 'is', 'will', 'the', 'can', 'global', 'tell', 'box', 'alarm', 'life', 'necessary'] def print_password(nums): if len(nums) < 1: print("Must provide a list of at least one number i.e. [1]") print("flag{{{}}}".format(" ".join([arr[num] for num in nums]))) def left_shift(s, n): return ''.join(chr(ord(char) - n) for char in s) print_password(arr)
724b3bab9c882076d9c4dd46bd0ae34e
{ "intermediate": 0.24886201322078705, "beginner": 0.4214312434196472, "expert": 0.32970669865608215 }
22,234
I used your code: while True: if df is not None: quantity = bch_amount_rounded / 2 signals = signal_generator(df) mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 if signals == ['buy'] or signals == ['sell']: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}") if 'buy' in signals and active_signal != 'buy': try: active_signal = 'buy' buy_entry_price = mark_price # Record the Buy entry price print(f"Buy Entry Price: {buy_entry_price}") client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) print("Long order executed!") except binance.error.ClientError as e: print(f"Error executing long order: ") if sell_entry_price is not None and buy_entry_price is not None: sell_exit_price = mark_price difference_sell = calculate_percentage_difference_sell(sell_entry_price, sell_exit_price) profit_sell = difference_sell total_profit_sell = profit_sell profit_sell_percent = total_profit_sell - 4 print(f"sell entry price {sell_entry_price}, sell exit price {sell_exit_price} , Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%") else: print("Sell Entry price or Buy Entry price is not defined.") israel = [] depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = buy_price order = buy_price and buy_qty executed_orders = buy_price == mark_price for buy_price, buy_qty in bid_depth: if buy_price == mark_price: order = buy_qty executed_orders_buy = order buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 executed_orders_buy = float(executed_orders_buy) if executed_orders_buy else 0.0 buy_result = buy_qty - executed_orders_buy # Subtract executed order quantity from buy_qty buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 if (buy_result < 0.01 + sell_qty) and (sell_price < mark_price - 0.02): active_signal = None israel.append("Long !!! EXIT !!!") if buy_entry_price is not None and israel is not None: buy_exit_price = mark_price difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price) profit_buy = difference_buy total_profit_buy = profit_buy profit_buy_percent = total_profit_buy - 4 try: client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) except binance.error.ClientError as e: print(f"Long position successfully exited! ") print(" !!! EXIT !!! ") print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} buy entry price {buy_entry_price}, buy exit price: {mark_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%") buy_entry_price = None else: print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met else: israel.append('') elif 'sell' in signals and active_signal != 'sell': try: active_signal = 'sell' sell_entry_price = mark_price # Record the sell entry price print(f"Sell Entry Price: {sell_entry_price}") client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) print("Short order executed!") except binance.error.ClientError as e: print(f"Error executing short order: ") if buy_entry_price is not None and sell_entry_price is not None: buy_exit_price = mark_price difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price) profit_buy = difference_buy total_profit_buy = profit_buy profit_buy_percent = total_profit_buy - 4 print(f"buy entry price {buy_entry_price}, buy exit price: {sell_entry_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%") else: print("Buy Entry price or Sell Entry price is not defined.") jerusalem = [] depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = sell_price executed_orders = order_price == mark_price for sell_price, sell_qty in ask_depth: if sell_price == mark_price: order = sell_qty executed_orders_sell = order sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 sell_result = sell_qty - executed_orders_sell # Subtract executed order quantity from buy_qty sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 if (sell_result < buy_qty - 0.01) and (buy_price > mark_price + 0.02): active_signal = None jerusalem.append("Short !!! EXIT !!!") if sell_entry_price is not None and jerusalem is not None: sell_exit_price = mark_price difference_sell = calculate_percentage_difference_buy(sell_entry_price, sell_exit_price) profit_sell = difference_sell total_profit_sell = profit_sell profit_sell_percent = total_profit_sell - 4 try: client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) except binance.error.ClientError as e: print(f"Short position successfully exited!") print(" !!! EXIT !!! ") print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} sell entry price {sell_entry_price}, sell exit price: {mark_price}, Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%") sell_entry_price = None else: print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met else: jerusalem.append('') time.sleep(1) But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 307, in <module> executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 ^^^^^^^^^^^^^^^^^^^^ NameError: name 'executed_orders_sell' is not defined. Did you mean: 'executed_orders_buy'?
253ad539210d66a782d1a963858b86cd
{ "intermediate": 0.35497501492500305, "beginner": 0.49867257475852966, "expert": 0.14635241031646729 }
22,235
Tell me please how to install mysql 5.6 on manjaro linux
8ddf0c35e2ac2cfa1e13b76cb5d479b4
{ "intermediate": 0.5067940950393677, "beginner": 0.22017358243465424, "expert": 0.27303239703178406 }
22,236
void TreeLevelOrder(BiTree root){ Queue pq; QueueInit(&pq); if(root) QueuePush(&pq, root); while(!QueueEmpty(&pq)){ BiTree front=QueueFront(&pq); printf("%d ",front->data); if(front->lchild) QueuePush(&pq,front->lchild); if(front->rchild ) QueuePush(&pq,front->rchild ); QueuePop(&pq); } QueueDestory(&pq); }
d06b358f36444c4a3553df28b16e2e76
{ "intermediate": 0.3705824911594391, "beginner": 0.3937385380268097, "expert": 0.23567897081375122 }
22,237
#include<stdio.h> #include<stdlib.h> #define datatype int//二叉树数据的类型 typedef struct BiNode { datatype data;//数据域 struct BiNode* lchild;//左孩子 struct BiNode* rchild;//右孩子 }BiNode,*BiTree; void CreateBiTree(BiTree& T) { datatype value; scanf("%d", &value); if (value == '#') T = NULL; else { T = new BiNode; T->data = value; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } } void CreateBiTree_In_Post(BiTree& T, datatype* InStr, datatype* PostStr, int in1, int in2, int post1, int post2) { // 创建新的结点 T = (BiTree)malloc(sizeof(BiNode)); // 新结点数据为 后序序列 的第一个数据,即根节点数据 T->data = PostStr[post2]; // 根据后序最后一个元素为根结点元素,寻找中序序列中的根结点位置 int root;//根结点在中序中的位置 for (root = 0; root <= in2; root++) { if (PostStr[post2] == InStr[root]) { //printf("后序序列根节点(%c)在中序的位置 = %d\n", PreStr[L1], root); break; } } // 判断中序序列中<root>的左边是否存在左子序列 if (root - in1 != 0) { CreateBiTree_In_Post(T->lchild, InStr,PostStr, in1, root-1, post1, post1+root -in1- 1); } //其实这个分割区间很好理解的,你们自己理解吧我懒得讲 else //看看别的博主也行 { T->lchild = NULL; } // 判断中序序列中<root>的右边是否存在右子序列 if (in2 - root != 0) { CreateBiTree_In_Post(T->rchild, InStr,PostStr,root+1, in2, post1+root-in1 , post2-1); } else { T->rchild = NULL; } } typedef struct QueueNode{ BiTree node; struct QueueNode* next; }QueueNode; typedef struct Queue{ QueueNode* head; QueueNode* tail; }Queue; void QueueInit(Queue* pq){ pq->head=pq->tail=NULL; } void QueueDestory(Queue *pq){ QueueNode* cur=pq->head; while(cur){ QueueNode* next=cur->next; next=cur->next; free(cur); cur=next; } pq->head=pq->tail=NULL; } void QueuePush(Queue* pq,BiTree x){ QueueNode* newNode=(QueueNode*)malloc(sizeof(QueueNode)); newNode->node =x; newNode->next=NULL; if(pq->tail==NULL) pq->head=pq->tail=newNode; else{ pq->tail->next=newNode; pq->tail=newNode; } } void QueuePop(Queue* pq){ if(pq->head->next==NULL){ free(pq->head); pq->head=pq->tail=NULL; } else{ QueueNode* next=pq->head->next; free(pq->head); pq->head=next; } } BiTree QueueFront(Queue* pq){ return pq->head->node; } BiTree QueueBack(Queue* pq){ return pq->tail->node; } int QueueSize(Queue* pq){ QueueNode* cur=pq->head; int cnt=0; while(cur){ cur=cur->next; cnt++; } return cnt; } Queue pq; void TreeLevelOrder(BiTree root){ QueueInit(&pq); if(root) QueuePush(&pq, root); BiTree front; int a=QueueSize(&pq),flag=1; while( a!=1||flag==1){ flag=0; front=QueueFront(&pq); printf("%d ",front->data); if(front->lchild) QueuePush(&pq,front->lchild); if(front->rchild ) QueuePush(&pq,front->rchild ); QueuePop(&pq); a=QueueSize(&pq); } front=QueueFront(&pq); printf("%d",front->data); QueueDestory(&pq); } int postStr[50]={0},inStr[50]={0}; BiTree T; int main() { int num,in1 = 0,post1 = 0,in2,post2; scanf("%d",&num); for(int i=0;i<num;i++) scanf("%d",&postStr[i]); for(int i=0;i<num;i++) scanf("%d",&inStr[i]); num--; CreateBiTree_In_Post(T, inStr, postStr, in1, num, post1, num); TreeLevelOrder(T); }
20c30b2ff76d7b5bfcd9e2a65af568e0
{ "intermediate": 0.37635985016822815, "beginner": 0.4682116210460663, "expert": 0.15542861819267273 }
22,238
write the code in fortran program language to create an orthogonal quad mesh for a Rectangle with length of (L) and width (W). the program first should get data of (L,W,N,M) which (N,M) are the number of nodes in axis of (x,y) . write in detail in the end, write the equations from which equation it start and end to which equation that used in code. and explain all lines of code in detail, and say what this code gonna do and where should use it again?
b10e0991aabdea9fd8f7a23efcdc1bd0
{ "intermediate": 0.3307192325592041, "beginner": 0.12931479513645172, "expert": 0.5399659872055054 }
22,239
whats a good way to preform a pcap untill either untill the files a certain size or its been an x ammmmount of time? I have constant ddos attacks against my server so i wanna capture and mmitigate it myself.
9dab32e370fc8d09d238506faf89a693
{ "intermediate": 0.4577457904815674, "beginner": 0.23808203637599945, "expert": 0.30417218804359436 }
22,240
write the code in fortran program language to create an orthogonal quad mesh for a Rectangle with length of (L) and width (W). the program first should get data of (L,W,N,M) which (N,M) are the number of nodes in axis of (x,y) . write all nodes in array of (x,y) and then export mesh data in the format of tecplt 360. write in detail in the end, write the equations from which equation it start and end to which equation that used in code. and explain all lines of code in detail, and say what this code gonna do and where should use it again?
4a02aeadda2b0227e955076394a11e00
{ "intermediate": 0.35142919421195984, "beginner": 0.18282189965248108, "expert": 0.4657489061355591 }
22,241
tell me please how to install native mysql 5.6 in latest version of Manjaro
d67cd183fd29ee66b9ed0a891e737ed3
{ "intermediate": 0.5963108539581299, "beginner": 0.1875024288892746, "expert": 0.2161867767572403 }
22,242
Write a template function to calculate the sum for all elements in an array of numerical values (e.g., int, double). The function should work for any size of array. Use const parameter when appropriate. You should write a driver to test your code, but you don't need to submit it.
f27d1705eda4e6232b1c8c7a1d2ecc95
{ "intermediate": 0.46440574526786804, "beginner": 0.28537580370903015, "expert": 0.2502184510231018 }
22,243
A transmitter sends the voltages 𝑋=−2,+2 with equal probability. A malicious channel subtracts from the input the number of heads counted in two tosses of a healthy coin. A) Find all pairs of inputs and outputs and their probabilities using a tree diagram. b) Calculate the probability that the input 𝑋=+2, if the output 𝑌=𝑘 is measured
0675470e13513eff507cd735ae6561d3
{ "intermediate": 0.3209371864795685, "beginner": 0.2931993901729584, "expert": 0.38586339354515076 }
22,244
I would like to change the VBA code below to do the following; If Cells(i, "I") = "" Then Set copyRange = wscf.Range("J" & i) with the value of Cells(i, "H") added Values in "H" are either empty or contain a date value For i = 5 To lastRow If wscf.Cells(i, "I") = "" Then If copyRange Is Nothing Then Set copyRange = wscf.Range("J" & i) Application.ScreenUpdating = True Application.EnableEvents = True Else Set copyRange = Union(copyRange, wscf.Range("J" & i)) Application.ScreenUpdating = True Application.EnableEvents = True End If End If Next i
df4fafef4c4a475b5bee0a1f2758a0ed
{ "intermediate": 0.4744487404823303, "beginner": 0.30291837453842163, "expert": 0.22263287007808685 }
22,245
I am getting an error on this line 'Set copyRange = wscf.Range("J" & i) & wscf.Cells(i, "H").Value' in the following code: For i = 5 To lastRow If wscf.Cells(i, "I") = "" Then If copyRange Is Nothing Then Set copyRange = wscf.Range("J" & i) & wscf.Cells(i, "H").Value Else Set copyRange = Union(copyRange, wscf.Range("J" & i) & wscf.Cells(i, "H").Value) End If End If Next i
e02918bc3b002065047ee3e4b4072652
{ "intermediate": 0.3643048107624054, "beginner": 0.4533938467502594, "expert": 0.1823013424873352 }
22,246
how to calculate potential vorticity in python
76e1edb3073a5acdd58f26eea7988997
{ "intermediate": 0.19556497037410736, "beginner": 0.08329188078641891, "expert": 0.7211431264877319 }
22,247
write a program to send a simple udp packet with text data in C
7ed5081cc0c43401b3688042a2383a41
{ "intermediate": 0.38787275552749634, "beginner": 0.28124645352363586, "expert": 0.3308808207511902 }
22,248
I am getting an error 'Object Required' on this line 'Set copyRange = Union(copyRange, wscf.Range("J" & i) & wscf.Cells(i, "H"))' in this code below. For i = 5 To lastRow If wscf.Cells(i, "I") = "" Then If copyRange Is Nothing Then Set copyRange = wscf.Range("J" & i) If wscf.Cells(i, "H").Value <> "" Then copyRange.Value = wscf.Range("J" & i) & wscf.Cells(i, "H") End If Else Set copyRange = Union(copyRange, wscf.Range("J" & i) & wscf.Cells(i, "H")) End If End If Next i
ecd1e444cd9a004e0ddba5657a2f462f
{ "intermediate": 0.3371255099773407, "beginner": 0.43642428517341614, "expert": 0.22645017504692078 }
22,249
Dim copyRange As Range Dim i As Long Dim lastRow As Long Dim offsetCount As Long lastRow = wscf.Cells(wscf.Rows.Count, “I”).End(xlUp).Row offsetCount = 0 For i = 5 To lastRow If wscf.Cells(i, “I”).Value = “” Then If copyRange Is Nothing Then Set copyRange = wscf.Cells(i, “J”) Else Set copyRange = Union(copyRange, wscf.Cells(i, “J”)) End If If wscf.Cells(i, “H”).Value <> “” Then offsetCount = offsetCount + 1 copyRange.Cells(offsetCount).Offset(0, 1).Value = wscf.Cells(i, “J”).Value & " " & wscf.Cells(i, “H”).Value End If End If Next i The Values in column "I" are listed as follows: I5: 20/10/23 I6: I7: I8: I9: I10: The Values in column "J" are listed as follows: J5: Completed Tasks J6: Shower Head descale J7: Legionella Analysis J8: Hot & Cold Water Temperature J9: Water Tank Inspection J10: Sports Building Water Tank The Corresponding row values in "H" are listed as follows: H5: H6: 05/09/2023 H7: 09/12/2023 H8: 15/09/2023 H9: 28/08/2024 H10: When I run the code above, this is what I am expecting as the output: Shower Head descale 05/09/2023 Legionella Analysis 09/12/2023 Hot & Cold Water Temperature 15/09/2023 Water Tank Inspection 28/08/2024 Sports Building Water Tank Unfortunately the values in H are not concatenate correctly as shown in the output below: Shower Head descale05/09/202305/09/202305/09/2023 Legionella Analysis Hot & Cold Water Temperature Checks Water Tank Inspection Sports Building Water Tank Sediment Clean
78cf2ab23668d4e1ab1cc3f92bd32502
{ "intermediate": 0.3515426218509674, "beginner": 0.3505343496799469, "expert": 0.2979229986667633 }
22,250
Write an ANSI C function to read a binary file and return it as a character array. Try to make it fast.
1eb0bf74b4dee946e839591904e0ce09
{ "intermediate": 0.3034006357192993, "beginner": 0.37009185552597046, "expert": 0.3265075087547302 }
22,251
hi
36c16c30889b518058e36e7f97274259
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
22,252
Hi there!
90852e0f3042a6f797c66cde28901357
{ "intermediate": 0.32267293334007263, "beginner": 0.25843358039855957, "expert": 0.4188934564590454 }
22,253
how get sprite position in Defold engine from Lua?
8374c3499855111690f33d7bec74a8e8
{ "intermediate": 0.49925634264945984, "beginner": 0.2049531489610672, "expert": 0.295790433883667 }
22,254
c program The program is a text adventure game that lets the user explore a dungeon and fight monsters. The program uses a 2D dynamic array to store the map of the dungeon, and uses linked lists to store the items and monsters in each room. Approx. 2^8..2^9 lines of C code. All elements of the program must be standard and portable. (ISO/IEC 9899:1990) Extensive use of the advanced features of C is required: the program must be structurally built, must use functions. Use appropriate data structures with dynamic memory handling (2D dynamic array, linked list or binary tree). File handling must be used. Your code must be indented for readability. Use comments to document the code (min. 10%). The program should compile without warnings (except for certain safe function alternative warnings in Visual Studio). No global variables. I want the user to win if he finds the one treasure randomlz hidden in one of the rooms. the user starts with 50 health, and if while going through the map he finds a dragon, he loses 20 health, there is also health potion randomlz in rooms, this gives him back 10 health. the user loses if the health is at 0. i want the program to ask the user for name and map size, also score the users name and his score (health) in a file when he wins or loses
2502045ddf3879a616bb1b078a452d40
{ "intermediate": 0.2815047800540924, "beginner": 0.43390774726867676, "expert": 0.28458747267723083 }
22,255
can you please explain this formula: DATEVALUE(RIGHT(D9,LEN(D9)-FIND("" "",D9)))>TODAY()+40"
89572ecb475d5f3091aefafaa66b1ebf
{ "intermediate": 0.33114567399024963, "beginner": 0.167124405503273, "expert": 0.5017299056053162 }
22,256
write steganography code in go to convert base64 data into normal sentences and so other
46590127cca198ef82a1b39f4930bea1
{ "intermediate": 0.565688967704773, "beginner": 0.09413668513298035, "expert": 0.34017425775527954 }
22,257
I used this code: while True: if df is not None: quantity = bch_amount_rounded / 2 signals = signal_generator(df) mark_price_data = client.ticker_price(symbol=symbol) mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0 if signals == ['buy'] or signals == ['sell']: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}") if 'buy' in signals and active_signal != 'buy': try: active_signal = 'buy' buy_entry_price = mark_price # Record the Buy entry price print(f"Buy Entry Price: {buy_entry_price}") client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) print("Long order executed!") except binance.error.ClientError as e: print(f"Error executing long order: ") if sell_entry_price is not None and buy_entry_price is not None: sell_exit_price = mark_price difference_sell = calculate_percentage_difference_sell(sell_entry_price, sell_exit_price) profit_sell = difference_sell total_profit_sell = profit_sell profit_sell_percent = total_profit_sell - 4 print(f"sell entry price {sell_entry_price}, sell exit price {sell_exit_price} , Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%") else: print("Sell Entry price or Buy Entry price is not defined.") israel = [] depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = buy_price order = buy_price and buy_qty executed_orders = buy_price == mark_price for buy_price, buy_qty in bid_depth: if buy_price == mark_price: order = buy_qty executed_orders_buy = order buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 executed_orders_buy = float(executed_orders_buy) if executed_orders_buy else 0.0 buy_result = buy_qty - executed_orders_buy # Subtract executed order quantity from buy_qty buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 if (buy_result < 0.01 + sell_qty) and (sell_price < mark_price - 0.02): active_signal = None israel.append("Long !!! EXIT !!!") if buy_entry_price is not None and israel is not None: buy_exit_price = mark_price difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price) profit_buy = difference_buy total_profit_buy = profit_buy profit_buy_percent = total_profit_buy - 4 try: client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) except binance.error.ClientError as e: print(f"Long position successfully exited! ") print(" !!! EXIT !!! ") print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} buy entry price {buy_entry_price}, buy exit price: {mark_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%") buy_entry_price = None else: print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met else: israel.append('') elif 'sell' in signals and active_signal != 'sell': try: active_signal = 'sell' sell_entry_price = mark_price # Record the sell entry price print(f"Sell Entry Price: {sell_entry_price}") client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity) print("Short order executed!") except binance.error.ClientError as e: print(f"Error executing short order: ") if buy_entry_price is not None and sell_entry_price is not None: buy_exit_price = mark_price difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price) profit_buy = difference_buy total_profit_buy = profit_buy profit_buy_percent = total_profit_buy - 4 print(f"buy entry price {buy_entry_price}, buy exit price: {sell_entry_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%") else: print("Buy Entry price or Sell Entry price is not defined.") jerusalem = [] depth_data = client.depth(symbol=symbol) bid_depth = depth_data['bids'] ask_depth = depth_data['asks'] buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0 sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_qty = 0.0 order_price = sell_price order = sell_price and sell_qty executed_orders = sell_price == mark_price for sell_price, sell_qty in ask_depth: if sell_price == mark_price: order = sell_qty executed_orders_sell = order sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 sell_result = sell_qty - executed_orders_sell # Subtract executed order quantity from sell_qty sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0 sell_price = float(ask_depth[0][0]) if ask_depth else 0.0 buy_price = float(bid_depth[0][0]) if bid_depth else 0.0 if (sell_result < buy_qty - 0.01) and (buy_price > mark_price + 0.02): active_signal = None jerusalem.append("Short !!! EXIT !!!") if sell_entry_price is not None and jerusalem is not None: sell_exit_price = mark_price difference_sell = calculate_percentage_difference_buy(sell_entry_price, sell_exit_price) profit_sell = difference_sell total_profit_sell = profit_sell profit_sell_percent = total_profit_sell - 4 try: client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity) except binance.error.ClientError as e: print(f"Short position successfully exited!") print(" !!! EXIT !!! ") print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} sell entry price {sell_entry_price}, sell exit price: {mark_price}, Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%") sell_entry_price = None else: print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met else: jerusalem.append('') time.sleep(1) But I getting ERROR: The signal time is: 2023-10-21 22:50:33, Price 242.98 - Signals: ['sell'] Sell Entry Price: 242.98 Error executing short order: buy entry price 242.11, buy exit price: 242.98, Buy P&L: 14.37% with fee 10.37% Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 308, in <module> executed_orders_sell = float(executed_orders_sell) if executed_orders_sell else 0.0 ^^^^^^^^^^^^^^^^^^^^ NameError: name 'executed_orders_sell' is not defined. Did you mean: 'executed_orders_buy'?
0f486173788059b61ceffbfc6fe63831
{ "intermediate": 0.3469100594520569, "beginner": 0.5138322114944458, "expert": 0.13925772905349731 }
22,258
Please write a program PrintStarsSquare.java that prints a square of * and takes edge length as input:
41d9d14c198fc547b07c497e375aeb7d
{ "intermediate": 0.4450189471244812, "beginner": 0.25025513768196106, "expert": 0.30472585558891296 }
22,259
An important part of a project is to identify the key process input variables (KPIV) and key process output variables (KPOV). Suppose that you are in charge of a hospital emergency room. Discuss the KPIVs and KPOVs for this business. How do they relate to possible customer CTQs?
163d0f28ef49ef952f3cc99087e67a9a
{ "intermediate": 0.28958144783973694, "beginner": 0.3531411588191986, "expert": 0.35727739334106445 }
22,260
give me an code for binary search tree
75a7afa709525ea124e3b4f7a251ee65
{ "intermediate": 0.3007626235485077, "beginner": 0.09131250530481339, "expert": 0.6079248785972595 }
22,261
hi
b2a73966c39839182b23069d01d46ed6
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
22,262
Act as software engineer who needs to rewrite c# code into lua for defold, i will send blocks of code and you need give me lua version of this block, are you ready?
f3b721429cb97106beb13efc27bbc604
{ "intermediate": 0.4232420027256012, "beginner": 0.20064014196395874, "expert": 0.3761177957057953 }
22,263
intervals <- c() # initialize an empty vector to store the intervals for (i in 1:(length(trt$Subject_ID)-1)) { if (trt$Subject_ID[i] == trt$Subject_ID[i+1]) { interval <- difftime(trt$datetime[i+1], trt$datetime[i], units = "hours") intervals <- c(intervals, interval) } }how to fix this code to meet calculate the interval based on the same subject and the same analyte, for analyte which stands for the same drug
418ab22f65c5e3efec3f14faa56623af
{ "intermediate": 0.38247016072273254, "beginner": 0.31682103872299194, "expert": 0.3007087707519531 }
22,264
how to use runge kutta in matlab for ordinary differential equation
7340f7753dea0fb45239db942c29ddc9
{ "intermediate": 0.32320043444633484, "beginner": 0.4224611818790436, "expert": 0.25433841347694397 }
22,265
given a real number. Find the value of (a) using the function f(x) shown in Figure 1.a-1.d.y=1/x^2,y=x^2,y=4
1c84851973cb2a7811d783ed3f780f55
{ "intermediate": 0.35408130288124084, "beginner": 0.367739737033844, "expert": 0.2781789004802704 }
22,266
I implement the offline map with leaflet.js and OSM data that is the form of .mbtiles extension. but the problem is when I want to serve the file of .mbtiles that is 70GB, it fails and says database is failed. what should I do ?
cdcc9695bf13fe9d71577dde01b0bfc8
{ "intermediate": 0.5765115022659302, "beginner": 0.21915172040462494, "expert": 0.20433679223060608 }
22,267
如何解决ovs-vsctl: unix:/var/run/openvswitch/db.sock: database connection failed (No such file or directory)
8087257978c7199780c46f3a1f072d77
{ "intermediate": 0.3627113699913025, "beginner": 0.27100738883018494, "expert": 0.3662812113761902 }
22,268
hi
aaa1d4e72c868ba07662a1e041aaaf7e
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
22,269
P <- sub_trt1 %>% arrange(trtpn) %>% group_by(trtpn) %>% mutate(CL0=as.numeric(CL), V0=as.numeric(V))%>% summarise(P = list(rep(CL0, V0))) %>% ungroup() %>% pull(P) HOW TO FIX THIS CODE TO ACHIEVE P=(5.45,6) IF CL0=5.45,V0=6
a9c17ef5858cd1ba3dd0d8ca05290260
{ "intermediate": 0.2594507038593292, "beginner": 0.45635363459587097, "expert": 0.28419575095176697 }
22,270
{ type: 'label', label: '计划年度', field: 'planYear', required: true, }, { type: 'handler', field: 'planYear', render: data => ( <el-date-picker style="width:100%" vModel={data['planYear']} type="year" placeholder="请选择" onChange={this.onYearPlanHasChange} /> ), },解决报错[Vue warn]: Invalid handler for event "change": got undefined
7c795848a685395c8863671cea6acf90
{ "intermediate": 0.34559527039527893, "beginner": 0.4125567078590393, "expert": 0.24184800684452057 }
22,271
Please write a program PrintLetters.java that prints the following matrix on the screen (Hint: you’ll need nested loops and other control structures. Try it from scratch only with the material you have from the lecture).
a9d932d87403698686a7b838d57ab69c
{ "intermediate": 0.14558956027030945, "beginner": 0.7513406872749329, "expert": 0.10306984186172485 }
22,272
使用devstack安装openstack多节点的控制节点时,出现ovs-vsctl: unix:/var/run/openvswitch/db.sock: database connection failed (No such file or directory)报错,有什么解决办法么
3265766795ffa597baf25efdbbf29fd5
{ "intermediate": 0.5717688202857971, "beginner": 0.17406027019023895, "expert": 0.25417086482048035 }
22,273
if study <-data.framer(Parameter, Value) , and the value is stands for studyid, how to get the value studyid <-value () in R
e79964a4862ca76cebcfc1a1283a531f
{ "intermediate": 0.5835093855857849, "beginner": 0.19278563559055328, "expert": 0.22370494902133942 }
22,274
почему не вызывается func draw(_ rect: CGRect) для UIRenderView
c14078ed29493b76cc30f3faaf8b2c1b
{ "intermediate": 0.36944156885147095, "beginner": 0.35618317127227783, "expert": 0.2743752598762512 }
22,275
improve and optimize the following code : "classifier = TextClassifier.load('en-sentiment') tokenizer = AutoTokenizer.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment') model = AutoModelForSequenceClassification.from_pretrained('nlptown/bert-base-multilingual-uncased-sentiment') # Retrieve webpage content url = 'https://finance.yahoo.com/news/stricter-verification-laws-u-won-130000216.html' response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') # Extract main article text crypto_paragraphs = [] for paragraph in soup.find_all('p'): crypto_paragraphs.append(paragraph.text.strip()) tb_sentiments = [] vs_sentiments = [] flair_sentiments = [] bert_sentiments = [] for paragraph in crypto_paragraphs: #sentiment s1 = analyzer.polarity_scores(paragraph)['compound'] #Vs s2 = TextBlob(paragraph).sentiment.polarity #Flair sentence = Sentence(paragraph) classifier.predict(sentence) s3 = sentence.labels[0].score if sentence.labels[0].value == 'NEGATIVE': s3 = s3 * -1 #Bert inputs = tokenizer(paragraph, return_tensors='pt', padding=True, truncation=True) outputs = model(**inputs) sentiments = torch.softmax(outputs.logits, dim=1).tolist() positive_sentiment = sum([sentiment[2] for sentiment in sentiments]) / len(sentiments) negative_sentiment = sum([sentiment[0] for sentiment in sentiments]) / len(sentiments) s4 = positive_sentiment - negative_sentiment # Append sentiment scores to lists vs_sentiments.append(s1) tb_sentiments.append(s2) flair_sentiments.append(s3) bert_sentiments.append(s4) # Calculate the overall sentiment of all paragraphs using each method tb_sentiment = sum(tb_sentiments) / len(tb_sentiments) vs_sentiment = sum(vs_sentiments) / len(vs_sentiments) flair_sentiment = sum(flair_sentiments) / len(flair_sentiments) bert_sentiment = sum(bert_sentiments) / len(bert_sentiments) # Assess the importance of the news based on the overall sentiment overall_sentiment = (tb_sentiment + vs_sentiment + flair_sentiment + bert_sentiment) / 4 print(tb_sentiment,vs_sentiment,flair_sentiment,bert_sentiment,overall_sentiment)"
6562a63cd31a9c59f6d67465ecf00992
{ "intermediate": 0.23582661151885986, "beginner": 0.09980103373527527, "expert": 0.6643723249435425 }
22,276
Напиши реализацию по прототипу на typescript и сделай хук для реакт для взаимодействия с этим client("https://...", abort => setTimeout(abort, 2000)) .get() .query({ id: 1 }, { Authorization: "..." }) .cache(1500) .retry(3) .then(res => res.json())
2bb4aa3cecfc25fcc2add04613cda061
{ "intermediate": 0.30969497561454773, "beginner": 0.4492206275463104, "expert": 0.24108436703681946 }
22,277
How do I change color of text in html?
178f5750542dd59ead5850cf708cee37
{ "intermediate": 0.4196096360683441, "beginner": 0.33103930950164795, "expert": 0.24935108423233032 }
22,278
can only concatenate str (not "NoneType") to str fordibben = ['!', '"', '#', '$', '%', '&', "'", '*', '+', ',', ':', ';', '<', '>', '=', '?', '[', ']', '{', '}', ' ', '|', '^', '`'] for i in fordibben: if i in url: return HttpResponseRedirect('/new?e=Invalid+URL&title=' + title + "&url=" + url + "&filepath=" + filepath) Site.objects.create(url=url, title=title, content=file.read().decode('utf-8'), author=username) return HttpResponseRedirect('/panel')
78ee5ee12b3a7c4fdfaddc7bd76ebe9f
{ "intermediate": 0.4188063144683838, "beginner": 0.349913090467453, "expert": 0.23128058016300201 }
22,279
give me a meteogram in port of genoa on June 7, 2020.
41513ee525925b92a208d8954d0d3a39
{ "intermediate": 0.3807549774646759, "beginner": 0.2834496796131134, "expert": 0.33579540252685547 }
22,280
Tell me shortly if you have order book and mark price how you will count which order is eecuted and how many qty you need to minus form order book ?
f29b358ae3c644ad75eed9b49efebcb7
{ "intermediate": 0.420348584651947, "beginner": 0.213128462433815, "expert": 0.3665229380130768 }
22,281
devstack部署计算节点出现awk: fatal: cannot open file `/opt/stack/nova/setup.cfg' for reading: No such file or directory
23785b3320ae5c01743bea083df4c8b5
{ "intermediate": 0.4225788116455078, "beginner": 0.2427840232849121, "expert": 0.33463719487190247 }
22,282
Привет! Можешь создать мне Keras модель с LSTM слоями
00a9db0e0096f57595eafc81058dda75
{ "intermediate": 0.2740474045276642, "beginner": 0.17931994795799255, "expert": 0.5466326475143433 }
22,283
Using redis I need to set up a db for my captcha solver. the db is gonna include the challange type which holds all the diffrent challange images hashes present in the type and with that image hash it will hold an answer. the problems are: 1. I dont know exactly how i'd set this up since I dont have tables like in a r elational db. so how would I store the actual challange type and the actual challanges without this?
1e96e6ad8fe5e5e2a45af2f3cdc6023b
{ "intermediate": 0.6935084462165833, "beginner": 0.10562451928853989, "expert": 0.20086704194545746 }
22,284
any way I can make this logger easier to use?
95af2410db9200b9bb26cacd120ffa1f
{ "intermediate": 0.29421961307525635, "beginner": 0.32132741808891296, "expert": 0.3844529688358307 }
22,285
Write a function template named maximum. The function takes two values of the same type as its arguments and returns the larger of the two arguments (or either value if they are equal). Give both the function declaration and the function definition for the template. You will use the operator < in your definition. Therefore, this function template will apply only to types for which < is defined. Write a comment for the function declaration that explains this restriction.
a0b68c17ee45fbe3335bc6daa1903d37
{ "intermediate": 0.2584592401981354, "beginner": 0.42742764949798584, "expert": 0.31411314010620117 }
22,286
部署devstack计算节点的时候遇到oscwrap project show admin -f value -c idThe request you have made requires authentication. (HTTP 401) (Request-ID: req-9e08f1ac-aada-487b-8592-a74a2215bef4)该怎么解决
d0f7049a6adb8ab8414c042dec78540e
{ "intermediate": 0.5645732283592224, "beginner": 0.13221865892410278, "expert": 0.3032081723213196 }
22,287
we are given a string S with length N. A sequence of 2 adjacents in that string S is called a diagram. The distance between the 2 diagrams is the distance between the first letter of the first diagram and the first letter of the second diagram.
92b66a25152f1c0733738a3631d95089
{ "intermediate": 0.405497282743454, "beginner": 0.21962454915046692, "expert": 0.3748781681060791 }
22,288
montre moi le test unitaire pour vérifier l'initialisation de la structure Game et les valeurs retournées de la fonction CreateGame, en prenant en compte la strcture du test "const Penduel = artifacts.require("Penduel"); const { BN, expectRevert, expectEvent } = require('@openzeppelin/test-helpers'); const { expect } = require('chai'); const Web3 = require('web3'); contract("Penduel", accounts => { let penduelInstance; const subId = 12226; const player1 = accounts[0]; const player2 = accounts[1]; const s_owner = accounts[2]; const web3 = new Web3("http://localhost:7545"); context ("FONCTION DE MISE EN PLACE DU JEU PLAYER 1", () => { before(async function() { penduelInstance = await Penduel.new(subId); }); describe("vérifie les valeurs retournées de createGame", () => { it("doit créer une nouvelle partie", async () => {" test des fonctios n "createGame" qui appelle la fonction "initializeBet" function createGame() public { currentPlayer = msg.sender; gameId++; games[gameId] = Game({ player1: currentPlayer, player2: address(0), player1Joined: false, player2Joined: false, player2HasBet: false, player1Bet: initializeBet(), player2Bet: initializeBet(), player2HasWithdrawn: false, player1HasWithdrawn: false, isPlayer2Turn: true }); playerBalances[gameId][currentPlayer].balance = 0; games[gameId].player1Joined = true; state = State.gameCreated; emit GameCreated(gameId, currentPlayer); } /** * @notice initialise player1Bet et player2Bet */ function initializeBet() private pure returns (Bet memory) { return Bet({ bet: 0, totalBet: 0, balance: 0 }); }"
2bfb1822c284a145b79d9ca7d0e6f4b0
{ "intermediate": 0.34116482734680176, "beginner": 0.40795937180519104, "expert": 0.2508758306503296 }
22,289
How to extract Unity games assets on Linux ?
27321eddcd514ea46fdc55d47a25d06c
{ "intermediate": 0.38460150361061096, "beginner": 0.3037989139556885, "expert": 0.31159964203834534 }
22,290
Implement the following into the script: - fastest way to scrape - utilize concurrent features - send a PUT request - make sure {customer} starts from 1 to 450,000 max import requests customer = '' url = f"https://admin.playthe.net/profile/personal_info/{customer}" form_data = "name=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&surname=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&email=NEGOTIATIONS%40t.meTmux0&lang=es_ES&alias=&birthday=01%2F11%2F2002&gender=M&country=AFG&province=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&city=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&address=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&zipcode=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&phone=HACKED+SELLING+DATA+t.me%2Ftmux0+FOR+NEGOTIATIONS+&checkPassword=on&password=&confirm_password=&likes=&civil_state=1&education_uid=1&education_expertise=&education_center=&job_field=&job_uid=1&business_uid=1&nombre=&nif=B06933477&apellidos=&email_facturation=&tlfFijo=&tlfMovil=&nombreViaEnvio=&numeroViaEnvio=&restoViaEnvio=&provinciaEnvio=506701004&codigoPostalEnvio=&paisEnvio=AFG&tipoFactura=1&destinoFactura=2&tipoImpositivo=1&modoPago=6&is_owner=on&crm_uid=B06933477&is_advanced_owner=on&is_owner=true&is_advanced_owner=true&is_agency=false" put request
a51a16238896bfd50189e00db8ac6641
{ "intermediate": 0.47930580377578735, "beginner": 0.264153391122818, "expert": 0.25654080510139465 }
22,291
The template sort routine in Display 16.3 is based on an algorithm called the selection sort. Another related sorting algorithm is called insertion sort. The insertion sort algorithm is the sort method often used to sort a Bridge hand. Consider each element in turn, inserting it into its proper place among the elements at the start of the array that are already sorted. The element being considered is inserted by moving the larger elements “to the right” to make space and inserting the vacated place. For example, the following shows the steps in a selection sort of an array of ints a. The values of a[0] through a[4] are given on each line. The asterisk marks the boundary between the sorted and unsorted portions of the array. 2 * 5 3 4 2 5 * 3 4 2 3 5 * 4 2 3 4 5 * First, write an insertion sort function that works for ints. Next, write the template version of this sort function. Finally, test thoroughly using several primitive types, using a type you create with the minimal machinery necessary to use the sort routine.
90acfabce7672f4710817693167f50bd
{ "intermediate": 0.28364846110343933, "beginner": 0.19525328278541565, "expert": 0.521098256111145 }
22,292
by this code I created a mesh for a rectangle of l an h. program mesh implicit none real :: l,h real, allocatable :: x(:), y(:), t(:,:) integer :: n,m call input(l,h,n,m) allocate (x(n),y(m),t(n,m)) call Mesh_generation(l,h,n,m,x,y) call Solver(n,m,x,y,t) call Output(n,m,x,y,t) end program subroutine input(l,h,n,m) implicit none real :: l,h integer :: n,m open (10, file = 'input.txt') read (10,*) read (10,*) l read (10,*) read (10,*) h read (10,*) read (10,*) n read (10,*) read (10,*) m end subroutine subroutine Mesh_generation(l,h,n,m,x,y) implicit none real :: l,h,x(n),y(m),dx,dy integer :: n,m,i,j dx = l/(n-1.0) dy = h/(m-1.0) Do i = 1,n x(i) = (i-1) * dx End Do Do j = 1,m y(j) = (j-1) * dy End Do end subroutine subroutine Solver(n,m,x,y,t) implicit none real :: x(n), y(m),t(n,m) integer :: n,m,i,j Do i = 1,n Do j = 1,m t(i,j) = (sin(x(i)))**2.0 + (cos(y(j)))**2.0 End Do End Do end subroutine subroutine Output(n,m,x,y,t) implicit none real :: x(n), y(m),t(n,m) integer :: n,m,i,j open (11, file = 'temp.plt') open (12, file = 'mesh.plt') write(11,*)'variables = x,y,T zone i =',n,'j=',m Do j = 1,m Do i = 1,n write (11,*) x(i), y(j), t(i,j) End Do End Do write(12,*)'variables = x,y zone i =',n,'j=',m Do j = 1,m Do i = 1,n write (12,*) x(i), y(j) End Do End Do end subroutine Now I want the mesh to be small near the walls.
298861fb03f440429292650682336d12
{ "intermediate": 0.323631227016449, "beginner": 0.2777620553970337, "expert": 0.39860668778419495 }
22,293
should you run lets say an ssh honey pot on your own machine?
c2616c0dba19983746af402c9140c8ab
{ "intermediate": 0.3526414632797241, "beginner": 0.1776427924633026, "expert": 0.46971574425697327 }
22,294
Create a program that takes as input one argument n, Then create an array that holds the logarithm of each whole number from 1 to n. Then prints out the table on a single line; separating values by commas. n can be any number. so when creating the table, you will need to dynamically allocate memory of size n. Also your table will be of type float You will need to use the cmath library to access the std::log() function
1f6d4e60ed83516bc57f3ab3886c085b
{ "intermediate": 0.5054264068603516, "beginner": 0.24610483646392822, "expert": 0.24846874177455902 }
22,295
flask-msearch how to take into account punctuation
d59c9559c8171d39904349e6ebde4aaf
{ "intermediate": 0.4108574092388153, "beginner": 0.20207802951335907, "expert": 0.3870645761489868 }
22,296
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(LineRenderer))] public class Grappler : MonoBehaviour, IGadget { public enum eMode { gIdle, gOut, gRetract, gPull} [Header("Inscribed")] [Tooltip("Speed at which Grappler extends (doubled in gRetract mode)")] public float grappleSpd = 10; [Tooltip("Maximum length that Grappler will reach")] public float maxLength = 7.25f; [Tooltip("Minimum distance of Grappler from Dray")] public float minLength = 0.5f; [Tooltip("Health deducted when Dray ends a grapple on an unsafe tile")] public int unsafeTileHealthPenalty = 2; [Header("Dynamic")] [SerializeField] private eMode _mode = eMode.gIdle; public eMode mode { get { return _mode; } private set { _mode = value; } } private LineRenderer line; private Rigidbody2D rigid; private Collider2D colld; private Vector3 p0, p1; private int facing; private Dray dray; private System.Func<IGadget, bool> gadgetDoneCallback; private Vector2[] directions = new Vector2[] { Vector2.right, Vector2.up, Vector2.left, Vector2.down }; private Vector3[] dirV3s = new Vector3[] { Vector3.right, Vector3.up, Vector3.left, Vector3.down }; private void Awake() { //Get component references to use throughout the script line = GetComponent<LineRenderer>(); rigid = GetComponent<Rigidbody2D>(); colld = GetComponent<Collider2D>(); } void Start() { gameObject.SetActive(false); //Initially disable this GameObject } void SetGrappleMode(eMode newMode) { switch (newMode) { case eMode.gIdle: transform.DetachChildren(); //Release any child Transforms gameObject.SetActive(false); if (dray != null && dray.controlledBy == this as IGadget) { dray.controlledBy = null; dray.physicsEnabled = true; } break; case eMode.gOut: gameObject.SetActive(true); rigid.velocity = directions[facing] * grappleSpd; break; case eMode.gRetract: rigid.velocity = -directions[facing] * (grappleSpd * 2); break; case eMode.gPull: p1 = transform.position; rigid.velocity = Vector2.zero; dray.controlledBy = this; dray.physicsEnabled = false; break; } mode = newMode; } private void FixedUpdate() { p1 = transform.position; line.SetPosition(1, p1); switch (mode) { case eMode.gOut: //Grappler shooting out //See if the Grappler reached its limit without hitting anything if ((p1 - p0).magnitude >= maxLength) { SetGrappleMode(eMode.gRetract); } break; case eMode.gRetract: //Grappler missed; return at double speed //Check to see if the Grappler is no longer in front of Dray if (Vector3.Dot((p1 - p0), dirV3s[facing]) < 0) GrappleDone(); break; case eMode.gPull: if ((p1-p0).magnitude > minLength) { //Move Dray toward the Grappler hit point p0 += dirV3s[facing] * grappleSpd * Time.fixedDeltaTime; dray.transform.position = p0; line.SetPosition(0, p0); //Stop Grappler from moving with Dray transform.position = p1; } else { //Dray is close enough to stop grappling p0 = p1 - (dirV3s[facing] * minLength); dray.transform.position = p0; //Check whether Dray landed on an unsafe tile Vector2 checkPos = (Vector2)p0 + new Vector2(0, -0.25f); if (MapInfo.UNSAFE_TILE_AT_VECTOR2(checkPos)) { //Dray landed on an unsafe tile dray.ResetInRoom(unsafeTileHealthPenalty); } GrappleDone(); } break; } } //Ensures that p1 is aligned with the Grappler head private void LateUpdate() { p1 = transform.position; line.SetPosition(1, p1); } ///<summary> ///Called when the Grappler hits a Trigger or Collider in the GrapTiles, Items, or Enemies Physics Layers (Grappler's Collider is a Trigger) /// </summary> /// <param name="coll"></param> void OnTriggerEnter2D(Collider2D colld) { //The Grappler has collided with something, but what? string otherLayer = LayerMask.LayerToName(colld.gameObject.layer); switch (otherLayer) { case "Items": //We've possibly hit a PickUp PickUp pup = colld.GetComponent<PickUp>(); if (pup == null) return; //If this IS a PickUp, make it a child of this Transform so it moves with the Grappler head pup.transform.SetParent(transform); pup.transform.localPosition = Vector3.zero; SetGrappleMode(eMode.gRetract); break; case "Enemies": //We've hit an Enemy //The Grappler should return when it hits an Enemy Enemy e = colld.GetComponent<Enemy>(); if (e != null) SetGrappleMode(eMode.gRetract); //Damaging the Enemy is handled by the DamageEffect & Enemy scripts break; case "GrapTiles": //We've hit a GrapTile //SetGrappleMode(eMode.gRetract); SetGrappleMode(eMode.gPull); break; default: SetGrappleMode(eMode.gRetract); break; } } void GrappleDone() { SetGrappleMode(eMode.gIdle); //Callback to Dray so he returns to normal controls gadgetDoneCallback(this); } #region IGadget_Implementation //Implementation of IGadget //Called by Dray to use this IGadget public bool GadgetUse(Dray tDray, System.Func<IGadget,bool> tCallback) { if (mode != eMode.gIdle) return false; dray = tDray; gadgetDoneCallback = tCallback; transform.localPosition = Vector3.zero; facing = dray.GetFacing(); p0 = dray.transform.position; p1 = p0 + (dirV3s[facing] * minLength); gameObject.transform.position = p1; gameObject.transform.rotation = Quaternion.Euler(0, 0, 90 * facing); line.positionCount = 2; line.SetPosition(0, p0); line.SetPosition(1, p1); SetGrappleMode(eMode.gOut); return true; } //Called by Dray if he is hit while grappling and mode != eMode.inHit public bool GadgetCancel() { //If pulling Dray to a wall, ignore GadgetCancel if (mode == eMode.gPull) return false; SetGrappleMode(eMode.gIdle); gameObject.SetActive(false); return true; } //string name is already part of Grappler (inherited from Object) #endregion } Add an if statement to this script under the void OnTriggerEnter2D method and under case "Enemies" that says if it the grappler hit an enemy it will stun the enemy for 1 second
a04a3c636072d191801cc3ac81351428
{ "intermediate": 0.3782612681388855, "beginner": 0.47874942421913147, "expert": 0.14298932254314423 }
22,297
write a method that will stun an enemy for 1 second in C# for unity
a62453e276eab401556dc5f9bbb05fb4
{ "intermediate": 0.29943907260894775, "beginner": 0.1721809208393097, "expert": 0.5283799767494202 }
22,298
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(InRoom))] public class Dray : MonoBehaviour, IFacingMover, IKeyMaster { static public Dray S; static public IFacingMover IFM; public enum eMode { idle, move, attack, roomTrans, knockback, gadget} [Header("Inscribed")] public float speed = 5; public float attackDuration = 0.25f; //Number of seconds to attack public float attackDelay = 0.5f; //Delay between attacks public float roomTransDelay = 0.5f; //Room transition delay public int maxHealth = 10; public float knockbackSpeed = 10; public float knockbackDuration = 0.25f; public float invincibleDuration = 0.5f; public int healthPickupAmount = 2; public KeyCode keyAttack = KeyCode.Z; public KeyCode keyGadget = KeyCode.X; [SerializeField] private bool startWithGrappler = true; [Header("Dynamic")] public int dirHeld = -1; //Direction of the held movement key public int facing = 1; //Direction Dray is facing public eMode mode = eMode.idle; public bool invincible = false; [SerializeField] [Range(0, 20)] private int _numKeys = 0; [SerializeField] [Range(0, 10)] private int _health; public int health { get { return _health; } set { _health = value; } } private float timeAtkDone = 0; private float timeAtkNext = 0; private float roomTransDone = 0; private Vector2 roomTransPos; private float knockbackDone = 0; private float invincibleDone = 0; private Vector2 knockbackVel; private Vector3 lastSafeLoc; private int lastSafeFacing; private Collider2D colld; private Grappler grappler; private SpriteRenderer sRend; private Rigidbody2D rigid; private Animator anim; private InRoom inRm; private Vector2[] directions = new Vector2[] { Vector2.right, Vector2.up, Vector2.left, Vector2.down }; private KeyCode[] keys = new KeyCode[] { KeyCode.RightArrow, KeyCode.UpArrow, KeyCode.LeftArrow, KeyCode.DownArrow, KeyCode.D, KeyCode.W, KeyCode.A, KeyCode.S }; private void Awake() { S = this; IFM = this; sRend = GetComponent<SpriteRenderer>(); rigid = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); inRm = GetComponent<InRoom>(); health = maxHealth; grappler = GetComponentInChildren<Grappler>(); if (startWithGrappler) currentGadget = grappler; colld = GetComponent<Collider2D>(); } void Start() { lastSafeLoc = transform.position; lastSafeFacing = facing; } void Update() { if (isControlled) return; //Check knockback and invincibility if (invincible && Time.time > invincibleDone) invincible = false; sRend.color = invincible ? Color.red : Color.white; if (mode == eMode.knockback) { rigid.velocity = knockbackVel; if (Time.time < knockbackDone) return; //The following line is only reached if Time.time >= knockbackDone mode = eMode.idle; } if (mode == eMode.roomTrans) { rigid.velocity = Vector3.zero; anim.speed = 0; posInRoom = roomTransPos; //Keeps Dray in place if (Time.time < roomTransDone) return; //The following line is only reached if Time.time >= transitionDone mode = eMode.idle; } //Finish the attack when it's over if (mode == eMode.attack && Time.time >= timeAtkDone) { mode = eMode.idle; } //Handle Keyboard Input in idle or move Modes if (mode == eMode.idle || mode == eMode.move) { dirHeld = -1; for (int i=0; i < keys.Length; i++) { if (Input.GetKey(keys[i])) dirHeld = i % 4; } //Choosing the proper movement or idle mode based on dirHeld if (dirHeld == -1) { mode = eMode.idle; } else { facing = dirHeld; mode = eMode.move; } //Pressing the gadget button if (Input.GetKeyDown(keyGadget)) { if (currentGadget != null) { if (currentGadget.GadgetUse(this, GadgetIsDone)) { mode = eMode.gadget; rigid.velocity = Vector2.zero; } } } //Pressing the attack button if (Input.GetKeyDown(keyAttack) && Time.time >= timeAtkNext) { mode = eMode.attack; timeAtkDone = Time.time + attackDuration; timeAtkNext = Time.time + attackDelay; } } //Act on the current mode Vector2 vel = Vector2.zero; switch (mode) { case eMode.attack: //Show the Attack pose in the correct direction anim.Play("Dray_Attack_" + facing); anim.speed = 0; break; case eMode.idle: //Show frame 1 in the correct direction anim.Play("Dray_Walk_" + facing); anim.speed = 0; break; case eMode.move: //Play walking animation in the correct direction vel = directions[dirHeld]; anim.Play("Dray_Walk_" + facing); anim.speed = 1; break; case eMode.gadget: //Show Attack pose & wait for IGadget to be done anim.Play("Dray_Attack_" + facing); anim.speed = 0; break; } rigid.velocity = vel * speed; //dirHeld = -1; //if (Input.GetKey(KeyCode.RightArrow)) dirHeld = 0; //if (Input.GetKey(KeyCode.UpArrow)) dirHeld = 1; //if (Input.GetKey(KeyCode.LeftArrow)) dirHeld = 2; //if (Input.GetKey(KeyCode.DownArrow)) dirHeld = 3; //for (int i=0; i < keys.Length; i++) //{ // if (Input.GetKey(keys[i])) dirHeld = i % 4; //} //Vector2 vel = Vector2.zero; //switch (dirHeld) //{ // case 0: // vel = Vector2.right; // break; // case 1: // vel = Vector2.up; // break; // case 2: // vel = Vector2.left; // break; // case 3: // vel = Vector2.down; // break; //} //if (dirHeld > -1) vel = directions[dirHeld]; //rigid.velocity = vel * speed; //Animation //if (dirHeld == -1) //{ // anim.speed = 0; //} //else //{ // anim.Play("Dray_Walk_" + dirHeld); // anim.speed = 1; //} } void LateUpdate() { if (isControlled) return; //Get the nearest quarter-grid position to Dray Vector2 gridPosIR = GetGridPosInRoom(0.25f); //Check to see whether we're in a Door tile int doorNum; for (doorNum=0; doorNum < 4; doorNum++) { if (gridPosIR == InRoom.DOORS[doorNum]) { break; } } if (doorNum > 3 || doorNum != facing) return; //Move to the next room Vector2 rm = roomNum; switch (doorNum) { case 0: rm.x += 1; break; case 1: rm.y += 1; break; case 2: rm.x -= 1; break; case 3: rm.y -= 1; break; } //Make sure that the rm we want to jump to is valid if (0 <= rm.x && rm.x <= InRoom.MAX_RM_X) { if (0 <= rm.y && rm.y <= InRoom.MAX_RM_Y) { roomNum = rm; roomTransPos = InRoom.DOORS[(doorNum + 2) % 4]; posInRoom = roomTransPos; mode = eMode.roomTrans; roomTransDone = Time.time + roomTransDelay; lastSafeLoc = transform.position; lastSafeFacing = facing; } } } void OnCollisionEnter2D(Collision2D coll) { if (isControlled) return; if (invincible) return; //Return if Dray can't be damaged DamageEffect dEf = coll.gameObject.GetComponent<DamageEffect>(); if (dEf == null) return; //If no DamageEffect, exit this method health -= dEf.damage; //Subtract the damage amount from health invincible = true; //Make Dray invincible invincibleDone = Time.time + invincibleDuration; if (dEf.knockback) { //Knockback Dray //Determine the direction of knockback from relative position Vector2 delta = transform.position - coll.transform.position; if (Mathf.Abs(delta.x) >= Mathf.Abs(delta.y)) { //Knockback should be horizontal delta.x = (delta.x > 0) ? 1 : -1; delta.y = 0; } else { //Knockback should be vertical delta.x = 0; delta.y = (delta.y > 0) ? 1 : -1; } //Apply knockback speed to the Rigidbody knockbackVel = delta * knockbackSpeed; rigid.velocity = knockbackVel; //Set mode to knockback and set time to stop knockback //mode = eMode.knockback; //knockbackDone = Time.time + knockbackDuration; //If not in gadget mode OR if GadgetCancel is successful if (mode != eMode.gadget || currentGadget.GadgetCancel()) { //Set mode to knockback and set time to stop knockback mode = eMode.knockback; knockbackDone = Time.time + knockbackDuration; } } } void OnTriggerEnter2D(Collider2D colld) { if (isControlled) return; PickUp pup = colld.GetComponent<PickUp>(); if (pup == null) return; switch (pup.itemType) { case PickUp.eType.health: health = Mathf.Min(health + healthPickupAmount, maxHealth); break; case PickUp.eType.key: _numKeys++; break; case PickUp.eType.grappler: currentGadget = grappler; break; default: Debug.LogError("No case for PickUp type " + pup.itemType); break; } Destroy(pup.gameObject); } public void ResetInRoom(int healthLoss = 0) { transform.position = lastSafeLoc; facing = lastSafeFacing; health -= healthLoss; invincible = true; //Make Dray invincible invincibleDone = Time.time + invincibleDuration; } static public int HEALTH { get { return S._health; } } static public int NUM_KEYS { get { return S._numKeys; } } //Implementation of IFacingMover public int GetFacing() { return facing; } public float GetSpeed() { return speed; } public bool moving { get { return (mode == eMode.move); } } public float gridMult { get { return inRm.gridMult; } } public bool isInRoom { get { return inRm.isInRoom; } } public Vector2 roomNum { get { return inRm.roomNum; } set { inRm.roomNum = value; } } public Vector2 posInRoom { get { return inRm.posInRoom; } set { inRm.posInRoom = value; } } public Vector2 GetGridPosInRoom(float mult = -1) { return inRm.GetGridPosInRoom(mult); } //Implementation of IKeyMaster public int keyCount { get { return _numKeys; } set { _numKeys = value; } } public Vector2 pos { get { return (Vector2)transform.position; } } #region IGadget_Affordances //IGadget Affordances public IGadget currentGadget { get; private set; } ///<summary> ///Called by an IGadget when it is done ///Sets mode to eMode.idle ///Matches the System.Func<IGadget, bool> delegate type required by the tDoneCallback parameter of IGadget.GadgetUse() /// </summary> ///<param name="gadget">The IGadget calling this method</param> ///<returns>true if successful, false if not</returns> public bool GadgetIsDone(IGadget gadget) { if (gadget != currentGadget) { Debug.LogError("A non-current Gadget called GadgetDone" + "\ncurrentGadget: " + currentGadget.name + "\tcalled by: " + gadget.name); } controlledBy = null; physicsEnabled = true; mode = eMode.idle; return true; } public IGadget controlledBy { get; set; } public bool isControlled { get { return (controlledBy != null); } } [SerializeField] private bool _physicsEnabled = true; public bool physicsEnabled { get { return _physicsEnabled; } set { if (_physicsEnabled != value) { _physicsEnabled = value; colld.enabled = _physicsEnabled; rigid.simulated = _physicsEnabled; } } } #endregion } Add a part to this script where Dray can die
dfe685b8667d6fbfcdcda95e5352489e
{ "intermediate": 0.2995615601539612, "beginner": 0.5940203070640564, "expert": 0.10641808807849884 }
22,299
make me a platformer in python using only the standard library
93acd1b52358f62e0c85525653421ab5
{ "intermediate": 0.7698043584823608, "beginner": 0.15011052787303925, "expert": 0.08008510619401932 }
22,300
How do I make my own color scheme in Firefox?
7458977eb31802fa4d99af86516ec32b
{ "intermediate": 0.45199915766716003, "beginner": 0.23987022042274475, "expert": 0.30813056230545044 }
22,301
function updateVideoTags(sessionLinks, noteLinks) { const sessionIconsContainers = document.querySelectorAll( '.session-icons-container' ); const sessionVideos = document.querySelectorAll('.session-video'); const sessionNotes = document.querySelectorAll('.session-note'); // const videoPlayers = new Array(sessionLinks.length).fill(null); // Array to store YouTube players const notePlayers = new Array(noteLinks.length).fill(null); // Function to create a new YouTube player with a given video ID function createYouTubePlayer(videoId, index) { if (!videoPlayers[index]) { videoPlayers[index] = new YT.Player(`player${index}`, { height: '515', width: '960', videoId: videoId, playerVars: { showinfo: 0, // Hide video title and uploader modestbranding: 1, // Minimal YouTube branding rel: 0, // Hide related videos at the end }, events: { onReady: onPlayerReady, }, }); } } // Function to handle the "onReady" event for the YouTube player function onPlayerReady(event) { // Player is ready, but pause the video immediately event.target.pauseVideo(); } sessionIconsContainers.forEach((container, index) => { const videoLink = container.querySelector('.video-icon'); videoLink.addEventListener('click', function (e) { e.preventDefault(); // Set the YouTube video ID based on the sessionLinks array const videoId = getYouTubeVideoId(sessionLinks[index]); if (videoId) { createYouTubePlayer(videoId, index); } // Toggle the visibility and play/pause of the video const sessionVideo = sessionVideos[index]; if (sessionVideo.style.display === 'block') { sessionVideo.style.display = 'none'; players[index].pauseVideo(); } else { sessionVideo.style.display = 'block'; players[index].playVideo(); } }); const noteLink = container.querySelector('.notes-icon'); noteLink.addEventListener('click', function (e) { e.preventDefault(); const videoId = getYouTubeVideoId(noteLinks[index]); if (videoId) { createYouTubePlayer(videoId, index); } // Toggle the visibility of the notes const sessionNote = sessionNotes[index]; if (sessionNote.style.display === 'block') { sessionNote.style.display = 'none'; } else { sessionNote.style.display = 'block'; } }); }); } <li class="sessions-li"> <div class="session-container"> <span class="session-number">S0</span> <span class="session-title" >Fundamentos de la Energía e Ingeniería de Hábitos</span > </div> <div class="session-icons-container"> <a id="s0-video-href" href="#" data-session-index="0"> <ion-icon class="video-icon" name="videocam-outline"></ion-icon> </a> <a id="s0-note-href" href="#" data-session-index="0" ><ion-icon class="notes-icon" name="document-outline"></ion-icon ></a> <span class="status-icon done">Done</span> </div> </li> <div class="session-video"> <div id="player0"></div> </div> I have an error on this function, the notes part is not working
fc6388d36938ed2d60cd4f06461452cb
{ "intermediate": 0.24590101838111877, "beginner": 0.5957012176513672, "expert": 0.15839779376983643 }
22,302
peux tu me montrer le test unitaire en utilisant "context ("FONCTION RETRAIT - GAGNANT", () => { before(async function() { penduelInstance = await Penduel.new(subId); describe ("Vérifie la fonction withdraw avec le gagnant", () => { it("devrait permettre au gagnant de retirer avec succès", async () => { la fonction : function withdraw(uint256 _gameId, address _currentPlayer, uint256 _amount) public payable { require(_currentPlayer == games[_gameId].player1 || _currentPlayer == games[_gameId].player2, "You re not a player"); require(!(_currentPlayer == games[_gameId].player1 && games[_gameId].player1HasWithdrawn) && !(_currentPlayer == games[_gameId].player2 && games[_gameId].player2HasWithdrawn), "withdrawn balance"); uint256 balance = playerBalances[_gameId][_currentPlayer].balance; require(balance >= _amount, "Insufficient balance"); address winner = games[_gameId].winner; require(_currentPlayer == winner); playerBalances[_gameId][_currentPlayer].balance = balance - _amount; (bool success, ) = payable(_currentPlayer).call{value: _amount}(""); require(success, "The withdrawal failed"); if (_currentPlayer == games[_gameId].player1) { games[_gameId].player1HasWithdrawn = true; } else { games[_gameId].player2HasWithdrawn = true; } emit Withdraw(_gameId); }"
9c5fbba5987db45ddfa78cf11ec3a290
{ "intermediate": 0.43334296345710754, "beginner": 0.37208330631256104, "expert": 0.19457368552684784 }