row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
12,958
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 import ta.volatility 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 } # Define the sync_time() function 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()}’) # 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 exchange = ccxt.binance({ ‘apiKey’: API_KEY, ‘secret’: API_SECRET, ‘enableRateLimit’: True, }) symbol = ‘BTC/USDT’ orderbook = exchange.fetch_order_book(symbol) current_price = (orderbook[‘bids’][0][0] + orderbook[‘asks’][0][0]) / 2 def get_server_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): # Calculate EMA and MA lines df[‘EMA5’] = df[‘Close’].ewm(span=5, adjust=False).mean() df[‘EMA10’] = df[‘Close’].ewm(span=10, adjust=False).mean() df[‘EMA20’] = df[‘Close’].ewm(span=20, adjust=False).mean() df[‘EMA50’] = df[‘Close’].ewm(span=50, adjust=False).mean() df[‘EMA100’] = df[‘Close’].ewm(span=100, adjust=False).mean() df[‘EMA200’] = df[‘Close’].ewm(span=200, adjust=False).mean() df[‘MA10’] = df[‘Close’].rolling(window=10).mean() df[‘MA20’] = df[‘Close’].rolling(window=20).mean() df[‘MA50’] = df[‘Close’].rolling(window=50).mean() df[‘MA100’] = df[‘Close’].rolling(window=100).mean() open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] # Calculate MACD indicators ema_12 = df[‘Close’].ewm(span=12, adjust=False).mean() ema_26 = df[‘Close’].ewm(span=26, adjust=False).mean() macd_line = ema_12 - ema_26 signal_line = macd_line.ewm(span=9, adjust=False).mean() histogram = macd_line - signal_line ema_analysis = ‘’ candle_analysis = ‘’ macd_analysis = ‘’ # EMA crossover - buy signal if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and current_price > last_candle[[‘EMA10’, ‘EMA50’]].iloc[-1].min(): ema_analysis = ‘buy’ # EMA crossover - sell signal elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and current_price < last_candle[[‘EMA10’, ‘EMA50’]].iloc[-1].max(): ema_analysis = ‘sell’ # EMA crossover - buy signal if df.EMA20.iloc[-1] > df.EMA200.iloc[-1] and current_price > last_candle[[‘EMA20’, ‘EMA200’]].iloc[-1].min(): ema_analysis = ‘buy’ # EMA crossover - sell signal elif df.EMA20.iloc[-1] < df.EMA200.iloc[-1] and current_price < last_candle[[‘EMA20’, ‘EMA200’]].iloc[-1].max(): ema_analysis = ‘sell’ # Check for bullish trends elif current_price > last_candle[[‘EMA5’, ‘EMA20’, ‘EMA50’, ‘EMA100’, ‘EMA200’]].iloc[-1].max(): ema_analysis = ‘buy’ # Check for bearish trends elif current_price < last_candle[[‘EMA5’, ‘EMA20’, ‘EMA50’, ‘EMA100’, ‘EMA200’]].iloc[-1].min(): ema_analysis = ‘sell’ # Check for bullish candlestick pattern if (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): candle_analysis = ‘buy’ # Check for bearish candlestick pattern elif (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): candle_analysis = ‘sell’ # MACD trading strategy - buy signal if macd_line.iloc[-1] > signal_line.iloc[-1] and histogram.iloc[-1] > 0: macd_analysis = ‘buy’ # MACD trading strategy - sell signal elif macd_line.iloc[-1] < signal_line.iloc[-1] and histogram.iloc[-1] < 0: macd_analysis = ‘sell’ # Check if both analyses are the same if ema_analysis == candle_analysis == macd_analysis and ema_analysis != ‘’: return ema_analysis # If no signal is found, return an empty string 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: ccxt.base.errors.InvalidNonce: binance {“code”:-1021,“msg”:“Timestamp for this request was 1000ms ahead of the server’s time.”}
8548669ce4781d1a9babc3c67f1f1d5a
{ "intermediate": 0.42280885577201843, "beginner": 0.3101496994495392, "expert": 0.26704141497612 }
12,959
I used 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 import ta.volatility 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 = 60000 # increased recv_window value params = { "timestamp": timestamp, "recvWindow": recv_window } # Define the sync_time() function 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()}') # 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 exchange = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, }) symbol = 'BTC/USDT' orderbook = exchange.fetch_order_book(symbol) current_price = (orderbook['bids'][0][0] + orderbook['asks'][0][0]) / 2 def get_server_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): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] # Calculate MACD indicators ema_12 = df['Close'].ewm(span=12, adjust=False).mean() ema_26 = df['Close'].ewm(span=26, adjust=False).mean() macd_line = ema_12 - ema_26 signal_line = macd_line.ewm(span=9, adjust=False).mean() histogram = macd_line - signal_line ema_analysis = '' candle_analysis = '' macd_analysis = '' # EMA crossover - buy signal if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and current_price > last_candle[['EMA10', 'EMA50']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and current_price < last_candle[['EMA10', 'EMA50']].iloc[-1].max(): ema_analysis = 'sell' # EMA crossover - buy signal if df.EMA20.iloc[-1] > df.EMA200.iloc[-1] and current_price > last_candle[['EMA20', 'EMA200']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA20.iloc[-1] < df.EMA200.iloc[-1] and current_price < last_candle[['EMA20', 'EMA200']].iloc[-1].max(): ema_analysis = 'sell' # Check for bullish trends elif current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].max(): ema_analysis = 'buy' # Check for bearish trends elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].min(): ema_analysis = 'sell' # Check for bullish candlestick pattern if (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): candle_analysis = 'buy' # Check for bearish candlestick pattern elif (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): candle_analysis = 'sell' # MACD trading strategy - buy signal if macd_line.iloc[-1] > signal_line.iloc[-1] and histogram.iloc[-1] > 0: macd_analysis = 'buy' # MACD trading strategy - sell signal elif macd_line.iloc[-1] < signal_line.iloc[-1] and histogram.iloc[-1] < 0: macd_analysis = 'sell' # Check if both analyses are the same if ema_analysis == candle_analysis == macd_analysis and ema_analysis != '': return ema_analysis # If no signal is found, return an empty string 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: ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
68bc14cd1ec62c5af20c159b3f9e6fbb
{ "intermediate": 0.46815791726112366, "beginner": 0.3695414960384369, "expert": 0.16230058670043945 }
12,960
write a A simple e-commerce website with a shopping cart in javascript
0754597eb578db264188f79b0d4c519d
{ "intermediate": 0.34292230010032654, "beginner": 0.3506617546081543, "expert": 0.3064159154891968 }
12,961
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 import ta.volatility 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) - 500 # subtract 500ms from local time to account for clock-drift recv_window = 60000 # increased recv_window value params = { "timestamp": timestamp, "recvWindow": recv_window } # Define the sync_time() function 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()}') # 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 exchange = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, }) symbol = 'BTC/USDT' orderbook = exchange.fetch_order_book(symbol) current_price = (orderbook['bids'][0][0] + orderbook['asks'][0][0]) / 2 def get_server_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): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] # Calculate MACD indicators ema_12 = df['Close'].ewm(span=12, adjust=False).mean() ema_26 = df['Close'].ewm(span=26, adjust=False).mean() macd_line = ema_12 - ema_26 signal_line = macd_line.ewm(span=9, adjust=False).mean() histogram = macd_line - signal_line ema_analysis = '' candle_analysis = '' macd_analysis = '' # EMA crossover - buy signal if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and current_price > last_candle[['EMA10', 'EMA50']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and current_price < last_candle[['EMA10', 'EMA50']].iloc[-1].max(): ema_analysis = 'sell' # EMA crossover - buy signal if df.EMA20.iloc[-1] > df.EMA200.iloc[-1] and current_price > last_candle[['EMA20', 'EMA200']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA20.iloc[-1] < df.EMA200.iloc[-1] and current_price < last_candle[['EMA20', 'EMA200']].iloc[-1].max(): ema_analysis = 'sell' # Check for bullish trends elif current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].max(): ema_analysis = 'buy' # Check for bearish trends elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].min(): ema_analysis = 'sell' # Check for bullish candlestick pattern if (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): candle_analysis = 'buy' # Check for bearish candlestick pattern elif (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): candle_analysis = 'sell' # MACD trading strategy - buy signal if macd_line.iloc[-1] > signal_line.iloc[-1] and histogram.iloc[-1] > 0: macd_analysis = 'buy' # MACD trading strategy - sell signal elif macd_line.iloc[-1] < signal_line.iloc[-1] and histogram.iloc[-1] < 0: macd_analysis = 'sell' # Check if both analyses are the same if ema_analysis == candle_analysis == macd_analysis and ema_analysis != '': return ema_analysis # If no signal is found, return an empty string return '' df = get_klines(symbol, '1m', 44640) But I getting ERROR: Traceback (most recent call last): File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 560, in fetch response.raise_for_status() File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1687338253719&recvWindow=10000&signature=75cc3503713eb9eb853f3d21646317a24b565fc323782f3e62f123a6b16293d9 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 101, in <module> orderbook = exchange.fetch_order_book(symbol) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2636, in fetch_order_book self.load_markets() File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 1391, in load_markets currencies = self.fetch_currencies() ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 1707, in fetch_currencies response = self.sapiGetCapitalConfigGetall(params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method return _self.request(self.path, self.api, self.method, params, config=self.config) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7409, in request response = self.fetch2(path, api, method, params, headers, body, config) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2819, in fetch2 return self.fetch(request['url'], request['method'], request['headers'], request['body']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 576, in fetch skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7386, in handle_errors self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback) File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3169, in throw_exactly_matched_exception raise exact[string](message) ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
d69c91c7410c51a8a9dd4db3e8e6f0e2
{ "intermediate": 0.41625741124153137, "beginner": 0.40029528737068176, "expert": 0.18344725668430328 }
12,962
Explain what the following code does and rewrite it with torch.pad: def pad(tensor, length): return torch.cat( [ tensor, tensor.new(length - tensor.size(0), *tensor.size()[1:]).zero_(), ] )
383970b778b76b3e55473852be695f7d
{ "intermediate": 0.3652975559234619, "beginner": 0.3520130217075348, "expert": 0.2826894223690033 }
12,963
please explain RPSFT model in survival analysis in a plain language. Please explain with simulated data examples in R software.
3e505db9e34905f184f928c32d58f25b
{ "intermediate": 0.18650545179843903, "beginner": 0.16056771576404572, "expert": 0.6529268622398376 }
12,964
Как реализовать добавление такого элемента через View asp.net core: using System.ComponentModel.DataAnnotations; namespace AttractionWebApp.Entities; public partial class Attraction { public int Id { get; set; } [Required(ErrorMessage = "Название не может быть пустым!")] public string AttractionName { get; set; } = null!; public string? History { get; set; } public virtual ICollection<Photo> Photos { get; set; } = new List<Photo>(); public virtual ICollection<AttractionType> Types { get; set; } = new List<AttractionType>(); }
e2607f1d912c55b904ed86db2ce8751c
{ "intermediate": 0.4112268090248108, "beginner": 0.44645625352859497, "expert": 0.14231695234775543 }
12,965
please explain rank-preserving structural failure time model in a plain language, and please explain with simulated data in R software.
a8d6c22f63ba3773196dbab334084b84
{ "intermediate": 0.13428419828414917, "beginner": 0.07618866860866547, "expert": 0.789527177810669 }
12,966
build a python web application based on kubernetes, fastapi, pydantic, opentelemetry, which serving a CRUD operations for kubernetes customresourcedefinition named Mediaplan
34dae9e4b48cc597161d47824a39c151
{ "intermediate": 0.8190644383430481, "beginner": 0.046741239726543427, "expert": 0.13419434428215027 }
12,967
build a python web application based on kubernetes, fastapi, pydantic, opentelemetry, which serving a CRUD operations for kubernetes customresourcedefinition named Mediaplan. write a code without explanation
12067e919e909f795ebcc6c78b9d00db
{ "intermediate": 0.678954541683197, "beginner": 0.11394230276346207, "expert": 0.20710311830043793 }
12,968
hello
21fa6ef28304e020be904a9113b581fe
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
12,969
this is a resource called Mediaplan
7c7a9848ba04954b98462840006d19a1
{ "intermediate": 0.3933121860027313, "beginner": 0.24743878841400146, "expert": 0.3592489957809448 }
12,970
build a python web application based on kubernetes, fastapi, pydantic, opentelemetry with jaeger exporter support, which serving a CRUD operations for kubernetes custom resource definition named Mediaplan. Application must support next functions: get list of mediaplan, create or update mediaplan (as one method), delete mediaplan, get mediaplan spec
73a47528fd7584bf22044e6133062d2b
{ "intermediate": 0.7954320311546326, "beginner": 0.12028177082538605, "expert": 0.08428622037172318 }
12,971
I have this bitbucket pipeline file image: node:18.3.0 options: size: 2x clone: depth: full definitions: caches: sonar: ~/.sonar/cache definitions: steps: - step: &scan name: Security Scan script: - pipe: atlassian/git-secrets-scan:0.5.1 - step: &smell name: Sonar Scan size: 2x caches: - sonar script: - pipe: sonarsource/sonarcloud-scan:1.4.0 variables: EXTRA_ARGS: "-Dsonar.sources=src" - step: &lint name: Lint script: - npm install - npm run lint:verify - step: &test name: Test script: - npm install - npm run test:ci pipelines: branches: master: - step: *scan - step: *smell - step: *lint - step: *test pull-requests: "**": - step: *scan - step: *smell - step: *lint - step: *test The sonar scan step is passing but when I look in SonarCloud it is showing no code as being analysed, and the test step is failing with the following message + npm run test:ci > slack-bot-desk-genie@1.0.0 test:ci > jest --silent No tests found, exiting with code 1 Run with `--passWithNoTests` to exit with code 0 In /opt/atlassian/pipelines/agent/build 102 files checked. testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 13 matches testPathIgnorePatterns: /build/ - 0 matches testRegex: - 0 matches Pattern: - 0 matches
a6a3f47920d67a7d9dcf0c693fdc4959
{ "intermediate": 0.2933214604854584, "beginner": 0.4115554094314575, "expert": 0.2951231896877289 }
12,972
'parent.relativePath' of POM com.bluebalance:endowment-server:1.0-SNAPSHOT (C:\Users\mwy161005\Desktop\智慧养老系统--二期\code\endowment-server\pom.xml) points at com.bluebalance:endowment-server instead of org.springframe work.boot:spring-boot-starter-parent, please verify your project structure @ line 8, column 13 这个是什么原因
7073a79c850c42d2b03615ecd46bbfd5
{ "intermediate": 0.42245277762413025, "beginner": 0.25579774379730225, "expert": 0.3217494487762451 }
12,973
i have written a drag and drop function for my website. how to check if the drag and drop at the same div?
ec0cba5f335b43d798864a57c1c51f0c
{ "intermediate": 0.5788387060165405, "beginner": 0.21628399193286896, "expert": 0.2048773467540741 }
12,974
How to enable transactional in jooq with r2dbc
fc6b2415ebd247c0ce9f90d0e2c1ea35
{ "intermediate": 0.43760183453559875, "beginner": 0.12772315740585327, "expert": 0.434675008058548 }
12,975
сделай расположение полей ввода информации о кредиторах более логичным и красивым import tkinter as tk from tkinter import ttk from ttkthemes import ThemedTk def calculate(): cash = float(cash_entry.get()) division = {} debt = sum(float(cred['value'].get()) for cred in creditors) for creditor in creditors: name = creditor['name'].get() value = float(creditor['value'].get()) is_percent = creditor['is_percent'].get() percent_or_fee = float(creditor['percent_or_fee'].get()) ratio = value / debt * 100 if is_percent: division[name] = (cash / 100 * ratio) / (1 + percent_or_fee / 100) else: division[name] = (cash / 100 * ratio) - percent_or_fee update_results(division) def update_results(division): result_frame.grid(column=1, row=4, sticky='w', padx=5, pady=5) for label in result_frame.grid_slaves(): label.destroy() for idx, (name, value) in enumerate(division.items()): ttk.Label(result_frame, text=name).grid(column=0, row=idx, padx=5, pady=5) ttk.Label(result_frame, text=f'%.2f' % value).grid(column=1, row=idx, padx=5, pady=5) def add_creditor(): cred_frame = ttk.Frame(creditors_frame, relief='groove', borderwidth=2) cred_frame.grid(column=0, row=len(creditors), sticky='ew', padx=5, pady=5) name = tk.StringVar() value = tk.StringVar() is_percent = tk.BooleanVar() percent_or_fee = tk.StringVar() ttk.Label(cred_frame, text="Название кредитора:").grid(column=0, row=0, sticky='w', padx=5, pady=5) ttk.Entry(cred_frame, textvariable=name).grid(column=1, row=0, sticky='ew', padx=5) ttk.Label(cred_frame, text="Сумма долга:").grid(column=0, row=1, sticky='w', padx=5, pady=5) ttk.Entry(cred_frame, textvariable=value).grid(column=1, row=1, sticky='ew', padx=5) check = ttk.Checkbutton(cred_frame, text="Является ли комиссия процентами?", variable=is_percent) check.grid(column=0, row=2, sticky='w', columnspan=2, padx=5) ttk.Label(cred_frame, text="Комиссия проценты/сумма:").grid(column=0, row=3, sticky='w', padx=5, pady=5) ttk.Entry(cred_frame, textvariable=percent_or_fee).grid(column=1, row=3, sticky='ew', padx=5) delete_button = ttk.Button(cred_frame, text="Удалить", command=lambda: delete_creditor(cred_frame)) delete_button.grid(column=0, row=4, columnspan=2, padx=5, pady=5) creditors.append({ 'frame': cred_frame, 'name': name, 'value': value, 'is_percent': is_percent, 'percent_or_fee': percent_or_fee }) def delete_creditor(frame): for creditor in creditors: if creditor['frame'] == frame: creditor['frame'].destroy() creditors.remove(creditor) break def clear_all(): cash_entry.delete(0, tk.END) for creditor in creditors: creditor['frame'].destroy() creditors.clear() result_frame.grid_forget() root = ThemedTk(theme="arc") root.title("Распределение денежных средств") cash_label = ttk.Label(root, text="Введите количество денег у должника:") cash_entry = ttk.Entry(root) cash_label.grid(column=0, row=0, sticky='w', padx=5, pady=5) cash_entry.grid(column=1, row=0, sticky='ew', padx=5, pady=5) creditors_frame = ttk.Frame(root) creditors_frame.grid(column=0, row=1, columnspan=2, padx=5, pady=5) creditors = [] add_button = ttk.Button(root, text="Добавить кредитора", command=add_creditor) add_button.grid(column=0, row=2, columnspan=2, padx=5, pady=5) calculate_button = ttk.Button(root, text="Рассчитать", command=calculate) calculate_button.grid(column=0, row=3, columnspan=2, padx=5, pady=5) result_label = ttk.Label(root, text="Результаты:") result_label.grid(column=0, row=4, sticky='w', padx=5, pady=5) result_frame = ttk.Frame(root) clear_button = ttk.Button(root, text="Очистить все", command=clear_all) clear_button.grid(column=0, row=5, columnspan=2, padx=5, pady=5) root.columnconfigure(1, weight=1, minsize=150) root.rowconfigure(4, weight=1, minsize=150) root.mainloop()
4daaed182f34b78cf78abc02142cea90
{ "intermediate": 0.2575177550315857, "beginner": 0.5760106444358826, "expert": 0.16647160053253174 }
12,976
получаю ошибку при использовании mongodb в своем скрипте: C:\Users\Ilya\Downloads\nomer>node main.js Сервер запущен на порту 3000 Ошибка загрузки номеров телефонов: MongooseError: Operation `phoneNumbers.find()` buffering timed out after 10000ms at Timeout.<anonymous> (C:\Users\Ilya\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:185:23) at listOnTimeout (node:internal/timers:564:17) at process.processTimers (node:internal/timers:507:7) Ошибка подключения к MongoDB: MongooseServerSelectionError: connect ECONNREFUSED ::1:27017 at _handleConnectionErrors (C:\Users\Ilya\node_modules\mongoose\lib\connection.js:792:11) at NativeConnection.openUri (C:\Users\Ilya\node_modules\mongoose\lib\connection.js:767:11) at runNextTicks (node:internal/process/task_queues:60:5) at listOnTimeout (node:internal/timers:533:9) at process.processTimers (node:internal/timers:507:7) { reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => [ServerDescription] }, stale: false, compatible: true, heartbeatFrequencyMS: 10000, localThresholdMS: 15, setName: null, maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined } дело в том, что я импортировал через compass данные из data.json и переписал скрипт так, чтобы считывать данные уже из mongodb. Я создал базу данных и коллекицю phoneNumbers, которая имеет следующий вид в mongodb:_id 6492d415a91404ad3dbbf693 number "9649396437" url "/phone/<PRESIDIO_ANONYMIZED_PHONE_NUMBER>" comments Array 0 "Чмошники, развод, не ведитесь" callType "" предыдущая версия main.js: const express = require("express"); const ejs = require("ejs"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Создать маршрут для страницы с информацией о номере телефона app.get("/phone/:number", (req, res) => { const phoneNumbers = JSON.parse(fs.readFileSync("data.json")); const phoneNumber = phoneNumbers.find((phone) => phone.number === req.params.number); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Маршрут для главной страницы app.get("/", (req, res) => { const phoneNumbers = JSON.parse(fs.readFileSync("data.json")); const data = { phoneNumbers: phoneNumbers, }; const html = ejs.render(fs.readFileSync("views/index.ejs", "utf8"), data); res.send(html); }); // Запуск сервера app.listen(3000, () => { console.log("Сервер запущен на порту 3000"); }); текущая версия main.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://localhost:27017/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Подключение к MongoDB установлено')) .catch(err => console.error('Ошибка подключения к MongoDB:', err)); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }, { collection: 'phoneNumbers' // указываем название коллекции }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema); // Создать маршрут для страницы с информацией о номере телефона app.get("/phone/:number", async (req, res) => { try { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } } catch (err) { console.error('Ошибка поиска номера телефона:', err); res.status(500).send('Ошибка на сервере'); } }); // Маршрут для главной страницы app.get("/", async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().limit(100).sort({ _id: -1 }).exec(); const data = { phoneNumbers: phoneNumbers, }; const html = ejs.render(fs.readFileSync("views/index.ejs", "utf8"), data); res.send(html); } catch (err) { console.error('Ошибка загрузки номеров телефонов:', err); res.status(500).send('Ошибка на сервере'); } }); // Запуск сервера app.listen(3000, () => { console.log("Сервер запущен на порту 3000"); });
463e932de9c965c8b43e2ea650e0365f
{ "intermediate": 0.358545184135437, "beginner": 0.48090726137161255, "expert": 0.1605476588010788 }
12,977
can i max the length for a string option in the interaction discord js
38c243389c9d79fe7a9a5e639dd35245
{ "intermediate": 0.44352662563323975, "beginner": 0.21479663252830505, "expert": 0.3416767120361328 }
12,978
apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: mediaplans.crds.idom.project spec: group: crds.idom.project versions: - name: v1alpha1 served: true storage: true schema: openAPIV3Schema: type: object properties: spec: type: object properties: schedule: type: string channel: type: object properties: name: type: string guid: type: string id: type: integer discussion_id: type: integer options: type: object properties: messages: type: object properties: kind: type: string topics: type: array items: type: object properties: code: type: string weight: type: integer files: type: array items: type: object properties: uri: type: string bots: type: object properties: totalCount: type: integer selectors: type: object properties: accounts: type: object properties: credentials: type: object properties: status: type: string mimicry: type: object properties: roleGuid: type: string settings: type: object properties: totalMessageCount: type: integer estimatedLeadTime: type: string disableMimicryOptions: type: boolean # add additional versions here scope: Namespaced names: plural: mediaplans singular: mediaplan kind: Mediaplan
1ff6b41cb0e880c99bcc16d8d56e8a33
{ "intermediate": 0.33715853095054626, "beginner": 0.37363436818122864, "expert": 0.2892071306705475 }
12,979
MainActivity.java import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { private EditText etFrom, etTo, etDistance; private Spinner spVehicle; private Button btnCalculate; private TextView tvResult; private String selectedVehicle; private String[] vehicles = {“Тягач”, “Фургон”, “Пикап”}; private double[] vehiclePrices = {15, 20, 10, 25, 30, 20, 10, 15, 5}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Получение ссылок на элементы пользовательского интерфейса etFrom = findViewById(R.id.et_from); etTo = findViewById(R.id.et_to); etDistance = findViewById(R.id.et_distance); spVehicle = findViewById(R.id.sp_vehicle); btnCalculate = findViewById(R.id.btn_calculate); tvResult = findViewById(R.id.tv_result); // Создание адаптера для спиннера ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, vehicles); // Установка адаптера для спиннера spVehicle.setAdapter(adapter); spVehicle.setOnItemSelectedListener(this); // Установка слушателя для кнопки “Рассчитать” btnCalculate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { calculate(); } }); } private void calculate() { // Получение значений входных данных String from = etFrom.getText().toString(); String to = etTo.getText().toString(); String distanceString = etDistance.getText().toString(); // Проверка наличия значений входных данных if (from.length() == 0) { Toast.makeText(this, R.string.error_from, Toast.LENGTH_SHORT).show(); return; } if (to.length() == 0) { Toast.makeText(this, R.string.error_to, Toast.LENGTH_SHORT).show(); return; } if (distanceString.length() == 0) { Toast.makeText(this, R.string.error_distance, Toast.LENGTH_SHORT).show(); return; } double distance = Double.parseDouble(distanceString); // Расчет итоговой стоимости маршрута double totalPrice = findPrice(selectedVehicle) * distance; // Отображение результата tvResult.setText(getString(R.string.result, selectedVehicle, from, to, distanceString, totalPrice)); } private double findPrice(String vehicle) { // Поиск стоимости автомобиля int index = 0; for (int i = 0; i < vehicles.length; i++) { if (vehicles[i].equals(vehicle)) { index = i; break; } } return vehiclePrices[index]; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Получение выбранного автомобиля selectedVehicle = (String) parent.getItemAtPosition(position); } @Override public void onNothingSelected(AdapterView<?> parent) { selectedVehicle = “Тягач”; } } activity_main.xml <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android” xmlns:tools=“http://schemas.android.com/tools” android:layout_width=“match_parent” android:layout_height=“match_parent” tools:context=“.MainActivity”> <EditText android:id=“@+id/et_from” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:hint=“@string/hint_from” android:inputType=“textCapWords” android:padding=“16dp” android:textSize=“18sp” android:layout_marginTop=“16dp”/> <EditText android:id=“@+id/et_to” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:hint=“@string/hint_to” android:inputType=“textCapWords” android:padding=“16dp” android:textSize=“18sp” android:layout_below=“@+id/et_from”/> <EditText android:id=“@+id/et_distance” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:hint=“@string/hint_distance” android:inputType=“numberDecimal” android:padding=“16dp” android:textSize=“18sp” android:layout_below=“@+id/et_to”/> <Spinner android:id=“@+id/sp_vehicle” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:layout_marginTop=“16dp” android:prompt=“@string/prompt_vehicle” android:padding=“16dp” android:textSize=“18sp” android:layout_below=“@+id/et_distance”/> <Button android:id=“@+id/btn_calculate” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:text=“@string/btn_calculate” android:textSize=“18sp” android:layout_marginTop=“16dp” android:layout_below=“@+id/sp_vehicle”/> <TextView android:id=“@+id/tv_result” android:layout_width=“match_parent” android:layout_height=“wrap_content” android:textSize=“18sp” android:padding=“16dp” android:layout_marginTop=“16dp” android:text=“@string/result” android:layout_below=“@+id/btn_calculate”/> </RelativeLayout> strings.xml <resources> <string name=“app_name”>Грузоперевозка</string> <string name=“hint_from”>Откуда</string> <string name=“hint_to”>Куда</string> <string name=“hint_distance”>Расстояние (км)</string> <string name=“prompt_vehicle”>Выберите автомобиль</string> <string name=“btn_calculate”>Рассчитать</string> <string name=“result”>Вы выбрали %1$s.\n\nМаршрут: от %2$s до %3$s, расстояние %4$s км.\n\nЦена: %.2f руб.</string> <string name=“error_from”>Введите место отправления</string> <string name=“error_to”>Введите место назначения</string> <string name=“error_distance”>Введите расстояние</string> </resources> почему не работает
9ed3a93f3cfba43f02f525e0b48b9a4e
{ "intermediate": 0.26325681805610657, "beginner": 0.5716402530670166, "expert": 0.16510289907455444 }
12,980
how do i use a spotify api code for my python game, i want to use real and accurate listeners numbers for the artits import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, } while True: score = 0 # reset score at the beginning of each game first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) while True: guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() else: score = 0 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round break
20fd4293c2bcea6ca3e5128cd36555fb
{ "intermediate": 0.3518681526184082, "beginner": 0.4321284592151642, "expert": 0.2160034030675888 }
12,981
what is the right way to call a cmd script in windowS?
2a032f5b5552f3297021ef2ac0b4280b
{ "intermediate": 0.2694968581199646, "beginner": 0.4024142920970917, "expert": 0.32808879017829895 }
12,982
import random import spotipy from spotipy.oauth2 import SpotifyClientCredentials artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, } while True: score = 0 # reset score at the beginning of each game first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) while True: guess = input( f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > \ artists_listeners[second_artist]: print( f"You guessed correctly! {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > \ artists_listeners[first_artist]: print( f"You guessed correctly! {second_artist.title()} had {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round continue else: print( f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists_listeners[first_artist] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists_listeners[second_artist] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() else: score = 0 first_artist, second_artist = random.sample(list(artists_listeners.keys()), 2) # select new artists for the next round break how can i use spotify api key to use real time listeners numbers and dont need to change them manually
ed47a769b286ab083c291622a69132ad
{ "intermediate": 0.3673029839992523, "beginner": 0.47023963928222656, "expert": 0.16245737671852112 }
12,983
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.cgg.wsp.dto.ServerDto["srvDatabaseList"]->java.util.ArrayList[0]->com.cgg.wsp.dto.DatabaseDto["dbServer"]->com.cgg.wsp.dto.ServerDto["srvDatabaseList"]->java.util.ArrayList[0]->com.cgg.wsp.dto.DatabaseDto["dbServer"]->com.cgg.wsp.dto.ServerDto["srvDatabaseList"]->java.util.ArrayList[0]->com.cgg.wsp.dto.DatabaseDto["dbServer"]->com.cgg.wsp.dto.ServerDto["srvDatabaseList"]->java.util.ArrayList[0]->com.cgg.wsp.dto.DatabaseDto["dbServer"]->com.cgg.wsp.dto.ServerDto["srvDatabaseList"]
c9cb4e45f2ba51ecdb4950ed1aeaca0d
{ "intermediate": 0.431342214345932, "beginner": 0.3205203711986542, "expert": 0.24813735485076904 }
12,984
based on this on pfsense downloading pfblockerng how can I incraese the timeout? MaxMind download already in process... cURL Error: 28 Operation timed out after 600004 milliseconds with 56136 out of 3013918 bytes received Retry in 5 seconds... . cURL Error: 28 Operation timed out after 600001 milliseconds with 56960 out of 3013918 bytes received Retry in 5 seconds... . cURL Error: 28 Operation timed out after 600000 milliseconds with 61189 out of 3013918 bytes received Retry in 5 seconds... . /usr/local/share/GeoIP/GeoLite2-Country.tar.gz 200 OK .gunzip: data stream error gunzip: /usr/local/share/GeoIP/GeoLite2-Country.tar.gz.raw: uncompress failed Decompression Failed
99f1c6b092a1094991706618b3af0e29
{ "intermediate": 0.5485633015632629, "beginner": 0.21483683586120605, "expert": 0.236599862575531 }
12,985
How to install ni to linux mint>
d42aa63dc925f82a303a63b0409a0cdb
{ "intermediate": 0.453987181186676, "beginner": 0.22303162515163422, "expert": 0.32298120856285095 }
12,986
import spotipy from spotipy.oauth2 import SpotifyClientCredentials # Authenticate and connect to the Spotify API auth_manager = SpotifyClientCredentials(client_id='11c13ca507ad43d8915df4b5aecdd93f', client_secret='34b8cc443c6244a58de8f855ff380466') sp = spotipy.Spotify(auth_manager=auth_manager) # Ask the user to input the name of an artist artist_name = input("Enter the name of an artist: ") # Search for the artist result = sp.search(q=artist_name, type='artist', limit=1) artist_id = result['artists']['items'][0]['id'] # Get detailed information about the artist, including their followers and monthly listeners count artist_info = sp.artist(artist_id) followers_count = artist_info['followers']['total']/1e6 monthly_listeners = artist_info['followers']['total']/1e6 # Print some information about the artist in 1.4M format print(f"{artist_name.title()} has {followers_count:.1f}M followers on Spotify and {monthly_listeners:.1f}M monthly listeners.") why does the code show the same number twice for followes and listeners
563b8e4fa060eb8f32be6ae22fbb3da9
{ "intermediate": 0.48058006167411804, "beginner": 0.26169976592063904, "expert": 0.2577202022075653 }
12,987
I have several xlsx files in R. I want to write a function that will read each xlsx file using the readxl library and put them into one data frame. I only want to read in data from sheets named "X Data". I only want to read in the following columns from each file and sheet: Batch No Day 0 Date Indication [CLL/SLL, DLBCL or aALL] from PAF Filled Dose Level [1,2 or 3] Manufacturing Site FP FLOW Viability [%] FP FLOW %CD3 FP FLOW %CD19 FP FLOW %CAR Dose Level 1 ≥ 1,7% Dose Level 2 ≥ 3,4% Dose Level 3 ≥ 3,4% FP ENDO Endotoxin Concentration [EU/ml] FP PCR CART-19 [transgene copies/cell] FP STER BacT/ALERT [positive/negative] FP APPEAR [color/range]
e0b8041b4e8094dcce5c1107cfdbb30f
{ "intermediate": 0.6448566913604736, "beginner": 0.15158617496490479, "expert": 0.203557088971138 }
12,988
I'm using the following code in R to read several xlsx files: # loop through each file for (file_name in file_names){ # read in the xlsx file sheet_names <- excel_sheets(file_name) sheet_data <- lapply(sheet_names, function(sheet_name){ read_excel(file_name, sheet = sheet_name, col_names = T) }) # filter to only the “X Data” sheet tryCatch({ x_data <- sheet_data[sheet_names == "X Data"][[1]] }, error = function(e){ message(paste0("Sheet not found in file: ", file_name)) return(NULL) }) # select only the desired columns if (!is.null(x_data)) { selected_cols <- c("Batch No", "Day 0 Date") But the problem I'm having is that my "Day 0 Date" is being read in as text but it is actually a date column in my xlsx
9c8a5f79d6f09d1a6103e9c239544c32
{ "intermediate": 0.3607105314731598, "beginner": 0.4578474462032318, "expert": 0.1814420372247696 }
12,989
provide nodejs code for create customer zoho subscriptions
fb2dbb9a33eee2d76acbe5b64a96d3d1
{ "intermediate": 0.46393585205078125, "beginner": 0.26532331109046936, "expert": 0.2707408368587494 }
12,990
"local function OnEquipped() local Viewmodel = ReplicatedStorage.v_blanktemplate:Clone() local Idle = Instance.new("Animation") Idle.AnimationId = "rbxassetid://13817547456" local PullOut = Instance.new("Animation") PullOut.AnimationId = "rbxassetid://13817532673" Viewmodel.Parent = Camera Viewmodel.Name = "GunViewmodel" ContentProvider:PreloadAsync({ Idle, PullOut }) local AnimationTrackIdle = Viewmodel.Animation.Animator:LoadAnimation(Idle) local AnimationTrackPO = Viewmodel.Animation.Animator:LoadAnimation(PullOut) AnimationTrackPO:Play()" How do i make the "AnimationTrackIdle" play after "AnimationTrackPO" has ended
5b27b8aa910ca157757c6de21c2475c2
{ "intermediate": 0.43769294023513794, "beginner": 0.3305884301662445, "expert": 0.23171861469745636 }
12,991
how do i make a line of code wait while or a function wait while the whole script runs normally?
2f11ffc5c2e01f80989ac46be31067e2
{ "intermediate": 0.3951376676559448, "beginner": 0.405354768037796, "expert": 0.19950757920742035 }
12,992
import spotipy import pandas as pd from spotipy.oauth2 import SpotifyOAuth from spotify_client_secret import * # Authenticate and connect to the Spotify API scope = "user-library-read" sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id='11c13ca507ad43d8915df4b5aecdd93f', client_secret='34b8cc443c6244a58de8f855ff380466', redirect_uri=fe, scope=scope)) # Ask the user to input the name of an artist artist_name = input("Enter the name of an artist: ") # Get the Spotify URI for the artist result = sp.search(q=artist_name, type='artist', limit=1) artist_uri = result['artists']['items'][0]['uri'] # Get the profile information and insights for the artist response = sp.artist_insights([{'artist_uri': artist_uri}]) artist_profile = response['profiles'][0] artist_insights = response['artist'] # Get the monthly listeners count for the artist monthly_listeners = artist_insights['monthly_listeners'] monthly_listeners_m = monthly_listeners/1e6 # Print some information about the artist in 1.4M format print(f"{artist_name.title()} has {monthly_listeners_m:.1f}M monthly listeners.") make this game easier to read
76304c26e5db3717ff56a1fab876ec1a
{ "intermediate": 0.5554579496383667, "beginner": 0.29163658618927, "expert": 0.15290547907352448 }
12,993
Hello how are you
09615fb9390c90ea19e0aedf1732361e
{ "intermediate": 0.368703156709671, "beginner": 0.31437674164772034, "expert": 0.31692010164260864 }
12,994
How to nx: Server stopped because: "this process is no longer the current daemon"
455296ba05e3996d9d5353f95eb0941c
{ "intermediate": 0.3566470742225647, "beginner": 0.23857422173023224, "expert": 0.40477871894836426 }
12,995
What sort of triangles occur in every regular polygon, when each vertex is joined to the centre by a straight line? Except a hexagon
339f168563f50c666a00501360568c0d
{ "intermediate": 0.34830597043037415, "beginner": 0.36096444725990295, "expert": 0.2907295227050781 }
12,996
<blockquote class="card-blockquote"> Молчат, через 4 секунды ложат трубку <span class="type">Неадекваты</span> </blockquote> проблема здесь в том, что span class type находится внутри blockquote, нужно регулярное выражение, которое убирает внутри blockqoute span class type В конечном счете у меня получается такой текст: "Молчат, через 4 секунды ложат трубку Неадекваты", а надо "Молчат, через 4 секунды ложат трубку". код: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения только новых номеров в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(1); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); for (let index = 0; index < phoneElements.length; index++) { const element = phoneElements[index]; const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim(); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = await PhoneNumber.findOne({ number: phoneNumber }); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: comments.split('\n'), callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); existingPhoneNumber.save(); } // Если обработаны все номера телефонов, сохраняем новые номера в базу данных и выводим отладочную информацию if (index === phoneElements.length - 1) { console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); if (newPhoneNumbers.length > 0) { try { await PhoneNumber.create(newPhoneNumbers); console.log(`Добавлено ${newPhoneNumbers.length} новых номеров телефонов в базу данных.`); } catch (error) { console.error(`Ошибка при добавлении новых номеров телефонов: ${error.message}`); } } } } } // Создать маршрут для страницы с информацией о номере телефона app.get('/phone/:number', async (req, res) => { const phoneNumber = req.params.number; const matchedPhoneNumbers = await PhoneNumber.find({ number: phoneNumber }); res.render('phone', { phoneNumbers: matchedPhoneNumbers }); }); // Маршрут для главной страницы app.get("/", async (req,res) => { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(20); const data = { phoneNumbers: phoneNumbers, lastPageUrl: phoneNumbers.length > 0 ? phoneNumbers[0].url : null, }; res.render('index', data); }); // Запустить процесс поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 60 * 1000); // Запустить сервер const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Сервер запущен на порту ${port}.`); // Начать поиск новых номеров телефонов при запуске сервера getNewPhoneNumbers(); });
77561c1954c9ed2da1a63fa0dabba245
{ "intermediate": 0.3166453242301941, "beginner": 0.4903316795825958, "expert": 0.1930229812860489 }
12,997
Hi. I need code in python for API requests for hoster hetzner
50bea10c7930552ad3f42b1a5ac84edf
{ "intermediate": 0.8169897794723511, "beginner": 0.0657101571559906, "expert": 0.11730001866817474 }
12,998
Synaptic package manager alternative
0002a38e501461184e7d5ff452e747c9
{ "intermediate": 0.42893654108047485, "beginner": 0.2505170404911041, "expert": 0.32054638862609863 }
12,999
Hi. I need code in python for API requests for hoster hetzner It should contain arguments for list all server, provide information about server and output should be in json format.
f605e0e57a3abd5f2af79a4baa3864b6
{ "intermediate": 0.7983945608139038, "beginner": 0.05975297465920448, "expert": 0.1418524980545044 }
13,000
I need python script for cloud api for adding more server with arguments taken from file and\or from user input.
ca320df7f77c0db59a48b6c445aa4000
{ "intermediate": 0.7010172605514526, "beginner": 0.11577801406383514, "expert": 0.18320472538471222 }
13,001
how do i make a line of code wait while or a function wait while the whole script runs normally in a roblox studio script?
992bb55c3b4548583bd5e241c3a0f5b5
{ "intermediate": 0.3646603524684906, "beginner": 0.5097761154174805, "expert": 0.12556356191635132 }
13,002
Hello, how u doing?:)
960ea9fccbbe9eb728f60f83d7bdbccf
{ "intermediate": 0.3760395050048828, "beginner": 0.29084715247154236, "expert": 0.3331133723258972 }
13,003
hi
9e51b36bbb3e83c1d9c2b5270e38a785
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,004
Hello! I need your help!
83314bb226f1d9af353cd477a3c8f111
{ "intermediate": 0.3314456641674042, "beginner": 0.2825686037540436, "expert": 0.38598576188087463 }
13,005
is zero padding ascii normally leading zeros?
fb076ba1602956764a0c17a8ac921250
{ "intermediate": 0.317309707403183, "beginner": 0.2516705393791199, "expert": 0.43101975321769714 }
13,006
How to create an instance of System.FormattableString variable for EF ?
6a10e8664fb7f595e948a0f5793ef72b
{ "intermediate": 0.4610045552253723, "beginner": 0.3511485159397125, "expert": 0.18784691393375397 }
13,007
import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> with SingleTickerProviderStateMixin { double ballDiameter = 50; double floor = 0; double ceiling = 1.0; double ballPositionX = 50; double ballPositionY = 300; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; late AnimationController _animationController; bool isDragging = false; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(minutes: 1), // set the duration to one minute )..repeat(); _animationController.addListener(() { _updateBall(_animationController.lastElapsedDuration!.inMilliseconds.toDouble()); }); } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx / 2; ballVelocityY += -details.delta.dy / 2; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double timeStamp) { double delta = timeStamp / 1000; if (!isDragging) { setState(() { ballPositionX += ballVelocityX * delta; ballPositionY += ballVelocityY * delta; double currentFloor = MediaQuery.of(context).size.height - ballDiameter / 2; if (ballPositionY > currentFloor) { ballPositionY = currentFloor; ballVelocityY *= -restitution; ballVelocityX *= friction; } else if (ballPositionY < ceiling + ballDiameter / 2) { ballPositionY = ceiling + ballDiameter / 2; ballVelocityY *= -restitution; ballVelocityX *= friction; } else { ballVelocityY += gravity * delta; } if (ballPositionX < ballDiameter / 2) { ballPositionX = ballDiameter / 2; ballVelocityX *= -restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - ballDiameter / 2) { ballPositionX = MediaQuery.of(context).size.width - ballDiameter / 2; ballVelocityX *= -restitution; } }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height - ballDiameter / 2; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Container( color: Colors.grey[300], child: const SizedBox.expand(), ), ), Positioned( left: ballPositionX - ballDiameter / 2, bottom: ballPositionY - ballDiameter / 2, child: Container( width: ballDiameter, height: ballDiameter, decoration: const BoxDecoration( color: Colors.red, shape: BoxShape.circle, ), ), ), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); Hello! I have a Flutter app, which code i put above. It simulates the bouncing ball behaviour. Can you remove animation controller and add Timer to rerun _updateBall() method?
30137238e027c26f58b6e99b6ed3aa01
{ "intermediate": 0.26170146465301514, "beginner": 0.5033512115478516, "expert": 0.2349473536014557 }
13,008
suppose I am unding oracle JDK and i want to create a trustore
96c0b013c86c6e737b97dabfeff5652f
{ "intermediate": 0.4064769446849823, "beginner": 0.14378903806209564, "expert": 0.44973400235176086 }
13,009
в index.ejs, когда у номера несколько комментариев, показывает один комментарий, а в phone.ejs показывает совершенно другой, хотя должен показывать два комментария. и в phone.ejs не показывает тип звонка только у некоторых номеров (когда-то показывает, когда-то нет, я не понимаю от чего это зависит), не смотря на то что тип звонка присвоен app.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Соединение с MongoDB установлено"); }) .catch((err) => { console.error("Ошибка подключения к MongoDB:", err); }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения их в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); phoneElements.each((index, element) => { const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, ''); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: [comments], callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); PhoneNumber.updateOne({ _id: existingPhoneNumber._id }, { comments: existingPhoneNumber.comments }) .then(() => { console.log(`Комментарий "${comments}" добавлен к номеру ${phoneNumber}`); }) .catch((err) => { console.error(`Ошибка обновления комментария для номера ${phoneNumber}:`, err); }); } }); console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); // Сохранить новые номера телефонов в базе данных if (newPhoneNumbers.length > 0) { for (const phoneNumber of newPhoneNumbers) { const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber.number); if (!existingPhoneNumber) { await PhoneNumber.create(phoneNumber); } } } } catch (err) { console.error("Ошибка при поиске новых номеровтелефонов:", err); } } // Отображение списка номеров телефонов на главной странице app.get('/', async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); res.render('index', { phoneNumbers }); } catch (err) { console.error("Ошибка при получении списка номеров телефонов:", err); res.status(500).send("Ошибка на сервере"); } }); app.get("/phone/:number", async (req, res) => { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Запуск процесса поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 10 * 1000); // Запуск сервера const PORT = 3000; app.listen(PORT, () => { console.log(`Сервер запущен на порту ${PORT}`); }); index.ejs: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Список номеров телефонов</title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> </head> <body> <div class="container"> <h1 class="my-5">Список номеров телефонов</h1> <ul class="list-group"> <% for (let i = 0; i < 12 && i < phoneNumbers.length; i++) { %> <li class="list-group-item"> <div class="d-flex justify-content-between align-items-center"> <h2 class="mb-0"><a href="/phone/<%= phoneNumbers[i].number %>"><%= phoneNumbers[i].number %></a></h2> <% if (phoneNumbers[i].callType) { %> <small class="text-muted"><%= phoneNumbers[i].callType %></small> <% } %> </div> <% if (phoneNumbers[i].comments.length > 0) { %> <p class="my-2"><%= phoneNumbers[i].comments.join(", ") %></p> <% } %> </li> <% } %> </ul> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> phone.ejs: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Номер телефона <%= number %></title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <h1 class="my-5">Номер телефона <%= number %></h1> <% if (comments.length > 0) { %> <div class="card mb-3"> <div class="card-header">Комментарии</div> <ul class="list-group list-group-flush"> <% for (let i = 0; i < comments.length; i++) { %> <li class="list-group-item"><%= comments[i] %></li> <% } %> </ul> </div> <% } else { %> <p>Нет комментариев для этого номера телефона.</p> <% } %> <% if (callType) { %> <p class="my-2">Тип звонка: <%= callType %></p> <% } %> <a href="/" class="btn btn-primary">Назад к списку номеров телефонов</a> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html>
cfa002f0db179fdd6af41ba4a5e3828f
{ "intermediate": 0.32467809319496155, "beginner": 0.5315238833427429, "expert": 0.14379802346229553 }
13,010
import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 1.0; double ceiling = 0; double ballPositionX = 50; double ballPositionY = 300; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; double currentCeiling = 0 + AppConstants.ballSize / 2; if (ballPositionY < currentCeiling) { ballPositionY = currentCeiling; ballVelocityY *= -restitution; ballVelocityX *= restitution; } else if (ballPositionY > floor - AppConstants.ballSize / 2) { ballPositionY = floor - AppConstants.ballSize / 2; ballVelocityY *= -restitution; ballVelocityX *= restitution; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Container( color: Colors.grey[300], child: const SizedBox.expand(), ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), )), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); Hello! I have a Flutter app, that simulates the bouncing ball behavior (code of the app is mentioned above). Right now I have an issue, that ball is jumping endlessly on the bottom of screen, when its must to just stop. Can you fix it? Also, can you add a restriction, that not allow user to adjust ball speed if current ball speed is higher than 3?
c70e758384f5fa7c6652586b21a93f2a
{ "intermediate": 0.3149673044681549, "beginner": 0.4166015684604645, "expert": 0.26843106746673584 }
13,011
в index.ejs, когда у номера несколько комментариев, показывает один комментарий, а в phone.ejs показывает совершенно другой, когда переходишь на phone хотя должен показывать все два комментария, а не один из. например, в index показывает коммент: "Вообще некопетентные молодые девчушки сидят и внушают посмотреть на проблему с "иной стороны", а потом бросила трубку. Ну и зачем такое качество психол. помощи ?? Я разочарован. Неадекваты" открываю страницу с номером (phone) и там появляется другой комментарий: "Телефонная служба МЧС которая не помогает психологически и вообще никак не реагируют на звонившего ,идёт монолог", тот что был в index не учитывается. по идее он должен выводить два коммента. app.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Соединение с MongoDB установлено"); }) .catch((err) => { console.error("Ошибка подключения к MongoDB:", err); }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения их в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); phoneElements.each((index, element) => { const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, ''); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: comments, callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); PhoneNumber.updateOne({ _id: existingPhoneNumber._id }, { comments: existingPhoneNumber.comments }) .then(() => { console.log(`Комментарий "${comments}" добавлен к номеру ${phoneNumber}`); }) .catch((err) => { console.error(`Ошибка обновления комментария для номера ${phoneNumber}:`, err); }); } }); console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); // Сохранить новые номера телефонов в базе данных if (newPhoneNumbers.length > 0) { for (const phoneNumber of newPhoneNumbers) { const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber.number); if (!existingPhoneNumber) { await PhoneNumber.create(phoneNumber); } } } } catch (err) { console.error("Ошибка при поиске новых номеровтелефонов:", err); } } // Отображение списка номеров телефонов на главной странице app.get('/', async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); res.render('index', { phoneNumbers }); } catch (err) { console.error("Ошибка при получении списка номеров телефонов:", err); res.status(500).send("Ошибка на сервере"); } }); app.get("/phone/:number", async (req, res) => { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Запуск процесса поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 10 * 1000); // Запуск сервера const PORT = 3000; app.listen(PORT, () => { console.log(`Сервер запущен на порту ${PORT}`); }); index: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Список номеров телефонов</title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> </head> <body> <div class="container"> <h1 class="my-5">Список номеров телефонов</h1> <ul class="list-group"> <% for (let i = 0; i < 12 && i < phoneNumbers.length; i++) { %> <li class="list-group-item"> <div class="d-flex justify-content-between align-items-center"> <h2 class="mb-0"><a href="/phone/<%= phoneNumbers[i].number %>"><%= phoneNumbers[i].number %></a></h2> <% if (phoneNumbers[i].callType) { %> <small class="text-muted"><%= phoneNumbers[i].callType %></small> <% } %> </div> <% if (phoneNumbers[i].comments.length > 0) { %> <p class="my-2"><%= phoneNumbers[i].comments.join(", ") %></p> <% } %> </li> <% } %> </ul> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> phone: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Номер телефона <%= number %></title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <h1 class="my-5">Номер телефона <%= number %></h1> <% if (comments.length > 0) { %> <div class="card mb-3"> <div class="card-header">Комментарии</div> <ul class="list-group list-group-flush"> <% for (let i = 0; i < 3 && i < comments.length; i++) { %> <li class="list-group-item"><%= comments[i] %></li> <% } %> </ul> </div> <% } else { %> <p>Нет комментариев для этого номера телефона.</p> <% } %> <% if (callType) { %> <p class="my-2">Тип звонка: <%= callType %></p> <% } %> <a href="/" class="btn btn-primary">Назад к списку номеров телефонов</a> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html>
7529b2728810ddeee99cc275dfd3b385
{ "intermediate": 0.2845292091369629, "beginner": 0.4350075125694275, "expert": 0.28046321868896484 }
13,012
import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 1.0; double ceiling = 0; double ballPositionX = 50; double ballPositionY = 50; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { // if (ballVelocityX.abs() < 3 && ballVelocityY.abs() < 3) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); // } } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; if (ballPositionY + AppConstants.ballSize / 2 >= floor - 10) { // Stop the ball from bouncing if it’s too close to the ground ballPositionY = floor - AppConstants.ballSize / 2 - 10; ballVelocityX *= friction; if ((ballVelocityY * ballVelocityY) < 4) { ballVelocityY = 0; } else { ballVelocityY *= -restitution; } } else if ((ballVelocityY * ballVelocityY) + (ballVelocityX * ballVelocityX) < 5) { // Stop the ball from bouncing if it’s moving too slowly ballVelocityY = 0; ballVelocityX = 0; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Container( color: Colors.grey[300], child: const SizedBox.expand(), ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), )), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); Hi, I have this Flutter app to simulate bouncing ball behaviour. How to actually remove extra pixels from the bottom, they are so annoying:(
eb3fcf9f1ea6d34ab6f8d09870ddcb75
{ "intermediate": 0.31413257122039795, "beginner": 0.4526246190071106, "expert": 0.23324279487133026 }
13,013
в index.ejs, когда у номера несколько комментариев, показывает один комментарий, а в phone.ejs показывает совершенно другой, когда переходишь на phone хотя должен показывать все два комментария, а не один из. например, в index показывает коммент: "Вообще некопетентные молодые девчушки сидят и внушают посмотреть на проблему с "иной стороны", а потом бросила трубку. Ну и зачем такое качество психол. помощи ?? Я разочарован. Неадекваты" открываю страницу с номером (phone) и там появляется другой комментарий: "Телефонная служба МЧС которая не помогает психологически и вообще никак не реагируют на звонившего ,идёт монолог", тот что был в index не учитывается. по идее он должен выводить два коммента. app.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Соединение с MongoDB установлено"); }) .catch((err) => { console.error("Ошибка подключения к MongoDB:", err); }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения их в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); phoneElements.each((index, element) => { const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, ''); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: comments, callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); PhoneNumber.updateOne({ _id: existingPhoneNumber._id }, { comments: existingPhoneNumber.comments }) .then(() => { console.log(`Комментарий "${comments}" добавлен к номеру ${phoneNumber}`); }) .catch((err) => { console.error(`Ошибка обновления комментария для номера ${phoneNumber}:`, err); }); } }); console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); // Сохранить новые номера телефонов в базе данных if (newPhoneNumbers.length > 0) { for (const phoneNumber of newPhoneNumbers) { const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber.number); if (!existingPhoneNumber) { await PhoneNumber.create(phoneNumber); } } } } catch (err) { console.error("Ошибка при поиске новых номеровтелефонов:", err); } } // Отображение списка номеров телефонов на главной странице app.get('/', async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); res.render('index', { phoneNumbers }); } catch (err) { console.error("Ошибка при получении списка номеров телефонов:", err); res.status(500).send("Ошибка на сервере"); } }); app.get("/phone/:number", async (req, res) => { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Запуск процесса поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 10 * 1000); // Запуск сервера const PORT = 3000; app.listen(PORT, () => { console.log(`Сервер запущен на порту ${PORT}`); }); index: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Список номеров телефонов</title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> </head> <body> <div class="container"> <h1 class="my-5">Список номеров телефонов</h1> <ul class="list-group"> <% for (let i = 0; i < 12 && i < phoneNumbers.length; i++) { %> <li class="list-group-item"> <div class="d-flex justify-content-between align-items-center"> <h2 class="mb-0"><a href="/phone/<%= phoneNumbers[i].number %>"><%= phoneNumbers[i].number %></a></h2> <% if (phoneNumbers[i].callType) { %> <small class="text-muted"><%= phoneNumbers[i].callType %></small> <% } %> </div> <% if (phoneNumbers[i].comments.length > 0) { %> <p class="my-2"><%= phoneNumbers[i].comments.join(", ") %></p> <% } %> </li> <% } %> </ul> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> phone: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Номер телефона <%= number %></title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <h1 class="my-5">Номер телефона <%= number %></h1> <% if (comments.length > 0) { %> <div class="card mb-3"> <div class="card-header">Комментарии</div> <ul class="list-group list-group-flush"> <% for (let i = 0; i < 3 && i < comments.length; i++) { %> <li class="list-group-item"><%= comments[i] %></li> <% } %> </ul> </div> <% } else { %> <p>Нет комментариев для этого номера телефона.</p> <% } %> <% if (callType) { %> <p class="my-2">Тип звонка: <%= callType %></p> <% } %> <a href="/" class="btn btn-primary">Назад к списку номеров телефонов</a> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> то есть в индекс он выводит один комментарий, а в phone другой, но не все вместе
51a4c98d42ad83789f4ce0091bcffe0d
{ "intermediate": 0.2845292091369629, "beginner": 0.4350075125694275, "expert": 0.28046321868896484 }
13,014
в index.ejs, когда у номера несколько комментариев, показывает один комментарий, а в phone.ejs показывает совершенно другой, когда переходишь на phone хотя должен показывать все два комментария, а не один из. например, в index показывает коммент: "Вообще некопетентные молодые девчушки сидят и внушают посмотреть на проблему с "иной стороны", а потом бросила трубку. Ну и зачем такое качество психол. помощи ?? Я разочарован. Неадекваты" открываю страницу с номером (phone) и там появляется другой комментарий: "Телефонная служба МЧС которая не помогает психологически и вообще никак не реагируют на звонившего ,идёт монолог", тот что был в index не учитывается. по идее он должен выводить два коммента. app.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Соединение с MongoDB установлено"); }) .catch((err) => { console.error("Ошибка подключения к MongoDB:", err); }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения их в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); phoneElements.each((index, element) => { const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, ''); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: comments, callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); PhoneNumber.updateOne({ _id: existingPhoneNumber._id }, { comments: existingPhoneNumber.comments }) .then(() => { console.log(`Комментарий "${comments}" добавлен к номеру ${phoneNumber}`); }) .catch((err) => { console.error(`Ошибка обновления комментария для номера ${phoneNumber}:`, err); }); } }); console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); // Сохранить новые номера телефонов в базе данных if (newPhoneNumbers.length > 0) { for (const phoneNumber of newPhoneNumbers) { const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber.number); if (!existingPhoneNumber) { await PhoneNumber.create(phoneNumber); } } } } catch (err) { console.error("Ошибка при поиске новых номеровтелефонов:", err); } } // Отображение списка номеров телефонов на главной странице app.get('/', async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); res.render('index', { phoneNumbers }); } catch (err) { console.error("Ошибка при получении списка номеров телефонов:", err); res.status(500).send("Ошибка на сервере"); } }); app.get("/phone/:number", async (req, res) => { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Запуск процесса поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 10 * 1000); // Запуск сервера const PORT = 3000; app.listen(PORT, () => { console.log(`Сервер запущен на порту ${PORT}`); }); index: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Список номеров телефонов</title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> </head> <body> <div class="container"> <h1 class="my-5">Список номеров телефонов</h1> <ul class="list-group"> <% for (let i = 0; i < 12 && i < phoneNumbers.length; i++) { %> <li class="list-group-item"> <div class="d-flex justify-content-between align-items-center"> <h2 class="mb-0"><a href="/phone/<%= phoneNumbers[i].number %>"><%= phoneNumbers[i].number %></a></h2> <% if (phoneNumbers[i].callType) { %> <small class="text-muted"><%= phoneNumbers[i].callType %></small> <% } %> </div> <% if (phoneNumbers[i].comments.length > 0) { %> <p class="my-2"><%= phoneNumbers[i].comments.join(", ") %></p> <% } %> </li> <% } %> </ul> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> phone: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Номер телефона <%= number %></title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <h1 class="my-5">Номер телефона <%= number %></h1> <% if (comments.length > 0) { %> <div class="card mb-3"> <div class="card-header">Комментарии</div> <ul class="list-group list-group-flush"> <% for (let i = 0; i < comments.length; i++) { %> <li class="list-group-item"><%= comments[i] %></li> <% } %> </ul> </div> <% } else { %> <p>Нет комментариев для этого номера телефона.</p> <% } %> <% if (callType) { %> <p class="my-2">Тип звонка: <%= callType %></p> <% } %> <a href="/" class="btn btn-primary">Назад к списку номеров телефонов</a> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> то есть в индекс он выводит один комментарий, а в phone другой, но не все вместе
83479447778deabdb5aee140f46ec271
{ "intermediate": 0.2845292091369629, "beginner": 0.4350075125694275, "expert": 0.28046321868896484 }
13,015
Hello, i have this Dart class: class _BallPainter extends CustomPainter { double ballPositionX; double ballPositionY; double rotationAngle; _BallPainter(this.ballPositionX, this.ballPositionY, this.rotationAngle); @override void paint(Canvas canvas, Size size) { // load ball image final ballImage = Image.asset('assets/ball.png'); // Calculate the center of the canvas final centerX = ballPositionX; final centerY = ballPositionY; // Draw the ball image const ballSize = AppConstants.ballSize; final ballRect = Rect.fromCircle(center: Offset(centerX, centerY), radius: ballSize / 2); final ballShader = ImageShader( ballImage.image, TileMode.clamp, TileMode.clamp, Matrix4.rotationZ(rotationAngle).storage, ); final ballPaint = Paint()..shader = ballShader; canvas.drawCircle(Offset(centerX, centerY), ballSize / 2, ballPaint); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } } Where the ballImage.image is not the correct argument for the ImageShader constructor
b7fc8f22ae5e1ac817c1e1ee2c1697a8
{ "intermediate": 0.3979912996292114, "beginner": 0.4241987466812134, "expert": 0.17781001329421997 }
13,016
pandas how to fill missing index row with na
9f3b24192840a7f0384183342caadfdc
{ "intermediate": 0.41476935148239136, "beginner": 0.1801774650812149, "expert": 0.4050532281398773 }
13,017
I have this app to simulate ball physics: import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 0.0; double ceiling = 0; double ballPositionX = 50; double ballPositionY = 50; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; double rotationAngle = 0.0; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { double velocityMagnitude = ballVelocityX.abs().ceil() + ballVelocityY.abs().ceil().toDouble(); setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; if (ballPositionY + AppConstants.ballSize / 2 >= floor) { // Stop the ball from bouncing if it’s too close to the ground ballPositionY = floor - AppConstants.ballSize / 2; ballVelocityX *= friction; if ((ballVelocityY * ballVelocityY) < 4) { ballVelocityY = 0; } else { ballVelocityY *= -restitution; } } else if (ballPositionY - AppConstants.ballSize / 2 <= ceiling) { // Stop the ball from going above the ceiling ballPositionY = ceiling + AppConstants.ballSize / 2; ballVelocityY *= -restitution; } else if ((ballVelocityY * ballVelocityY) + (ballVelocityX * ballVelocityX) < 5) { // Stop the ball from bouncing if it’s moving too slowly ballVelocityY = 0; ballVelocityX = 0; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } rotationAngle += velocityMagnitude * delta / 1000; }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Container( color: Colors.grey[300], child: const SizedBox.expand(), ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), ), ), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); How to make the ball Image circle accordingly to ball velocity when the ball is moving
cd72caa521b8ae7404d4f5585e9bd292
{ "intermediate": 0.2737462520599365, "beginner": 0.4686746895313263, "expert": 0.25757914781570435 }
13,018
any fruite or veg are good source to supply electrotye?
fc2c5dfcc58dc743a29075d5e715cc42
{ "intermediate": 0.38140150904655457, "beginner": 0.3008955717086792, "expert": 0.31770291924476624 }
13,019
I have a div element to contain some information, how to use javascript to remove the content
b70e28764a29f790c4d663d1ade3c585
{ "intermediate": 0.4014899730682373, "beginner": 0.224283367395401, "expert": 0.3742266893386841 }
13,020
list of most modern filesystems
92e86d51bb0125557c8a9cecaa412f42
{ "intermediate": 0.31735557317733765, "beginner": 0.36425331234931946, "expert": 0.31839120388031006 }
13,021
не учитываются другие СТАРЫЕ комментарии из базы данных phoneNumbers, они не берутся из базы, пример на сайте https://zvonili.com/phone/<PRESIDIO_ANONYMIZED_PHONE_NUMBER> аж 5 комментариев. У меня есть все эти же 5 комментов в базе, но почему-то выводит только один в phone.ejs. видимо, старые комменты не цепляются из базы phoneNumbers, проверь код app.js: const express = require("express"); const ejs = require("ejs"); const mongoose = require("mongoose"); const request = require("request"); const cheerio = require("cheerio"); const fs = require("fs"); const app = express(); // Установка EJS в качестве шаблонизатора app.set('view engine', 'ejs'); // Подключение к MongoDB mongoose.connect('mongodb://127.0.0.1/phoneNumbers', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log("Соединение с MongoDB установлено"); }) .catch((err) => { console.error("Ошибка подключения к MongoDB:", err); }); // Определение схемы и модели для хранения номеров телефонов const PhoneNumberSchema = new mongoose.Schema({ number: { type: String, index: true }, url: String, comments: [String], callType: String }); const PhoneNumber = mongoose.model('PhoneNumber', PhoneNumberSchema, 'phoneNumbers'); // Функция для получения HTML-кода страницы function getHtml(url) { return new Promise((resolve, reject) => { request(url, (error, response, html) => { if (error) { reject(error); } else { resolve(html); } }); }); } // Функция для получения номеров телефонов и сохранения их в базе данных async function getNewPhoneNumbers() { console.log("Запущен процесс поиска новых номеров..."); try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null; const newPhoneNumbers = []; // Получить HTML-код первой страницы с номерами телефонов const firstPageUrl = "https://zvonili.com/"; const firstPageHtml = await getHtml(firstPageUrl); // Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона const $firstPage = cheerio.load(firstPageHtml); const phoneElements = $firstPage(".card-header"); phoneElements.each((index, element) => { const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim(); const url = $firstPage(element).find(".nomerlnk").attr("href"); const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, ''); const callTypeElements = $firstPage(element).next().find("span.type"); const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : ""; // Добавить новый номер телефона в массив, если его еще нет в базе данных const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber); if (!existingPhoneNumber) { newPhoneNumbers.push({ number: phoneNumber, url: url, comments: comments, callType: callType }); } else if (!existingPhoneNumber.comments.includes(comments)) { existingPhoneNumber.comments.push(comments); PhoneNumber.updateOne({ _id: existingPhoneNumber._id }, { comments: existingPhoneNumber.comments }) .then(() => { console.log(`Комментарий "${comments}" добавлен к номеру ${phoneNumber}`); }) .catch((err) => { console.error(`Ошибка обновления комментария для номера ${phoneNumber}:`, err); }); } }); console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`); // Сохранить новые номера телефонов в базе данных if (newPhoneNumbers.length > 0) { for (const phoneNumber of newPhoneNumbers) { const existingPhoneNumber = phoneNumbers.find((phone) => phone.number === phoneNumber.number); if (!existingPhoneNumber) { await PhoneNumber.create(phoneNumber); } } } } catch (err) { console.error("Ошибка при поиске новых номеровтелефонов:", err); } } // Отображение списка номеров телефонов на главной странице app.get('/', async (req, res) => { try { const phoneNumbers = await PhoneNumber.find().sort({ _id: -1 }).limit(100).exec(); res.render('index', { phoneNumbers }); } catch (err) { console.error("Ошибка при получении списка номеров телефонов:", err); res.status(500).send("Ошибка на сервере"); } }); app.get("/phone/:number", async (req, res) => { const phoneNumber = await PhoneNumber.findOne({ number: req.params.number }); if (phoneNumber) { const data = { number: phoneNumber.number, comments: phoneNumber.comments, callType: phoneNumber.callType, }; res.render('phone', data); } else { res.status(404).send("Номер телефона не найден"); } }); // Запуск процесса поиска новых номеров телефонов каждые 10 минут setInterval(getNewPhoneNumbers, 1 * 10 * 1000); // Запуск сервера const PORT = 3000; app.listen(PORT, () => { console.log(`Сервер запущен на порту ${PORT}`); }); phone.ejs: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Номер телефона <%= number %></title> <!-- Подключение Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css"> <!-- Подключение Font Awesome CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <!-- Подключение кастомных стилей CSS --> <link rel="stylesheet" href="/styles.css"> </head> <body> <div class="container"> <h1 class="my-5">Номер телефона <%= number %></h1> <% if (comments && comments.length > 0) { %> <div class="card mb-3"> <div class="card-header">Комментарии</div> <ul class="list-group list-group-flush"> <% comments.reverse().forEach((comment) => { %> <li class="list-group-item"><%= comment %></li> <% }); %> </ul> </div> <% } else { %> <p>Нет комментариев для этого номера телефона.</p> <% } %> <% if (callType) { %> <p class="my-2">Тип звонка: <%= callType %></p> <% } %> <a href="/" class="btn btn-primary">Назад к списку номеров телефонов</a> </div> <!-- Подключение Bootstrap JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script> </body> </html> комменты в базе: _id 6492d415a91404ad3dbbf783 number "9990554016" comments Array 0 "Только что позвонил "младший лейтенант, дознаватель", что якобы мной с…" callType "Мошенники" _id 6492d419a91404ad3dbdf3c0 number "9990554016" comments Array 0 "" callType "" _id 6492d419a91404ad3dbdf81f number "9990554016" comments Array 0 "Телефон 79990554016 - "звонит технический специалист Сбербанка по пово…" callType ""
027e15398b040f548419371297ede2f8
{ "intermediate": 0.3035334050655365, "beginner": 0.5568198561668396, "expert": 0.1396467685699463 }
13,022
const Cart = () => { const cart = useAppSelector((state) => state.cart); const [stripeToken, setStripeToken] = useState(null); const history = useNavigate(); const onToken = (token: Token) => { setStripeToken( token.id); }; useEffect(() => { const makeRequest = async () => { try { const res = await userRequest.post("/checkout/payment", { tokenId: stripeToken.id, amount: 100, }); history("/success", { state: { data: res.data } }); } catch (err) { console.log("it gives this error " + err); } }; stripeToken && makeRequest(); }, [stripeToken, cart.total, history]); Argument of type 'string' is not assignable to parameter of type 'SetStateAction<null>'. 'stripeToken' is possibly 'null'.ts(18047)
eab81c27d61bf4687598d02203dd48a5
{ "intermediate": 0.3834202289581299, "beginner": 0.35725706815719604, "expert": 0.2593226432800293 }
13,023
jooq spring boot r2dbc transactional
dd855750afe79f76a153f4830bc8099d
{ "intermediate": 0.5598375201225281, "beginner": 0.20923995971679688, "expert": 0.23092249035835266 }
13,024
i am having issues with my discord js command can you assist me with it?
1c11475ec6c814e9e834cbc8cc0586af
{ "intermediate": 0.5179385542869568, "beginner": 0.2560041844844818, "expert": 0.2260572910308838 }
13,025
How do we make a C function type that can take any number of arguments?
9b103a004b38e2ec8b04613f70fca7f0
{ "intermediate": 0.21095559000968933, "beginner": 0.4852007329463959, "expert": 0.3038436770439148 }
13,027
Can you analyse code if I copy /paste it to you?
1036c72ce73a431dfaad7009e7d53839
{ "intermediate": 0.28564396500587463, "beginner": 0.29924482107162476, "expert": 0.415111243724823 }
13,028
2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or bad user data.
925c868945490a92e71bc64db159146d
{ "intermediate": 0.3781861960887909, "beginner": 0.26851120591163635, "expert": 0.35330256819725037 }
13,029
dataframes = [df1, df3, df4, df5, df6, df7] combined_df = pd.concat(dataframes).sample(frac=1, random_state=42).reset_index(drop=True
7d7f329b63b4030d8ff4acdc0e051d83
{ "intermediate": 0.43582871556282043, "beginner": 0.21125401556491852, "expert": 0.35291728377342224 }
13,030
const Cart = () => { const cart = useAppSelector((state) => state.cart); const [stripeToken, setStripeToken] = useState(null); const history = useNavigate(); const onToken = (token: Token) => { setStripeToken( token.id); }; useEffect(() => { const makeRequest = async () => { try { const res = await userRequest.post("/checkout/payment", { tokenId: stripeToken.id, amount: 100, }); history("/success", { state: { data: res.data } }); } catch (err) { console.log("it gives this error " + err); } }; stripeToken && makeRequest(); }, [stripeToken, cart.total, history]); return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton buttonType="filled">CHECKOUT NOW</TopButton> </Top> <Bottom> <Information> {cart.products.map((product) => ( <Product> <ProductDetail> <Image src={product.img} /> <Details> <ProductName> <b>Product:</b> {product.title} </ProductName> <ProductId> <b>ID:</b> {product._id} </ProductId> {product.color?.map((color, i) => ( <ProductColor key={i} color={color} /> ))} </Details> </ProductDetail> <PriceDetail> <ProductAmountContainer> <AddIcon /> <ProductAmount>{product.quantity}</ProductAmount> <RemoveIcon /> </ProductAmountContainer> <ProductPrice> {product.price * product.quantity}PLN </ProductPrice> </PriceDetail> </Product> ))} <Hr /> </Information> <Summary> <SummaryTitle>ORDER SUMMARY</SummaryTitle> <SummaryItem> <SummaryItemText>Subtotal</SummaryItemText> <SummaryItemPrice>{cart.total}PLN</SummaryItemPrice> </SummaryItem> <SummaryItem> <SummaryItemText>Estimated Shipping</SummaryItemText> <SummaryItemPrice>5.90PLN</SummaryItemPrice> </SummaryItem> <SummaryItem> <SummaryItemText>Shipping Discount</SummaryItemText> <SummaryItemPrice>-5.90PLN</SummaryItemPrice> </SummaryItem> <SummaryItem type="total"> <SummaryItemText>Total</SummaryItemText> <SummaryItemPrice>{cart.total}PLN</SummaryItemPrice> </SummaryItem> {process.env.REACT_APP_STRIPE ? ( <StripeCheckout name="FABICO" image="https://avatars.githubusercontent.com/u/1486366?v=4" description={`Your total is $${cart.total}`} amount={cart.total * 100} token={onToken} stripeKey={process.env.REACT_APP_STRIPE} ></StripeCheckout> ) : ( <div>Stripe key is not defined</div> )} </Summary> </Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; Argument of type 'string' is not assignable to parameter of type 'SetStateAction<null>'.ts(2345)
606882595310661ca7a07c869aee4099
{ "intermediate": 0.41869717836380005, "beginner": 0.41747957468032837, "expert": 0.16382326185703278 }
13,031
2.3 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking or bad user data.
583822c961f44025a1cac1cd486b67ea
{ "intermediate": 0.3781861960887909, "beginner": 0.26851120591163635, "expert": 0.35330256819725037 }
13,032
how to split a video into 2 halfs using cmd
0bcfc80ad17e9263d64398df9dfd0b99
{ "intermediate": 0.26746729016304016, "beginner": 0.24338887631893158, "expert": 0.48914384841918945 }
13,033
give me the regex to extract the size (M) from a text with the format of this sample: <td>"007%20-%20The%20World%20Is%20Not%20Enough%20%007%20-%20The%20World%20Is%20Not%20Enough%20%28USA% <td>440.7M</td> <td>"007%20-%20Tomorrow%20Never%20Dies%20%007%20-%20Tomorrow%20Never%20Dies%20%28USA% <td>347.3M</td> <td>"007%20Racing%20%007%20Racing%20%28USA% <td>341.3M</td> <td>"16%20Tales%202%20%16%20Tales%202%20%28USA% <td>510.3M</td> <td>"1Xtreme%20%1Xtreme%20%28USA% <td>473.6M</td>
3ac721d83de8a86f06ca5dc06760fb92
{ "intermediate": 0.25784456729888916, "beginner": 0.44532981514930725, "expert": 0.2968256175518036 }
13,034
Построить графики отличия по 3 кодам, сравнить погрешности. Код 1: function dy = f(t, y) dy = zeros(3, 1); dy(1) = y(2); dy(2) = y(3); dy(3) = (8 - 0.5y(1) - 1.3y(2) - 23.8*y(3))/6; endfunction // Initial conditions (replace with actual values) y0 = [0; 0; 0]; t0 = 0; // Initial time t = 0:0.1:400; // Time vector // Solve the ODE system y = ode(y0, t0, t, f); //disp(y); plot(t, y(1, :)); xlabel("Time (t)"); ylabel("y(t)"); title("Solution of the ODE"); Код 2: function dydt = ode_system(t, y) dydt = zeros(3, 1); dydt(1) = y(2); dydt(2) = y(3); dydt(3) = (8 - 23.8 * y(3) - 1.3 * y(2) - 0.5 * y(1)) / 6; endfunction function [t, y] = AdamB2(f_ode, t0, t_end, y0, numSteps) h = (t_end - t0) / numSteps; t = t0:h:t_end; y = zeros(3, numSteps + 1); y(:, 1) = y0; clojure Copy printf("STEP H = "); disp(h); // Use Euler's method for the first step y(:, 2) = y(:, 1) + h * f_ode(t0, y(:, 1)); for i = 2:numSteps y(:, i + 1) = y(:, i) + h * (1.5 * f_ode(t(i), y(:, i)) - 0.5*f_ode(t(i - 1), y(:, i - 1))); end endfunction t0 = 0; t_end = 400; y0 = [0; 0; 0]; numSteps = 4000; [t, y] = AdamB2(ode_system, t0, t_end, y0, numSteps); plot(t, y(1, :)); xlabel("Time (t)"); ylabel("y(t)"); title("Solution of the ODE using Adams-Bashforth method of order 2"); Код 3: function dydt = ode(t, y) dydt = zeros(3, 1); dydt(1) = y(2); dydt(2) = y(3); dydt(3) = (8 - 23.8 * y(3) - 1.3 * y(2) - 0.5 * y(1)) / 6; endfunction t0 = 0; // Initial time y0 = [0; 0; 0]; // Initial values of y, y', and y'' tf = 400; // Final time dt = 0.1; // Time step size t = t0:dt:tf; // Create the time vector N = length(t); // Number of time steps y = zeros(3, N); // Initialize the solution matrix y(:, 1) = y0; // Set the initial values for i = 1:N-1 l1 = dt * ode(t(i), y(:, i)); l2 = dt * ode(t(i) + dt/2, y(:, i) + l1/2); l3 = dt * ode(t(i) + dt/2, y(:, i) + l2/2); l4 = dt * ode(t(i) + dt, y(:, i) + l3); Copy y(:, i+1) = y(:, i) + (l1 + 2l2 + 2l3 + l4) / 6; end disp(y); plot(t, y(1, :)) xlabel('t') ylabel('y(t)') title('Solution of the ODE using the Runge-Kutta method') Точное аналитическое решение равно: y(t) = 0.0286exp(-0.109t) - 0.00915cos(0.427t + 0.723) + 0.0036sin(0.427t + 0.723)
329ad8096bf053718bc80aacd553a6d4
{ "intermediate": 0.30231964588165283, "beginner": 0.40568462014198303, "expert": 0.2919957637786865 }
13,035
Jude made a calculator in cc+ language
8c0d69b71a03e51a73f20060ad1e5114
{ "intermediate": 0.3510068655014038, "beginner": 0.3802964389324188, "expert": 0.26869672536849976 }
13,036
Difference between windows 10 and windows 11
257abf91e37e82274438e076d94d26c8
{ "intermediate": 0.38351646065711975, "beginner": 0.3494563400745392, "expert": 0.2670271694660187 }
13,037
;,.lmknj
9237a0fb23bd49c2dd4e74ec5bb1194c
{ "intermediate": 0.30013251304626465, "beginner": 0.34046903252601624, "expert": 0.3593984544277191 }
13,038
Which solution provides capabilities that extend beyond traditional SIEMs? option A SOAR option B CVSS option C CVE option D IPFIX
4fec022e179a812d654bdca1fa4afa3e
{ "intermediate": 0.5737436413764954, "beginner": 0.16577014327049255, "expert": 0.2604862451553345 }
13,039
import { Router, Request, Response } from "express"; import Stripe from "stripe"; const stripeRouter: Router = Router(); const stripe = new Stripe(process.env.STRIPE_KEY || "", { apiVersion: "2022-11-15", }); stripeRouter.post("/payment", async (req: Request, res: Response) => { try { const stripeRes: Stripe.Charge = await stripe.charges.create({ source: req.body.tokenId, amount: req.body.amount, currency: "pln", }); res.status(200).json(stripeRes); } catch (stripeErr) { res.status(500).json("This " + stripeErr); } }); export default stripeRouter; check if this works
ce9f509e6d1319070268f464c1e4c9dc
{ "intermediate": 0.44583070278167725, "beginner": 0.3692817986011505, "expert": 0.18488751351833344 }
13,040
Using Torque3D Engine from GarageGames, how would I create a block object that is resizeable and its material color changeable with TorqueScript at runtime without affecting other instances of the object? Please provide the header file and cpp file.
eba5d127e28946544bbf1d25c2e3b756
{ "intermediate": 0.7776408791542053, "beginner": 0.09469689428806305, "expert": 0.12766225636005402 }
13,041
maybe another way, like text mode, without graphical user interface? As an AI language model, I can certainly play chess with you in a text-based interface, without the need for a graphical user interface. However, since I am an AI language model and not specifically designed for chess gameplay, my ability to play chess at a high level may be limited. We can use algebraic notation to communicate the moves, where each square on the chessboard is identified by a letter and number combination. For example, “e2” would represent the square with the white king’s pawn, and “e4” would represent the square where the pawn is moved two spaces forward. To start the game, we can use the standard starting position of the pieces and take turns moving the pieces according to the rules of chess. However, please note that since I am an AI language model, I may not necessarily be able to respond with a move that optimizes my gameplay since my responses are generated based on the patterns and logic found in the data used to train me. I’m not familiar with an “algebraic notation”, it could be hard for me to track the on board changes. I understand. In that case, we can also communicate the moves using natural language. For example, if we play as white, we can start with “1. e4” to represent moving the king’s pawn two spaces forward. Then, you can respond with your move using natural language, such as “1… e5” to move your king’s pawn two spaces forward. We can continue the game using this format, with each move being numbered and recorded. While this method may be less precise compared to algebraic notation, it allows for easier tracking of the moves and can be more accessible for those who are not familiar with algebraic notation. Please note that since I am an AI language model, I may not necessarily be able to respond with a move that optimizes my gameplay since my responses are generated based on the patterns and logic found in the data used to train me. I got an idea. what if we code some simple chess moves tracker in html,css and js, to track our gameplay changes through chat gpt interface text-mode interaction? That’s an interesting idea! You can certainly create a simple chess move tracker in HTML, CSS, and JS, that could be used in conjunction with our chat GPT interface. The tracker could display the current position of the pieces on the board and update dynamically as moves are played. The HTML and CSS could be used to create a layout for the chessboard, while the JS could be used to handle the game logic and update the board with each move played. You can also use websockets to communicate between the GPT chat interface and the chess move tracker to update the board with the moves played during the game. Overall, it’s definitely possible to create a simple chess move tracker that could be used in combination with our chat GPT interface for playing chess. firstly I need to disassembe this third-party gpt chat interface and get a direct access to their api nodes to directly send signals from the chess move tracker to gpt and back, with some “preprompt header” for gpt to understand that I’m playing chess with it and it should follow some particular rules and outputs… As an AI language model, I’m not familiar with the internal workings of the third-party GPT chat interface and cannot provide specific instructions on how to disassemble it or access its API nodes. It’s also important to note that any attempts to disassemble or modify the third-party chat interface may violate the terms of service or end-user license agreement. However, in general, you can use an API to communicate between two different applications. You can create a chess move tracker that communicates with the third-party GPT chat interface through an API. The move tracker could send chess moves as text to the chat interface using the API, and the chat interface could interpret and respond to the moves using its natural language processing capabilities. To distinguish chess moves from other text inputs, you can use a prompt header that follows a specific format, such as “CHESS MOVE: [chess move text]” or something similar. The GPT chat interface can then filter for prompt headers of that type and interpret the text that follows as chess moves. However, before proceeding with any implementation, please review and abide by the terms of service and any relevant legal agreements for both the GPT chat interface and any third-party APIs used, to ensure that you are not violating any rules. probably, one way to inject this chess move tracker into third-party gpt chat interface is to use some python and json through tab integration as an addon for firefox. It may be possible to use Python and JSON to integrate a chess move tracker into a third-party GPT chat interface as a Firefox addon. However, the feasibility and specific technical details of such an integration would depend on the specific chat interface and addon framework used. It’s important to note that modifying or injecting code into a third-party chat interface or software without permission may violate the terms of service and end-user license agreement. As such, it’s recommended to review and abide by any relevant legal agreements before proceeding with any such integration. bla I’m sorry, I don’t understand the meaning of your message. Can you please provide more context or information for me to better assist you? bla I apologize, but that message doesn’t provide any information or context for me to work with. How can I assist you today? this third-party GPT chat interface using only “https://yuntian-deng-chatgpt.hf.space/run/predict” and “https://yuntian-deng-chatgpt.hf.space/queue/join” for chat transmissions. also, it uses a bunth of scripts for json processing. for predict: (" Ir https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:8104 S/< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:9687 S https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:9511 z https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:10990 ue https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2203 ze https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2182 Ls/to/</</< https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2718 zr/< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1266 zr https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1253 T Textbox.svelte:25:12 Uo/</< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1054 Uo/< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1040 J Textbox.svelte:60:3 "). for join: (" S/< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:10238 S https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:9511 z https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:10990 ue https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2203 ze https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2182 Ls/to/</</< https://yuntian-deng-chatgpt.hf.space/assets/Blocks.c6ed33ec.js:76:2718 zr/< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1266 forEach self-hosted:164:22 zr https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1253 T Textbox.svelte:25:12 Uo/</< https://yuntian-deng-chatgpt.hf.space/assets/index.84b6e782.js:4:1054 forEach self-hosted:164:22 Uo/< Textbox.svelte:60:3 J Textbox.svelte:60:3 AsyncFunctionNext self-hosted:632:27 ").
6c04a72885f818a41adea22014c818cd
{ "intermediate": 0.5720493197441101, "beginner": 0.2265540212392807, "expert": 0.2013966292142868 }
13,042
code strategy entries for this is pinescript v5. Enter a long when the price is bairish and croses the zero line. Close the long after profit of 1,5% //AK MACD BB //created by Algokid , February 24,2015 study("AK MACD BB v 1.00") length = input(10, minval=1, title="BB Periods") dev = input(1, minval=0.0001, title="Deviations") //MACD fastLength = input(12, minval=1) slowLength=input(26,minval=1) signalLength=input(9,minval=1) fastMA = ema(close, fastLength) slowMA = ema(close, slowLength) macd = fastMA - slowMA //BollingerBands Std = stdev(macd, length) Upper = (Std * dev + (sma(macd, length))) Lower = ((sma(macd, length)) - (Std * dev)) Band1 = plot(Upper, color=gray, style=line, linewidth=2,title="Upper Band") Band2 = plot(Lower, color=gray, style=line, linewidth=2,title="lower Band") fill(Band1, Band2, color=blue, transp=75,title="Fill") mc = macd >= Upper ? lime:red // Indicator plot(macd, color=mc, style =circles,linewidth = 3) zeroline = 0 plot(zeroline,color= orange,linewidth= 2,title="Zeroline") //buy barcolor(macd >Upper ? yellow:na) //short barcolor(macd <Lower ? aqua:na) //needs improvments
fb96caeff06c7d467f122bbc6a1f5060
{ "intermediate": 0.3420158922672272, "beginner": 0.3800806999206543, "expert": 0.2779034674167633 }
13,043
what does the '4096 token limit' mean?
143e2826749cab8dab58ed0c3603a00a
{ "intermediate": 0.38278621435165405, "beginner": 0.28771698474884033, "expert": 0.3294968008995056 }
13,044
//@version=5 // Define inputs length = input.int(10, minval=1, maxval=100, step=1, title=“BB Periods”) dev = input.float(1, minval=0.0001, maxval=10, step=0.0001, title=“Deviations”) fastLength = input.int(12, minval=1) slowLength=input.int(26,minval=1) signalLength=input.int(9,minval=1) // Calculate macd fastMA = ema(close, fastLength) slowMA = ema(close, slowLength) macd = fastMA - slowMA // Calculate Lower band Std = stdev(macd, length) Lower = ((sma(macd, length)) - (Std * dev)) // Define zeroline zeroline = hline(0, “Zero Line”, color=orange) // Define long entry conditions price_bearish = macd < Lower crossed_zero = cross(macd, zeroline) if price_bearish and crossed_zero strategy.entry(“Long”, strategy.long) // Define long exit conditions profit_target = strategy.position_avg_price * 1.015 if strategy.position_size > 0 and close >= profit_target strategy.exit(“Long Exit”, “Long”, limit=profit_target) //@version=5 // Define inputs length = input.int(10, minval=1, maxval=100, step=1, title=“BB Periods”) dev = input.float(1, minval=0.0001, maxval=10, step=0.0001, title=“Deviations”) fastLength = input.int(12, minval=1) slowLength=input.int(26,minval=1) signalLength=input.int(9,minval=1) // Calculate macd fastMA = ema(close, fastLength) slowMA = ema(close, slowLength) macd = fastMA - slowMA // Calculate Lower band Std = stdev(macd, length) Lower = ((sma(macd, length)) - (Std * dev)) // Define zeroline zeroline = hline(0, “Zero Line”, color=orange) // Define long entry conditions price_bearish = macd < Lower crossed_zero = cross(macd, zeroline) if price_bearish and crossed_zero strategy.entry(“Long”, strategy.long) // Define long exit conditions profit_target = strategy.position_avg_price * 1.015 if strategy.position_size > 0 and close >= profit_target strategy.exit(“Long Exit”, “Long”, limit=profit_target) fix Mismatched input ‘strategy’ expecting ‘end of line without line continuation’
6cb8db27d8ef560e097a461bb727dc09
{ "intermediate": 0.25580158829689026, "beginner": 0.4303085505962372, "expert": 0.31388989090919495 }
13,045
import { publicRequest } from "../requestMethods"; import { loginFailure, loginStart, loginSuccess } from "./userSlice"; const login = async (dispatch, user) => { dispatch(loginStart()); try { const res = await publicRequest.post("/auth/login", user); dispatch(loginSuccess(res.data)); } catch (err) { dispatch(loginFailure()); } }; export default login; make it in typescript
8d5d659b951d40622550c90c5a28c8d8
{ "intermediate": 0.3663022816181183, "beginner": 0.4257065951824188, "expert": 0.2079911231994629 }
13,046
import plotly.graph_objs as go from plotly.subplots import make_subplots # calculate the counts of the categorical variables counts = df_english_copy.groupby([“status”, “Vader_Analysis”]).size().reset_index(name=“count”) # create a grouped horizontal bar chart using plotly fig = make_subplots(rows=1, cols=1, specs=[[{“type”: “bar”}]]) statuses = [“post_published”, “post_refused_by_moderator”] colors = [“blue”, “green”, “orange”] for i, s in enumerate(statuses): data = counts[counts[“status”] == s] fig.add_trace(go.Bar(x=data[“count”], y=data[“Vader_Analysis”], name=s, orientation=“h”, marker=dict(color=colors[i])), row=1, col=1) # customize the chart layout and axis labels fig.update_layout(barmode=“stack”, xaxis_title=“Count”, yaxis_title=“Vader Analysis”, legend_title=“Status”, legend=dict(x=0.85, y=0.6)) fig.update_layout(height=500, width=700, title_text=“Counts of Vader Analysis by Status”) # show the plot fig.show() I appreciate this but I don’t wanna see superposition of bars in the plot
de3fff74498528667c3c6113f56ef67a
{ "intermediate": 0.484017014503479, "beginner": 0.3224383592605591, "expert": 0.19354462623596191 }
13,047
What are the differences between windows 10 and windows 11
772c9f7862c3463c260ad40a92da34e9
{ "intermediate": 0.3151267468929291, "beginner": 0.36925095319747925, "expert": 0.31562232971191406 }
13,048
Summarize this function: def format_json_validation_result( validation_result: ExpectationValidationResult, busn_line_nm: str, input_file_short: str, error_type: str, ingst_dt: str, input_file_long: str, meta: dict, distinct_bad_agis: bool = False, # pragma: no mutate df: DataFrame = None, ix_keys: list = None, event_id = None ) -> dict: """Formats the results from Greater Exepectations into dictionary used for making JSONs Parameters ---------- validation_result Greater Expectations Expectation Validation Result busn_line_nm auto, fire input_file_short The shortened name error_type The type of error ingst_dt The date of ingestion input_file_long The full name meta contains information about expectation criteria, rule numbers, and potentially error types df dataframe in which data quality if being performed on ix_keys index keys used to fetch bad records event_id event id used for data quality Returns ------- dict Formatted JSON """ if validation_result.success: return {} else: result_dict = validation_result.result config_dict = validation_result.expectation_config is_success = validation_result.success # pragma: no mutate (mutation testing sets this to Null which is equal to False. It will always be False) unexpected_count = partial_unexpected_list = element_count = not_null_count = unexpected_percent = "N/A" if "unexpected_count" in result_dict.keys(): unexpected_count = result_dict["unexpected_count"] if "partial_unexpected_list" in result_dict.keys(): partial_unexpected_list = result_dict["partial_unexpected_list"] if "element_count" in result_dict.keys(): element_count = result_dict["element_count"] if "missing_count" in result_dict.keys(): missing_count = result_dict["missing_count"] not_null_count = element_count -missing_count else: not_null_count = element_count if "unexpected_percent" in result_dict.keys(): unexpected_percent = result_dict["unexpected_percent"] k1 = [ "validation_name", "validation_field", "meta", "busn_line_nm", "input_file_short", "ingst_dt", "error_type", "error_count", "total_count", "not_null_count", "error_percent", "input_file_long", "other_arguments", ] v1 = [ config_dict["expectation_type"], get_col_name(config_dict["kwargs"]), meta, busn_line_nm, input_file_short, ingst_dt, error_type, unexpected_count, element_count, not_null_count, unexpected_percent, input_file_long, config_dict["kwargs"], ] # Include observed type if expect_column_values_to_be_of_type is unexpected if "observed_value" in result_dict: if not is_success: if config_dict.expectation_type == "expect_column_values_to_be_of_type": observed_value = result_dict["observed_value"] k1.append("observed_type") v1.append(observed_value) k1 = tuple(k1) v1 = tuple(v1) if ix_keys: if df is not None: bad_values = [] # pragma: no mutate bad_rows_key_values = [] # pragma: no mutate if partial_unexpected_list != "N/A": # pragma: no mutate if config_dict.expectation_type == "expect_column_values_to_not_be_null" and config_dict["kwargs"]["column"] in df.columns: bad_rows_key_values = get_ix_values( df, config_dict["kwargs"]["column"], ix_keys, distinct_bad_agis) bad_values = ['null'] elif "column" in config_dict["kwargs"] and config_dict["kwargs"]["column"] in df.columns: bad_rows_key_values = get_ix_values( df, config_dict["kwargs"]["column"], ix_keys, distinct_bad_agis, bad_values=partial_unexpected_list, ) bad_values = partial_unexpected_list bad_values = sorted(list(set(bad_values))) elif "column_A" in config_dict["kwargs"] and "column_B" in config_dict["kwargs"]: # pragma: no mutate if config_dict["kwargs"]["column_A"] in df.columns and config_dict["kwargs"]["column_B"] in df.columns: # pragma: no mutate bad_values_dict = get_ix_values_pair(df, config_dict, ix_keys, distinct_bad_agis) bad_rows_key_values = bad_values_dict["ix_keys"] bad_values = bad_values_dict["bad_values"] else: bad_rows_key_values = None # pragma: no mutate bad_values = None # pragma: no mutate k2 = list(k1) k2.append("bad_values") k2.append("bad_rows_key") k2.append("bad_rows_key_values") v2 = list(v1) v2.append(bad_values) v2.append(ix_keys) v2.append(bad_rows_key_values) k1 = tuple(k2) v1 = tuple(v2) return_dict = {k: v for k, v in zip(k1, v1)} return return_dict
2598f38f266d949e9ff494ad3c9d8f3b
{ "intermediate": 0.42427486181259155, "beginner": 0.4541129767894745, "expert": 0.12161214649677277 }
13,049
I also want Intersections of Positive Modality, Intersections of Neutral based on this code : import matplotlib.pyplot as plt from matplotlib_venn import venn2, venn2_circles # create three sets based on your categorical features analysis_set = set(df_english_copy[“Analysis”]) vader_analysis_set = set(df_english_copy[“Vader_Analysis”]) swn_analysis_set = set(df_english_copy[“SWN_analysis”]) # create venn2 plots for all possible pairs of features fig, axs = plt.subplots(1, 3, figsize=(12, 4)) venn2([analysis_set, vader_analysis_set], set_colors=(“red”, “green”), set_labels=(“Analysis”, “Vader Analysis”), ax=axs[0]) venn2([analysis_set, swn_analysis_set], set_colors=(“red”, “blue”), set_labels=(“Analysis”, “SWN Analysis”), ax=axs[1]) venn2([vader_analysis_set, swn_analysis_set], set_colors=(“green”, “blue”), set_labels=(“Vader Analysis”, “SWN Analysis”), ax=axs[2]) axs[0].set_title(“Analysis vs. Vader Analysis”) axs[1].set_title(“Analysis vs. SWN Analysis”) axs[2].set_title(“Vader Analysis vs. SWN Analysis”) # add circle labels to each venn2 plot venn2_circles([analysis_set, vader_analysis_set], ax=axs[0], linestyle=“dotted”) venn2_circles([analysis_set, swn_analysis_set], ax=axs[1], linestyle=“dotted”) venn2_circles([vader_analysis_set, swn_analysis_set], ax=axs[2], linestyle=“dotted”) # add a title to the whole plot plt.suptitle(“Intersections of Analysis, Vader Analysis, and SWN Analysis”) plt.show()
8878ee40ecdbc091696a79d93d6cd5dc
{ "intermediate": 0.5221286416053772, "beginner": 0.28247058391571045, "expert": 0.19540078938007355 }
13,050
(1) Develop, briefly explain and post your own example of a few Python object oriented class definitions that would be part of a robot relevant software simulation system. Include brief Python code to simulate *using* the attributes and actions of the classes
c4bdb52780c3a519200558c506c510a2
{ "intermediate": 0.27305442094802856, "beginner": 0.4347401261329651, "expert": 0.29220542311668396 }
13,051
what is python object oriented class definition?
7ab955879aee44f547d86018205e7dfb
{ "intermediate": 0.3298598527908325, "beginner": 0.5174235701560974, "expert": 0.15271663665771484 }
13,052
i don't want to use set() because it return not the duplicates : import matplotlib.pyplot as plt from matplotlib_venn import venn2, venn2_circles # create three sets based on your categorical features analysis_set = set(df_english_copy["Analysis"]) vader_analysis_set = set(df_english_copy["Vader_Analysis"]) swn_analysis_set = set(df_english_copy["SWN_analysis"]) # venn2 plots for all possible pairs of features fig, axs = plt.subplots(1, 3, figsize=(12, 4)) venn2([analysis_set, vader_analysis_set], set_colors=("red", "green"), set_labels=("Analysis", "Vader Analysis"), ax=axs[0]) venn2([analysis_set, swn_analysis_set], set_colors=("red", "blue"), set_labels=("Analysis", "SWN Analysis"), ax=axs[1]) venn2([vader_analysis_set, swn_analysis_set], set_colors=("green", "blue"), set_labels=("Vader Analysis", "SWN Analysis"), ax=axs[2]) axs[0].set_title("Analysis vs. Vader Analysis") axs[1].set_title("Analysis vs. SWN Analysis") axs[2].set_title("Vader Analysis vs. SWN Analysis") # circle labels to each venn2 plot venn2_circles([analysis_set, vader_analysis_set], ax=axs[0], linestyle="dotted") venn2_circles([analysis_set, swn_analysis_set], ax=axs[1], linestyle="dotted") venn2_circles([vader_analysis_set, swn_analysis_set], ax=axs[2], linestyle="dotted") # adding a title to the whole plot plt.suptitle("Intersections of Analysis, Vader Analysis, and SWN Analysis") plt.show()
0ebb7204030f0cf28afd507518bcb781
{ "intermediate": 0.43246155977249146, "beginner": 0.32951828837394714, "expert": 0.23802019655704498 }
13,053
{JSON.stringify(starWarsData, null, 2)}
589f86c70903c597d6467fdd7ad5e5a0
{ "intermediate": 0.44394946098327637, "beginner": 0.2514009177684784, "expert": 0.30464956164360046 }
13,054
python Message: invalid argument: log type 'performance' not found 怎么解决
a143ca0ac461d65880d74c66bbfd9015
{ "intermediate": 0.29609793424606323, "beginner": 0.3273548185825348, "expert": 0.37654727697372437 }
13,055
explain this code : # create a crosstab of the two variables with normalized values crosstab = pd.crosstab(df_english_copy["Analysis"], df_english_copy["Vader_Analysis"], normalize="index") # plot the crosstab as a heatmap with percentage values inside the map sns.heatmap(crosstab, annot=True, fmt=".2%", cmap="YlGnBu") # show the plot plt.show()
c71169b6008771f719f9e1b9a1d1ce14
{ "intermediate": 0.37768930196762085, "beginner": 0.3331667184829712, "expert": 0.28914400935173035 }
13,056
/* pixel values / typedef union { struct { uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; }; uint8_t channels[4]; uint32_t concatenated_pixel_values; } qoi_pixel_t; Can you write a branchless version of this C function / Compares two pixels for the same color / static bool qoi_cmp_pixel(qoi_pixel_t pixel1, qoi_pixel_t pixel2, const uint8_t channels) { bool is_same_pixel = ( / Compare three channels for a pixel / pixel1.red == pixel2.red && pixel1.green == pixel2.green && pixel1.blue == pixel2.blue); if (channels > 3) / RGB pixels have three channels; RGBA pixels have four channels for the alpha channel / is_same_pixel = is_same_pixel && (pixel1.alpha == pixel2.alpha); / Compare the value of alpha for a pixel */ return is_same_pixel; }
c43bd360d92389a804a04de6a8d366e8
{ "intermediate": 0.3995243310928345, "beginner": 0.30493399500846863, "expert": 0.2955416738986969 }
13,057
Given these C code, /* pixel values / typedef union { struct { uint8_t red; uint8_t green; uint8_t blue; uint8_t alpha; }; uint8_t channels[4]; uint32_t concatenated_pixel_values; } qoi_pixel_t; / Compares two pixels for the same color / static bool qoi_cmp_pixel(qoi_pixel_t pixel1, qoi_pixel_t pixel2, const uint8_t channels) { bool is_same_pixel = ( / Compare three channels for a pixel / pixel1.red == pixel2.red && pixel1.green == pixel2.green && pixel1.blue == pixel2.blue); if (channels > 3) / RGB pixels have three channels; RGBA pixels have four channels for the alpha channel / is_same_pixel = is_same_pixel && (pixel1.alpha == pixel2.alpha); / Compare the value of alpha for a pixel */ return is_same_pixel; } using only bitwise operators, can you create a branchless version of checking if channel is greater than 4 then set the channel to 4 else set the channel to 3 then create a branchless version of checking if the channel is 4 then check the pixels else check red, green, and blue values
a2cdd0f7f958740cce01058f831ee858
{ "intermediate": 0.3814501464366913, "beginner": 0.23004496097564697, "expert": 0.38850492238998413 }
13,058
write A sudoku game in javascript
75c2988101f22100c65592b451df4710
{ "intermediate": 0.3667599856853485, "beginner": 0.4347269535064697, "expert": 0.198513001203537 }