row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
21,702
I have a table with columnd ID, Data, and Target. ID is identification number of customer. Data contains a list of Merchant Category Codes for purchases that have been made. Each customer has different number of purchases. Morevover, codes are given according to the sequence of purchases. Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Take into account that variable Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use seqential model. As a metric use mapk def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)])
24d3ea1c1fb261d5d7a6a9f8e80985a1
{ "intermediate": 0.38955211639404297, "beginner": 0.2359614074230194, "expert": 0.37448644638061523 }
21,703
Call Frame Instruction op 45 in vendor extension space is not handled on this architecture
08fbb4a2a62955c61263f093c7c737a9
{ "intermediate": 0.4426575303077698, "beginner": 0.25565633177757263, "expert": 0.30168619751930237 }
21,704
I have a table with columns Document Date, Customer Code, SCU Code, Итого отгрузка, л., Отгрузка по акции, л., start_date, end_date, comment, Type. What this function do def find_matching_rows(data): # Filter rows with type ‘Рег. продажи’ and empty comment b_rows = data[(data['Type'] == 'Рег. продажи') & (data['comment'].isnull())] # Iterate over each row matching_rows = [] for index, row in b_rows.iterrows(): # Find matching rows with same customer, SKU, and end_date matched_rows = data[ (data['Customer Code'] == row['Customer Code']) & (data['SCU Code'] == row['SCU Code']) & (data['end_date'] == row['Document Date']) & (data['Type'] == 'Промо продажи') ] if not matched_rows.empty: matching_rows.append(matched_rows) return pd.concat(matching_rows) if matching_rows else None # Return the matched rows as a DataFrame
2894a7a595bff30443bf7f0b8480b61c
{ "intermediate": 0.478107750415802, "beginner": 0.2763400673866272, "expert": 0.24555210769176483 }
21,705
I have a table with columns Document Date, Customer Code, SCU Code, Итого отгрузка, л., Отгрузка по акции, л., start_date, end_date, comment, Type. I have a function def find_matching_rows(data): # Filter rows with type ‘Рег. продажи’ and empty comment b_rows = data[(data[‘Type’] == ‘Рег. продажи’) & (data[‘comment’].isnull())] # Iterate over each row in b_rows matching_rows = [] for index, row in b_rows.iterrows(): # Find matching rows in data with same customer, SKU, and end_date matched_rows = data[ (data[‘Customer Code’] == row[‘Customer Code’]) & (data[‘SCU Code’] == row[‘SCU Code’]) & (data[‘end_date’] == row[‘Document Date’]) & (data[‘Type’] == ‘Промо продажи’) ] if not matched_rows.empty: matching_rows.append(row) # Append the current row from b_rows return pd.DataFrame(matching_rows) if matching_rows else None # Return the matched rows from b_rows as a DataFrame I have a table with 1 million rows. Does any more efficient algorithm exist to get the same result as the function find_matching_rows?
dfa0128ef320dfd3d7d819ae9ae19029
{ "intermediate": 0.34508001804351807, "beginner": 0.12644915282726288, "expert": 0.5284708142280579 }
21,706
we have Playwright Typescript fixtures like below: export const adminTest = baseTest.extend<{}, { workerStorageState: string }>({ storageState: ({ workerStorageState }, use) => use(workerStorageState), workerStorageState: [async ({ browser }, use) => { if (!checkEnvVars()) { adminTest.skip(); } const id = adminTest.info().parallelIndex; const adminFileName = path.resolve(adminTest.info().project.outputDir, `../state/state.admin.${id}.json`); if (fs.existsSync(adminFileName)) { await use(adminFileName); return; } let page = await browser.newPage({ storageState: undefined }); let adminlogin = new LoginPage(page); await adminlogin.loginWithAdminCredentials(); await page.context().storageState({ path: adminFileName }); await use(adminFileName); await page.context().close(); await page.close(); fs.unlinkSync(adminFileName); }, { scope: 'worker' }], }); export const singleProjectUserTest = baseTest.extend<{}, { workerStorageState: string }>({ storageState: ({ workerStorageState }, use) => use(workerStorageState), workerStorageState: [async ({ browser }, use) => { if (!checkEnvVars()) { singleProjectUserTest.skip(); } const id = singleProjectUserTest.info().parallelIndex; const singleProjectUserFileName = path.resolve(singleProjectUserTest.info().project.outputDir, `../state/state.single.project.user.${id}.json`); if (fs.existsSync(singleProjectUserFileName)) { await use(singleProjectUserFileName); return; } let page = await browser.newPage({ storageState: undefined }); let singleProjectUserlogin = new LoginPage(page); await singleProjectUserlogin.loginWithSingleProjectUserCredentials(); await page.context().storageState({ path: singleProjectUserFileName }); await use(singleProjectUserFileName); await page.context().close(); await page.close(); fs.unlinkSync(singleProjectUserFileName); }, { scope: 'worker' }], }); and test file like below: import { adminTest, singleProjectUserTest, adminWorkerStorageState, singleProjectUserWorkerStorageState } from '../fixtures/fixtures'; import { test } from '@playwright/test'; import { AttachmentsPage } from '../pages/attachments.page'; test.describe.configure({ mode: 'serial' }); test('Attachments test for Admin and Single Project User', async ({ browser }) => { // adminContext and all pages inside, including adminPage, are signed in as "admin". const adminContext = await browser.newContext({ storageState: String(adminWorkerStorageState) }); const adminPage = await adminContext.newPage(); // userContext and all pages inside, including userPage, are signed in as "user". const singleProjectUserContext = await browser.newContext({ storageState: String(singleProjectUserWorkerStorageState) }); const singleProjectUserPage = await singleProjectUserContext.newPage(); // ... interact with both adminPage and userPage ... let attachmentsPage = new AttachmentsPage(adminPage); await attachmentsPage.selectProjectB(); await attachmentsPage.nevigateNewRecordPage(); await attachmentsPage.createNewRecord(); await attachmentsPage.navigateToAttachmentPage(); await attachmentsPage.assignAttachmentToMe(); await adminPage.close(); let singleProjectUserAttachmentsPage = new AttachmentsPage(singleProjectUserPage); await singleProjectUserAttachmentsPage.navigateToRecordsPageAsSingleProjectUser(); await singleProjectUserAttachmentsPage.findRecordInRecordsList(); await singleProjectUserAttachmentsPage.navigateToAttachmentPage(); await singleProjectUserAttachmentsPage.verifyAttachmentIsReadOnly(); await singleProjectUserPage.close(); singleProjectUserAttachmentsPage = new AttachmentsPage(singleProjectUserPage); await singleProjectUserAttachmentsPage.navigateToRecordsPageAsSingleProjectUser(); await singleProjectUserAttachmentsPage.findRecordInRecordsList(); await singleProjectUserAttachmentsPage.navigateToAttachmentPage(); await singleProjectUserAttachmentsPage.assignAttachmentToMe(); await singleProjectUserAttachmentsPage.verifyAttachmentIsEditable(); await singleProjectUserAttachmentsPage.verifyAttachmentHistory(); await singleProjectUserPage.close(); await adminContext.close(); await singleProjectUserContext.close(); }); how to inherit test in the scope of test file from both adminTest and singleProjectUserTest fixtures?
ad8f5aea874ed496ba7fd3236c60c5d1
{ "intermediate": 0.4221917390823364, "beginner": 0.4770110845565796, "expert": 0.1007971316576004 }
21,707
I have this code: df = client.depth(symbol=symbol) 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 if (sell_qty > (1 + threshold) > buy_qty) and (sell_price < mark_price - price_threshold): signal.append('sell') elif (buy_qty > (1 + threshold) > sell_qty) and (buy_price > mark_price + price_threshold): signal.append('buy') else: signal.append('') return signal secret_key = API_KEY_BINANCE access_key = API_SECRET_BINANCE lookback = 10080 active_signal = None buy_entry_price = None sell_entry_price = None import binance def calculate_percentage_difference_buy(entry_price, exit_price): result = exit_price - entry_price price_result = entry_price / 100 final_result = result / price_result result = final_result * 50 return result def calculate_percentage_difference_sell(sell_entry_price, sell_exit_price): percentage_difference = sell_entry_price - sell_exit_price price_result = sell_entry_price / 100 # price result = 1% price_percent_difference = percentage_difference / price_result result = price_percent_difference * 50 return result while True: if df is not None: quantity = bch_amount_rounded 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}") # Execute Buy orders here 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.") 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}") # Execute sell orders here 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.") time.sleep(1)
fbfb2c4f4437f7dba4fe18122a288213
{ "intermediate": 0.3786001205444336, "beginner": 0.36562612652778625, "expert": 0.25577375292778015 }
21,708
in pyhton, why we have sometime only import and some other ime, from and import ?
108ec9282ff6d64d3adc2774c2f4da01
{ "intermediate": 0.5278002023696899, "beginner": 0.20765794813632965, "expert": 0.2645418345928192 }
21,709
namt <- ifelse(nrow(sub_trt2)>group, sapply(unique(sub_trt2$ananum), function(x) sum(sub_trt2$ananum == x)), sapply(nrow(sub_trt2), function(x), 1)) how to fix this code
9b30678885f554310b6576546bf59c4c
{ "intermediate": 0.3394838571548462, "beginner": 0.44726160168647766, "expert": 0.21325455605983734 }
21,710
The velocity of a freely falling object near the Earth's surface is described by the equation: dv/dt = -g. where v is the velocity and g = 9.8 m/s^2 is the acceleration due to gravity. Write a MatLab program that employs the Euler method to compute the solution to the freely falling object. That is, calculate v as a function of time. Consider different starting velocities over a time range from t=0 to t=10 s. Repeat the calculation for several different values of the time step, and compare the results with the exact solution. It turns out that for this problem the Euler method is exact. Verify this by comparing your numerical solution to the exact solution within your program. Plot your results.
cfbfcef3c5e036d6ea9f897c74426712
{ "intermediate": 0.3902621269226074, "beginner": 0.20231567323207855, "expert": 0.4074222147464752 }
21,711
Can you code a c program that with n input, for example with input = 3 would print 33333 32223 32123 32223 33333
f559728c375541c8c0efbb6db4793363
{ "intermediate": 0.1758224070072174, "beginner": 0.4615969955921173, "expert": 0.3625805675983429 }
21,712
I used this code: df = client.depth(symbol=symbol) 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 if (sell_qty > (1 + threshold) > buy_qty) and (sell_price < mark_price - price_threshold): signal.append('sell') elif (buy_qty > (1 + threshold) > sell_qty) and (buy_price > mark_price + price_threshold): signal.append('buy') else: signal.append('') return signal secret_key = API_KEY_BINANCE access_key = API_SECRET_BINANCE lookback = 10080 active_signal = None buy_entry_price = None sell_entry_price = None import binance def calculate_percentage_difference_buy(entry_price, exit_price): result = exit_price - entry_price price_result = entry_price / 100 final_result = result / price_result result = final_result * 50 return result def calculate_percentage_difference_sell(sell_entry_price, sell_exit_price): percentage_difference = sell_entry_price - sell_exit_price price_result = sell_entry_price / 100 # price result = 1% price_percent_difference = percentage_difference / price_result result = price_percent_difference * 50 return result while True: if df is not None: quantity = bch_amount_rounded 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}") # Execute Buy orders here 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.") if 'buy' in signals: active_signal = 'buy' buy_entry_price = mark_price # Record the Buy entry price print(f"Buy Entry Price: {buy_entry_price}") # Execute Buy orders here while True: # Retrieve depth data every second 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_qty executed_orders = order_price == mark_price # Check executed order quantity based on order price and mark price for buy_price in executed_orders: order_price = buy_price if order_price == mark_price: executed_orders_qty += buy_qty # 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 # Calculate the result if result < sell_qty: print("Long !!! EXIT !!!") 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.") # Print israel when condition is met time.sleep(1) # Wait for 1 second before checking again 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}") # Execute sell orders here 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.") 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 196, in <module> for buy_price in executed_orders: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'bool' object is not iterable
8b331c57ba8a7f2fa7fe0c3c439adb92
{ "intermediate": 0.37616947293281555, "beginner": 0.3699476718902588, "expert": 0.25388291478157043 }
21,713
Hi, I would like to prepare a printable professional diary, propose the necessary sections and the general design, you can make a sketchy table of the sections and the design
b8ba1e9827bf9348bc60df6a3770e973
{ "intermediate": 0.40154874324798584, "beginner": 0.16117456555366516, "expert": 0.437276691198349 }
21,714
I have a table with columnd ID, Data, and Target. ID is identification number of customer. Data contains a list of Merchant Category Codes for purchases that have been made.Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. If Target contains more that 10 codes limit they by 10. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)])
f7e5d505032313ef294f8613a12f707f
{ "intermediate": 0.39396122097969055, "beginner": 0.2573036551475525, "expert": 0.34873509407043457 }
21,715
The velocity of a freely falling object near the Earth's surface is described by the equation: dv/dt = −𝑔 , where 𝑣 is the velocity and 𝑔 = 9.8 𝑚/𝑠^2 is the acceleration due to gravity. Write a program that employs the Euler method to compute the solution to the freely falling object. That is, calculate 𝑣 as a function of time. Consider different starting velocities over a time range from 𝑡 = 0 to 𝑡 = 10 s. Repeat the calculation for several different values of the time step, and compare the results with the exact solution. It turns out that for this problem the Euler method is exact. Verify this by comparing your numerical solution to the exact solution within your program. Plot your results and upload your MATLAB script that does this calculation.
4f4a3fcb0f3fc51c3e8b61b9511e55dc
{ "intermediate": 0.3726286292076111, "beginner": 0.17860694229602814, "expert": 0.44876447319984436 }
21,716
const callback = (response) => { // This callback will be triggered when the user selects or login to // his Google account from the popup console.log("Handle the response", response); }; how to convert the above function to a function of methods in vue 3 project
d092f4df2a2df78a4d3f483e840364ec
{ "intermediate": 0.4970830976963043, "beginner": 0.4024600386619568, "expert": 0.10045690089464188 }
21,717
what is happening in the code below: string numFile = argv[1]; string outFile = argv[2];
7b4524f2f67f7dd17fa415c0068d61b8
{ "intermediate": 0.3064228296279907, "beginner": 0.5184590220451355, "expert": 0.17511814832687378 }
21,718
how to read json file in python
560d7b5758f1a97b08b141b2c9aaaf58
{ "intermediate": 0.5537241697311401, "beginner": 0.2097058892250061, "expert": 0.23656998574733734 }
21,719
how to do a jest test mock for /* eslint-disable react/function-component-definition */ import * as React from 'react'; import { ForbiddenError, BadRequestError, UnauthorizedError, PageNotFoundError, InternalServerError, BadGatewayError, ServiceUnavailableError, GatewayTimeoutError, } from 'presentation/components/ErrorPage/ErrorImages'; export type ErrorImageProps = { errorCode?: string }; export const ErrorImage: React.FC<ErrorImageProps> = ({ errorCode }) => { switch (errorCode) { case '400': return BadRequestError; case '401': return UnauthorizedError; case '403': return ForbiddenError; case '404': return PageNotFoundError; case '500': return InternalServerError; case '502': return BadGatewayError; case '503': return ServiceUnavailableError; case '504': return GatewayTimeoutError; default: return <div data-testid="NoMatchingImage">No Matching Image</div>; } };
d9f91958b4b8fa7de907bfbba2820121
{ "intermediate": 0.41990694403648376, "beginner": 0.37994563579559326, "expert": 0.20014740526676178 }
21,720
Please check my code below for errors: ofstream numFile; numFile.open("numbers.dat");
713e0e6d72cc3722836d6430bb9c2217
{ "intermediate": 0.40368735790252686, "beginner": 0.33857953548431396, "expert": 0.25773313641548157 }
21,721
I need my text and button to be separated by 8dp. My code displays acceptable enough result" <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingStart="16dp" android:paddingTop="19dp" android:paddingEnd="12dp" android:paddingBottom="18dp"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/settings_share" android:textColor="@color/screen2_font_black" /> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:background="@color/white" android:src="@drawable/share" /> </LinearLayout>" but the fact that the markup on Figma has these 8dp colored as a red field as opposed to blue used for different padding bothers me. Based on android studio code for different screens that I say I think this red field corresponds to app:iconPadding. Can I use iconPadding in ImageButton? Is there something similar I can use instead to guarantee that my button and my text have 8dp between them?
7c24b4662138a911df8e98a9dfafbb13
{ "intermediate": 0.61696457862854, "beginner": 0.21037925779819489, "expert": 0.17265614867210388 }
21,722
waht is __get__ in python
33255147e186df933e684a1b299df084
{ "intermediate": 0.33877629041671753, "beginner": 0.288899689912796, "expert": 0.37232401967048645 }
21,723
how to do the following in jest using typescript global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(mockFetch), }) );
6c3e9b4e8bfa522968dd263980075d0c
{ "intermediate": 0.34442001581192017, "beginner": 0.5352582931518555, "expert": 0.12032175064086914 }
21,724
the following questions are about C++
5182dad9803014c59f38537da59251d3
{ "intermediate": 0.356260746717453, "beginner": 0.5033671259880066, "expert": 0.14037209749221802 }
21,725
use svm to classify X_train_vectors_tfidf, y_train
065c49e8bd4fc246df4136541c3bd884
{ "intermediate": 0.16622518002986908, "beginner": 0.08910303562879562, "expert": 0.7446717619895935 }
21,726
How do I solve this problem?: org.hibernate.type.descriptor.java.spi.JdbcTypeRecommendationException: Could not determine recommended JdbcType for Java type 'com.mycompany.myapp.Watermelon' Watermelon.java: package com.mycompany.myapp; import jakarta.persistence.Basic; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.OneToOne; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.type.SqlTypes; import java.time.LocalDateTime; @Entity public class Watermelon { @Id @GeneratedValue(strategy = GenerationType.UUID) private Watermelon watermelon; private double purchasePrice; @Basic private LocalDateTime purchaseTimestamp; @OneToOne @JoinColumn(name="basketUuid") private Basket basket; @Override public String toString() { return "Watermelon{" + "watermelon='" + watermelon + '\'' + ", purchasePrice=" + purchasePrice + ", purchaseTimestamp=" + purchaseTimestamp + ", basket=" + basket + '}'; } public Watermelon() { // this(0.0, LocalDateTime.now()); } public Watermelon(double purchasePrice, LocalDateTime purchaseTimestamp) { this.purchasePrice = purchasePrice; this.purchaseTimestamp = purchaseTimestamp; } public Basket getBasket() { return basket; } public void setBasket(Basket basket) { this.basket = basket; } public Watermelon getWatermelon() { return watermelon; } public void setWatermelon(Watermelon watermelon) { this.watermelon = watermelon; } public double getPurchasePrice() { return purchasePrice; } public void setPurchasePrice(double purchasePrice) { this.purchasePrice = purchasePrice; } public LocalDateTime getPurchaseTimestamp() { return purchaseTimestamp; } public void setPurchaseTimestamp(LocalDateTime purchaseTimestamp) { this.purchaseTimestamp = purchaseTimestamp; } }
d59eebce4a6501ceebcf7efab98f663c
{ "intermediate": 0.3122155964374542, "beginner": 0.5596425533294678, "expert": 0.128141850233078 }
21,727
public async Task<ActionResult<String>> DoesMenuAuthorityExist(string username) { var authorities = await _dbContext.Users .Where(a => a.Username == username) .Select(a => a.Authority.AuthorityName) .FirstAsync(); return Ok(authorities); } is this correct?
0568099a38e85a0cbf60bbfd212de89f
{ "intermediate": 0.4615546464920044, "beginner": 0.3893235921859741, "expert": 0.14912180602550507 }
21,728
make a regexp to match strings that contain ips and ports
70e6aaf038daf52307b004641dac8d2c
{ "intermediate": 0.30676937103271484, "beginner": 0.22216494381427765, "expert": 0.4710656404495239 }
21,729
Write me a simple CODEsys code.
a2505ed68b0b10cd7043708faf270d76
{ "intermediate": 0.17433364689350128, "beginner": 0.5669138431549072, "expert": 0.2587524354457855 }
21,730
Напиши программу на Python которая будет выполнять следующие действия: Получить Dataset (данные). Сгенерировать численные данные с помощью генератора случайных чисел. Числа – целые, диапазон: от -10000 до 10000; количество чисел – 1000. Сформировать объект Series. Рассчитать стандартные числовые характеристики для набора данных Series - определить минимальное значений - определить количество повторяющихся значений - определить максимальное значение - определить сумму чисел - определить среднеквадратическое отклонение Результирующие данные вывести в консоль с пояснениями. При выполнении данного задания можно использовать все стандартные функции Python. Визуализировать данные с помощью стандартных библиотек по заданным критериям - построить линейный график - построить гистограмму (прямоугольную), округлив значения набора данных до сотен. Округление выполнить по математическому правилу. Сформировать Dataframe из данных Series и добавить к этим данным следующие столбцы - столбец, содержащий отсортированные значения исходного Series по возрастанию - столбец, содержащий отсортированные значения исходного Series по убыванию Визуализировать данные, полученные в результате промежуточного анализа (вычислений) - на одном plt построить два линейных графика: отсортированных значений по возрастанию и убыванию
2f6b670fde49b79712a621394aa3ca36
{ "intermediate": 0.19896450638771057, "beginner": 0.538699209690094, "expert": 0.26233628392219543 }
21,731
Write a program to create an array of GeometricObject  Create instances, let some of elements of the array are Circle and the others are Rectangle  Write a loop to sum up the total area of all elements of the array  Some example code: GeometricObject[] objects = new GeometricObject[10]; objects[0] = new Circle(); objects[1] = new Rectangle(); ... totalArea += objects[i].getArea();
23cb847f11cb502d2000f343fc8c8709
{ "intermediate": 0.21066077053546906, "beginner": 0.6608483195304871, "expert": 0.1284908801317215 }
21,732
write an android app in Kotlin that can turns on my flashlight
9fadf1f19ebc28bc551ccbe2cd3923fe
{ "intermediate": 0.5397284030914307, "beginner": 0.16730712354183197, "expert": 0.29296448826789856 }
21,733
how to fix below code : dat <-list() for (i in 1:group) { dat[[i]] <- sim( ode = pk1, parameters = p[[i]], regimen = r[[i]], n_ind=3, only_obs=TRUE,## only output concentration## t_obs=ACTHOUR )%>% rename(ACTHOUR=t)%>% mutate( trtpn=i ) %>% mutate(conc=format(y,scientific = FALSE)*100000)%>% mutate(min_random = 0,max_random = 0.2)%>% mutate(random_value = runif(1, min_random, max_random))%>% ### randomization logic need to update mutate(y1=y+ random_value) ##this section need to double confirmed }
106a2597f0d800da5a5d1642596014b4
{ "intermediate": 0.3564905524253845, "beginner": 0.32440420985221863, "expert": 0.31910526752471924 }
21,734
Hello, how to fix this problem on Wpf App (.Net Framework) on C# System.Windows.Data Error: 7 : ConvertBack cannot convert value 'gg' (type 'String'). BindingExpression:Path=IsDone; DataItem='TodoModel' (HashCode=47528147); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Строка не распознана как действительное логическое значение.
b8a6fceca2de43aeb7817e3ed545b855
{ "intermediate": 0.87783282995224, "beginner": 0.08370599150657654, "expert": 0.03846118226647377 }
21,735
Give a very short explanation and example of .dump() and .dumps()
571299705d538a92adf2d72da93cdaa8
{ "intermediate": 0.602973997592926, "beginner": 0.06790170818567276, "expert": 0.3291242718696594 }
21,736
which mail we have for advertising ?
32fe90c9a02c162060ca03e69e8d8f6b
{ "intermediate": 0.3676535189151764, "beginner": 0.3607024550437927, "expert": 0.2716439962387085 }
21,737
I'm supposed to review an Angular 11 project for security adherence at project code level. Can you tell me what all I can check and which file I need to check for it
92bdf60197ea94f03d924b0e05140258
{ "intermediate": 0.4614325761795044, "beginner": 0.3069165050983429, "expert": 0.2316509336233139 }
21,738
amt <- list() # Initialize amt > for (i in 1:max(sub_trt2$trtpn)) { + amt_tmp <- c() # Initialize amt_tmp + for (j in 1:nrow(sub_trt2)) { + if (is.na(namt[i]) | namt[i] == 1) { + amt_tmp <- c(rep(sub_trt2$dose[j], sub_trt2$No_TRT[j])) ## no dose changed for one subject + } + else if (namt[i] != 1 && namt[i] > j && namt[i] == 2) { + amt_tmp <- c(rep(sub_trt2$dose[j], sub_trt2$No_TRT[j]), + rep(sub_trt2$dose[j+1], sub_trt2$No_TRT[j+1])) + } else if (namt[i] != 1 && namt[i] > j && namt[i] == 3) { + amt_tmp <- c(rep(sub_trt2$dose[j], sub_trt2$No_TRT[j]), + rep(sub_trt2$dose[j+1], sub_trt2$No_TRT[j+1]), + rep(sub_trt2$dose[j+2], sub_trt2$No_TRT[j+2])) + } else if (namt[i] != 1 && namt[i] == j && i >= 2 && namt[i] == 2 && (nrow(sub_trt2) - j + 2 <= nrow(sub_trt2))) { + amt_tmp <- c(rep(sub_trt2$dose[nrow(sub_trt2)-j+1], sub_trt2$No_TRT[nrow(sub_trt2)-j+1]), + rep(sub_trt2$dose[nrow(sub_trt2)-j+2], sub_trt2$No_TRT[nrow(sub_trt2)-j+2])) + } else if (namt[i] != 1 && namt[i] == j && i >= 2 && namt[i] == 3 && (nrow(sub_trt2) - j + 3 <= nrow(sub_trt2))) { + amt_tmp <- c(rep(sub_trt2$dose[nrow(sub_trt2)-j+1], sub_trt2$No_TRT[nrow(sub_trt2)-j+1]), + rep(sub_trt2$dose[nrow(sub_trt2)-j+2], sub_trt2$No_TRT[nrow(sub_trt2)-j+2]), + rep(sub_trt2$dose[nrow(sub_trt2)-j+3], sub_trt2$No_TRT[nrow(sub_trt2)-j+3])) + } + } + } > amt[[i]] <- amt_tmp > amt[[1]] NULL why a null value exits
4e3025234986ed7a35456c0391a9e132
{ "intermediate": 0.3387084901332855, "beginner": 0.4206419289112091, "expert": 0.2406495064496994 }
21,739
I have a table with columnd ID, Data, and Target. ID is identification number of customer. Data contains a list of Merchant Category Codes for purchases that have been made.Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. If Target contains more that 10 codes limit they by 10. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) See an example ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,66622]|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,66622]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478]
c15f4ecf1830bd363c4472d4b0f0391e
{ "intermediate": 0.3487880825996399, "beginner": 0.23649324476718903, "expert": 0.4147185981273651 }
21,740
sub_trt3$trtpn <-ifelse (all(sub_trt3$order==1),cumsum(n_distinct(sub_trt3$Dose_Amount) ),sub_trt3$pnum) how to fix this code to achieve if Dose_Amount <- (300,300,300,100,100,100,300,300,300) trtpn <-(1,1,1,2,2,2,1,1,1)
ade78299257a2c378d28bf14dbe5eb8d
{ "intermediate": 0.3717744052410126, "beginner": 0.34716537594795227, "expert": 0.28106024861335754 }
21,741
Static and Dynamic Linking in Operating Systems C++ example code
ddfb109b6be1c9721de9c5aec78173fb
{ "intermediate": 0.3862651586532593, "beginner": 0.2933645248413086, "expert": 0.32037025690078735 }
21,742
I have a table with columnd ID, Data, and Target. ID is identification number of customer. Data contains a list of Merchant Category Codes for purchases that have been made.Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. If Target contains more that 10 codes limit they by 10. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) See an example ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,66622]|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,66622]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478] Note that the model should predict MCC codes, not probabilities!
de07eeecf3c5327e234d7f46122a3f0b
{ "intermediate": 0.3639281094074249, "beginner": 0.21643930673599243, "expert": 0.41963255405426025 }
21,743
#include <iostream> using namespace std; int main(){ int n; cin >> n; for (int i=1;i<=2n-1;i++) { int t= static_cast<int>(2i - 3); if (i<=n){ for (int m=n-i;0<m;m--) cout << ' '; for (int j=1;j<=2t-1;j+=2) cout << '*'; cout << endl;} else if (i>n){ for (int w=1;w<n-1;n++) cout << ' '; for (int h=2t-3;h>0;h-=2) cout << '*'; cout << endl; } } return 0; }哪里有错
716e5704a765b155e7c35e6496ad2621
{ "intermediate": 0.3487105667591095, "beginner": 0.42507073283195496, "expert": 0.22621871531009674 }
21,744
Есть такая анимация val path2 = Path().apply { arcTo( -view1Location[0].toFloat(), -view2Location[1].toFloat(), view1Location[0].toFloat(), view2Location[1].toFloat(), -0f, 90f, false ) } val positionAnimator = ObjectAnimator.ofFloat(view3, View.X, View.Y, path2).apply { duration = 2000 start() } И получается что view3 летит от view1 до view2. Как изменить это? Чтобы он летел от view1 до view2. Как то заинвертить path или еще что то такое
fef37416c92b1e566c7cd17be80b807f
{ "intermediate": 0.36304357647895813, "beginner": 0.40671205520629883, "expert": 0.23024435341358185 }
21,745
why this is wrong? var materialStatus = await _dbContext.MaterialTransferSummaries .Where(m=>m.Status == 0 || m.Status == 1) .Select(mts => new { mts.SummaryMaterialTransfer, mts.TicketNo, Package = mts.Package.PackageName, Material = mts.Material.MaterialTypeName, SourceLocation = mts.Route.SourceLocationNavigation.LocationName, DestinationLocation = mts.Route.DestinationLocationNavigation.LocationName, mts.Requestor, Status = (mts.Status == 0) ? "Open" : (mts.Status == 1) ? "In Progress" : (mts.Status == 2) ? "Completed" : null, CreatedDate = mts.CreatedDate != null ? mts.CreatedDate.Value.ToString("dd/MM/yyyy HH:mm:ss") : "", mts.RouteId, authStatus = await _dbContext.RouteDetails .Where(r => r.RouteSummaryId == RouteId && r.Sequence == 1) .Select(r => r.RouteLocationNavigation.LocationId) .FirstOrDefaultAsync() }) .ToListAsync();
925d76176a6370a86ca17341c90bc5af
{ "intermediate": 0.42089933156967163, "beginner": 0.340938538312912, "expert": 0.23816213011741638 }
21,746
sub_visit1 <- sub_visit %>% group_by( Subject_ID, Visit, next_visit, ananum, Analyte, trtpn ) %>% summarise(pnum = n()) %>% ungroup() %>% mutate(grouping = ifelse(pnum > 1, “Group1”, “Group2”)) %>% group_by(Subject_ID, Visit, next_visit, ananum, Analyte, trtpn, grouping) %>% summarise(num = list(seq(Visit, next_visit))) %>% unnest(num) %>% ungroup() %>% mutate( Visit = num, Analyte = ifelse(grouping == “Group1”, Analyte, NA), trtpn = ifelse(grouping == “Group1”, trtpn, trtpn) ) %>% select( Subject_ID, Visit, ananum, Analyte, trtpn ) %>% rename(Visit = num) how to fix this code
58c78805b42c8ac06315854e9c37d9f2
{ "intermediate": 0.34980714321136475, "beginner": 0.3718201518058777, "expert": 0.27837270498275757 }
21,747
sub_visit1<-sub_visit %>% group_by(Subject_ID,Visit,next_visit,ananum,Analyte,trtpn) %>% summarise(num=list(seq(Visit,next_visit))) %>% unnest(num) %>% ungroup()%>% select(Subject_ID,num,ananum,Analyte,trtpn) %>% rename(Visit=num) how to fix this code add logic if pnum>1 then group_by(Subject_ID,Visit,next_visit,ananum,Analyte,trtpn) else group_by(Subject_ID,Visit,next_visit,ananum,Analyte,trtpn)
3a12a41cfe810cb34245be63c060797f
{ "intermediate": 0.3432765603065491, "beginner": 0.4428916275501251, "expert": 0.2138317972421646 }
21,748
I have a table with columnd ID, Data, and Target. See an example ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,66622]|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,6662]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478] ID is identification number of customer. Data contains a list of consecutive Merchant Category Codes for purchases that have been made.Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) Note that the model should predict MCC codes, not probabilities! After training model, I need to load new Data to get Target values that are 10 MCC codes. If I unclear describe this, ask questions
4826106de4e227cff61ed296565e87cd
{ "intermediate": 0.3899398148059845, "beginner": 0.2910504639148712, "expert": 0.3190096914768219 }
21,749
je veux tester " require(state == State.firstLetter, "no first letter"); " l'extrait de la fonction : "function proposeLetter(string memory _letterToGuess, string memory _wordToGuess) public { gameId = getGameId(); require(state == State.firstLetter, "no first letter"); require(state == State.firstLetter, "no first letter");" cependant j'ai une erreur sur le premier require " require(state == State.firstLetter, "no first letter");" " Error: VM Exception while processing transaction: revert Bad ID -- Reason given: Bad ID" alors que j'ai défini "gameId" dans le test. le test : " it("devrait rejeter si l'état n'est pas firstLetter", async () => { const gameId = 1; const letterToGuess = "i"; const wordToGuess = "immuable"; const initialState = await penduelInstance.state(); assert.equal(initialState, 0, "L'état initial devrait être gameCreated"); await penduelInstance.proposeLetter(letterToGuess, wordToGuess); await expectRevert( penduelInstance.proposeLetter("I", "IMMUABLE", { from: player1, gameId }), "no first letter" ); });" ou est l"erreur ?
e74c6a3baedf473f1e1ee08e2715cb54
{ "intermediate": 0.45607873797416687, "beginner": 0.4271668493747711, "expert": 0.11675437539815903 }
21,750
import cv2 def var_abs_laplacian(image): kernelSize = 3 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) sobel = cv2.sobel(gray, cv2.CV_64F, ksize=kernelSize) sobel_square = sobel * sobel measure = sobel_square.sum() return measure if __name__ == '__main__': # Read input video filename filename = r'focus-test.mp4' # Create a VideoCapture object cap = cv2.imread(filename) # Read first frame from the video ret, frame = cap.read() # Display total number of frames in the video print("Total number of frames : {}".format(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))) # Max measure of focus maxV = 0 # Frame with maximum measure of focus bestFrame = 0 # Frame ID of frame with maximum measure of focus bestFrameId = 0 # Get measures of focus from both methods val = var_abs_laplacian(frame) # Specify the ROI for the flower in the frame top = 50 bottom = 150 left = 200 right = 300 # Iterate over all the frames present in the video while(ret): # Crop the flower region out of the frame flower = frame[top:bottom, left:right] # Get measures of focus val = var_abs_laplacian(frame) # If the current measure of focus is greater than the current maximum if val > maxV: # Revise the current maximum maxV = val # Get frame ID of the new best frame bestFrameId = int(cap.get(cv2.CAP_PROP_POS_FRAMES)) # Revise the new best frame bestFrame = frame.copy() # Read a new frame ret, frame = cap.read() print("================================================") print("Frame ID of the best frame: {}".format(bestFrameId)) cap.release() cv2.namedWindow("Best Frame", cv2.WINDOW_AUTOSIZE) cv2.imshow("Best Frame", bestFrame) cv2.waitKey()上述代码运行时出现错误Traceback (most recent call last): File "D:\pycharm\opencv\test1.py", line 21, in <module> ret, frame = cap.read() AttributeError: 'NoneType' object has no attribute 'read'怎么解决
2c92666b1d3b5bab970cabde9853e991
{ "intermediate": 0.35400521755218506, "beginner": 0.48736506700515747, "expert": 0.15862973034381866 }
21,751
Error in render: "TypeError: Cannot read properties of null (reading 'map')" const units = ref<StatReport[]>([]) onMounted(async() => { const res = await reportUnits() units.value = res.result.reports }) const formatedUnits = computed(() => { return unref(units).map((unit) => { const additional = { cpuUsagePercent: parseFloat(unit.cpuUsagePercent).toFixed(2) } return { ...unit, ...additional } }) }) как решить ошибку?
f7a4b324fd6ec5d4ab942582fdff3a6d
{ "intermediate": 0.49058541655540466, "beginner": 0.32076123356819153, "expert": 0.18865327537059784 }
21,752
I need to learn about Control Flow and Conditionals • Learn about if-else statements and switch statements.
ab52b7e775623472d209dc679fcbe3ae
{ "intermediate": 0.38843804597854614, "beginner": 0.3927296996116638, "expert": 0.21883223950862885 }
21,753
I have a table with columnd ID, Data, and Target. See an example ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,6622]|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,6662]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478] 3|[6688,6669,6662,5541,5541,6623,7451,5541,6623,7451,2545,7711,7711,8985,8865]|[5541,5541,1478,6125,5541,5541,6125,5541,5541,4125] ID is identification number of customer. Data contains a list of consecutive Merchant Category Codes for purchases that have been made. Merchant Category Codes always have four digits. Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) Note that the model should predict MCC codes, not probabilities! After training model, I need to load new Data to get Target values that are 10 MCC codes. ID|Data 1|[5541,5541,6623,7451,2545,5541,5541,6623] 2|[5541,5541,6623,7451,2545,6688,6669,6622,7451,5541,6623,7451,2545,6688,6669,6662] 3|[6688,6669,5541,6623,7451,5541,6623,7451,2545,7711,8865] If I unclear describe this, ask questions
63afbf3bc65708a40ce65ba5240e9ef8
{ "intermediate": 0.4013029932975769, "beginner": 0.1992269903421402, "expert": 0.3994700610637665 }
21,754
Please convert this patternt for grok processor elasticsearch: %{SYSLOGTIMESTAMP:syslog_timestamp} %{IPORHOST:syslog_server} %{SYSLOGPROG}: %{IP:client_ip}:%{INT:client_port} \[%{HAPROXYDATE:accept_date}\] %{NOTSPACE:frontend_name} %{NOTSPACE:backend_name}/%{NOTSPACE:server_name} %{INT:time_request}/%{INT:time_queue}/%{INT:time_backend_connect}/%{INT:time_backend_response}/%{NOTSPACE:time_duration} %{INT:http_status_code} %{NOTSPACE:bytes_read} %{DATA:captured_request_cookie} %{DATA:captured_response_cookie} %{NOTSPACE:termination_state} %{INT:actconn}/%{INT:feconn}/%{INT:beconn}/%{INT:srvconn}/%{NOTSPACE:retries} %{INT:srv_queue}/%{INT:backend_queue} {%{DATA:request_header_x_forwarded_for}\|%{DATA:request_header_user_agent}\|%{DATA:request_header_referer}} "%{WORD:http_verb} %{URIPATHPARAM:http_request}( HTTP/%{NUMBER:http_version}")?
446f3add0bde7c2bbf5f8a2e28ee2d3b
{ "intermediate": 0.3753577470779419, "beginner": 0.3736453056335449, "expert": 0.25099700689315796 }
21,755
function setRandomColors(){ cols.forEach((col) => { const text = col.querySelectorAll('h2'); const color = generateRandomColor(); //col.style.background = generateRandomColor(); text.textContent = color; col.style.background = color; }) } Почему текст не менятеся на странице? html: <h2>Text</h2> <button><i class="fa fa-lock" aria-hidden="true"></i> <!-- <i class="fa fa-unlock" aria-hidden="true"></i> --> </button>
c78b2dd8c15155c9bb31da76d85d00ad
{ "intermediate": 0.3868424892425537, "beginner": 0.4414047300815582, "expert": 0.17175275087356567 }
21,756
I have a table with columnd ID, Data, and Target. See an example of first three rows ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,6622,5541,6623,7451,2545,6688,6669,6622|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,666251,5541,6623,7451]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478] 3|[6688,6669,6662,5541,5541,6623,7451,5541,6623,7451,2545,7711,7711,8985,8865]|[5541,5541,1478,6125,5541,5541,6125,5541,5541,4125] ID is identification number of customer. Data contains a list of consecutive Merchant Category Codes for purchases that have been made. Merchant Category Codes always have four digits. Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use mapk as a measure def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) The goal is to maximize mapk. Note that the model should predict MCC codes, not probabilities! After training model, I need to load new Data to get Target values that are 10 MCC codes. Here is the example of first three rows ID|Data 1|[5541,5541,6623,7451,2545,5541,5541,6623] 2|[5541,5541,6623,7451,2545,6688,6669,6622,7451,5541,6623,7451,2545,6688,6669,6662] 3|[6688,6669,5541,6623,7451,5541,6623,7451,2545,7711,8865] If I unclear describe this, ask questions. The order of MCC codes matter
e2a4dffacf6f245d22d1628f1cc46c9a
{ "intermediate": 0.398496150970459, "beginner": 0.21487262845039368, "expert": 0.38663119077682495 }
21,757
Create a data frame with Column, ID, Target, where ID and Target conatin lists
287f370e722aca0b9dcde380fb80a40e
{ "intermediate": 0.5399168133735657, "beginner": 0.1330483853816986, "expert": 0.3270348012447357 }
21,758
mongodb vs postgres write speed
f911f86953c11734c0f83e3d465398a8
{ "intermediate": 0.4004881978034973, "beginner": 0.3401623070240021, "expert": 0.2593494653701782 }
21,759
I have a table with columns ID, Data, and Target. See an example of first three rows data = { ‘ID’: [1, 2, 3], ‘Data: [[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,6622,5541,6623,7451,2545,6688,6669,6622], [5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,666251,5541,6623,7451], [6688,6669,6662,5541,5541,6623,7451,5541,6623,7451,2545,7711,7711,8985,8865]], ‘Target’: [[4125,5541,5541,4125,5541,5541,4125,5541,5541,1471], [6125,5541,5541,6125,5541,5541,4125,5541,5541,1478], [5541,5541,1478,6125,5541,5541,6125,5541,5541,4125]] } Predict Target based on Data. The order of codes matters. Write Python script
e942fcce855719dfd6f941a53362e551
{ "intermediate": 0.3587086498737335, "beginner": 0.2129218578338623, "expert": 0.42836952209472656 }
21,760
Hi, I have a winforms application and use Telerik UI for Winforms for formattering text to html-format. I want to use the code below to set the styling properties for new tables by default to 100% width. I have to set up events that fire at inserting tables, but I do not understand how I can achieve this. Do you have any suggestions? private void Editor_CommandExecuted(object sender, CommandExecutedEventArgs e) { if (e.Command is InsertTableCommand || e.Command is ShowInsertTableDialogCommand) { Table table = Editor.Document.CaretPosition.GetCurrentTableBox()?.AssociatedTable; if (table != null) { table.PreferredWidth = new TableWidthUnit(TableWidthUnitType.Percent, 100); } } }
640a00dfd6c9c2649ae6d66845175ff0
{ "intermediate": 0.5393311977386475, "beginner": 0.29321661591529846, "expert": 0.16745220124721527 }
21,761
исправь код php и сделай так что-бы при успешной оплате статус автоматический менялся с pending на c succeeded и дай запрос на крон раз в минуту, если оплата прошла и статус поменялся на succeeded то оповещения перестают приходить об успешной оплате, вот php code <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); include_once('base.php'); include_once('Watbot.php'); if (!function_exists('array_key_first')) { function array_key_first(array $arr) { foreach ($arr as $key => $unused) { return $key; } return null; } } $yoo = new Yookassa($conn); if (isset($_GET['amount'], $_GET['u_id'])) { $amount = intval($_GET['amount']); echo $yoo->createPayment($amount, $_GET['u_id']); } elseif (isset($_GET['cancel_payment'])) { $paymentId = intval($_GET['cancel_payment']); echo $yoo->cancelPayment($paymentId . '/cancellations'); } // список платежей 5555 5555 5555 4477 https://kashtan-yalta.ru/pay/yookassa.php?count=1 $yoo->getPayments(); ///print_r($yoo->getIdStatus('2ca03d28-000f-5000-9000-1f24b752e530')); if (filter_has_var(INPUT_GET, 'check')) { // print_r($watbot->getContactIdByTelegram(5191807577)); // $res = getContactIdByTelegramBotId('65aza7U3HU8NXFPxvV5l8XbALiFxyeUtHCThOdPcGPfPujYHEWxqtrAZQ41E', 5191807577); //$resss = removeTagtoContact('65aza7U3HU8NXFPxvV5l8XbALiFxyeUtHCThOdPcGPfPujYHEWxqtrAZQ41E', $res['id'], 'Активная подписка Голограма.Net'); ///$watbot->attachTagToContact(1254438, 'Активная подписка Голограма.Net', true); if (!empty($ids)) { $in = str_repeat('?,', count($ids) - 1) . '?'; $sql = "UPDATE pay SET pay_status = 'succeeded' WHERE tg_id IN ($ids)"; $stm = $this->db->prepare($sql); return $stm->execute($ids); $watbot = new Watbot(); foreach ($ids as $tg_id) { // по api получаем id контакта в watbot $resWatbot = $watbot->getContactIdByTelegram($tg_id); if (!empty($resWatbot['id'])) { // присваиваем тег $watbot->attachTagToContact($resWatbot['id']); } } } print_r($yoo->getPendingDBPayments()); die; } else if (filter_has_var(INPUT_GET, 'clean')) { print_r($yoo->getOverdueOrder()); die; } //print_r($yoo->getPayments()); class Yookassa { private $db; private $api_key = 'test_NEvl8LbPCwKe6UNYFKeJ8CbNAGDfium9GY8pUABxtrU'; private $id = 257700; private $base_url = 'https://api.yookassa.ru/v3/'; private $data_amount = [ '30' => 1, ]; private $data_data = [ '30' => "30", ]; public function __construct(PDO $db) { $this->db = $db; } public function sendTelegram(array $data) { $botToken = '6388483992:AAGJyVctma1_QSzcLsi71LSB3FmUMN7CMoY'; $chatId = '1486741815'; if (!empty($data)) { $ids = []; foreach ($data as $item) { $pdo = new PDO('mysql:host=localhost;dbname=der409_test', 'der409_test', 'Gans1998'); $stmt = $pdo->prepare('SELECT * FROM pay_user WHERE user_id = ?'); $stmt->execute([$item['tg_id']]); $user = $stmt->fetch(PDO::FETCH_ASSOC); $username = $user['message']['from']['username']; $message = 'Поступила оплата от пользователя с email ' . $user['email'] . ' и id ' . $item['tg_id'] . ' на сумму ' . $item['pay_sum'].' рублей'; $url = 'https://api.telegram.org/bot'.$botToken.'/sendMessage?'.http_build_query(array( 'chat_id' => '1486741815', 'text' => $message, )); $res = json_decode(file_get_contents($url)); if ($res->ok == 1) { $ids[] = $item['id']; } ////отправка об успехе пользователю $message = 'Оплата прошла успешно, на сумму ' . $item['pay_sum'].' рублей'; $url = 'https://api.telegram.org/bot6576907933:AAGR2T-mhzdJAH9tE2rQIFMIqUDGYaWzzLw/sendMessage?'.http_build_query(array( 'chat_id' => '' . $item['tg_id'] . '', 'text' => $message, )); $res = json_decode(file_get_contents($url)); if ($res->ok == 1) { $ids[] = $item['id']; } } // обновляем статус платежа в бд и прикрепляем тег в watbot if (!empty($ids)) { $in = str_repeat('?,', count($arr) - 1) . '?'; $sql = "UPDATE pay SET pay_status = 'succeeded' WHERE tg_id IN ($in)"; $stm = $this->db->prepare($sql); return $stm->execute($ids); $watbot = new Watbot(); foreach ($ids as $tg_id) { // по api получаем id контакта в watbot $resWatbot = $watbot->getContactIdByTelegram($tg_id); if (!empty($resWatbot['id'])) { // присваиваем тег $watbot->attachTagToContact($resWatbot['id']); } } } } return false; } public function getOverdueOrder () { $now = new DateTime('+ 30 days'); // на 30 дней вперед $daysLater = $now->format('Y-m-d H:i:s'); $stm = $this->db->prepare("SELECT `tg_id`, `pay_date`, `id` FROM pay WHERE `pay_status` = 'succeeded'"); $stm->execute(); $res = $stm->fetchAll(); if (!empty($res)) { $watbot = new Watbot(); $dataIds = []; foreach ($res as $item) { // если прошло 30 дней if ($item['pay_date'] >= $daysLater) { $resWatbot = $watbot->getContactIdByTelegram($item['tg_id']); if (!empty($resWatbot['id'])) { $dataIds[] = $item['id']; // удаляем тег $watbot->attachTagToContact($resWatbot['id'], true); } } } // удаляем из бд if (!empty($dataIds)) { $in = str_repeat('?,', count($dataIds) - 1) . '?'; $sql = "DELETE FROM pay WHERE id IN ($in)"; $stm = $this->db->prepare($sql); $stm->execute($dataIds); } } return false; } /** * заказы, которые не обновлены в бд * для оповещения тг * @return array|false */ public function getPendingDBPayments() { $arr = $this->getIdsPayments([ 'status' => 'succeeded' ]); $in = str_repeat('?,', count($arr) - 1) . '?'; $sql = "SELECT * FROM pay WHERE user_id IN ($in) AND pay_status = 'pending'"; $stm = $this->db->prepare($sql); $stm->execute($arr); $data = $stm->fetchAll(); return $this->sendTelegram($data); } /** * получаем ид оплат * @param array $status * @return array */ public function getIdsPayments(array $status = []) { $ids = []; $data = $this->getPayments($status); foreach ($data as $item) { $ids[] = $item->id; } return $ids; } public function listWebhooks() { $this->request('webhooks ', [], 'get'); } public function createWebhooks(string $url) { $this->request('webhooks ', [ 'event' => 'payment.succeeded', 'url' => $url ]); } /** * Информация по платежу * @param $id - ид платежа * @return mixed|string */ public function getIdStatus($id) { return $this->request('payments/' . $id, [], 'get'); } /** * Список платежей (GET) * @param array $filter - фильтр для поиска, Пример: status=succeeded * @return mixed */ public function getPayments(array $filter = []) { $res = $this->request('payments?' . http_build_query($filter), [], 'get'); return $res->items; } /** * Отмена платежа (POST) * @param string $uri - uri с id который нужно отменить * @return bool */ public function cancelPayment(string $uri) { return $this->request($uri); } /** * Создание платежа (POST) * @param int $selectedAmount * @param int $u_id - ид тг юзера * @return string|void */ public function createPayment(int $selectedAmount = 30, int $u_id) { $amount = $this->data_amount[array_key_first($this->data_amount)]; $datas = $this->data_data[array_key_first($this->data_data)]; // Проверяем, есть ли такая буква в массиве if (array_key_exists($selectedAmount, $this->data_amount)) { $amount = $this->data_amount[$selectedAmount]; $datas = $this->data_data[array_key_first($this->data_data)]; } // Данные для создания платежа $data = array( 'amount' => array( 'value' => $amount, // Сумма платежа 'currency' => 'RUB', // Валюта (рубли) ), 'description' => 'Оплата подписки на ' . $datas . ' дней', // Описание платежа 'confirmation' => array( 'type' => 'redirect', 'return_url' => 'https://larchmos.ru/bot/yookassa.php?count=1', // URL для возврата после оплаты ), 'capture' => true, 'save_payment_method' => true, 'payment_method_data' => array( 'type' => 'bank_card', // Метод оплаты банковская карта //'type' => 'yoo_money', // Метод оплаты YooMoney //'type' => 'wallet', //Метод оплаты со счета пользователя // 'type' => 'cash' // Метод оплаты наличными //'type' => 'tinkoff_bank',// Метод оплаты Тинькофф банк ), 'subscription' => array( 'start_date' => date('Y-m-d'), // Дата начала подписки (сегодня) 'interval' => 'P30D', // Интервал подключения оплаты (раз в 30 дней) ),); $res = $this->request('payments', $data); if ($res->type == 'error') { return $res->description; } try { $stm = $this->db->prepare("SELECT * FROM pay WHERE tg_id = ? LIMIT 1"); $stm->execute([$u_id]); if (empty($stm->fetch())) { $sql = "INSERT INTO pay (user_id, pay_sum, pay_key, pay_status, tg_id) VALUES (?, ?, ?, ?, ?)"; $stm = $this->db->prepare($sql); $stm->execute([$res->id, $amount, 'test', 'pending', $u_id]); } else { $sql = "UPDATE pay SET user_id = ?, pay_sum = ?, pay_key = ?, pay_status = ? WHERE tg_id = ?"; $stm = $this->db->prepare($sql); $stm->execute([$res->id, $amount, 'test', 'pending', $u_id]); } header('Location: ' . $res->confirmation->confirmation_url); exit(); // Завершаем выполнение скрипта } catch (Exception $e) { return 'Ошибка'; } } /** * @param string $uri - uri api * @param array $data - данные для отправки * @param string $type - get/post * @return mixed|string */ private function request(string $uri, array $data = [], string $type = 'post') { $ch = curl_init($this->base_url . $uri); if ($type === 'post') { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers()); $response = curl_exec($ch); if ($response === false) { return 'Ошибка curl: ' . curl_error($ch); } $res = $this->responseParse($response); curl_close($ch); return $res; } /** * @param string $response * @return mixed */ private function responseParse(string $response) { // \{(.*?)\} preg_match('/{((?:[^{}]++|(?R))*)}/i', $response, $matches); $res = json_decode($matches[0]); return $res; } /** * заголовки для авторизации * @return string[] */ private function headers() { return [ 'Content-Type: application/json', 'Idempotence-Key: ' . uniqid('', true), 'Authorization: Basic ' . base64_encode($this->id . ':' . $this->api_key) ]; } }
a1a4b2b971d64b86e1cd8f9f634cf5bc
{ "intermediate": 0.3144179880619049, "beginner": 0.44141680002212524, "expert": 0.24416521191596985 }
21,762
pk_frame4 <- pk_frame3 %>% group_by(Subject_ID,Analyte) %>% arrange(Subject_ID,Analyte) %>% mutate( last_conc=lag(conc_), next_conc=lead(conc_), ) %>% ungroup() %>% mutate( diff1= min(as.numeric(interval( conc_, next_conc))/2, diff2= min(as.numeric(interval(last_conc, conc ))/2, rand_conc=rnorm(n(), (diff1-diff2)/2), rand_conc1=round(runif(n(),min=0,max=40)) ) how to fix this
c232ee49e8bbf5ca660c05691c8a68fd
{ "intermediate": 0.32710525393486023, "beginner": 0.30216366052627563, "expert": 0.37073108553886414 }
21,763
pk_frame4 <- pk_frame3 %>% group_by(Subject_ID, Analyte) %>% arrange(Subject_ID, collection_time) %>% mutate( last_conc = lag(conc_), next_conc = lead(conc_) ) %>% ungroup() %>% mutate( diff1 = min(interval(as.POSIXct(conc_), as.POSIXct(next_conc))/2, na.rm = TRUE), diff2 = min(interval(as.POSIXct(last_conc), as.POSIXct(conc_))/2, na.rm = TRUE), min_diff = min(diff1, diff2, na.rm = TRUE), rand_conc = rnorm(n(), min_diff/2) ) if conc_ is not a date variable, it is a concentration variable ,how to fix this code
4d02cd50de80288e784a954f46b7c96b
{ "intermediate": 0.37255990505218506, "beginner": 0.42226067185401917, "expert": 0.20517942309379578 }
21,764
how do you convert a pdf file to a tiff file in linux?
11bfddbd26d47bf829e2738c489fcf26
{ "intermediate": 0.43848270177841187, "beginner": 0.29261961579322815, "expert": 0.2688977122306824 }
21,765
difference between no inverting cuk and cuk converter
16d4e477d54bcfb9ff0dd448ef00a087
{ "intermediate": 0.28604814410209656, "beginner": 0.1994996964931488, "expert": 0.5144521594047546 }
21,766
fix the code. "ALL Strings are CrEaTeD equal" == "All STRINGS are CrEaTED Equal"
cd414ec7aa8497ecbad3eb20f3a68d03
{ "intermediate": 0.3124944567680359, "beginner": 0.37960293889045715, "expert": 0.30790260434150696 }
21,767
hello
2ae325a23ab0d2bfaff13f6cb4cc1d5a
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
21,768
if conc <- (100.25,300.52,677.82) how to calculate the difference between two records
341277fa705f1278d1a353bae8a35e03
{ "intermediate": 0.36006680130958557, "beginner": 0.26000601053237915, "expert": 0.3799271583557129 }
21,769
• Install R package carData. • After attaching package carData (with library("carData")) the data.frame Salaries is available. • Use R code to solve the following problems (i.e., do not only read the documentation): 1. How many rows and how many columns does Salaries have? 2. How many columns are numerical, how many columns contain factors? 3. Create a new data.frame, salaries_a, that only contains the data from discipline = "A". How many rows does this data.frame have? Check the documentation, what does discipline = "A" stand for?
0a0f7c8c2ab5396752a6a629d21100e6
{ "intermediate": 0.6732293367385864, "beginner": 0.18084892630577087, "expert": 0.1459217518568039 }
21,770
fix this for me: invalid method declaration: return type required in the following code: public class Intro { public static Tools () { Scanner story = new Scanner (System.in); System.out.println("Choose your tools (MAX 3)"); System.out.println("Katana\nCrowbar\nCrossbow\nBolt Action Rifle\nBackpack\nFirst aid kit\nLockpick set/nKali Linux\nWelding tool\nWater Purification Tablets\nAmmo (one mag)"); wait(10); } }
7a6d6f75d6ce50cbd7b64364304d9a17
{ "intermediate": 0.2535422444343567, "beginner": 0.6179366111755371, "expert": 0.1285211592912674 }
21,771
unsched_pk<-TRUE if(unsched_pk){ unsched_data<-pk_frame5 %>% filter(rowid %in% round(runif(sample(c(1,2),1),min=1,max=bign6),0)) %>% rename(temp_visit_date=shifted_time) unsched_data<-unsched_data%>% mutate( visit_date=as.POSIXct(ifelse( PSCHHOUR <0|PSCHMIN <0|PSCHDAY!=1, ifelse( is.na(last_finaldt), temp_visit_date %m+% days(-1), ), ifelse( is.na(next_finaldt), temp_visit_dt %m+% days(1), ) ), VISITTYP=2 #2=Unscheduled ) %>% select(-temp_final_dt) pk_frame6<-rbind(pk_frame5,unsched_data) } how to fix it
91d29c19b79bc57892dd2a69d25bbc53
{ "intermediate": 0.3638995587825775, "beginner": 0.42687126994132996, "expert": 0.20922912657260895 }
21,772
what does the following python code do? from torch import nn from torch.nn import functional as F #some code left out #here is the actual code of interest: self.norm = nn.LayerNorm(d_ffn)
adaebcb0dc3320470c872fe6a4ae8960
{ "intermediate": 0.3835805356502533, "beginner": 0.3018362820148468, "expert": 0.3145831525325775 }
21,773
write me pet simulator x script
4871a790e1338cfb87a62821faae9f70
{ "intermediate": 0.2020406872034073, "beginner": 0.5126002430915833, "expert": 0.28535905480384827 }
21,774
I'd like you to look at the following Python code (using Torch) and produce easy to understand vb code. I’m not fluent in Python and its imported libraries, so please use lower-level code like arrays instead of tensors and higher level functions. Here is the code: class SpatialGatingUnit(nn.Module): def __init__(self, d_ffn, seq_len): super().__init__() self.norm = nn.LayerNorm(d_ffn) self.spatial_proj = nn.Conv1d(seq_len, seq_len, kernel_size=1) nn.init.constant_(self.spatial_proj.bias, 1.0) def forward(self, x): u, v = x.chunk(2, dim=-1) v = self.norm(v) v = self.spatial_proj(v) out = u * v return out class gMLPBlock(nn.Module): def __init__(self, d_model, d_ffn, seq_len): super().__init__() self.norm = nn.LayerNorm(d_model) self.channel_proj1 = nn.Linear(d_model, d_ffn * 2) self.channel_proj2 = nn.Linear(d_ffn, d_model) self.sgu = SpatialGatingUnit(d_ffn, seq_len) def forward(self, x): residual = x x = self.norm(x) x = F.gelu(self.channel_proj1(x)) x = self.sgu(x) x = self.channel_proj2(x) out = x + residual return out class gMLP(nn.Module): def __init__(self, d_model=256, d_ffn=1536, seq_len=256, depth=30): super().__init__() self.model = nn.Sequential( *[gMLPBlock(d_model, d_ffn, seq_len) for _ in range(depth)] ) def forward(self, x): return self.model(x)
80abe78ba275594ecfe992eb7ad830cf
{ "intermediate": 0.39484772086143494, "beginner": 0.36791905760765076, "expert": 0.23723317682743073 }
21,775
Is oit difficult to make a program in C++ which could transform any images to Autostereograms or Magic Eyes with OpenCV?
def2138c22b586c20cc5b3a076f72519
{ "intermediate": 0.3188910484313965, "beginner": 0.12528935074806213, "expert": 0.555819571018219 }
21,776
Please convert the following code into easy to understand BASIC code. Do not use external libraries or higher level functionality. Use floating points, arrays with corresponding for/next loops. Do not use line numbers but labels instead. Here is the code:
fb090d73d7230c42d49975f444294079
{ "intermediate": 0.11036229878664017, "beginner": 0.8003928065299988, "expert": 0.08924493193626404 }
21,777
Here is code in Python I'd like you look and understand. I'd like you to convert the forward function into simple to understand procedural (not OOP) code in the BASIC programming language. Do not use imports or higher level functions. Only use primitive data types like integers and floating points. Use arrays and for/next loops to compute the equivalent functionality from the Python code. Here is the code: class SpatialGatingUnit(nn.Module): def __init__(self, d_ffn, seq_len): super().__init__() self.norm = nn.LayerNorm(d_ffn) self.spatial_proj = nn.Conv1d(seq_len, seq_len, kernel_size=1) nn.init.constant_(self.spatial_proj.bias, 1.0) def forward(self, x): u, v = x.chunk(2, dim=-1) v = self.norm(v) v = self.spatial_proj(v) out = u * v return out class gMLPBlock(nn.Module): def __init__(self, d_model, d_ffn, seq_len): super().__init__() self.norm = nn.LayerNorm(d_model) self.channel_proj1 = nn.Linear(d_model, d_ffn * 2) self.channel_proj2 = nn.Linear(d_ffn, d_model) self.sgu = SpatialGatingUnit(d_ffn, seq_len) def forward(self, x): residual = x x = self.norm(x) x = F.gelu(self.channel_proj1(x)) x = self.sgu(x) x = self.channel_proj2(x) out = x + residual return out class gMLP(nn.Module): def __init__(self, d_model=256, d_ffn=1536, seq_len=256, depth=30): super().__init__() self.model = nn.Sequential( *[gMLPBlock(d_model, d_ffn, seq_len) for _ in range(depth)] ) def forward(self, x): return self.model(x)
70109fcd007889803c4f91f88198e1c3
{ "intermediate": 0.4210383892059326, "beginner": 0.3607504963874817, "expert": 0.2182111293077469 }
21,778
how to format cell value to be YYYY-MM-DD Using DataFormat in APachi poi
e53f35be38d948772787a748b61515d4
{ "intermediate": 0.4828106462955475, "beginner": 0.1917480230331421, "expert": 0.3254413306713104 }
21,779
mapping IT controls applications
12ee908a11626393e56bf091bb68b01d
{ "intermediate": 0.556505560874939, "beginner": 0.2529618740081787, "expert": 0.19053250551223755 }
21,780
How do I safely convert response data into JSON while handling the possible error .json() might throw? This is my line: let json = await response.json();
3f0f28b7ce7116413da1b29334d255f0
{ "intermediate": 0.7305351495742798, "beginner": 0.11547710001468658, "expert": 0.1539877951145172 }
21,781
write ansible code to restart a windows server
9a743a383055fc350e28219ae23f70e7
{ "intermediate": 0.479187548160553, "beginner": 0.23860807716846466, "expert": 0.28220444917678833 }
21,782
export const fetchDataAssetWsServer = async() => { try { const response = await fetch("wsServers.json"); const jsonData = await response.json(); console.log(jsonData); } catch (error) { console.error("Ошибка при загрузке данных:", error); } }; const Trad = () =>{ fetchDataAssetWsServer(); как правильно сделать запрос и получить wsServers.json
dbffc7de01a1141b6d65649ddea2b5fc
{ "intermediate": 0.353040486574173, "beginner": 0.3619374632835388, "expert": 0.2850220501422882 }
21,783
Use an object-oriented approach to create an application that allows an administrator to add, search, update, and delete applications for a career-training institution. Currently, the application form is shown below, and you must categorize all of the information into one or more classes.It should be highlighted that different applicants may know more than two languages and are not limited to Spanish and English, and the same goes to educational background; they may have more than two certificates. Your application should include a user-friendly menu that allows the administrator to manage the list of applications. Along with your Python source files, you'll also need to use the "drawio" tool to create a UML class diagram. Full name Date of birth:day,month,year Sex: Home address Phone number(home) mobile phone number Email address
f766cae69ece1973b628147fc1097f87
{ "intermediate": 0.31882908940315247, "beginner": 0.33810698986053467, "expert": 0.34306395053863525 }
21,784
how do i query a dataframe in python to get the sum of balances and count of customers and create a new attribute that checks the count of products and flags with Y or N if it's equal to 1 or greater than 1
d57a0af2152dc0a00e57cc759b9dfc83
{ "intermediate": 0.6854044198989868, "beginner": 0.07801171392202377, "expert": 0.2365838587284088 }
21,785
export const fetchDataAssetWsServer = async() => { try { const response = await fetch(“wsServers.json”); const jsonData = await response.json(); console.log(jsonData); } catch (error) { console.error(“Ошибка при загрузке данных:”, error); } }; const Trad = () =>{ fetchDataAssetWsServer(); как правильно сделать запрос и получить wsServers.json Trad это компонент, нужно в нем создать useState, нужно через функцию получать wsServers.json и сетать полученный ответ в useState. используем then
7cc93d4eb047608b398dfadfcd5915e3
{ "intermediate": 0.38845744729042053, "beginner": 0.32066190242767334, "expert": 0.2908806800842285 }
21,786
I have a column DATA that contains lists of lists. See an example [[1250, 4551, 2255, 4566], [7895, 1456, 4562], [1234, 5789, 5456, 1245, 1258]] Write Python code to get new column where 1 and 2 element are merged, 2 and 3 are merged. So I need [[12504551, 4551255, 22554566], [78951456, 14564562], [12345789, 57895456, 54561245, 12451258]]
03768c30ffbcb8b721ef95c951a1276b
{ "intermediate": 0.508955717086792, "beginner": 0.20612768828868866, "expert": 0.284916490316391 }
21,787
make a reaper script to move all effect with the name "SS" down to be the last on the chain
816e9024b44f6e81c92e7c664a8e6575
{ "intermediate": 0.2358187586069107, "beginner": 0.23937153816223145, "expert": 0.524809718132019 }
21,788
sample text
9516b7d5285632e4163d4b812d9cde99
{ "intermediate": 0.30922120809555054, "beginner": 0.32919880747795105, "expert": 0.3615800738334656 }
21,789
check what could be wrong here???:
fd8fdfff6ad1a0a193a2eb4fc7a1bf53
{ "intermediate": 0.3849642276763916, "beginner": 0.2909916043281555, "expert": 0.3240441679954529 }
21,790
check what could be wrong here???:
d366e045da161d42a20d3a0d29231680
{ "intermediate": 0.3849642276763916, "beginner": 0.2909916043281555, "expert": 0.3240441679954529 }
21,791
check what could be wrong here???:
099984fe2094af03b4677345adbf8647
{ "intermediate": 0.3849642276763916, "beginner": 0.2909916043281555, "expert": 0.3240441679954529 }
21,792
this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?:
dc0eebf1eab5229485e56b679ae7a0db
{ "intermediate": 0.3750811815261841, "beginner": 0.36610105633735657, "expert": 0.25881773233413696 }
21,793
this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?:
afc08a3cd69445454d1c24b476f94752
{ "intermediate": 0.3750811815261841, "beginner": 0.36610105633735657, "expert": 0.25881773233413696 }
21,794
this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?:
b16d3e5d262665b08ffbbbf739a2ee21
{ "intermediate": 0.3750811815261841, "beginner": 0.36610105633735657, "expert": 0.25881773233413696 }
21,795
this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?:
8de65d0e98925487bea1df434fba0160
{ "intermediate": 0.3750811815261841, "beginner": 0.36610105633735657, "expert": 0.25881773233413696 }
21,796
I'm trying to implement this code to work with my button, but While I sucessfully subbed View in val image out for Button, I can't don't lnow what to do with View.OnClickListener (View doesn't exist as a class and Button doesn't seem to have this method) and Toast (shows error as unimplemented class. " override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_main) val image = findViewById<ImageView>(R.id.poster) val imageClickListener: View.OnClickListener = object : View.OnClickListener { override fun onClick(v: View?) { Toast.makeText(this@MainActivity, "Нажали на картинку!", Toast.LENGTH_SHORT).show() } }"
554cd0ff91417405dfb3614e2c97074f
{ "intermediate": 0.3858868479728699, "beginner": 0.48701953887939453, "expert": 0.1270936280488968 }
21,797
My interface is set up like this: public interface Settings<Type> {}. I want children of this interface to use a generic type that is only a primitive type, like Integer, Short, Boolean, Double, etc. Even a solution where Type has to be in a certain package would be fine. What can I do
f345a3c7434bf12cafadc7d09e9daba7
{ "intermediate": 0.39433035254478455, "beginner": 0.22140653431415558, "expert": 0.3842630982398987 }
21,798
this is my c++ code and it is giving me error because I need to define a wxPoint before using setposition, can you fix it? this->SetPosition((value = config->ReadKey("FRAMEMAIN_WINDOW_X")) != "" ? Utils::GetIntFromString(value) : this->GetPosition().x, (value = config->ReadKey("FRAMEMAIN_WINDOW_Y")) != "" ? Utils::GetIntFromString(value) : this->GetPosition().y);
9ff46307d545669faa4568ad69e998c2
{ "intermediate": 0.7344387173652649, "beginner": 0.2204636186361313, "expert": 0.04509764537215233 }
21,799
in python, edit the MachineGuid to change the hwid. Sure! Here is a simple Python program that prints the current MachineGuid and replaces it with a specified
ab5c78e980d2630d4f01460e78b312dd
{ "intermediate": 0.39411240816116333, "beginner": 0.12477380782365799, "expert": 0.4811137914657593 }
21,800
this is just a code piece from larger code. check what could be wrong here??? specifically timeouts used for queuing a backend. maybe some weird stuff is happening in timings?:
82c20a2d8895e9fb17a39d01cabf21ac
{ "intermediate": 0.3750811815261841, "beginner": 0.36610105633735657, "expert": 0.25881773233413696 }
21,801
Create a C++ program that prints even numbers from 1 to 100
63056b71551086d7ca9cda2a48093c1a
{ "intermediate": 0.3420921564102173, "beginner": 0.2908772826194763, "expert": 0.36703065037727356 }