row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
12,153
|
any high fiber fruit or food with low calories?
|
c44f4aef59bdab5876c2135b068b0bf0
|
{
"intermediate": 0.3913664221763611,
"beginner": 0.3093690574169159,
"expert": 0.2992645800113678
}
|
12,154
|
последняя карточка/обложка выглядит урезанной, не единообразной со всеми остальными, смотри скриншот:https://yadi.sk/d/ujtX2xJRF96n9A
<!-- audio player -->
<div class="selling-right-now">
<h3>Selling right now</h3>
<div class="selling-right-now-track">
<% tracks.forEach((track, index) => { %>
<div class="card" style="height: auto; display: flex;">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>" style="object-fit: cover; max-width: 200px; height: 200px;">
<div class="card-body">
<h4><%= track.title %></h4>
<p><%= track.album_title || "No Album" %></p>
<div class="player-wrapper">
<i class="fa fa-play"></i>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio>
</div>
</div>
</div>
<% }); %>
</div>
</div> <!-- end -->
css:
.selling-right-now {
margin: 50px auto;
max-width: auto;
justify-content: center;
}
.selling-right-now h3 {
text-align: center;
}
.selling-right-now-track {
display: flex;
justify-content: center;
align-items: center;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
flex-wrap: nowrap;
}
.card {
margin-right: 20px;
margin-bottom: 20px;
flex-shrink: 0;
max-width: 300px;
text-align: center;
position: relative;
}
.card-img {
position: relative;
width: 100%;
height: 0;
padding-bottom: 100%;
}
.card-img img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.card-body {
padding: 10px;
}
.card-body h4 {
margin-top: 0;
font-size: 18px;
font-weight: bold;
}
.card-body p {
margin-bottom: 0;
font-size: 14px;
}
/ audio player styles */
.player-wrapper {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.player-wrapper i {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 30px;
color: #333;
cursor: pointer;
}
|
10de3afff0ca5fbe9bc152f9eb708224
|
{
"intermediate": 0.29929596185684204,
"beginner": 0.40982872247695923,
"expert": 0.2908753454685211
}
|
12,155
|
fix any error in the following items and make it clear
o The Deep Blue and Alpha Go moment will come to asset management domain, when AI outperform the best human experts.
o Similar to chess and Go, currently, the best players are human assisted by AI. The future alpha will be coming from collaboration between man and machine.
|
a23f143d8873a8fe1e42cac395ebace6
|
{
"intermediate": 0.24641326069831848,
"beginner": 0.27539312839508057,
"expert": 0.47819358110427856
}
|
12,156
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
recv_window = 10000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
# Define function to generate trading signals
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicator
ema = ta.trend.EMAIndicator(df['Close'], window=10)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator
ema_value = ema.ema_indicator()[-1] #get the EMA indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But time to time I getting wrong signals, what I need to change in my code ?
|
278521b12c247b51ae1d924be0fd56fa
|
{
"intermediate": 0.43918803334236145,
"beginner": 0.40406325459480286,
"expert": 0.1567487120628357
}
|
12,157
|
I'm working as a desktop application developer
|
dc14742d4324e0a2bfdbffe9f80d72ed
|
{
"intermediate": 0.3509271442890167,
"beginner": 0.4118558168411255,
"expert": 0.2372169941663742
}
|
12,158
|
I have a matrix called A, which contains one column and 2928 row , I want to sperate every 24 row of matrix A and place in one of column of Matrix B and do it until end. write the code for matlab.
|
baf69ecf941945d432b950ec0466b250
|
{
"intermediate": 0.395430326461792,
"beginner": 0.1935783475637436,
"expert": 0.4109913408756256
}
|
12,159
|
I have a pysaprk dataframe and one column JSON_DATA has values like {“a:1”:1, “b:2”:2, “c:3”:3}, how can I expand the column with the key in the json object? and I hope the column name will be a, b, c.
|
5f05c3daa091989bfdd0215d90fa8240
|
{
"intermediate": 0.5857862830162048,
"beginner": 0.1856636106967926,
"expert": 0.22855007648468018
}
|
12,160
|
pack 2 4 bits number into 1 byte, in both binary interger and byte string representation
|
4e45f368d1ec8344739738911d8f7a8c
|
{
"intermediate": 0.36218810081481934,
"beginner": 0.21625465154647827,
"expert": 0.42155721783638
}
|
12,161
|
can i import a abstract class in any class in java? i made a servicio.java that class is abstract
|
3ccb9e11765c3758937a0d9dd42c640d
|
{
"intermediate": 0.48480886220932007,
"beginner": 0.2937983274459839,
"expert": 0.22139284014701843
}
|
12,162
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 5000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = '&'.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
recv_window = 10000
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicators
ema_10 = ta.trend.EMAIndicator(df['Close'], window=10)
ema_50 = ta.trend.EMAIndicator(df['Close'], window=50)
ema_100 = ta.trend.EMAIndicator(df['Close'], window=100)
ema_200 = ta.trend.EMAIndicator(df['Close'], window=200)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator values
ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame
ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame
ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame
ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But I getting ERROR: Error fetching markets: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
a83b3ed4736ec0b158d7810a1abb1a4b
|
{
"intermediate": 0.43918803334236145,
"beginner": 0.40406325459480286,
"expert": 0.1567487120628357
}
|
12,163
|
I need a C++ winAPI function to get selected display current resolution
|
483a8bae15d7a2727dff6df5c80ec5f3
|
{
"intermediate": 0.7269570231437683,
"beginner": 0.13706938922405243,
"expert": 0.13597355782985687
}
|
12,164
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 10000 # update the recv_window value
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sync your local time with the server time
sync_time()
# Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicators
ema_10 = ta.trend.EMAIndicator(df['Close'], window=10)
ema_50 = ta.trend.EMAIndicator(df['Close'], window=50)
ema_100 = ta.trend.EMAIndicator(df['Close'], window=100)
ema_200 = ta.trend.EMAIndicator(df['Close'], window=200)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator values
ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame
ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame
ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame
ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
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 35, in <module>
sync_time()
^^^^^^^^^
NameError: name 'sync_time' is not defined
|
c5810719a3aed83eb37ae1b56dbaa217
|
{
"intermediate": 0.3979807496070862,
"beginner": 0.33084455132484436,
"expert": 0.27117466926574707
}
|
12,165
|
Есть приложение на java. Вот серверная часть:
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = “<%s>Ack”;
private static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println(“Server started on port " + port);
System.out.println(”============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
clientSocketChannel.register(selector, SelectionKey.OP_READ);
System.out.println(“Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
int bytesRead;
while ((bytesRead = clientSocketChannel.read(buffer)) > 0) {
buffer.flip();
// проверяем наличие данных в буфере
if (buffer.remaining() < 8) {
continue;
}
// читаем длину имени файла в байтах
int nameLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < nameLength + 4) {
buffer.position(buffer.position() - 4);
buffer.compact();
continue;
}
// читаем имя файла
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
String fileName = new String(nameBytes, StandardCharsets.UTF_8);
// читаем длину файла в байтах
int fileLength = buffer.getInt();
// проверяем наличие данных в буфере
if (buffer.remaining() < fileLength + 8) {
buffer.position(buffer.position() - 8);
buffer.compact();
continue;
}
// читаем содержимое файла
byte[] fileContent = new byte[fileLength];
buffer.get(fileContent, 0, fileLength);
// проверяем разделитель
long separator = buffer.getLong();
if (separator != 0) {
throw new RuntimeException(“Invalid separator”);
}
// очищаем буфер
buffer.clear();
// сохраняем файл
saveFile(fileName, fileContent);
// отправляем подтверждение о сохранении файла
sendAck(clientSocketChannel, fileName);
}
if (bytesRead == -1) {
System.out.println(“Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println(”============ * ============”);
}
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File(“files\” + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(fileContent);
}
System.out.println(“File " + filename + " saved successfully”);
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
package serverUtils;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
public class Console {
public void start() throws IOException {
ConnectionManager connectionManager = new ConnectionManager(6789);
connectionManager.initialize();
Selector selector = Selector.open();
connectionManager.registerSelector(selector);
while (true) {
int readyChannelsCount = selector.select();
if (readyChannelsCount == 0) {
continue;
}
Iterator<SelectionKey> selectedKeysIterator = selector.selectedKeys().iterator();
while (selectedKeysIterator.hasNext()) {
SelectionKey key = selectedKeysIterator.next();
selectedKeysIterator.remove();
connectionManager.processQuery(selector, key);
}
}
}
}
Ее нужно исправить, добавив возможность обработки нескольких клиентов. Например, если один из клиентов остановился на передаче файла где-то на половине, и чтобы не крутиться в холостом цикле, в это время необходимо обрабатывать запросы других клиентов. Для достижения данного условия необходимо создать контекст соединения и связать его с конкретным соединением (Selection Key) и получать его через метод attachment. В этом же контексте можно хранить название файла, текущий состояние буффера, этап передачи файла.
|
0a4e49da3b15b071a3278724c513b234
|
{
"intermediate": 0.2945860028266907,
"beginner": 0.5462389588356018,
"expert": 0.15917500853538513
}
|
12,166
|
Write a function in c that receives an int number, a bit number and a boolean. The function should set or unset the bit in the int number according to the function arguments. The important part is the function cannot use any branching of any kind. No if conditions, no '?' and ':' operators, nothing of the sort.
|
1c04b0543ee090b530ab36573ed3f323
|
{
"intermediate": 0.3739008903503418,
"beginner": 0.3079330027103424,
"expert": 0.3181661367416382
}
|
12,167
|
НАладь работу этих блоков:
package serverUtils;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
public class Console {
public void start() throws IOException {
ConnectionManager connectionManager = new ConnectionManager(6789);
connectionManager.initialize();
Selector selector = Selector.open();
connectionManager.registerSelector(selector);
while (true) {
int readyChannelsCount = selector.selectNow();
if (readyChannelsCount == 0) {
continue;
}
Iterator<SelectionKey> selectedKeysIterator = selector.selectedKeys().iterator();
while (selectedKeysIterator.hasNext()) {
SelectionKey key = selectedKeysIterator.next();
selectedKeysIterator.remove();
connectionManager.processQuery(selector, key);
}
}
}
}
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = “<%s>Ack”;
static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println(“Server started on port " + port);
System.out.println(”============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
// Attach new ConnectionContext instance to the selection key
ConnectionContext context = new ConnectionContext();
clientSocketChannel.register(selector, SelectionKey.OP_READ, context);
System.out.println(“Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
ConnectionContext connectionContext = (ConnectionContext) key.attachment();
System.out.println(connectionContext);
if (connectionContext == null) {
connectionContext = new ConnectionContext();
key.attach(connectionContext);
}
ByteBuffer buffer = connectionContext.buffer;
int bytesRead = clientSocketChannel.read(buffer);
if (bytesRead < 0) {
System.out.println(“Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println(”============ * ============”);
return;
}
buffer.flip();
// handle file transmission
if (connectionContext.fileStarted) {
// check if we need more data to continue reading the file
if (connectionContext.fileName != null && connectionContext.fileLength >= 0 &&
buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
// read the file contents
byte[] fileContent = new byte[connectionContext.fileLength];
buffer.get(fileContent);
// check the separator
connectionContext.separator = buffer.getLong();
if (connectionContext.separator != 0L) {
throw new RuntimeException(“Invalid separator”);
}
// save the file and send an acknowledgement
saveFile(connectionContext.fileName, fileContent);
sendAck(clientSocketChannel, connectionContext.fileName);
// reset context for next file transfer
connectionContext.fileStarted = false;
connectionContext.fileCompleted = true;
connectionContext.fileName = null;
connectionContext.fileLength = -1;
// handle any remaining data in buffer
if (buffer.remaining() > 0) {
handleRead(key);
return;
}
}
} else {
// read the header of the file transfer
while (buffer.hasRemaining() && !connectionContext.fileStarted) {
// read the name length
if (connectionContext.fileName == null && buffer.remaining() >= Integer.BYTES) {
int nameLength = buffer.getInt();
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
connectionContext.fileName = new String(nameBytes, StandardCharsets.UTF_8);
}
// read the file length
if (connectionContext.fileLength < 0 && buffer.remaining() >= Integer.BYTES) {
connectionContext.fileLength = buffer.getInt();
if (connectionContext.fileLength < 0) {
throw new RuntimeException(“Invalid file length”);
}
connectionContext.fileStarted = true;
// check if we need more data to continue reading the file
if (buffer.remaining() < BUFFER_SIZE) {
buffer.compact();
return;
}
}
}
}
// handle file transmission continued with remaining data in buffer
if (connectionContext.fileStarted && !connectionContext.fileCompleted &&
buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
// read the file contents
byte[] fileContent = new byte[connectionContext.fileLength];
buffer.get(fileContent);
// check the separator
connectionContext.separator = buffer.getLong();
if (connectionContext.separator != 0L) {
throw new RuntimeException(“Invalid separator”);
}
// save the file and send an acknowledgement
saveFile(connectionContext.fileName, fileContent);
sendAck(clientSocketChannel, connectionContext.fileName);
// reset context for next file transfer
connectionContext.fileStarted = false;
connectionContext.fileCompleted = true;
connectionContext.fileName = null;
connectionContext.fileLength = -1;
// handle any remaining data in buffer
if (buffer.remaining() > 0) {
handleRead(key);
return;
}
}
buffer.compact();
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File(“files\” + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file, true)) {
int offset = 0;
while (offset < fileContent.length) {
int bytesToWrite = Math.min(BUFFER_SIZE, fileContent.length - offset);
outputStream.write(fileContent, offset, bytesToWrite);
offset += bytesToWrite;
}
outputStream.flush();
}
System.out.println(“File " + filename + " saved successfully”);
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
package serverUtils;
import java.nio.ByteBuffer;
public class ConnectionContext {
public String fileName;
public ByteBuffer buffer;
public int fileLength = -1;
public long separator = 0L;
public boolean fileStarted = false;
public boolean fileCompleted = false;
public ConnectionContext() {
this.buffer = ByteBuffer.allocate(ConnectionManager.BUFFER_SIZE);
}
}
package clientUtils;
import java.io.;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
String ip;
int port;
SocketChannel socketChannel;
public ConnectionManager(String ip, int port) {
this.ip = ip;
this.port = port;
}
void makeRequest(File file, FileInputStream fis) throws IOException {
// connect();
sendFile(file, fis);
receiveConfirmation();
// closeConnection();
}
void connect() throws IOException {
System.out.println(“Connected to the server”);
socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
socketChannel.configureBlocking(true);
}
void closeConnection() throws IOException {
socketChannel.close();
System.out.println(“Connection closed”);
}
private void sendFile(File file, FileInputStream fis) throws IOException {
// Создаем байтовый массив для передачи имени файла и его длины
byte[] nameBytes = file.getName().getBytes(StandardCharsets.UTF_8);
ByteBuffer nameLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length);
nameLengthBuffer.flip();
// Отправляем длину имени файла и само имя
socketChannel.write(nameLengthBuffer);
ByteBuffer nameBuffer = ByteBuffer.wrap(nameBytes);
socketChannel.write(nameBuffer);
// Отправляем длину файла
int fileLength = (int) file.length();
ByteBuffer fileLengthBuffer = ByteBuffer.allocate(Integer.BYTES).putInt(fileLength);
fileLengthBuffer.flip();
socketChannel.write(fileLengthBuffer);
// Определяем размер куска
int chunkSize = 1024;
byte[] buffer = new byte[chunkSize];
// Читаем данные из файла по кускам и отправляем их
int totalBytesRead = 0;
while (totalBytesRead < fileLength) {
int bytesRead = fis.read(buffer, 0, Math.min(chunkSize, fileLength - totalBytesRead));
if (bytesRead > 0) { // если прочитали что-то из файла
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead);
socketChannel.write(byteBuffer); // отправляем текущий кусок
totalBytesRead += bytesRead; // увеличиваем количество переданных байт
}
}
socketChannel.write(ByteBuffer.allocate(Long.BYTES)); // разделитель
fis.close();
System.out.println(“File " + file.getName() + " sent successfully”);
}
private void receiveConfirmation() throws IOException {
// Читаем длину сообщения
ByteBuffer lengthBuffer = ByteBuffer.allocate(Integer.BYTES);
socketChannel.read(lengthBuffer);
lengthBuffer.flip();
int messageLength = lengthBuffer.getInt();
// Читаем само сообщение
ByteBuffer messageBuffer = ByteBuffer.allocate(messageLength);
int bytesRead = 0;
while (bytesRead < messageLength) {
bytesRead += socketChannel.read(messageBuffer);
}
messageBuffer.rewind();
byte[] messageBytes = new byte[messageBuffer.remaining()];
messageBuffer.get(messageBytes);
String message = new String(messageBytes, StandardCharsets.UTF_8);
System.out.println("Received file: " + message);
}
}
|
d5791aab85626f316df192c91ce8f1fa
|
{
"intermediate": 0.30315789580345154,
"beginner": 0.4962957799434662,
"expert": 0.20054630935192108
}
|
12,168
|
void circularShift(char* buff, size_t size, Context *ctx) {
uint byteShift = ctx->shiftCount / 8;
uint bitShift = ctx->shiftCount % 8;
if (ctx->isNegShift == true) {
byteShift = (size - byteShift) % size;
}
char* temp = (char*)malloc(size);
memcpy(temp, buff, size);
for (size_t i = 0; i < size; i++) {
uint index = (i + byteShift) % size;
char byte = temp[index];
char shifted_byte;
if (ctx->isNegShift == true) {
shifted_byte = (byte << bitShift) | (byte >> (8 - bitShift));
} else {
shifted_byte = (byte >> bitShift) | (byte << (8 - bitShift));
}
buff[i] = shifted_byte;
}
writeToFile(ctx->tempFile, buff);
free(temp);
}
исправь этот код так, чтобы смещенные биты из соседних байтов переходили в лево, либо право стоящий
|
d5692e4745624e6ef97aaa8ff40144b7
|
{
"intermediate": 0.33551979064941406,
"beginner": 0.34016093611717224,
"expert": 0.3243192732334137
}
|
12,169
|
I have a script which stores informations into users.csv file now my script saving datas with headers like
user_id, username, first_name
1456693225,tyfndjddbvr,hishakh
but I want to my script must save informations like
index,name,id,status
1,hi,5795719742,NoneType
I'll send you my script modify it after modification my script must store informations like I before mention
|
8bebb7d609d41660ad6acd7e8a91abca
|
{
"intermediate": 0.46138542890548706,
"beginner": 0.18336746096611023,
"expert": 0.3552471399307251
}
|
12,170
|
как в react-query вернуть в data useQuery результат запроса, а не config, headers и тд
|
a488620f5d73f738c602944c83b668ea
|
{
"intermediate": 0.41311216354370117,
"beginner": 0.3287544548511505,
"expert": 0.2581333816051483
}
|
12,171
|
<iframe src="https://beesloveto.buzz" title="description"></iframe>
how do I make that html take up the whole screen
|
1179e45bd14dd2a8d4879757e187d665
|
{
"intermediate": 0.3639231324195862,
"beginner": 0.3201788365840912,
"expert": 0.315898060798645
}
|
12,172
|
I get this error: you provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.
input
label
ImageForm
div
div
div
|
824c6a9ca0275bbd979ff1c5ee8de419
|
{
"intermediate": 0.5817070007324219,
"beginner": 0.1918126791715622,
"expert": 0.22648027539253235
}
|
12,173
|
с++ unreal engine 4 montage end notify lambda
|
f7bc2e1cf4ce841f0ea5419bd3efca79
|
{
"intermediate": 0.24004994332790375,
"beginner": 0.42950305342674255,
"expert": 0.3304470181465149
}
|
12,174
|
Write code a pinescript v4 script for above
Structural Pivots Method (SPM)
Small Pivots
• In a rally, when we get 2 lower closes and lower lows, we get to mark Small Pivot High
(sph)
• In a decline, when we get 2 higher closes and higher highs, we get to mark Small Pivot
Low (spl)
_________________________________________________________________________________________
Structural Pivots Method (SPM) - Small Pivots
Concept of anchor/reference bar
Importance of creating rules objectively to mark the pivots
If rules are adhered, all will mark the same pivots
______________________________________________________________________________________________
Small Pivots – Rules for marking
a. Small Pivot High :-
• To mark sph, we need two lower lows
and two lower closes compared to
anchor bar
• SPH is the highest point in between 2
SPLs
• SPH alternates with SPL
b. Small Pivot Low :-
• To mark spl, we need two higher
highs and two higher closes
compared to the anchor bar
• SPL is the lowest point between 2
SPHs
• SPL and SPH alternate with each
other, SPL cannot follow another SPL
-----------------------------------------------------------------------------------------------------------
Common Rules
• Bar 1 & Bar 2 for marking small pivots does
not have to be consecutive bars UNTIL WE
GET TO MARK THE SMALL PIVOT (HIGH OR
LOW)
• Anchor Bar or a reference bar is taken as a
starting point to compare high/lows
• Only Bar2 of prev marked pivot can ‘start’
acting as the anchor bar to mark the next
pivot
• Recently marked small pivot is temporary. It
becomes permanent only after marking the
subsequent small pivot.
---------------------------------------------------------------------------------------------------------
SPM Large Pivots – Rules for marking
• To mark LPH, we need to break the previously marked spl(temp spl break is enough)
• To mark LPL, we need to break the previously marked sph(temp sph break is enough)
• LPH and LPL alternates...
• To mark LPH, we go back to see all the sphs (that were marked after the last LPL – including
highs) and mark the highest sph as LPH
• To mark LPL, we go back to see all the spls (that were marked after the last LPH – including
lows) and mark the lowest spl as LPL
• Once marked, Large pivots are permanent (no temp pivot concept like spl/sph)
_____________________________________________________________________________________________
buy when : Higher high and higher low LPs
sell when : Lower high and lower low LPs
_____________________________________________________________________________________________
Mark spl, sph with lower lower and upper arrow respectively
mark lpl, lph with 2 lower and 2 l upper arrows respectively
Also write detailed psedo code after writing pinescript
|
4751efa3ee72bf6eb28600f8f2e3bdaf
|
{
"intermediate": 0.42009878158569336,
"beginner": 0.22052794694900513,
"expert": 0.3593732714653015
}
|
12,175
|
с++ unreal engine 4 montage end notify lambda
|
6a42012cfb77b830fd52a45509ea05ea
|
{
"intermediate": 0.24004994332790375,
"beginner": 0.42950305342674255,
"expert": 0.3304470181465149
}
|
12,176
|
请编tampermonkey脚本,对https://10.236.83.1:11080/#/done页面实现以下输出信息的一健复制功能。console.log(document.getElementsByClassName(‘ant-input ant-input-disabled’)[0]._value+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[1]._value+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[2]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[0].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[3]._value+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[4]._value+’ ‘+document.getElementsByClassName(‘ant-input-number-input’)[‘sourcePort’]._value+’ ‘+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[2].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[5]._value+’ ‘+document.getElementsByClassName(‘ant-input-number-input’)[‘destPort’]._value+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[6]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[9].textContent+’ ‘+’ ‘+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[6].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[8]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[5].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[9]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[10].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[7]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[4].textContent+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[11].textContent+’ ‘+document.getElementsByClassName(‘ant-input ant-input-disabled’)[10]._value+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[1].textContent+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[2].textContent+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[3].textContent+’ ‘+document.getElementsByClassName(‘ant-select-selection-item’)[7].textContent+’ '+document.getElementsByClassName(‘ant-select-selection-item’)[8].textContent)
|
3b7f34590416bf319c42818c3d1d7d03
|
{
"intermediate": 0.3327033817768097,
"beginner": 0.37634095549583435,
"expert": 0.29095566272735596
}
|
12,177
|
Write a script in react that uses antd tabs, this component has 3 tabs, hide the tab selector but always show the content, in the content put a button that selects the next tab until it reaches the last one
|
8a5447f46eb4cac8a75d61e4091ea7db
|
{
"intermediate": 0.44445765018463135,
"beginner": 0.14497865736484528,
"expert": 0.41056370735168457
}
|
12,178
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
I am in the process of modifying the Renderer class to properly utilise Vulkan.hpp and RAII. Here are the old and new header files:
Old Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
New Renderer.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include “Window.h”
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include “Pipeline.h”
#include “Material.h”
#include “Mesh.h”
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
vk::DescriptorSetLayout CreateDescriptorSetLayout();
vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets);
vk::Device* GetDevice();
vk::PhysicalDevice* GetPhysicalDevice();
vk::CommandPool* GetCommandPool();
vk::Queue* GetGraphicsQueue();
vk::CommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<vk::Buffer> mvpBuffers;
std::vector<vk::DeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<vk::Image> swapChainImages;
std::vector<vk::ImageView> swapChainImageViews;
vk::Extent2D swapChainExtent;
vk::RenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
vk::Format swapChainImageFormat;
std::vector<vk::CommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
vk::CommandPool commandPool;
vk::CommandBuffer currentCommandBuffer;
std::vector<vk::Framebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<vk::Semaphore> imageAvailableSemaphores;
std::vector<vk::Semaphore> renderFinishedSemaphores;
std::vector<vk::Fence> inFlightFences;
size_t currentFrame;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface);
vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats);
vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes);
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice);
};
Please update and provide the code for the following portion of the Renderer.cpp to conform to the new header and to properly utilise both Vulkan.hpp and RAII. Notify me if there are no changes required.
void Renderer::CreateSyncObjects()
{
imageAvailableSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
renderFinishedSemaphores.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
inFlightFences.resize(kMaxFramesInFlight, VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo{};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create synchronization objects for a frame.");
}
}
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
SwapChainSupportDetails Renderer::querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface)
{
SwapChainSupportDetails details;
// Query the capabilities
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
// Query the supported formats
uint32_t formatCount;
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
if (formatCount != 0)
{
details.formats.resize(formatCount);
vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
}
// Query the supported present modes
uint32_t presentModeCount;
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
if (presentModeCount != 0)
{
details.presentModes.resize(presentModeCount);
vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
}
return details;
}
VkSurfaceFormatKHR Renderer::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats)
{
for (const auto& availableFormat : availableFormats)
{
if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{
return availableFormat;
}
}
return availableFormats[0];
}
VkPresentModeKHR Renderer::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes)
{
for (const auto& availablePresentMode : availablePresentModes)
{
if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR)
{
return availablePresentMode;
}
}
return VK_PRESENT_MODE_FIFO_KHR;
}
|
eb8e922a48a7c7390506960600439744
|
{
"intermediate": 0.35266053676605225,
"beginner": 0.4519357681274414,
"expert": 0.19540365040302277
}
|
12,179
|
ok = {32:'23'}
for i in ok:
print('give @s paper{CustomModelData:' + str(i) + ', display:{Name:'{"text":"' + i.get + '","color":"gray"}'}}')
Где тут ошибка
|
d3aa5c99e1406e021d52c4fee611f862
|
{
"intermediate": 0.26717880368232727,
"beginner": 0.5113997459411621,
"expert": 0.2214214950799942
}
|
12,180
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Can you modify the following header file to properly utilise Vulkan.hpp and RAII? We will then begin updating the class source file to conform to the new header and then expand to the broader codebase.
I am in the process of modifying the Renderer class to properly utilise Vulkan.hpp and RAII. Here are the old and new header files:
Old Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
New Renderer.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include “Window.h”
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include “Pipeline.h”
#include “Material.h”
#include “Mesh.h”
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
vk::DescriptorSetLayout CreateDescriptorSetLayout();
vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets);
vk::Device* GetDevice();
vk::PhysicalDevice* GetPhysicalDevice();
vk::CommandPool* GetCommandPool();
vk::Queue* GetGraphicsQueue();
vk::CommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<vk::Buffer> mvpBuffers;
std::vector<vk::DeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<vk::Image> swapChainImages;
std::vector<vk::ImageView> swapChainImageViews;
vk::Extent2D swapChainExtent;
vk::RenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
vk::Format swapChainImageFormat;
std::vector<vk::CommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
vk::Instance instance;
vk::PhysicalDevice physicalDevice;
vk::Device device;
vk::SurfaceKHR surface;
vk::SwapchainKHR swapchain;
vk::CommandPool commandPool;
vk::CommandBuffer currentCommandBuffer;
std::vector<vk::Framebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<vk::Semaphore> imageAvailableSemaphores;
std::vector<vk::Semaphore> renderFinishedSemaphores;
std::vector<vk::Fence> inFlightFences;
size_t currentFrame;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface);
vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats);
vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes);
vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice);
};
Please update and provide the code for the following portion of the Renderer.cpp to conform to the new header and to properly utilise both Vulkan.hpp and RAII. Notify me if there are no changes required.
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
void Renderer::CreateGraphicsPipeline(Mesh* mesh, Material* material) {
vkDeviceWaitIdle(device);
if (pipeline)
{
pipeline->Cleanup();
}
// Create pipeline object and configure its properties
pipeline = std::make_shared<Pipeline>();
pipeline->CreateGraphicsPipeline(mesh->GetVertexInputBindingDescriptions(),
mesh->GetVertexInputAttributeDescriptions(),
swapChainExtent,
{material->GetvertexShader().get(), material->GetfragmentShader().get()},
renderPass,
material->GetPipelineLayout(),
device);
}
std::shared_ptr<Pipeline> Renderer::GetPipeline() {
return pipeline;
}
std::pair<VkBuffer, VkDeviceMemory> Renderer::RequestMvpBuffer()
{
uint32_t mvpBufferIndex = currentMvpBufferIndex;
VkBuffer mvpBuffer = mvpBuffers[mvpBufferIndex];
VkDeviceMemory& requestedMvpBufferMemory = mvpBufferMemory[mvpBufferIndex]; // Changed the variable name
currentMvpBufferIndex = (currentMvpBufferIndex + 1) % kMvpBufferCount;
return std::make_pair(mvpBuffer, requestedMvpBufferMemory);
}
|
83168388acaddab832839cbdc11cfd0c
|
{
"intermediate": 0.35266053676605225,
"beginner": 0.4519357681274414,
"expert": 0.19540365040302277
}
|
12,181
|
altera o script para usar pywin32 em vez de win32gui, dá erro, e imprime o resultado, além da janela windows, também no prompt:
import whisper
import pyaudio
import wave
import win32gui
import time
import threading
import keyboard
model = whisper.load_model("small")
def transcribe(audio):
# load audio and pad/trim it to fit 30 seconds
audio = whisper.load_audio(audio)
audio = whisper.pad_or_trim(audio)
# make log-Mel spectrogram and move to the same device as the model
mel = whisper.log_mel_spectrogram(audio).to(model.device)
# detect the spoken language
_, probs = model.detect_language(mel)
print(f"Detected language: {max(probs, key=probs.get)}")
# decode the audio
options = whisper.DecodingOptions(fp16 = False)
result = whisper.decode(model, mel, options)
return result.text
CHUNK = 1024
FORMAT = pyaudio.paInt16 # Audio format
CHANNELS = 1 # Number of channels
RATE = 44100 # Sampling rate (number of samples per second)
THRESHOLD = 500
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
frames = []
recording = False
print("Waiting for voice...")
while True:
data = stream.read(CHUNK)
rms = int.from_bytes(data, byteorder='little')
if rms > THRESHOLD and not recording:
print("Recording...")
recording = True
if recording:
frames.append(data)
if len(frames) > RATE / CHUNK * 5:
break
print("Recording finished!")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open("output.wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
def write_in_window(text):
# get the handle of the current window
handle = win32gui.GetForegroundWindow()
# write text in the window
win32gui.SendMessage(handle, 0x000C, 0, text)
def transcribe_thread():
while True:
transcription = transcribe("output.wav")
print(transcription) # print transcription to console
write_in_window(transcription)
time.sleep(5)
t1 = threading.Thread(target=transcribe_thread)
t1.start()
while True:
if keyboard.is_pressed('ctrl+end'):
break
elif keyboard.is_pressed('ctrl+home'):
if t1.is_alive():
t1.join()
else:
t1.start()
Here’s an example of how you could modify the transcribe_thread function to continuously record and transcribe new audio:
def transcribe_thread():
while True:
# Record new audio
frames = []
recording = False
print("Waiting for voice...")
while True:
data = stream.read(CHUNK)
rms = int.from_bytes(data, byteorder='little')
if rms > THRESHOLD and not recording:
print("Recording...")
recording = True
if recording:
frames.append(data)
if len(frames) > RATE / CHUNK * 5:
break
print("Recording finished!")
# Save recorded audio to file
wf = wave.open("output.wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()
# Transcribe recorded audio
transcription = transcribe("output.wav")
print(transcription) # print transcription to console
write_in_window(transcription)
adapta o codigo anterior a esta alteração
|
6460277e42c56be3fda4f1397d39c38f
|
{
"intermediate": 0.37711071968078613,
"beginner": 0.4568836987018585,
"expert": 0.16600559651851654
}
|
12,182
|
User
hi I'm making a 2FA password set to an account using pyrogram script. from pyrogram import Client, filters
from pyrogram.errors import YouBlockedUser,RPCError,FloodWait,ChatAdminRequired,PeerFlood,PeerIdInvalid,UserIdInvalid,UserPrivacyRestricted,UserRestricted,ChannelPrivate,UserNotMutualContact,PhoneNumberBanned,UserChannelsTooMuch,UserKicked,UserAlreadyParticipant,ChatWriteForbidden,UserBannedInChannel
from pyrogram.raw import functions
import asyncio
import time
import csv
from csv import reader
from telethon.sync import utils
Api_id = 20180878
Api_hash = '739c6812f90822742851623860a112a4'
async def main():
with open('phone.csv', 'r') as f:
str_list = [row[0] for row in csv.reader(f)]
po = 0
for pphone in str_list:
phone = utils.parse_phone(pphone)
po += 1
app = Client(f"sessions/{phone}", Api_id, Api_hash, phone_number=f"{phone}")
async with app:
password = input("Enter your 2FA password: ")
password_settings = functions.account.UpdatePasswordSettings(
password=functions.account.InputPassword(
new_salt=app.salt,
new_password_hash=app.password_hash(password),
hint='',
email='',
)
)
# Execute the method and set the new password
app.send(password_settings)
asyncio.run(main())
input("chiqish uchun enterni bos") here is my script. I came accros errors https://docs.pyrogram.org/telegram/types/account/password#pyrogram.raw.types.account.Password use this reference and correct my mistakes rewrite my code to set 2FA password to my account
|
c78fd93eb4d78f30bf146891ec5131c3
|
{
"intermediate": 0.30630195140838623,
"beginner": 0.3715924918651581,
"expert": 0.3221055865287781
}
|
12,183
|
how do you define a function in python
|
ab9ccb076bee86c15e42d930034e507c
|
{
"intermediate": 0.26042550802230835,
"beginner": 0.5592997670173645,
"expert": 0.18027478456497192
}
|
12,184
|
I want to implement a moving average filter to a .mp3 file using c++, give a code where I can do that and also the command to compile it.
|
3eb017b26c5ac04fb09434e946f90863
|
{
"intermediate": 0.4652774930000305,
"beginner": 0.11542080342769623,
"expert": 0.41930171847343445
}
|
12,185
|
write me a script i can paste on terminal (macbook) to create in the desktop a folder called Loyer (Reçus) then in that folder, there will be folders from the year 2005 to the year 2022 included
|
9217409ce7f9ed6617562e96fb4893e4
|
{
"intermediate": 0.4057466387748718,
"beginner": 0.207799032330513,
"expert": 0.38645437359809875
}
|
12,186
|
can you explain to me operators in kotlin
|
91803fcd73caf5ba249a3cdd4f8ca64f
|
{
"intermediate": 0.3301781117916107,
"beginner": 0.400253564119339,
"expert": 0.2695682942867279
}
|
12,187
|
What libraries are needed for openg es to handle gamma correction, color range limitations, and color space?
|
b43ab9d6e59c959a9471c7b6fc2abfc4
|
{
"intermediate": 0.863027811050415,
"beginner": 0.04831972345709801,
"expert": 0.08865247666835785
}
|
12,188
|
Hi, I have to build a landing page html from a figma design
|
1fd87f593d5ce2c5bf3d0c2c41786969
|
{
"intermediate": 0.34995898604393005,
"beginner": 0.3334715664386749,
"expert": 0.3165695071220398
}
|
12,189
|
generate html contact form with modern ui which connects to nodejs back-end and a postgres db
|
81d9ad093b6905d96f09a57395822a10
|
{
"intermediate": 0.6868891716003418,
"beginner": 0.13794070482254028,
"expert": 0.17517006397247314
}
|
12,190
|
hi this code is giving me error Overload resolution ambiguity fun main() {
val num = 5
if (num > 0 && num < 10) {
println(“$num is between 0 and 10”)
} else{
println("no")
}
}
|
c6e9736b9b04ae65770a0123e86f4a52
|
{
"intermediate": 0.3316895663738251,
"beginner": 0.5815377235412598,
"expert": 0.08677274733781815
}
|
12,191
|
if i have a python file located at "C:\Users\Piers\Desktop\Word Adjacency Networks\WAN.py" and i want to use cmd to run that file and print its output in a text file, how do i do that
|
dd52eb5f9064f58b860895e22d13271e
|
{
"intermediate": 0.4020075798034668,
"beginner": 0.22743107378482819,
"expert": 0.3705613911151886
}
|
12,192
|
best way to replicate an array in ue5 when a value in the array changes i want to make it's replicated to all clients correctly. How can I achieve this? This is my code.void UEquipmentComponent::OnRep_Equipment()
{
UE_LOG(LogTemp, Warning, TEXT("Has Authority %s"), (GetOwner()->HasAuthority() ? TEXT("true") : TEXT("false")));
EquipmentChangeDelegate.Broadcast(EEquipmentType::Total_Equipment);
}void UEquipmentComponent::RemoveAmmoQuantity(int32 Quantity)
{
FEquipmentSlot& EquipmentSlot = EquipmentInventory[static_cast<int32>(EEquipmentType::Ammo)];
EquipmentSlot.EquippedActor->InventorySlot.Quantity -= Quantity;
if (EquipmentSlot.EquippedActor->InventorySlot.Quantity == 0)
{
Server_UnEquipEquipment(EEquipmentType::Ammo);
}
//bEquipmentInventoryChanged = !bEquipmentInventoryChanged;
} UPROPERTY(VisibleAnywhere, BlueprintReadOnly, ReplicatedUsing = OnRep_Equipment)
TArray<FEquipmentSlot> EquipmentInventory;
|
ae1de93a2511fb930b4299fdae04e393
|
{
"intermediate": 0.4326036274433136,
"beginner": 0.4220104217529297,
"expert": 0.1453859508037567
}
|
12,193
|
hi, why do we have to use !! in readline() on kotlin?
|
38d6f54c4f907e526db7c03e04396318
|
{
"intermediate": 0.48376816511154175,
"beginner": 0.30560076236724854,
"expert": 0.2106311023235321
}
|
12,194
|
hi what's wrong with this code fun main() {
println("enter the width of the rectangle")
val widthInput = readLine()?.toInt()
println("")
println("enter the height of the rectangle")
val heightInput = readLine()?.toInt()
val area = widthInput * heightInput
println("the area of the rectangle is: $area")
}
|
ec7bd827d4333696770b614f9d09aeb5
|
{
"intermediate": 0.2783208191394806,
"beginner": 0.5647478699684143,
"expert": 0.1569313108921051
}
|
12,195
|
hi is this code wrong, i run it but im unable to input a number, the program will finish before im able to fun main() {
println("enter the width of the rectangle")
val widthInput = readLine()?.toInt() ?:0
println("")
println("enter the height of the rectangle")
val heightInput = readLine()?.toInt() ?:0
val area = widthInput * heightInput
println("the area of the rectangle is: $area")
}
|
fdcd42214e2db26a35b9aeac19489c0d
|
{
"intermediate": 0.47971993684768677,
"beginner": 0.3551084101200104,
"expert": 0.16517165303230286
}
|
12,196
|
How to get annual dividend figures for HK stock yahoo finance python code
|
7dd5a16b3dbb90ddee881d67eff837b5
|
{
"intermediate": 0.34118688106536865,
"beginner": 0.2760779857635498,
"expert": 0.38273510336875916
}
|
12,197
|
hello
|
b4aa67dd02632173c8a0e095d30dd55d
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
12,198
|
HI
|
efef6928db17607ae2c1a0d34933d30e
|
{
"intermediate": 0.32988452911376953,
"beginner": 0.2611807882785797,
"expert": 0.40893468260765076
}
|
12,199
|
Write a Python code which make a photo
|
00d7be0df5c564856585a58e0760d368
|
{
"intermediate": 0.3486185371875763,
"beginner": 0.326985239982605,
"expert": 0.32439619302749634
}
|
12,200
|
this inspector supports x-www-form-urlencode
|
f1d8ffcb2866bb4e4897fdfc4e31c056
|
{
"intermediate": 0.3972257077693939,
"beginner": 0.296315997838974,
"expert": 0.3064582943916321
}
|
12,201
|
Below is an implementation of a sequence model which can be used like transformer model for modeling language. I will ask something about this code later.
|
bca1acb57130c243d3bddcfea032f499
|
{
"intermediate": 0.32864445447921753,
"beginner": 0.22998680174350739,
"expert": 0.4413687288761139
}
|
12,202
|
Перепиши эту программу с процедурами или функциями: Program thirteen;
const n = 3;
type lesson=record
vid:string[20];
naz:string[20];
fam:string[20];
end;
type lessons = array[1..n] of lesson;
var ls:lessons;
chit:array[1..n] of string[20];
i,j,a,k,chital:integer;
afam:string[20];
anaz:string[20];
famcurr:string[20];
procedure FillLessons(var ls: lessons);
var
i: integer;
begin
for i := 1 to n do begin
writeln('Занятие ', i);
write('Вид: ');
readln(ls[i].vid);
write('Название: ');
readln(ls[i].naz);
write('Преподаватель: ');
readln(ls[i].fam);
end;
end;
function a1(ls: lessons; afam, anaz: integer):integer;
var
i: integer;
begin
for i := 1 to n do begin
if((ls[i].fam = afam) and (ls[i].naz = anaz) and (ls[i].vid = 'лекция')) then
a += 1;
end;
a1 := a;
end;
begin
a := 0;
k := 1;
FillLessons(ls);
writeln('а) введите фамилию преподавателя');
readln(afam);
writeln('введите название предмета');
readln(anaz);
writeln('Количество лекций по предмету ', anaz,' прочитанных ', afam, ' = ',a1(ls, afam, anaz));
for i := 1 to n do begin
if(ls[i].vid = 'лекция') then begin
chit[k] := ls[i].fam;
k += 1;
end;
end;
write('Преподаватели, не читавшие лекции: ');
for i := 1 to n do begin
chital := 0;
for j := 1 to k do begin
if(ls[i].fam = chit[j]) then chital := 1;
end;
if(chital = 0) then writeln(ls[i].fam);
end;
end.
|
81e7cea57bc7a1b286177d8a49425a67
|
{
"intermediate": 0.3641125559806824,
"beginner": 0.41595587134361267,
"expert": 0.21993163228034973
}
|
12,203
|
hi how can i run kotlin on android studio, i mean in the log i dont want to run an apk
|
b34a62b1f5159468d3310b5c440cc2d8
|
{
"intermediate": 0.5407959818840027,
"beginner": 0.1569046676158905,
"expert": 0.3022993803024292
}
|
12,204
|
can you explain to me if, else, then in kotlin?
|
c6bf93b0dd5cf69824f952ed71971769
|
{
"intermediate": 0.30507850646972656,
"beginner": 0.40033480525016785,
"expert": 0.2945866882801056
}
|
12,205
|
I have 4 human face emotion classifier models implenet using mobilenet,resnet,shufflenet,squeezee net stored using .pth now I want to deploy this model using docker such that it takes images input and gives prediction output for different model which will be chosen by user (give steps with code to implement this)
|
6864114368c880a575a2be81f45db816
|
{
"intermediate": 0.3360995054244995,
"beginner": 0.054164592176675797,
"expert": 0.6097358465194702
}
|
12,206
|
Can you write sktipts for POSTMAN?
|
db50aa1971f8a901685dbac181946e2d
|
{
"intermediate": 0.6772778034210205,
"beginner": 0.19071486592292786,
"expert": 0.13200736045837402
}
|
12,207
|
public ResponseEntity<Distributions> getDistributionsV2(
@Valid @UserProfileInject UserProfile userProfile,
@AccountIdsMax @AccountIds @RequestHeader(value = "accountIds", required = false) Set<String> accountIds,
@NotEmpty @ValidResourceType @RequestParam(value = "resourceType") String resourceType,
@RequestParam(value = "startDate", required = false) String startDate,
@NotEmpty @Date(format = DATE_PATTERN_YYYY_MM_DD) @RequestParam(value = "endDate") String endDate) {
ResponseEntity<Distributions> distributions;
UserRequest userRequest = divCapGainsBuilder.buildDistributionUserRequest(userProfile.getPoid(), resourceType, startDate, endDate);
UserAccountValidationDto userAccountValidationDto = accountRetrievalService.validateAccounts(userProfile, accountIds);
List<UserAccount> userAccounts = userAccountValidationDto.getValidAccounts();
//get merged expanded account data
MergedExpandedAccountData mergedExpandedAccountData = mergedExpandedTAAccountsService.getMergedExpandedAccountData(userAccounts);
if (ResourceType.ACCRUED_DIVIDEND.equals(userRequest.getResourceType())) {
//get brokerage accrued dividends
BrokerageAccruedDividend brokerageAccruedDividend = brokerageAccruedDividendService.getBrokerageAccruedDividends(userAccounts, userRequest);
//get TA accrued dividends
MutualFundAccruedDividend mutualFundAccruedDividend = mutualFundAccruedDividendService.getMutualFundAccruedDividend(userAccounts, userRequest);
AccountAccruedDividend accountAccruedDividend = divCapGainsBuilder.buildDistributionAccountAccruedDividend(brokerageAccruedDividend, mutualFundAccruedDividend);
distributions = accruedDividendResponseMapper.mapResults(accountAccruedDividend, userAccounts, userAccountValidationDto);
} else {
//get the Brokerage Account transactions
CompletableFuture<BrokerageAccountsTransactions> cfBrokerageAccountsTransactions =
brokerageTransactionService.getBrokerageAccountsTransactionsAsync(userAccounts, userRequest);
//get the transactions for all TA accounts
MutualFundAccountsTransactions mutualFundAccountsTransactions = mutualFundTransactionService.getMutualFundAccountsTransactions(
userAccounts, mergedExpandedAccountData.getMergedTAAccountIds(), userRequest);
//Get Merged Expanded transactions from TA transactions
MergedExpandedAccountTransactions mergedExpandedAccountTransactions = mergedExpandedTAAccountsService
.getMergedExpandedAccountsTransactions(mergedExpandedAccountData, mutualFundAccountsTransactions);
AccountsTransactions accountsTransactions = divCapGainsBuilder.buildDistributionAccountsTransactions(
cfBrokerageAccountsTransactions, mutualFundAccountsTransactions,
mergedExpandedAccountTransactions, mergedExpandedAccountData.getMergedTAAccountIds());
//Get Security Details from BFP Service
List<SecurityDetail> securityDetails = securityRetrievalService.getSecurityDetails(accountsTransactions);
distributions = distributionsResponseMapper.mapResults(accountsTransactions, userAccounts, userRequest, securityDetails, userAccountValidationDto);
}
return distributions;
}
From this code generate square block diagram presentation
|
e1c1e29aae1db96882735b21892383ae
|
{
"intermediate": 0.41421568393707275,
"beginner": 0.4331359565258026,
"expert": 0.15264840424060822
}
|
12,208
|
I have 4 human face emotion classifier models implenet using mobilenet,resnet,shufflenet,squeezee net stored using .pth now I want to deploy this model using docker such that it takes images input and gives prediction output for different model which will be chosen by user (give steps with code to implement this)
the model is trained like this:
from google.colab import drive
drive.mount('/content/drive')
# Load the dataset from the zip file
import zipfile
with zipfile.ZipFile('/content/drive/MyDrive/archive (1).zip', 'r') as zip_ref:
zip_ref.extractall('/content/dataset')
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize, RandomRotation, RandomHorizontalFlip
from torchvision.datasets import ImageFolder
from matplotlib import pyplot as plt
import numpy as np
import os
import random
# Parameters
IMG_HEIGHT = 48
IMG_WIDTH = 48
batch_size = 32
epochs = 50
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Directories
import torchvision
train_data_dir = '/content/dataset/train'
validation_data_dir = '/content/dataset/test'
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
# Define the data transforms for train and test sets
data_transforms = {
'train': torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.RandomCrop(224), # Crop a random 224x224 patch from the image
torchvision.transforms.RandomRotation(30), # Rotate the image randomly by up to 30 degrees
torchvision.transforms.RandomHorizontalFlip(), # Flip the image horizontally with a probability of 0.5
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
]),
'test': torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.CenterCrop(224), # Crop the center 224x224 patch from the image
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
])
}
# Datasets
train_dataset = ImageFolder(train_data_dir, data_transforms['train'])
test_dataset = ImageFolder(validation_data_dir, data_transforms['test'])
# DataLoaders
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
import matplotlib.pyplot as plt
import numpy as np
batch = next(iter(train_loader))
images, labels = batch
images = images.numpy() / 2 + 0.5
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(8, 8))
for i, ax in enumerate(axes.flat):
ax.imshow(np.transpose(images[i], (1, 2, 0)))
ax.set_title(f"Label: {class_labels[labels[i]]}")
plt.show()
#Custom model
import torch.nn.functional as F
# Model architecture
class EmotionModel(nn.Module):
def __init__(self):
super(EmotionModel, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.pool2 = nn.MaxPool2d(2)
self.drop2 = nn.Dropout(0.1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3)
self.pool3 = nn.MaxPool2d(2)
self.drop3 = nn.Dropout(0.1)
self.conv4 = nn.Conv2d(128, 256, kernel_size=3)
self.pool4 = nn.MaxPool2d(2)
self.drop4 = nn.Dropout(0.1)
self.fc1 = nn.Linear(4096, 512)
self.drop5 = nn.Dropout(0.2)
self.fc2 = nn.Linear(512, 7)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.drop2(self.pool2(F.relu(self.conv2(x))))
x = self.drop3(self.pool3(F.relu(self.conv3(x))))
x = self.drop4(self.pool4(F.relu(self.conv4(x))))
# print(x.size()) # Add this line to print the size of the tensor
x = x.view(-1, 4096)
x = F.relu(self.fc1(x))
x = self.drop5(x)
x = self.fc2(x)
return x
model = EmotionModel().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}")
# Save the model
torch.save(model.state_dict(), 'emotion_detection_model_50epochs.pth')
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
# Display a few test images with original and predicted labels
n_display = 6
fig, axes = plt.subplots(1, n_display, figsize=(15, 3))
for i in range(n_display):
index = random.randint(0, len(test_dataset))
image, label = test_dataset[index]
image = image.to(device)
output = model(image.unsqueeze(0))
_, prediction = torch.max(output.data, 1)
orig_label = class_labels[label]
pred_label = class_labels[prediction.item()]
img = image.cpu().numpy().transpose((1, 2, 0))
img = img * 0.5 + 0.5 # Un-normalize
img = np.clip(img, 0, 1)
axes[i].imshow(img, cmap="gray")
axes[i].set_title(f"Original: {orig_label}\nPredicted: {pred_label}")
axes[i].axis("off")
plt.show()
#ResNet
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.models import resnet18
# Define the pre-trained ResNet18 model
model = resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}")
# Save the model
torch.save(model.state_dict(), 'emotion_detection_model_resnet.pth')
model = resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Load the pre-trained weights from a file
weights_path = "emotion_detection_model_resnet.pth"
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
# Display a few test images with original and predicted labels
n_display = 6
fig, axes = plt.subplots(1, n_display, figsize=(15, 3))
for i in range(n_display):
index = random.randint(0, len(test_dataset))
image, label = test_dataset[index]
image = image.to(device)
output = model(image.unsqueeze(0))
_, prediction = torch.max(output.data, 1)
orig_label = class_labels[label]
pred_label = class_labels[prediction.item()]
img = image.cpu().numpy().transpose((1, 2, 0))
img = img * 0.5 + 0.5 # Un-normalize
img = np.clip(img, 0, 1)
axes[i].imshow(img, cmap="gray")
axes[i].set_title(f"Original: {orig_label}\nPredicted: {pred_label}")
axes[i].axis("off")
plt.show()
#Mobilenet
from torchvision.models import mobilenet_v2
# Define the pre-trained MobileNetV2 model
model = mobilenet_v2(pretrained=True)
num_ftrs = model.classifier[1].in_features
model.classifier[1] = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}")
# Save the model
torch.save(model.state_dict(), 'emotion_detection_model_wideresnet.pth')
model = mobilenet_v2(pretrained=True)
num_ftrs = model.classifier[1].in_features
model.classifier[1] = nn.Linear(num_ftrs, 7)
model=model.to(device)
# Load the pre-trained weights from a file
weights_path = "/content/emotion_detection_model_wideresnet.pth"
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Squeezenet
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.models import squeezenet1_0
# Define the pre-trained SqueezeNet model
model = squeezenet1_0(pretrained=True)
num_ftrs = model.classifier[1].in_channels
model.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
# Move the model to the GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}")
# Save the model
torch.save(model.state_dict(), 'emotion_detection_model_squeezenet.pth')
model = squeezenet1_0(pretrained=True)
num_ftrs = model.classifier[1].in_channels
model.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
model=model.to(device)
# Load the pre-trained weights from a file
weights_path = "/content/emotion_detection_model_squeezenet.pth"
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Shufflenet
# Define the pre-trained ShuffleNetV2 model
from torchvision.models import shufflenet_v2_x1_0
model = shufflenet_v2_x1_0(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
num_epochs=50
for epoch in range(num_epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {running_loss / len(train_loader):.4f}")
# Save the model
torch.save(model.state_dict(), 'emotion_detection_model_shufflenet.pth')
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Neutral', 'Sad', 'Surprise']
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Tensorboard
import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import profile, record_function, ProfilerActivity
from torchvision.models import mobilenet_v2
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from google.colab import drive
drive.mount('/content/drive')
# Load the dataset from the zip file
import zipfile
with zipfile.ZipFile('/content/drive/MyDrive/archive.zip', 'r') as zip_ref:
zip_ref.extractall('/content/dataset')
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize, RandomRotation, RandomHorizontalFlip
from torchvision.datasets import ImageFolder
from matplotlib import pyplot as plt
import numpy as np
import os
import random
# Parameters
IMG_HEIGHT = 48
IMG_WIDTH = 48
batch_size = 32
epochs = 50
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Directories
import torchvision
train_data_dir = '/content/dataset/train'
validation_data_dir = '/content/dataset/test'
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
# Define the data transforms for train and test sets
data_transforms = {
'train': torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.RandomCrop(224), # Crop a random 224x224 patch from the image
torchvision.transforms.RandomRotation(30), # Rotate the image randomly by up to 30 degrees
torchvision.transforms.RandomHorizontalFlip(), # Flip the image horizontally with a probability of 0.5
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
]),
'test': torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.CenterCrop(224), # Crop the center 224x224 patch from the image
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
])
}
# Datasets
train_dataset = ImageFolder(train_data_dir, data_transforms['train'])
test_dataset = ImageFolder(validation_data_dir, data_transforms['test'])
# DataLoaders
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
!pip install tensorboard
!pip install torch-tb-profiler
def profile_model(model, weights_path, log_dir):
model.load_state_dict(torch.load(weights_path))
model = model.to(device)
writer = SummaryWriter(log_dir=log_dir)
with torch.profiler.profile(
schedule=torch.profiler.schedule(wait=0, warmup=2, active=6, repeat=1),
on_trace_ready=torch.profiler.tensorboard_trace_handler(log_dir), # Pass log_dir instead of writer
record_shapes=True,
profile_memory=True,
with_stack=True,
with_flops=True,
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
) as prof:
for i, (inputs, labels) in enumerate(test_loader):
inputs, labels = inputs.to(device), labels.to(device)
with record_function("forward"):
outputs = model(inputs)
loss = criterion(outputs, labels)
if i >= 10:
break
prof.step()
writer.close()
from torchvision.models import mobilenet_v2, shufflenet_v2_x1_0, resnet18, squeezenet1_0
resnet = resnet18(pretrained=True)
num_ftrs = resnet.fc.in_features
resnet.fc = nn.Linear(num_ftrs, 7)
mobilenet = mobilenet_v2(pretrained=True)
num_ftrs = mobilenet.classifier[1].in_features
mobilenet.classifier[1] = nn.Linear(num_ftrs, 7)
squeezenet = squeezenet1_0(pretrained=True)
num_ftrs = squeezenet.classifier[1].in_channels
squeezenet.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
shufflenet = shufflenet_v2_x1_0(pretrained=True)
num_ftrs = shufflenet.fc.in_features
shufflenet.fc = nn.Linear(num_ftrs, 7)
criterion = nn.CrossEntropyLoss()
models_and_paths = [
(mobilenet, "/content/drive/MyDrive/emotion_detection_model_mobilenet.pth", "runs/profiler_mobilenet"),
(shufflenet, "/content/drive/MyDrive/emotion_detection_model_shufflenet.pth", "runs/profiler_shufflenet"),
(resnet, "/content/drive/MyDrive/emotion_detection_model_resnet.pth", "runs/profiler_resnet"),
(squeezenet, "/content/drive/MyDrive/emotion_detection_model_squeezenet.pth", "runs/profiler_squeezenet"),
]
for model, weights_path, log_dir in models_and_paths:
profile_model(model, weights_path, log_dir)
%load_ext tensorboard
%tensorboard --logdir runs
|
52a042f02f801d54248a8d453cdba1e6
|
{
"intermediate": 0.43975841999053955,
"beginner": 0.34085214138031006,
"expert": 0.21938946843147278
}
|
12,209
|
javascript, how to get the browser display height
|
a1a5a7da4efb2f23dbbd38836588cacc
|
{
"intermediate": 0.3432881832122803,
"beginner": 0.3836483061313629,
"expert": 0.2730635106563568
}
|
12,210
|
I have 4 human face emotion classifier models implenet using mobilenet,resnet,shufflenet,squeezee net stored using .pth now I want to deploy this model using huggingface such that it takes images input and gives prediction output for different model which will be chosen by user (give steps with code to implement this):
Instruction:
- User will choose the model using a dropdown box menu
- User will upload image using a upload image button
- Prediction of image will be written just below it
The model is trained like this:
from google.colab import drive
drive.mount(‘/content/drive’)
# Load the dataset from the zip file
import zipfile
with zipfile.ZipFile(‘/content/drive/MyDrive/archive (1).zip’, ‘r’) as zip_ref:
zip_ref.extractall(‘/content/dataset’)
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize, RandomRotation, RandomHorizontalFlip
from torchvision.datasets import ImageFolder
from matplotlib import pyplot as plt
import numpy as np
import os
import random
# Parameters
IMG_HEIGHT = 48
IMG_WIDTH = 48
batch_size = 32
epochs = 50
device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
# Directories
import torchvision
train_data_dir = ‘/content/dataset/train’
validation_data_dir = ‘/content/dataset/test’
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
# Define the data transforms for train and test sets
data_transforms = {
‘train’: torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.RandomCrop(224), # Crop a random 224x224 patch from the image
torchvision.transforms.RandomRotation(30), # Rotate the image randomly by up to 30 degrees
torchvision.transforms.RandomHorizontalFlip(), # Flip the image horizontally with a probability of 0.5
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
]),
‘test’: torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.CenterCrop(224), # Crop the center 224x224 patch from the image
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
])
}
# Datasets
train_dataset = ImageFolder(train_data_dir, data_transforms[‘train’])
test_dataset = ImageFolder(validation_data_dir, data_transforms[‘test’])
# DataLoaders
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
import matplotlib.pyplot as plt
import numpy as np
batch = next(iter(train_loader))
images, labels = batch
images = images.numpy() / 2 + 0.5
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(8, 8))
for i, ax in enumerate(axes.flat):
ax.imshow(np.transpose(images[i], (1, 2, 0)))
ax.set_title(f"Label: {class_labels[labels[i]]}“)
plt.show()
#Custom model
import torch.nn.functional as F
# Model architecture
class EmotionModel(nn.Module):
def init(self):
super(EmotionModel, self).init()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.pool2 = nn.MaxPool2d(2)
self.drop2 = nn.Dropout(0.1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3)
self.pool3 = nn.MaxPool2d(2)
self.drop3 = nn.Dropout(0.1)
self.conv4 = nn.Conv2d(128, 256, kernel_size=3)
self.pool4 = nn.MaxPool2d(2)
self.drop4 = nn.Dropout(0.1)
self.fc1 = nn.Linear(4096, 512)
self.drop5 = nn.Dropout(0.2)
self.fc2 = nn.Linear(512, 7)
def forward(self, x):
x = F.relu(self.conv1(x))
x = self.drop2(self.pool2(F.relu(self.conv2(x))))
x = self.drop3(self.pool3(F.relu(self.conv3(x))))
x = self.drop4(self.pool4(F.relu(self.conv4(x))))
# print(x.size()) # Add this line to print the size of the tensor
x = x.view(-1, 4096)
x = F.relu(self.fc1(x))
x = self.drop5(x)
x = self.fc2(x)
return x
model = EmotionModel().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}”)
# Save the model
torch.save(model.state_dict(), ‘emotion_detection_model_50epochs.pth’)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%“)
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
# Display a few test images with original and predicted labels
n_display = 6
fig, axes = plt.subplots(1, n_display, figsize=(15, 3))
for i in range(n_display):
index = random.randint(0, len(test_dataset))
image, label = test_dataset[index]
image = image.to(device)
output = model(image.unsqueeze(0))
_, prediction = torch.max(output.data, 1)
orig_label = class_labels[label]
pred_label = class_labels[prediction.item()]
img = image.cpu().numpy().transpose((1, 2, 0))
img = img * 0.5 + 0.5 # Un-normalize
img = np.clip(img, 0, 1)
axes[i].imshow(img, cmap=“gray”)
axes[i].set_title(f"Original: {orig_label}\nPredicted: {pred_label}”)
axes[i].axis(“off”)
plt.show()
#ResNet
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.models import resnet18
# Define the pre-trained ResNet18 model
model = resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}“)
# Save the model
torch.save(model.state_dict(), ‘emotion_detection_model_resnet.pth’)
model = resnet18(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Load the pre-trained weights from a file
weights_path = “emotion_detection_model_resnet.pth”
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%”)
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
# Display a few test images with original and predicted labels
n_display = 6
fig, axes = plt.subplots(1, n_display, figsize=(15, 3))
for i in range(n_display):
index = random.randint(0, len(test_dataset))
image, label = test_dataset[index]
image = image.to(device)
output = model(image.unsqueeze(0))
_, prediction = torch.max(output.data, 1)
orig_label = class_labels[label]
pred_label = class_labels[prediction.item()]
img = image.cpu().numpy().transpose((1, 2, 0))
img = img * 0.5 + 0.5 # Un-normalize
img = np.clip(img, 0, 1)
axes[i].imshow(img, cmap=“gray”)
axes[i].set_title(f"Original: {orig_label}\nPredicted: {pred_label}“)
axes[i].axis(“off”)
plt.show()
#Mobilenet
from torchvision.models import mobilenet_v2
# Define the pre-trained MobileNetV2 model
model = mobilenet_v2(pretrained=True)
num_ftrs = model.classifier[1].in_features
model.classifier[1] = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}”)
# Save the model
torch.save(model.state_dict(), ‘emotion_detection_model_wideresnet.pth’)
model = mobilenet_v2(pretrained=True)
num_ftrs = model.classifier[1].in_features
model.classifier[1] = nn.Linear(num_ftrs, 7)
model=model.to(device)
# Load the pre-trained weights from a file
weights_path = “/content/emotion_detection_model_wideresnet.pth”
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%“)
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Squeezenet
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.models import squeezenet1_0
# Define the pre-trained SqueezeNet model
model = squeezenet1_0(pretrained=True)
num_ftrs = model.classifier[1].in_channels
model.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
# Move the model to the GPU if available
device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
for epoch in range(epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{epochs}, Loss: {running_loss / len(train_loader):.4f}”)
# Save the model
torch.save(model.state_dict(), ‘emotion_detection_model_squeezenet.pth’)
model = squeezenet1_0(pretrained=True)
num_ftrs = model.classifier[1].in_channels
model.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
model=model.to(device)
# Load the pre-trained weights from a file
weights_path = “/content/emotion_detection_model_squeezenet.pth”
model.load_state_dict(torch.load(weights_path))
model=model.to(device)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%“)
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Shufflenet
# Define the pre-trained ShuffleNetV2 model
from torchvision.models import shufflenet_v2_x1_0
model = shufflenet_v2_x1_0(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 7)
# Move the model to the GPU if available
device = torch.device(“cuda:0” if torch.cuda.is_available() else “cpu”)
model = model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
# Train the model
num_epochs=50
for epoch in range(num_epochs):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print(f"Epoch {epoch+1}/{num_epochs}, Loss: {running_loss / len(train_loader):.4f}”)
# Save the model
torch.save(model.state_dict(), ‘emotion_detection_model_shufflenet.pth’)
# Test the model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Accuracy: {100 * correct / total:.2f}%")
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = []
y_pred = []
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(predicted.cpu().numpy())
cm = confusion_matrix(y_true, y_pred)
class_labels = [‘Angry’, ‘Disgust’, ‘Fear’, ‘Happy’, ‘Neutral’, ‘Sad’, ‘Surprise’]
sns.heatmap(cm, annot=True, xticklabels=class_labels, yticklabels=class_labels)
plt.show()
#Tensorboard
import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import profile, record_function, ProfilerActivity
from torchvision.models import mobilenet_v2
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from google.colab import drive
drive.mount(‘/content/drive’)
# Load the dataset from the zip file
import zipfile
with zipfile.ZipFile(‘/content/drive/MyDrive/archive.zip’, ‘r’) as zip_ref:
zip_ref.extractall(‘/content/dataset’)
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, ToTensor, Normalize, RandomRotation, RandomHorizontalFlip
from torchvision.datasets import ImageFolder
from matplotlib import pyplot as plt
import numpy as np
import os
import random
# Parameters
IMG_HEIGHT = 48
IMG_WIDTH = 48
batch_size = 32
epochs = 50
device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
# Directories
import torchvision
train_data_dir = ‘/content/dataset/train’
validation_data_dir = ‘/content/dataset/test’
mean = [0.5, 0.5, 0.5]
std = [0.5, 0.5, 0.5]
# Define the data transforms for train and test sets
data_transforms = {
‘train’: torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.RandomCrop(224), # Crop a random 224x224 patch from the image
torchvision.transforms.RandomRotation(30), # Rotate the image randomly by up to 30 degrees
torchvision.transforms.RandomHorizontalFlip(), # Flip the image horizontally with a probability of 0.5
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
]),
‘test’: torchvision.transforms.Compose([
torchvision.transforms.Resize(256), # Resize the image to 256x256 pixels
torchvision.transforms.CenterCrop(224), # Crop the center 224x224 patch from the image
torchvision.transforms.ToTensor(), # Convert the image to a PyTorch tensor
torchvision.transforms.Normalize(mean, std) # Normalize the image using the mean and standard deviation
])
}
# Datasets
train_dataset = ImageFolder(train_data_dir, data_transforms[‘train’])
test_dataset = ImageFolder(validation_data_dir, data_transforms[‘test’])
# DataLoaders
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
!pip install tensorboard
!pip install torch-tb-profiler
def profile_model(model, weights_path, log_dir):
model.load_state_dict(torch.load(weights_path))
model = model.to(device)
writer = SummaryWriter(log_dir=log_dir)
with torch.profiler.profile(
schedule=torch.profiler.schedule(wait=0, warmup=2, active=6, repeat=1),
on_trace_ready=torch.profiler.tensorboard_trace_handler(log_dir), # Pass log_dir instead of writer
record_shapes=True,
profile_memory=True,
with_stack=True,
with_flops=True,
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
) as prof:
for i, (inputs, labels) in enumerate(test_loader):
inputs, labels = inputs.to(device), labels.to(device)
with record_function(“forward”):
outputs = model(inputs)
loss = criterion(outputs, labels)
if i >= 10:
break
prof.step()
writer.close()
from torchvision.models import mobilenet_v2, shufflenet_v2_x1_0, resnet18, squeezenet1_0
resnet = resnet18(pretrained=True)
num_ftrs = resnet.fc.in_features
resnet.fc = nn.Linear(num_ftrs, 7)
mobilenet = mobilenet_v2(pretrained=True)
num_ftrs = mobilenet.classifier[1].in_features
mobilenet.classifier[1] = nn.Linear(num_ftrs, 7)
squeezenet = squeezenet1_0(pretrained=True)
num_ftrs = squeezenet.classifier[1].in_channels
squeezenet.classifier[1] = nn.Conv2d(num_ftrs, 7, kernel_size=(1,1), stride=(1,1))
shufflenet = shufflenet_v2_x1_0(pretrained=True)
num_ftrs = shufflenet.fc.in_features
shufflenet.fc = nn.Linear(num_ftrs, 7)
criterion = nn.CrossEntropyLoss()
models_and_paths = [
(mobilenet, “/content/drive/MyDrive/emotion_detection_model_mobilenet.pth”, “runs/profiler_mobilenet”),
(shufflenet, “/content/drive/MyDrive/emotion_detection_model_shufflenet.pth”, “runs/profiler_shufflenet”),
(resnet, “/content/drive/MyDrive/emotion_detection_model_resnet.pth”, “runs/profiler_resnet”),
(squeezenet, “/content/drive/MyDrive/emotion_detection_model_squeezenet.pth”, “runs/profiler_squeezenet”),
]
for model, weights_path, log_dir in models_and_paths:
profile_model(model, weights_path, log_dir)
%load_ext tensorboard
%tensorboard --logdir runs
|
81fa960469896cf118f913934ac70bcd
|
{
"intermediate": 0.3592894673347473,
"beginner": 0.3509814143180847,
"expert": 0.2897290587425232
}
|
12,211
|
Write a DJANGO web application that: enable Patient of an hospital to send a large zip file, associated with name and surname and patient ID to a central repository , enable a doctor to review all data inserted an can export data to local folder, and by pushing a button enable the execution of command on the zip file.
|
32fd503d90d37b58ff93a1fb6345e72f
|
{
"intermediate": 0.4313264489173889,
"beginner": 0.09976406395435333,
"expert": 0.46890950202941895
}
|
12,212
|
/ Round numbers in each row to two decimal places
allData[row] = allData[row].map((cell) => {
// Check if the cell value is a number
if (!isNaN(parseFloat(cell))) {
// Round the number to two decimal places
return parseFloat(cell).toFixed(2);
}
return cell;
}); i used this code to round parsed data in my excel to two decimal places but i want to skip numbers like this 1401051 . now it converts them like this 1401051.00. how can i fix this. I want integers small or large to stay the same
|
712dc653384e84e0f20b18d479db3ef3
|
{
"intermediate": 0.4898984134197235,
"beginner": 0.3180355429649353,
"expert": 0.19206605851650238
}
|
12,213
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 10000 # update the recv_window value
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicators
ema_10 = ta.trend.EMAIndicator(df['Close'], window=10)
ema_50 = ta.trend.EMAIndicator(df['Close'], window=50)
ema_100 = ta.trend.EMAIndicator(df['Close'], window=100)
ema_200 = ta.trend.EMAIndicator(df['Close'], window=200)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator values
ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame
ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame
ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame
ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But i getting ERROR: Error fetching markets: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
BTC/USDT not found in the market
|
0e3973cb098a7a1b86010fc950ba5660
|
{
"intermediate": 0.37491005659103394,
"beginner": 0.40803396701812744,
"expert": 0.217056006193161
}
|
12,215
|
in my webpage, have this element <div id="px">test</div>, when the user click a button, it will go to this element by <a href="#px">go</a>. Since there is a top men with height "100px", how to display this element and go down 100px
|
7e473e4e37f5ae3fb652cd4fa0394825
|
{
"intermediate": 0.4444443881511688,
"beginner": 0.2345075011253357,
"expert": 0.3210481107234955
}
|
12,216
|
Hi!
|
c9836393b5fbe09c0f66c96b78877087
|
{
"intermediate": 0.3230988085269928,
"beginner": 0.2665199935436249,
"expert": 0.4103812277317047
}
|
12,217
|
Hello!
|
9c1eb09ca234d4909704e7c73fc62aa7
|
{
"intermediate": 0.3194829821586609,
"beginner": 0.26423266530036926,
"expert": 0.41628435254096985
}
|
12,218
|
Transaction already closed: A batch query cannot be executed on a closed transavtion error from prisma when importing large data with nested batch queries
|
abd53ced0e9b37894bb9b5765f0e7a7e
|
{
"intermediate": 0.5463317036628723,
"beginner": 0.1922435313463211,
"expert": 0.2614246904850006
}
|
12,219
|
Groovy obtains the timestamp of the current time
|
aa23ccc2b3609ec2ab3c7b72d6365f8e
|
{
"intermediate": 0.4797695577144623,
"beginner": 0.19978691637516022,
"expert": 0.3204434812068939
}
|
12,220
|
user schema for db
|
827851aeff14c2e7d05ace23a478e7c9
|
{
"intermediate": 0.3153684735298157,
"beginner": 0.3791898787021637,
"expert": 0.305441677570343
}
|
12,221
|
You didn't continue your code :
import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ‘’
API_SECRET = ‘’
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = “https://fapi.binance.com/fapi/v2/account”
recv_window = 10000 # update the recv_window value
params = {
“timestamp”: int(get_server_time() * 1000),
“recvWindow”: recv_window
}
# Sign the message using the Client’s secret key
message = “&”.join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params[‘signature’] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={‘X-MBX-APIKEY’: API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info[‘accountBalance’] if item[“asset”] == “USDT”), {“free”: 0})[‘free’]
except KeyError:
usdt_balance = 0
print(“Error: Could not retrieve USDT balance from API response.”)
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime(“%m/%d/%Y %H:%M:%S”)
print(date)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = ‘SELL’
POSITION_SIDE_LONG = ‘BUY’
quantity = 1
symbol = ‘BTC/USDT’
order_type = ‘market’
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
‘apiKey’: API_KEY,
‘secret’: API_SECRET,
‘enableRateLimit’: True, # enable rate limitation
‘options’: {
‘defaultType’: ‘future’,
‘adjustForTimeDifference’: True
},
‘future’: {
‘sideEffectType’: ‘MARGIN_BUY’, # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
params = {
“timestamp”: int(get_server_time() * 1000),
“recvWindow”: recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f’Error fetching markets: {e}‘)
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request(‘pool.ntp.org’)
return int(response.tx_time * 1000)
def get_time_difference():
server_time = get_server_time()
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = “https://fapi.binance.com/fapi/v1/klines”
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace(“/”, “”) # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36’
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print(‘No data found for the given timeframe and symbol’)
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime(’%Y-%m-%d %H:%M:%S’)
ohlc.append({
‘Open time’: timestamp,
‘Open’: float(d[1]),
‘High’: float(d[2]),
‘Low’: float(d[3]),
‘Close’: float(d[4]),
‘Volume’: float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index(‘Open time’, inplace=True)
return df
df = get_klines(symbol, ‘1m’, 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicators
ema_10 = ta.trend.EMAIndicator(df[‘Close’], window=10)
ema_50 = ta.trend.EMAIndicator(df[‘Close’], window=50)
ema_100 = ta.trend.EMAIndicator(df[‘Close’], window=100)
ema_200 = ta.trend.EMAIndicator(df[‘Close’], window=200)
# Calculate MA indicator
ma = ta.t
|
204f267816a3b841049cb9e102c68a03
|
{
"intermediate": 0.441356360912323,
"beginner": 0.38029319047927856,
"expert": 0.17835037410259247
}
|
12,222
|
how to know the ECS bucket that has highest number of versions from the CLI
|
676eaaaeaf2e12090549aa1cbf0ab1d8
|
{
"intermediate": 0.3355388939380646,
"beginner": 0.2855282723903656,
"expert": 0.3789328336715698
}
|
12,223
|
please explain me how it works pcolormesh in python. I have a grid and what are the colors for every x,y cell?
|
58752ca8433015f126e5c8bc74d07052
|
{
"intermediate": 0.5815226435661316,
"beginner": 0.11192411929368973,
"expert": 0.3065532445907593
}
|
12,224
|
write a python3 script to reverse a linked list provided via commandline
|
2999a088a1d81c0759c0bdaeba553573
|
{
"intermediate": 0.4344910681247711,
"beginner": 0.20303654670715332,
"expert": 0.36247241497039795
}
|
12,226
|
class LSTMTagger(nn.Module):
def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):
super(LSTMTagger, self).__init__()
self.hidden_dim = hidden_dim
self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)
# The LSTM takes word embeddings as inputs, and outputs hidden states
# with dimensionality hidden_dim.
self.lstm = nn.LSTM(embedding_dim, hidden_dim)
# The linear layer that maps from hidden state space to tag space
self.hidden2tag = nn.Linear(hidden_dim, tagset_size)
def forward(self, sentence):
embeds = self.word_embeddings(sentence)
lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))
tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1))
tag_scores = F.log_softmax(tag_space, dim=1)
return tag_scores
can you explain it line by line please
|
6a6ee05c8c57a46cf8901bdbd0f245c3
|
{
"intermediate": 0.4021318852901459,
"beginner": 0.3054748475551605,
"expert": 0.2923932671546936
}
|
12,227
|
Write a Python script for Windows 10 that prints all running processes and then allows the user to stop them or start new processes, or configure individual tasks. Do NOT use f-strings or Python modules that need to be installed separately (only use pre installed modules).
|
905af0a5dc848276b4b2651234bf834a
|
{
"intermediate": 0.5175010561943054,
"beginner": 0.19365936517715454,
"expert": 0.28883951902389526
}
|
12,228
|
帮我写一个tkinter程序 包含内容 1用户输入第一个数字位数 2 用户输入第二个数字位数 3 用户输入题目数量 4 用户输入校验答案位数
用户输入后提交跳转到 答题界面 题目根据上面用户输入的内容生成 并且提交后开始一个计时器
用户答题完毕后 再次点击提交 校验答案 并且把对错标记到每个输入框后 并且加上每题平均时间和总用时的显示
|
34451575c97c61d3a7813610a2a88581
|
{
"intermediate": 0.2666831314563751,
"beginner": 0.30900946259498596,
"expert": 0.4243074655532837
}
|
12,229
|
Write a c code to add 2 numbers
|
89bf7dfd45b747e5fe1e52e2f95b59ed
|
{
"intermediate": 0.30693453550338745,
"beginner": 0.3137392997741699,
"expert": 0.3793262243270874
}
|
12,230
|
when i use disctint in the manner below, i am missing people that once had many duplicates of, why?
|
3c5e06344c63da1ca7bbda68259131af
|
{
"intermediate": 0.44133487343788147,
"beginner": 0.20458057522773743,
"expert": 0.3540845215320587
}
|
12,231
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
recv_window = 10000 # update the recv_window value
params = {
"timestamp": int(time.time() * 1000),
"recvWindow": recv_window
}
# Get the Binance server time and calculate the time difference
async def get_server_time():
client = await Client.create("","")
server_time = client.time()['serverTime']
local_time = int(time.time() * 1000)
time_difference = server_time - local_time
return time_difference
time_difference = get_server_time()
# Adjust the timestamp to synchronize with the Binance server time
params = {
"timestamp": int(time.time() * 1000) + time_difference,
"recvWindow": recv_window
}
# Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},
'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
params = {
"timestamp": int(time.time() * 1000) + time_difference,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate EMA indicators
ema_10 = ta.trend.EMAIndicator(df['Close'], window=10)
ema_50 = ta.trend.EMAIndicator(df['Close'], window=50)
ema_100 = ta.trend.EMAIndicator(df['Close'], window=100)
ema_200 = ta.trend.EMAIndicator(df['Close'], window=200)
# Calculate MA indicator
ma = ta.trend.SMAIndicator(df['Close'], window=20)
# Calculate EMA indicator values
ema_10_value = ema_10.ema_indicator()[-1] #get the EMA 10 indicator value for the last value in the DataFrame
ema_50_value = ema_50.ema_indicator()[-1] #get the EMA 50 indicator value for the last value in the DataFrame
ema_100_value = ema_100.ema_indicator()[-1] #get the EMA 100 indicator value for the last value in the DataFrame
ema_200_value = ema_200.ema_indicator()[-1] #get the EMA 200 indicator value for the last value in the DataFrame
ma_value = ma.sma_indicator()[-1] #get the MA indicator value for the last value in the DataFrame
#Bearish pattern with EMA and MA indicators
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close and
close<ema_10_value and close<ema_50_value and close<ema_100_value and close<ema_200_value and close<ma_value):
return 'sell'
#Bullish pattern with EMA and MA indicators
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close and
close>ema_10_value and close>ema_50_value and close>ema_100_value and close>ema_200_value and close>ma_value):
return 'buy'
#No clear pattern with EMA and MA indicators
else:
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But I getting ERROR: File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 44, in <module>
"timestamp": int(time.time() * 1000) + time_difference,
~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'coroutine'
sys:1: RuntimeWarning: coroutine 'get_server_time' was never awaited
|
7cc32915689631e5f5a03e1533bd0d13
|
{
"intermediate": 0.34935256838798523,
"beginner": 0.41441482305526733,
"expert": 0.2362326830625534
}
|
12,232
|
import React from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { isAfter, isBefore, isValid } from 'date-fns';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import * as Yup from 'yup';
import { Button, DateTimePicker, MultiSelect } from 'components/common';
import {
ConfirmVoidByTimeRangeModal,
MarketsTableVoidByTimeRange,
} from 'components/manualActions';
import { DATE_FORMAT_WITH_SECONDS, MIN_DATE } from 'constants/manualActions';
import { STATE_SELECTOR_CONFIG } from 'constants/MultiSelect';
import { useManualActionsContext } from 'contexts/ManualActionsContext';
import { usePermissionsContext } from 'contexts/PermissionsContext';
import { BranchStatus } from 'models/BranchStatus';
import {
VoidByTimeRangeFormValues,
VoidByTimeRangePayload,
} from 'models/ManualActions';
import { Market } from 'models/Market';
import { State } from 'models/State';
import { isValidDate } from 'utils/Date';
export interface MarketCardProps {
markets: Market[];
states: State[];
}
export const MarketCardVoidByTimeRange: React.FC<MarketCardProps> = ({
markets,
states,
}) => {
const { t } = useTranslation();
const { isAdminUser } = usePermissionsContext();
const {
event,
voidByTimeRange,
voidByTimeRangeStatus,
setVoidByTimeRangeStatus,
} = useManualActionsContext();
const [isModalOpen, setIsModalOpen] = React.useState(false);
const [dateStart, setDateStart] = React.useState<string>('');
const [dateEnd, setDateEnd] = React.useState<string>('');
const [payload, setPayload] = React.useState<VoidByTimeRangePayload>();
const [selectedStates, setSelectedStates] = React.useState<string[]>(
states.map((state: State) => state.id),
);
const setMinDate = (date: Date) => {
if (isValidDate(date)) {
const minDate = new Date(date);
minDate.setSeconds(minDate.getSeconds() + 1);
return new Date(minDate.setMilliseconds(0)).toISOString();
}
return date;
};
const getDateTime = (date: Date) => new Date(date).setMilliseconds(0);
const { control, handleSubmit, setValue, watch } =
useForm<VoidByTimeRangeFormValues>({
resolver: yupResolver(
Yup.object().shape({
fromDate: Yup.date().required(),
toDate: Yup.date().required(),
states: Yup.array().required(),
}),
),
});
const toDateWatch = watch('toDate');
const fromDateWatch = watch('fromDate');
const maxDate = new Date(Date.now());
React.useEffect(() => {
setValue('states', selectedStates);
}, [selectedStates, setValue]);
const onVoid = async (data: VoidByTimeRangeFormValues) => {
setIsModalOpen(true);
setPayload({
instances: selectedStates,
event: event?.id as string,
markets: markets.map(({ id }) => id),
fromTime: (data.fromDate as Date).getTime(),
toTime: (data.toDate as Date).getTime(),
});
setDateStart((data.fromDate as Date).toUTCString());
setDateEnd((data.toDate as Date).toUTCString());
};
const onSuccess = () => setIsModalOpen(false);
const onFailure = () => setVoidByTimeRangeStatus(BranchStatus.IDLE);
const onConfirmVoidByTimeRange = async () => {
await voidByTimeRange(
onSuccess,
onFailure,
payload as VoidByTimeRangePayload,
);
setVoidByTimeRangeStatus(BranchStatus.IDLE);
};
return (
<>
{voidByTimeRangeStatus !== BranchStatus.FINISHED && (
<ConfirmVoidByTimeRangeModal
selectedStates={selectedStates}
states={states}
markets={markets}
open={isModalOpen}
onClose={() => {
setIsModalOpen(false);
}}
eventName={event?.name as string}
onConfirm={() => onConfirmVoidByTimeRange()}
isLoading={voidByTimeRangeStatus === BranchStatus.LOADING}
dateStart={dateStart}
dateEnd={dateEnd}
/>
)}
<div
className="market-card market-card--vtr"
data-testid="markets-card-vtr"
aria-label={t('accessibility.marketCard')}
>
<div className="market-card__header">
<div className="market-card__header-controls">
<form
className="market-card__form"
onSubmit={handleSubmit(onVoid)}
data-testid="markets-card-vtr-form"
>
<Controller
control={control}
name="fromDate"
defaultValue={null}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.from')}
testId="markets-card-vtr-form-from-field"
name={name}
value={fromDateWatch || value}
maxDate={toDateWatch || maxDate}
maxDateMessage={t('validations.fromMaxMessage')}
onChange={(updatedValue) => onChange(updatedValue)}
variant="dialog"
size="small"
format={DATE_FORMAT_WITH_SECONDS}
/>
)}
/>
<Controller
control={control}
name="toDate"
defaultValue={null}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.to')}
testId="markets-card-vtr-form-to-field"
name={name}
value={toDateWatch || value}
maxDate={maxDate}
minDate={setMinDate(fromDateWatch as Date)}
minDateMessage={t('validations.toMinMessage')}
maxDateMessage={t('validations.toMaxMessage')}
onChange={(updatedValue) => onChange(updatedValue)}
variant="dialog"
size="small"
format={DATE_FORMAT_WITH_SECONDS}
/>
)}
/>
<Controller
control={control}
name="states"
defaultValue={null}
render={() => (
<div className="market-card__states">
<MultiSelect
className="state-selector"
label={t('form.states')}
options={states.map((state) => ({
label: state.name,
value: state.id,
}))}
testId="markets-card-vtr-form-state-selector"
onChange={setSelectedStates}
value={selectedStates}
hasSelectAll
selectAllConfig={STATE_SELECTOR_CONFIG}
required
/>
</div>
)}
/>
<Button
testId="markets-card-vtr-submit-button"
type="submit"
buttonColor="positive"
disabled={
!isAdminUser ||
!isBefore(
getDateTime(fromDateWatch as Date),
getDateTime(toDateWatch as Date),
) ||
isAfter(
getDateTime(toDateWatch as Date),
getDateTime(maxDate),
) ||
!isValid(toDateWatch) ||
!isValid(fromDateWatch) ||
isBefore(fromDateWatch as Date, new Date(MIN_DATE)) ||
!selectedStates.length
}
className="market-card__submit-button"
>
{t('common.cta.void')}
</Button>
</form>
</div>
</div>
<MarketsTableVoidByTimeRange markets={markets} />
</div>
</>
);
};
can I use yup to avoid doing this disabled={
!isAdminUser ||
!isBefore(
getDateTime(fromDateWatch as Date),
getDateTime(toDateWatch as Date),
) ||
isAfter(
getDateTime(toDateWatch as Date),
getDateTime(maxDate),
) ||
!isValid(toDateWatch) ||
!isValid(fromDateWatch) ||
isBefore(fromDateWatch as Date, new Date(MIN_DATE)) ||
!selectedStates.length
}?
|
d68a91c71abe51b9bbab9d0bb3b51c76
|
{
"intermediate": 0.3849891424179077,
"beginner": 0.49039435386657715,
"expert": 0.12461655586957932
}
|
12,233
|
I need WebView example
|
036b4c8a6132b61544802b98f1dbd6bf
|
{
"intermediate": 0.44580528140068054,
"beginner": 0.2954874038696289,
"expert": 0.2587074041366577
}
|
12,234
|
#include "public.h"
#include "key.h"
#include "songdata.h"
#include "reg52.h"
#define Clk 0x070000
#define SMG_A_DP_PORT P0 //使用宏定义数码管段码口
#define RELOAD_COUNT 0xFA //宏定义波特率发生器的载入值 9600
unsigned char data val_H; //计数器高字节
unsigned char data val_L; //计数器低字节
//管脚定义
sbit BEEP=P2^5;
//共阴极数码管显示0~F的段码数据
u8 gsmg_code[17]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
// 音符频率数组
u16 tone[] = {262, 294, 330, 349, 392, 440, 494, 523, 587, 659, 698, 784, 880, 988, 1047, 1175}; // 音调数组
u8 music[32]; // 保存音乐的数组
u8 music_index = 0; // 音乐数组的索引
bit song_playing = 0; // 添加歌曲播放标志
void t0_isr() interrupt 1 //定时器 0 中断处理程序
{
if (song_playing) { // 当歌曲播放标志为真时,产生方波
BEEP = ~BEEP;
} else {
BEEP = 1; // 不产生方波,关闭蜂鸣器
}
TH0 = val_H; //重新装入计数值
TL0 = val_L;
}
void UART_Init(void)
{
SCON=0X50; //设置为工作方式1
TMOD=0X20; //设置计数器工作方式2
PCON=0X80; //波特率加倍
TH1=RELOAD_COUNT; //计数器初始值设置
TL1=TH1;
ES=1; //关闭接收中断
EA=1; //打开总中断
TR1=1; //打开计数器
}
void send_data(u8 sen_data)
{
SBUF = sen_data+0x30; // 将数据放入发送寄存器
while (!TI); // 等待发送数据完成
TI = 0;// 清除发送完成标志位
}
void save_music(u8 key_value)
{
int m=0;
if (music_index < 32)
{
music[music_index] = tone[key_value];
music_index++;
send_data(key_value);
}
else if(music_index>=32)
{
music_index = 0;
for( m = 0; m < 32; m++)
{
music[m] = 0;
}
}
}
void Delay(unsigned char cnt) //单位延时
{
unsigned char i;
unsigned int j;
for(i=0; i<cnt; i++)
{
for(j=0; j<0x3600; j++);
}
}
void main()
{
u8 key1 = 0;
u8 key = 0;
u8 key2 = 0;
u8 loop_flag=0;
unsigned char i = 0;
unsigned int val;
TMOD = 0x01; //初始化
IE = 0x82;
TR0 = 1;
UART_Init();//波特率为9600
while (1)
{
if (loop_flag) {
loop_flag = 0;
continue;
}
SMG_A_DP_PORT=gsmg_code[0];
key1=key_matrix_ranks_scan();
if(key1==13)
{
SMG_A_DP_PORT=gsmg_code[1];
while(!loop_flag)
{
key = key_matrix_ranks_scan(); //检测按键
if (key == 1) //K1按下,放第一首歌
{
i=0;
song_playing = 1;
while (freq_list1[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list1[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list1[i]);
i++;
if ((key_scan(0) != KEY_UNPRESS)||(key_matrix_ranks_scan()==16))
{
// 停止播放并退出循环
loop_flag = 1;
song_playing = 0;
break;
}
}
}
else if (key == 2) //K2按下放第二首歌
{
i=0;
song_playing = 1;
while (freq_list2[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list2[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list2[i]);
i++;
if ((key_scan(0) != KEY_UNPRESS)||(key_matrix_ranks_scan()==16))
{
// 停止播放并退出循环
loop_flag = 1;
song_playing = 0;
break;
}
}
}
else if (key == 3) //K3按下放第三首歌
{
i=0;
song_playing = 1;
while (freq_list3[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list3[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list3[i]);
i++;
if ((key_scan(0) != KEY_UNPRESS)||(key_matrix_ranks_scan()==16))
{
// 停止播放并退出循环
loop_flag = 1;
song_playing = 0;
break;
}
}
}
else if (key == 4) //K4按下放第四首歌
{
i=0;
song_playing = 1;
while (freq_list4[i]) // 频率为 0 重新开始
{
val = Clk / (freq_list4[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(time_list4[i]);
i++;
if (key_scan(0) != KEY_UNPRESS)
{
//停止播放并退出循环
loop_flag = 1;
song_playing = 0;
break;
}
}
}
}
}
//演奏功能
else if(key1==14)
{
SMG_A_DP_PORT=gsmg_code[2];
while (!loop_flag)
{
key2 = key_matrix_ranks_scan();
if (key2!=0)
{
song_playing = 1;
val = Clk / (tone[key2-1]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(2);
song_playing = 0;
save_music(key2-1);
}
else if(key_scan(0) != KEY_UNPRESS)
{
song_playing = 0;
loop_flag=1;
break;
}
}
}
//重复播放功能
else if(key1==15)
{ if(music_index==0)
{
SMG_A_DP_PORT=gsmg_code[14];
Delay(10);
break;
}
else
{
SMG_A_DP_PORT=gsmg_code[3];
while(!loop_flag)
{
song_playing = 1;
for (i=0;i<music_index;i++)
{
val = Clk / (music[i]);
val = 0xFFFF - val; // 计算计数值
val_H = (val >> 8) & 0xff;
val_L = val & 0xff;
TH0 = val_H;
TL0 = val_L;
Delay(4);
if (key_scan(0) != KEY_UNPRESS)
{
song_playing = 0;
loop_flag=1;
break;
}
}
}
}
}
}
}
演奏功能中,为什么第一次按按键后,蜂鸣器会响,再按按键的时候蜂鸣器就不响了?但是串口通信函数send_data还是能正常发送?
|
df6d479b4eb0ac94f0e3fe3887327b7d
|
{
"intermediate": 0.37030264735221863,
"beginner": 0.4311942160129547,
"expert": 0.19850313663482666
}
|
12,235
|
HTML code to get the Picklist beside the primary Quote
|
f9db1b490ffb4456e13f0d0f836cbb78
|
{
"intermediate": 0.3554913401603699,
"beginner": 0.36410167813301086,
"expert": 0.2804069519042969
}
|
12,236
|
$commit doesnt exist on transaction client error , how do i add $commit when setting up transaction client
|
77b0225e4e3651f85e6022910288250c
|
{
"intermediate": 0.568166971206665,
"beginner": 0.20274509489536285,
"expert": 0.22908787429332733
}
|
12,237
|
explain dynamic programming in dart code snippets
|
a7beef1d8e753e6422ea2c9ca80c5aab
|
{
"intermediate": 0.27016210556030273,
"beginner": 0.33140555024147034,
"expert": 0.39843231439590454
}
|
12,238
|
I have matrix Called B with 26 row and 122 columns , I want the data in row of 16 change by Data of row 12 in every columns. write the code for matlab
|
19ed6804e7d3702d00c33854a8689103
|
{
"intermediate": 0.5057079195976257,
"beginner": 0.18164916336536407,
"expert": 0.3126428723335266
}
|
12,239
|
how do I upload a bond trade in simcorp dimension
|
960285d9cce37ad4a0ea0d6a7bb5ce75
|
{
"intermediate": 0.3715744614601135,
"beginner": 0.1814032793045044,
"expert": 0.4470222294330597
}
|
12,240
|
Can we copy blob content from one database server to another database server table ?
|
f5a9d889bae5bb42473cfd8b43df2f53
|
{
"intermediate": 0.3828977644443512,
"beginner": 0.26934006810188293,
"expert": 0.34776222705841064
}
|
12,241
|
please suggest prompts, used to Act as a Software Tester who has excellent experience about software testing and generate UAT cases according to user requirements.
|
9d0091ebed30081f5f1eacd4c42105fc
|
{
"intermediate": 0.3661326766014099,
"beginner": 0.3590255081653595,
"expert": 0.27484187483787537
}
|
12,242
|
I have a div like this:
<div id="btn-category-group" style="height:420px;">
....
</div>
I will use jquery to change the css height:fit-content. So, the height of div will extend to appropiate height based on the content of div. I will it will extend with animation effect.
|
d1d33aca8092a556857aec4a06539172
|
{
"intermediate": 0.43347230553627014,
"beginner": 0.2857285439968109,
"expert": 0.28079912066459656
}
|
12,243
|
import { RenderResult, act, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { mockIpmaClient } from 'api/Client/ClientMock';
import { MarketCardVoidByTimeRange } from 'components/manualActions';
import { manualActionsEndpoints } from 'constants/manualActions';
import { roles } from 'constants/Roles';
import { mockVoidByTimeRangePayload } from 'models/ManualActions';
import { mockMarkets } from 'models/Market';
import { mockStates } from 'models/State';
import { StatusCode } from 'models/StatusCode';
import { ManualActionsWrapper, renderForTest } from 'testUtils';
import en from 'translations/en.json';
const testStrings = {
fromDate: '15/02/2022 14:30:00',
toDate: '15/02/2022 15:30:00',
};
describe('MarketCardVoidByTimeRange.tsx', () => {
let fromDate: HTMLElement, toDate: HTMLElement;
let wrapper: RenderResult;
describe('default', () => {
beforeEach(async () => {
await act(async () => {
wrapper = renderForTest(
<MarketCardVoidByTimeRange
markets={mockMarkets}
states={mockStates}
/>,
);
});
});
it('should render with the default snapshot', () => {
expect(wrapper.container).toMatchSnapshot();
});
it('should select a From date', async () => {
await act(async () => {
userEvent.type(
screen.getByRole(roles.textbox, { name: en.form.from }),
testStrings.fromDate,
);
});
expect(
screen.getByRole(roles.textbox, { name: en.form.from }),
).toHaveValue(testStrings.fromDate);
});
// it('should select a To date', async () => {
// const input = screen.getByRole(roles.textbox, { name: en.form.to });
// await act(async () => {
// userEvent.type(input, testStrings.toDate);
// });
// expect(input).toHaveValue(testStrings.toDate);
// });
it('should select equal From/To dates and show validation', () => {
fromDate = screen.getByRole(roles.textbox, { name: en.form.from });
toDate = screen.getByRole(roles.textbox, { name: en.form.to });
userEvent.type(fromDate, testStrings.fromDate);
userEvent.type(toDate, testStrings.fromDate);
expect(screen.getByText(en.validations.toMinMessage)).toBeInTheDocument();
});
});
// describe('void markets', () => {
// beforeAll(() => {
// mockIpmaClient
// .onPost(manualActionsEndpoints.postVoidByTimeRangeAPI)
// .reply(StatusCode.OK, mockVoidByTimeRangePayload);
// });
// beforeEach(async () => {
// wrapper = renderForTest(
// <ManualActionsWrapper>
// <MarketCardVoidByTimeRange
// markets={mockMarkets}
// states={mockStates}
// />
// </ManualActionsWrapper>,
// );
// fromDate = screen.getByRole(roles.textbox, { name: en.form.from });
// toDate = screen.getByRole(roles.textbox, { name: en.form.to });
// userEvent.type(fromDate, testStrings.fromDate);
// userEvent.type(toDate, testStrings.toDate);
// await act(async () => {
// userEvent.click(
// screen.getByRole(roles.button, { name: en.common.cta.void }),
// );
// });
// });
// it('should open confirmation modal', () => {
// expect(
// screen.getByRole(roles.dialog, { name: en.modal.vtr.title }),
// ).toBeInTheDocument();
// });
// it('should close confirmation modal when cancel button is clicked', async () => {
// userEvent.click(
// screen.getByRole(roles.button, { name: en.accessibility.close }),
// );
// await waitFor(() =>
// expect(
// screen.queryByRole(roles.dialog, { name: en.modal.vtr.title }),
// ).not.toBeInTheDocument(),
// );
// });
// it('should show a success toast after a successful void', async () => {
// userEvent.click(
// screen.getByRole(roles.button, { name: en.common.cta.void }),
// );
// expect(
// await screen.findByRole(roles.alert, {
// name: en.accessibility.success,
// }),
// ).toBeInTheDocument();
// });
// });
// describe('void error', () => {
// beforeAll(() => {
// mockIpmaClient
// .onPost(manualActionsEndpoints.postVoidByTimeRangeAPI)
// .reply(StatusCode.BAD_REQUEST, mockVoidByTimeRangePayload);
// });
// it('should show error toast and keep modal open', async () => {
// wrapper = renderForTest(
// <ManualActionsWrapper>
// <MarketCardVoidByTimeRange
// markets={mockMarkets}
// states={mockStates}
// />
// </ManualActionsWrapper>,
// );
// fromDate = screen.getByRole(roles.textbox, { name: en.form.from });
// toDate = screen.getByRole(roles.textbox, { name: en.form.to });
// userEvent.type(fromDate, testStrings.fromDate);
// userEvent.type(toDate, testStrings.toDate);
// await act(async () => {
// userEvent.click(
// screen.getByRole(roles.button, { name: en.common.cta.void }),
// );
// });
// userEvent.click(
// screen.getByRole(roles.button, { name: en.common.cta.void }),
// );
// expect(
// await screen.findByText(en.toast.errorVTRAllStates),
// ).toBeInTheDocument();
// expect(
// screen.getByRole(roles.dialog, { name: en.modal.vtr.title }),
// ).toBeInTheDocument();
// });
// });
});
console.error
Warning: An update to MarketCardVoidByTimeRange inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at MarketCardVoidByTimeRange (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/components/manualActions/voidByTimeRange/MarketCardVoidByTimeRange/MarketCardVoidByTimeRange.tsx:37:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/@tanstack/react-query/build/lib/QueryClientProvider.js:65:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/providers/QueryClientProvider/QueryClientProvider.tsx:16:3)
at FeedbackProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FeedbackContext/FeedbackContext.tsx:46:3)
at FeedbackWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeedbackUtils.tsx:4:3)
at ToastProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ToastContext/ToastContext.tsx:44:3)
at ToastWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/ToastUtils.tsx:6:3)
at I18nextProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-i18next/dist/commonjs/I18nextProvider.js:13:19)
at I18NWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/I18NUtils.tsx:8:3)
at FlagsProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FlagsContext/FlagsContext.tsx:36:3)
at FeatureFlagsWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeatureFlagsUtils.tsx:11:3)
at ThemeContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ThemeContext/ThemeContextMock.tsx:10:3)
at PermissionsContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/PermissionsContext/PermissionsContextMock.tsx:11:8)
at TestWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/TestUtils.tsx:32:3)
at Router (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-router/lib/components.tsx:290:13)
at RouterWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/RouterUtils.tsx:10:3)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
at node_modules/react-hook-form/src/useForm.ts:168:9
at node_modules/react-hook-form/src/useForm.ts:224:9
at node_modules/react-hook-form/src/useForm.ts:395:9
console.error
Warning: An update to MarketCardVoidByTimeRange inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at MarketCardVoidByTimeRange (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/components/manualActions/voidByTimeRange/MarketCardVoidByTimeRange/MarketCardVoidByTimeRange.tsx:37:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/@tanstack/react-query/build/lib/QueryClientProvider.js:65:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/providers/QueryClientProvider/QueryClientProvider.tsx:16:3)
at FeedbackProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FeedbackContext/FeedbackContext.tsx:46:3)
at FeedbackWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeedbackUtils.tsx:4:3)
at ToastProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ToastContext/ToastContext.tsx:44:3)
at ToastWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/ToastUtils.tsx:6:3)
at I18nextProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-i18next/dist/commonjs/I18nextProvider.js:13:19)
at I18NWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/I18NUtils.tsx:8:3)
at FlagsProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FlagsContext/FlagsContext.tsx:36:3)
at FeatureFlagsWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeatureFlagsUtils.tsx:11:3)
at ThemeContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ThemeContext/ThemeContextMock.tsx:10:3)
at PermissionsContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/PermissionsContext/PermissionsContextMock.tsx:11:8)
at TestWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/TestUtils.tsx:32:3)
at Router (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-router/lib/components.tsx:290:13)
at RouterWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/RouterUtils.tsx:10:3)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
at node_modules/react-hook-form/src/useForm.ts:168:9
at node_modules/react-hook-form/src/useForm.ts:224:9
at node_modules/react-hook-form/src/useForm.ts:395:9
console.error
Warning: An update to MarketCardVoidByTimeRange inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at MarketCardVoidByTimeRange (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/components/manualActions/voidByTimeRange/MarketCardVoidByTimeRange/MarketCardVoidByTimeRange.tsx:37:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/@tanstack/react-query/build/lib/QueryClientProvider.js:65:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/providers/QueryClientProvider/QueryClientProvider.tsx:16:3)
at FeedbackProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FeedbackContext/FeedbackContext.tsx:46:3)
at FeedbackWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeedbackUtils.tsx:4:3)
at ToastProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ToastContext/ToastContext.tsx:44:3)
at ToastWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/ToastUtils.tsx:6:3)
at I18nextProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-i18next/dist/commonjs/I18nextProvider.js:13:19)
at I18NWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/I18NUtils.tsx:8:3)
at FlagsProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FlagsContext/FlagsContext.tsx:36:3)
at FeatureFlagsWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeatureFlagsUtils.tsx:11:3)
at ThemeContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ThemeContext/ThemeContextMock.tsx:10:3)
at PermissionsContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/PermissionsContext/PermissionsContextMock.tsx:11:8)
at TestWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/TestUtils.tsx:32:3)
at Router (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-router/lib/components.tsx:290:13)
at RouterWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/RouterUtils.tsx:10:3)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
at node_modules/react-hook-form/src/useForm.ts:168:9
at node_modules/react-hook-form/src/useForm.ts:224:9
at node_modules/react-hook-form/src/useForm.ts:395:9
console.error
Warning: An update to MarketCardVoidByTimeRange inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
at MarketCardVoidByTimeRange (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/components/manualActions/voidByTimeRange/MarketCardVoidByTimeRange/MarketCardVoidByTimeRange.tsx:37:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/@tanstack/react-query/build/lib/QueryClientProvider.js:65:3)
at QueryClientProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/providers/QueryClientProvider/QueryClientProvider.tsx:16:3)
at FeedbackProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FeedbackContext/FeedbackContext.tsx:46:3)
at FeedbackWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeedbackUtils.tsx:4:3)
at ToastProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ToastContext/ToastContext.tsx:44:3)
at ToastWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/ToastUtils.tsx:6:3)
at I18nextProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-i18next/dist/commonjs/I18nextProvider.js:13:19)
at I18NWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/I18NUtils.tsx:8:3)
at FlagsProvider (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/FlagsContext/FlagsContext.tsx:36:3)
at FeatureFlagsWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/FeatureFlagsUtils.tsx:11:3)
at ThemeContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/ThemeContext/ThemeContextMock.tsx:10:3)
at PermissionsContextMock (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/contexts/PermissionsContext/PermissionsContextMock.tsx:11:8)
at TestWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/TestUtils.tsx:32:3)
at Router (/Users/ricardobarata/dev/repos/multi-state-management-ui/node_modules/react-router/lib/components.tsx:290:13)
at RouterWrapper (/Users/ricardobarata/dev/repos/multi-state-management-ui/src/testUtils/RouterUtils.tsx:10:3)
at printWarning (node_modules/react-dom/cjs/react-dom.development.js:86:30)
at error (node_modules/react-dom/cjs/react-dom.development.js:60:7)
at warnIfUpdatesNotWrappedWithActDEV (node_modules/react-dom/cjs/react-dom.development.js:27589:9)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:25508:5)
at dispatchSetState (node_modules/react-dom/cjs/react-dom.development.js:17527:7)
at node_modules/react-hook-form/src/useForm.ts:168:9
at node_modules/react-hook-form/src/useForm.ts:224:9
at node_modules/react-hook-form/src/useForm.ts:395:9 why?
|
c82123676ef5b33e7cfd66814a1efac4
|
{
"intermediate": 0.39765337109565735,
"beginner": 0.47864848375320435,
"expert": 0.12369812279939651
}
|
12,244
|
lockdown cron job linux
|
ae535c31f6eff5b1c12f5714f1d7879a
|
{
"intermediate": 0.3584286570549011,
"beginner": 0.3111704885959625,
"expert": 0.3304007649421692
}
|
12,245
|
В плеере (audio player) Кнопка play не работает, прогресс-бар не работает. Элементы плеера должны быть скрыты до тех пор на них не будет наведен курсор на карточку/обложку
index:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<% if (!userLoggedIn) { %>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
<% } else { %>
<li class="nav-item">
<a class="nav-link"><i class="fa fa-user" aria-hidden="true"></i> Hello, <%= username %></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/logout"><i class="fa fa-sign-out" aria-hidden="true"></i> Logout</a>
</li>
<% } %>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- audio player -->
<div class="audio-player">
<div class="audio-player-inner">
<div class="audio-tracklist">
<% tracks.forEach((track, index) => { %>
<div class="audio-track">
<div class="audio-track-image">
<img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>">
</div>
<div class="audio-track-info">
<h4><%= track.title %></h4>
<p class="album-title"><%= track.album_title || "No Album" %></p>
</div>
<div class="audio-player-wrapper">
<button class="audio-player-button" onclick="togglePlay(<%= index %>)">
<i class="audio-player-icon fa fa-play"></i>
</button>
<audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>" ontimeupdate="updateProgress(<%= index %>)"></audio>
<input type="range" id="progress-bar-<%= index %>" class="progress-bar" value="0" onchange="setProgress(<%= index %>, this.value)">
<span class="progress-time" id="progress-time-<%= index %>">0:00</span>
</div>
</div>
<% }); %>
</div>
</div>
</div>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script>
function togglePlay(index) {
const audio = document.getElementById(`audio-${index}`);
const button = document.querySelector(`.audio-track:nth-child(${index + 1}) .audio-player-button`);
if (audio.paused) {
audio.play();
button.innerHTML = '<i class="audio-player-icon fa fa-pause"></i>';
} else {
audio.pause();
button.innerHTML = '<i class="audio-player-icon fa fa-play"></i>';
}
}
function setProgress(index, value) {
const audio = document.getElementById(`audio-${index}`);
audio.currentTime = (value / 100) * audio.duration;
}
function updateProgress(index) {
const audio = document.getElementById(`audio-${index}`);
const progressBar = document.getElementById(`progress-bar-${index}`);
const progressTime = document.getElementById(`progress-time-${index}`);
const value = (audio.currentTime / audio.duration) * 100;
progressBar.value = value;
const minutes = Math.floor(audio.currentTime / 60);
const seconds = Math.floor(audio.currentTime % 60).toString().padStart(2, '0');
progressTime.innerHTML = `${minutes}:${seconds}`;
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script>
const playButtons = document.querySelectorAll('.fa-play');
playButtons.forEach((button, index) => {
const audio = document.querySelector(`#audio-${index}`);
button.addEventListener('click', () => {
audio.play();
});
});
</script>
<script>
$("#city").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
</script>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</script>
</body>
</html>
css:
/* audio player */
.audio-player {
margin: 50px auto;
max-width: 800px;
}
.audio-player-inner {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.audio-tracklist {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
margin: 0;
padding: 0;
list-style: none;
}
.audio-track {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-right: 20px;
margin-bottom: 20px;
max-width: 300px;
text-align: center;
height: auto;
position: relative;
}
.audio-track-image {
width: 100%;
height: 0;
padding-bottom: 100%;
position: relative;
}
.audio-track-image img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.audio-track-info {
width: 100%;
margin-top: 10px;
text-align: center;
}
.audio-track-info h4 {
margin-top: 0;
font-size: 18px;
font-weight: bold;
}
.audio-track-info p {
margin-bottom: 0;
font-size: 14px;
}
.audio-player-wrapper {
position: relative;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 50px;
margin-top: 10px;
}
.audio-player-button {
display: flex;
justify-content: center;
align-items: center;
border: none;
background: none;
cursor: pointer;
margin-right: 10px;
}
.audio-player-icon {
font-size: 24px;
color: #333;
}
.progress-bar {
width: 100%;
height: 5px;
-webkit-appearance: none;
appearance: none;
background: #ddd;
outline: none;
cursor: pointer;
}
.progress-bar::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: #333;
cursor: pointer;
}
.progress-bar::-moz-range-thumb {
width: 15px;
height: 15px;
border-radius: 50%;
background: #333;
cursor: pointer;
}
.progress-time {
font-size: 12px;
margin-left: 10px;
color: #666;
}
|
426a18d3f9aaf224277733082cca558a
|
{
"intermediate": 0.25799572467803955,
"beginner": 0.5962821841239929,
"expert": 0.14572201669216156
}
|
12,246
|
generate html landing page for "automatic code generation" with modern ui
|
7462d2b483401b6f1482774dec80a1c8
|
{
"intermediate": 0.3108541667461395,
"beginner": 0.2161998301744461,
"expert": 0.47294607758522034
}
|
12,247
|
Error --- PrismaClientKnownRequestError:
Invalid `tx.interpolatedQuote.create()` invocation in
/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1085:39
1082
1083 if (quoteId) {
1084 acc.push(
→ 1085 tx.interpolatedQuote.create(
Transaction API error: Transaction already closed: A batch query cannot be executed on a closed transaction..
at RequestHandler.handleRequestError (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/node_modules/@prisma/client/runtime/index.js:29909:13)
at RequestHandler.request (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/node_modules/@prisma/client/runtime/index.js:29892:12)
at async PrismaClient._request (/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/node_modules/@prisma/client/runtime/index.js:30864:16)
at async Promise.all (index 0) {
code: 'P2028',
clientVersion: '4.3.1',
meta: {
error: 'Transaction already closed: A batch query cannot be executed on a closed transaction..'
}
}
**msg
Invalid `tx.interpolatedQuote.create()` invocation in
/home/user/Documents/projects-r/360-dev/ess-backend/ess-backend/src/Controllers/StatisticianController.ts:1085:39
1082
1083 if (quoteId) {
1084 acc.push(
→ 1085 tx.interpolatedQuote.create(
how do i fix this error
|
47c8969fadb4d8884909dfe67953089b
|
{
"intermediate": 0.5924493074417114,
"beginner": 0.21345719695091248,
"expert": 0.1940934956073761
}
|
12,248
|
Есть код сервера на java. Но что если клиент пришлет файл больше, чем может вместить в себя буфер сервера? Исправь код так, чтобы эта проблема решалась корректно
package serverUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
public class ConnectionManager {
private static final String ACK_MESSAGE_PREFIX = "<%s>Ack";
static final int BUFFER_SIZE = 1024 * 1024;
ServerSocketChannel serverSocketChannel;
int port;
public ConnectionManager(int port) {
this.port = port;
}
public void initialize() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
System.out.println("Server started on port " + port);
System.out.println("============ * ============");
}
public void registerSelector(Selector selector) throws ClosedChannelException {
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void processQuery(Selector selector, SelectionKey key) throws IOException {
if (!key.isValid()) {
return;
}
if (key.isAcceptable()) {
acceptConnection(key, selector);
} else if (key.isReadable()) {
handleRead(key);
}
}
private void acceptConnection(SelectionKey key, Selector selector) throws IOException {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
SocketChannel clientSocketChannel = serverSocketChannel.accept();
clientSocketChannel.configureBlocking(false);
// Attach new ConnectionContext instance to the selection key
ConnectionContext context = new ConnectionContext();
clientSocketChannel.register(selector, SelectionKey.OP_READ, context);
System.out.println("Accepted connection from " + clientSocketChannel.getRemoteAddress());
}
private void handleRead(SelectionKey key) throws IOException {
SocketChannel clientSocketChannel = (SocketChannel) key.channel();
ConnectionContext connectionContext = (ConnectionContext) key.attachment();
if (connectionContext == null) {
connectionContext = new ConnectionContext();
key.attach(connectionContext);
}
ByteBuffer buffer = connectionContext.buffer;
int bytesRead = clientSocketChannel.read(buffer);
if (bytesRead < 0) {
System.out.println("Closed connection with " + clientSocketChannel.getRemoteAddress());
clientSocketChannel.close();
key.cancel();
System.out.println("============ * ============");
return;
}
buffer.flip();
// handle file transmission
if (connectionContext.fileStarted) {
// check if we need more data to continue reading the file
if (connectionContext.fileName != null && connectionContext.fileLength >= 0 &&
buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
// read the file contents
byte[] fileContent = new byte[connectionContext.fileLength];
buffer.get(fileContent);
// check the separator
connectionContext.separator = buffer.getLong();
if (connectionContext.separator != 0L) {
throw new RuntimeException("Invalid separator");
}
// save the file and send an acknowledgement
saveFile(connectionContext.fileName, fileContent);
sendAck(clientSocketChannel, connectionContext.fileName);
// reset context for next file transfer
connectionContext.fileStarted = false;
connectionContext.fileCompleted = true;
connectionContext.fileName = null;
connectionContext.fileLength = -1;
// handle any remaining data in buffer
if (buffer.remaining() > 0) {
handleRead(key);
return;
}
}
} else {
// read the header of the file transfer
while (buffer.hasRemaining() && !connectionContext.fileStarted) {
// read the name length
if (connectionContext.fileName == null && buffer.remaining() >= Integer.BYTES) {
int nameLength = buffer.getInt();
byte[] nameBytes = new byte[nameLength];
buffer.get(nameBytes);
connectionContext.fileName = new String(nameBytes, StandardCharsets.UTF_8);
}
// read the file length
if (connectionContext.fileLength < 0 && buffer.remaining() >= Integer.BYTES) {
connectionContext.fileLength = buffer.getInt();
if (connectionContext.fileLength < 0) {
throw new RuntimeException("Invalid file length");
}
connectionContext.fileStarted = true;
// check if we need more data to continue reading the file
if (buffer.remaining() < BUFFER_SIZE) {
buffer.compact();
return;
}
}
}
}
// handle file transmission continued with remaining data in buffer
if (connectionContext.fileStarted && !connectionContext.fileCompleted &&
buffer.remaining() >= connectionContext.fileLength + Long.BYTES) {
// read the file contents
byte[] fileContent = new byte[connectionContext.fileLength];
buffer.get(fileContent);
// check the separator
connectionContext.separator = buffer.getLong();
if (connectionContext.separator != 0L) {
throw new RuntimeException("Invalid separator");
}
// save the file and send an acknowledgement
saveFile(connectionContext.fileName, fileContent);
sendAck(clientSocketChannel, connectionContext.fileName);
// reset context for next file transfer
connectionContext.fileStarted = false;
connectionContext.fileCompleted = true;
connectionContext.fileName = null;
connectionContext.fileLength = -1;
// handle any remaining data in buffer
if (buffer.remaining() > 0) {
handleRead(key);
return;
}
}
buffer.compact();
}
private void saveFile(String filename, byte[] fileContent) throws IOException {
File file = new File("files\\" + filename);
System.out.println("Saving file " + filename);
try (FileOutputStream outputStream = new FileOutputStream(file, true)) {
int offset = 0;
while (offset < fileContent.length) {
int bytesToWrite = Math.min(BUFFER_SIZE, fileContent.length - offset);
outputStream.write(fileContent, offset, bytesToWrite);
offset += bytesToWrite;
}
outputStream.flush();
}
System.out.println("File " + filename + " saved successfully");
}
private void sendAck(SocketChannel clientSocketChannel, String filename) throws IOException {
String ackMessage = String.format(ACK_MESSAGE_PREFIX, filename);
byte[] ackMessageBytes = ackMessage.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(ackMessageBytes.length + Integer.BYTES);
buffer.putInt(ackMessageBytes.length);
buffer.put(ackMessageBytes);
buffer.flip();
while (buffer.hasRemaining()) {
clientSocketChannel.write(buffer);
}
System.out.println("Sent acknowledgement for " + filename);
buffer.clear(); // Очищаем буфер перед чтением новых данных
}
}
|
34dc49ceffe07de39a54cf899ed37c9a
|
{
"intermediate": 0.3445409834384918,
"beginner": 0.44155725836753845,
"expert": 0.21390168368816376
}
|
12,249
|
using ReactJS get the user Ip address and Mac address and post them with a form submission to the asp.net core backend
|
e115ab437bd71ecfcd06010961bb266e
|
{
"intermediate": 0.5354111194610596,
"beginner": 0.1749803125858307,
"expert": 0.28960859775543213
}
|
12,250
|
tell me a programming joke
|
d4f01b7b70dc9307ff4aedac2cd0a0f9
|
{
"intermediate": 0.24252457916736603,
"beginner": 0.29295438528060913,
"expert": 0.46452105045318604
}
|
12,251
|
from flask import Flask, current_app, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_basicauth import BasicAuth
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
from flask_admin.contrib.sqla.ajax import QueryAjaxModelLoader
from wtforms_sqlalchemy.fields import QuerySelectField
from flask_admin.form.widgets import Select2Widget
app = Flask(__name__)
app.config['FLASK_ADMIN_SWATCH'] = 'cyborg'
#app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:stargate16062012@localhost/mydb'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:stargate16062012@localhost/far_vbr_sqlalchemy'
app.config['SECRET_KEY'] = 'mysecret'
#app.config['BASIC_AUTH_USERNAME'] = 'admin'
#app.config['BASIC_AUTH_PASSWORD'] = 'admin'
db = SQLAlchemy(app)
#basic_auth = BasicAuth(app)
#auth = HTTPBasicAuth()
admin = Admin(app, name='vktu', template_mode='bootstrap3')
class Vbr(db.Model):
tablename = 'vbr'
id_vbr = db.Column(db.Integer, primary_key=True)
code_vbr = db.Column(db.BigInteger, nullable=False)
nasvanie_vbr = db.Column(db.String(255), nullable=False)
vid_vbr_id = db.Column(db.Integer, db.ForeignKey('vid_vbr.id_vid_vbr'))
vid_vbr_code = db.Column(db.BigInteger, nullable=False)
vid_vbr_nasvanie = db.Column(db.String(255), nullable=False)
vid_vbr = db.relationship('Vid_vbr', backref='vbrs')
class Vid_vbr(db.Model):
tablename = 'vid_vbr'
id_vid_vbr = db.Column(db.Integer, primary_key=True)
code_vid_vbr = db.Column(db.BigInteger, nullable=False)
nasvanie_vid_vbr = db.Column(db.String(255), nullable=False)
class VbrAdmin(ModelView):
column_choices = {}
def __init__(self, session):
# добавляем контекст приложения Flask
with app.app_context():
self.column_choices = {
'vid_vbr_nasvanie': [
(c.id_vid_vbr, c.nasvanie_vid_vbr) for c in Vid_vbr.query.order_by(Vid_vbr.nasvanie_vid_vbr).all()
]
}
super(VbrAdmin, self).__init__(Vbr, session)
with app.app_context():
admin.add_view(VbrAdmin(Vbr, db.session))
if __name__ == '__main__':
app.run()
|
6a0b0e71ddb9ffe343e353597d60835a
|
{
"intermediate": 0.3393853008747101,
"beginner": 0.5057823061943054,
"expert": 0.15483231842517853
}
|
12,252
|
How do websockets work?
|
9b782f70a895c938160e29d49e1aeece
|
{
"intermediate": 0.2684578001499176,
"beginner": 0.23296374082565308,
"expert": 0.49857842922210693
}
|
12,253
|
这个vba的语法错误在哪
If sourceSheet.Cells(i, 50).Value = "" Then:
kehu = sourceSheet.Cells(i, 40).Value
Else:
kehu = sourceSheet.Cells(i, 50).Value
|
af5279f37502c3ba385e9e98beef1f5c
|
{
"intermediate": 0.3589250445365906,
"beginner": 0.42457064986228943,
"expert": 0.21650438010692596
}
|
12,254
|
make a dockerfile for hosting a S3 container
|
559d49c2d6fd43bbc840efc2f9cf1456
|
{
"intermediate": 0.40038561820983887,
"beginner": 0.2466168850660324,
"expert": 0.3529975414276123
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.