row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,546
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders. need to preserve that clicking functionality to draw lines on grid. try integrate all described above but preserve mouse clicking on points that draw lines between 3d matrix grid points. output full javascript code, without shortages, but without html code included.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
96a458a3939548254eb9f222dd1e0dcb
|
{
"intermediate": 0.43943148851394653,
"beginner": 0.348894864320755,
"expert": 0.21167370676994324
}
|
10,547
|
write me c# code to load a video contain some car are running, i want to read iranian license plate from video and crop license plates into a picturebox live into picturebox ,also want to make it gray and noisless, and maybe marginal if necessery
|
eafb0208f23ccfed07b3033d6a1afe1b
|
{
"intermediate": 0.5991383194923401,
"beginner": 0.168230801820755,
"expert": 0.2326308935880661
}
|
10,548
|
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 requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
# 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)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
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': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Load the market symbols
markets = binance_futures.load_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):
server_time = exchange.fetch_currencies()
return server_time['timestamp']
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'
}
try:
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
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines(symbol, '1m', 89280)
def signal_generator(df):
if df is None:
return ""
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines(symbol, '1m', 89280)
def order_execution(symbol, signal, step_size, leverage, order_type):
# 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:
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
)
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialze 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 = FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# 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 = FUTURE_ORDER_TYPE_STOP_MARKET
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'askPrice' in ticker:
price = ticker['askPrice']
# 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:
try:
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)
except Exception as e:
print(f"Error rounding price: {e}")
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Update position_side based on opposite_position and current_position
if opposite_position is not None:
position_side = opposite_position['positionSide']
elif current_position is not None:
position_side = current_position['positionSide']
# Place order
order_params = {
"type": "MARKET" if signal == "buy" else "MARKET",
"side": "BUY" if signal == "buy" else "SELL",
"amount": quantity,
"price": price,
"closePosition": True,
"newClientOrderId": 'bot',
"type":order_type.upper(),
"responseType": "RESULT",
"timeInForce": "GTC",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": leverage
}
try:
order_params['symbol'] = symbol
response = binance_futures.create_order(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
return
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 89280) # 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}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage, order_type)
time.sleep(0.1)
But I getting ERROR
|
51d8f38d7861f289cb572e2e9d3347ba
|
{
"intermediate": 0.45047304034233093,
"beginner": 0.44051292538642883,
"expert": 0.10901406407356262
}
|
10,549
|
example usage of @Mutation decorator from type-graphql with 3 params: context, GraphQLResolveInfo, args
|
a24cadf4ae1b12ee846658bfd892781f
|
{
"intermediate": 0.5059651136398315,
"beginner": 0.23873507976531982,
"expert": 0.2552998661994934
}
|
10,550
|
here is my code
private int currentIndex = 0;
private string[] lines;
private void button1_Click(object sender, EventArgs e)
{
string filePath = @"D:\opencv\build\x64\vc14\bin\output.txt";
// Read the text file and store the lines
lines = File.ReadAllLines(filePath);
// Show the first image on the picture box
ShowImage();
// Increment the current index for the next line
currentIndex++;
}
private void ShowImage()
{
if (currentIndex >= lines.Length) return;
string line = lines[currentIndex];
// Extract the image path and coordinates of the bounding box
string[] values = line.Split(' ');
string imagePath = values[0];
int xmin = int.Parse(values[1]);
int ymin = int.Parse(values[2]);
int xmax = int.Parse(values[3]);
int ymax = int.Parse(values[4]);
// Load the image using OpenCVSharp
Mat image = Cv2.ImRead(imagePath);
// Draw the rectangle on the image
Rect rectangle = new Rect(xmin, ymin, xmax - xmin, ymax - ymin);
Cv2.Rectangle(image, rectangle, Scalar.Red); // Red color for visualization
// Show the image on the picture box
Bitmap bitmap = BitmapConverter.ToBitmap(image);
pictureBox1.Image = bitmap;
pictureBox1.Refresh();
}
save it and i want solve problems
|
18b8707911ae6bb6e809ee9437096a3d
|
{
"intermediate": 0.45783138275146484,
"beginner": 0.24268512427806854,
"expert": 0.2994835078716278
}
|
10,551
|
do zoom ability in here, to zoom in and out inside that cube grid with mouse wheel. also, do some rotation on all axis by mous dragging in empty space, set flag for auto-rotation to false. also, try to fit the entire 3d matrix grid on full canvas automatically, independent of gridSize or gridSpacing, with some small empty space around borders. need to preserve that clicking functionality to draw lines on grid. try integrate all described above but preserve mouse clicking on points that draw lines between 3d matrix grid points. output full javascript code, without shortages, but without html code included.: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mousedown", (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
40e2e72ba1c88a42c44d62a36a865886
|
{
"intermediate": 0.43943148851394653,
"beginner": 0.348894864320755,
"expert": 0.21167370676994324
}
|
10,552
|
i need a javascript regex to parse the following type out of a file. The comments should be ignored.
type classes = {
/** Styles applied to the root element. */
root?: string,
/** Styles applied to the root element unless `square={true}`. */
rounded?: string,
/** State class applied to the root element if `expanded={true}`. */
expanded?: string,
/** State class applied to the root element if `disabled={true}`. */
disabled?: string,
/** Styles applied to the root element unless `disableGutters={true}`. */
gutters?: string,
/** Styles applied to the region element, the container of the children. */
region?: string,
}
|
bc1dc093f6920937478e26a130ed728f
|
{
"intermediate": 0.27693507075309753,
"beginner": 0.5077967643737793,
"expert": 0.21526813507080078
}
|
10,553
|
hi need a bulk number validator
|
2cb9d20d7fde493b5ccbcd4b2a5b98e3
|
{
"intermediate": 0.35548970103263855,
"beginner": 0.20290254056453705,
"expert": 0.44160768389701843
}
|
10,554
|
Make a stock market prediction model indicating up and down trend (use below code just for demonstration your model should be better than this) make use of super trend also use NSETOOLS to get the data insted of yfinance data:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score, f1_score
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['H-L'] = data['High'] - data['Low']
data['H-PC'] = abs(data['High'] - data['Close'].shift(1))
data['L-PC'] = abs(data['Low'] - data['Close'].shift(1))
data['TR'] = data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
data['ATR'] = data['TR'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['High'] + data['Low']) / 2 + multiplier * data['ATR']
data['Lower Basic'] = (data['High'] + data['Low']) / 2 - multiplier * data['ATR']
data['Upper Band'] = data[['Upper Basic', 'Lower Basic']].apply(
lambda x: x['Upper Basic'] if x['Close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data[['Upper Basic', 'Lower Basic']].apply(
lambda x: x['Lower Basic'] if x['Close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.nan
for i in range(period, len(data)):
if data['Close'][i] <= data['Upper Band'][i - 1]:
data['Super Trend'][i] = data['Upper Band'][i]
elif data['Close'][i] > data['Upper Band'][i]:
data['Super Trend'][i] = data['Lower Band'][i]
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
stock_data.columns = stock_data.columns.astype(str) # Add this line
print(stock_data.columns)
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['Close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(1 if data_normalized[i, 0] > data_normalized[i - 1, 0] else 0)
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1)
return model, history
def evaluate_model(model, X_test, y_test):
y_pred = model.predict(X_test)
y_pred = np.where(y_pred > 0.5, 1, 0)
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print('Accuracy:', accuracy, 'F1 score:', f1)
def predict_stock_movement(model, X_input):
y_pred = model.predict(X_input)
return "up" if y_pred > 0.5 else "down"
ticker = '^NSEI'
start_date = '2010-01-01'
end_date = '2020-12-31'
window_size = 60
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size)
model = create_lstm_model(X_train.shape[1:])
batch_size = 32
epochs = 20
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Make predictions
y_pred = model.predict(X_test)
y_pred_direction = np.where(y_pred > 0.5, 1, 0)
# Plot actual and predicted values daywise
plt.figure(figsize=(14, 6))
plt.plot(y_test, label='Actual')
plt.plot(y_pred_direction, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Direction')
plt.title('NIFTY Stock Price Direction Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred_direction)
f1 = f1_score(y_test, y_pred_direction)
print('Accuracy:', accuracy, 'F1 score:', f1)
|
5dde6d721652c59898441bb3e2d11f52
|
{
"intermediate": 0.38581234216690063,
"beginner": 0.3500744104385376,
"expert": 0.26411324739456177
}
|
10,555
|
I'm a node.js developer
|
e77782e8fc710b3ff117602cb27e4dc3
|
{
"intermediate": 0.45789387822151184,
"beginner": 0.2578217685222626,
"expert": 0.2842843234539032
}
|
10,556
|
based on the entity import { Column, Entity, OneToMany } from 'typeorm';
import { AbstractIdEntity } from '../../../common/abstract.id.entity';
import { EventEntity } from '../../event/entities/event.entity';
import { LocationDto } from '../dto/location.dto';
@Entity({ name: 'location' })
export class LocationEntity extends AbstractIdEntity<LocationDto> {
@Column({ nullable: true })
name: string;
@Column({ nullable: true, type: 'int' })
color: number;
@OneToMany(() => EventEntity, (event) => event.location, { nullable: true })
events: EventEntity[];
dtoClass = LocationDto;
} update the dto import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsNumber, IsString, Max, Min } from 'class-validator';
export class LocationCreateDto {
@ApiProperty({
description: 'Name of location',
type: String,
})
@IsString({ message: 'should be string' })
@IsNotEmpty()
name: string;
@ApiProperty({
description: 'Color of location',
type: Number,
default: 5,
})
@IsNumber()
@Min(1)
@Max(20)
color: number;
}
|
050486061ae2f00cb3f68a2a896c9ac9
|
{
"intermediate": 0.48013925552368164,
"beginner": 0.3315954804420471,
"expert": 0.18826521933078766
}
|
10,557
|
Write a program code that, when entering the hash of a transaction in Bcscan, will output the method id that was used in the transaction. Use APIKey
|
da13ecc9b992650367e210d2364139d9
|
{
"intermediate": 0.6691612601280212,
"beginner": 0.08403667062520981,
"expert": 0.24680206179618835
}
|
10,558
|
Write VBA macro to do the following:
1. Ask user where are statuses? They enter capital letter, remember it, it is the column for all sheets where statuses are located.
2. Ask user where are values? They enter capital letter, remember it, it is the column for all sheets where values are located.
3. Add a new sheet. Call it 'Инфо по лотам'.
3. Walk all worksheets in current workbook.
4. From each sheet count unique values from column entered in 2.
5. From each sheet count occurrences of each unique status from column entered in 1.
6. Save this data to sheet 'Инфо по лотам' like so (starting from A1 cell):
{sheet name}
Количество лотов {number from point 4}
Статусы
{status 1 value} {number of occurrences of status 1}
...
{status n value} {number of occurrences of status n}
when you are done with a sheet, leave next 4 rows empty and continue for the next sheet in the same manner as described in point 6
|
24bdca12fdfbd297d92a589f7522b8b8
|
{
"intermediate": 0.41092756390571594,
"beginner": 0.3073384761810303,
"expert": 0.28173398971557617
}
|
10,559
|
Разбей на файлы(модули) следующий код
#include <GL/glut.h>
#include <iostream>
#include "map.h"
#include "drawpers.h"
#include "drawattribute.h"
#include <cstdlib>
#include <ctime>
#include "interface.h"
#include <algorithm>
struct Position {
float x, y;
};
struct Figur {
Position pos;
bool isRight;
GLfloat health;
} figur;
struct Enemy {
Position pos;
bool isRight;
GLfloat health;
};
struct Knife {
Position pos;
bool isAlive;
bool isRight;
};
const int MAX_KNIVES = 10;
Knife knives[MAX_KNIVES];
int knifeSpawnDelay = 700; // Задержка между спавном ножей
int lastKnifeSpawnTime = 0; // Время последнего спавна ножа
int napr_nog1 = 0;
int napr_nog2 = 0;
const int MAX_ENEMIES = 100;
Enemy enemies[MAX_ENEMIES];
Position pos = {0.0, 0.0};
bool isGameOver = false;
bool immune = false;
float legStep = 15; //поворота ноги
float legAngle = 0;
float mapMinX = -10.0;
float mapMaxX = 10.0;
float mapMinY = -10.0;
float mapMaxY = 10.0;
void renderScene(void);
void geralt();
void cirila();
void yovert();
void drawMap();
void leg1g();
void leg2g();
void ghost();
void wildhunt();
void processKeys(unsigned char key, int x, int y);
void drawEnemies();
void drawGameOver();
void drawHealthBar();
void update(int value);
void generateRandomEnemies();
bool checkCollision(Position pos1, Position pos2, float radius1, float radius2);
void handleCollisions();
void drawUI();
void legTimer(int value);
void drawKnives();
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(800, 800);
glutCreateWindow("Game");
glutDisplayFunc(renderScene);
glutKeyboardFunc(processKeys);
glClearColor(0, 0, 0, 0);
//начальные значений игрока
figur.pos.x = 0.0f;
figur.pos.y = 0.0f;
pos.x = 0.0f;
pos.y = 0.0f;
figur.health=10;
//начальные значений мобов
for (int i = 0; i < MAX_ENEMIES; ++i) {
enemies[i].pos.x = 0.05;
enemies[i].pos.y = 0;
enemies[i].health = 3;
}
//генерация рандомных мобов
generateRandomEnemies();
glutTimerFunc(16, update, 0); // движение мобов
glutTimerFunc(1, legTimer, 0);
glutMainLoop();
return 0;
}
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (isGameOver) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glPushMatrix();
drawGameOver();
glPopMatrix();
} else {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Перемещение камеры
glTranslatef(-figur.pos.x, -figur.pos.y, 0.0f);
drawMap();
//границы
if (figur.pos.x < mapMinX) {
figur.pos.x = mapMinX; // Ограничение движения по X влево
} else if (figur.pos.x > mapMaxX) {
figur.pos.x = mapMaxX; // Ограничение движения по X вправо
}
if (figur.pos.y < mapMinY) {
figur.pos.y = mapMinY; // Ограничение движения по Y вниз
} else if (figur.pos.y > mapMaxY) {
figur.pos.y = mapMaxY; // Ограничение движения по Y вверх
}
drawUI();
glPushMatrix();
glTranslatef(figur.pos.x, figur.pos.y, 0.0f);
if (figur.isRight) {
glRotatef(180, 0.0f, 1.0f, 0.0f);
} else {
glRotatef(0, 0.0f, 1.0f, 0.0f);
}
glScalef(0.3, 0.3, 0.3);
glPushMatrix();
geralt();
//ciri
//yovert
glPushMatrix();
glRotatef(legAngle, 0.0, 0.0, 1.0);
if (legAngle >= -45.0f) {
napr_nog1 = -1;
} else if (legAngle <= 45.0f) {
napr_nog1 = 1;
}
leg1g();
if (napr_nog1 == 1) {
glTranslatef(0.0, 0.0, 0.0);
glRotatef(legAngle, 0.0, 0.0, 1.0);
}
if (napr_nog1 == -1) {
glRotatef(-legAngle, 0.0, 0.0, 1.0); // Возвращение ноги в исходное положение
glTranslatef(0.0, 0.0, 0.0);
}
leg2g();
if (napr_nog1 == 1) {
glTranslatef(0.0, 0.0, 0.0);
glRotatef(-legAngle, 0.0, 0.0, 1.0);
}
if (napr_nog1 == -1) {
glRotatef(legAngle, 0.0, 0.0, 1.0); // Возвращение ноги в исходное положение
glTranslatef(0.0, 0.0, 0.0);
}
glPopMatrix();
drawEnemies();
glPushMatrix();
drawKnives();
glPopMatrix();
glPopMatrix();
glPopMatrix();
drawHealthBar();
}
glutSwapBuffers();
}
void processKeys(unsigned char key, int x, int y) {
switch (key) {
case 'w':
figur.pos.y += 0.1;
legAngle = 0;
legAngle += legStep;
break;
case 's':
figur.pos.y -= 0.1;
legAngle = 0;
legAngle += legStep;
break;
case 'a':
figur.pos.x -= 0.1;
figur.isRight = false;
napr_nog1 = 1;
legAngle += legStep;
break;
case 'd':
figur.pos.x += 0.1;
figur.isRight = true;
napr_nog1 = -1;
legAngle += legStep;
break;
for (int i = 0; i < MAX_KNIVES; ++i) {
if (!knives[i].isAlive) {
knives[i].pos = figur.pos;
knives[i].isAlive = true;
knives[i].isRight = figur.isRight;
break;
}
}
break;
default:
return;
glutPostRedisplay();
}
}
void legTimer(int value) {
glutPostRedisplay();
// Ограничение угла
if (legAngle > 45.0f) {
legAngle = -15;
}
// Переключение направления ноги
if (legAngle >= 45.0f || legAngle <= -15) {
legStep = -legStep;
}
glutTimerFunc(10, legTimer, 0);
}
void spawnRandomEnemy(void) {
int randomNum = rand() % 2; // генерация случайных видов мобов
if (randomNum == 0) {
wildhunt();
} else {
ghost();
}
}
void drawEnemies(void) {
srand(42);
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].health > 0) {
glPushMatrix();
glTranslatef(enemies[i].pos.x, enemies[i].pos.y, 0.0f);
glScalef(0.4, 0.4, 0.4);
if (enemies[i].isRight) {
glRotatef(180, 0.0f, 1.0f, 0.0f);
}
spawnRandomEnemy();
}
glPopMatrix();
}
}
bool checkCollision(Position pos1, Position pos2, float radius1, float radius2) {
float distance = sqrt(pow(pos1.x - pos2.x, 2) + pow(pos1.y - pos2.y, 2));
return distance <= radius1 + radius2;
}
void handleCollisions(void) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (checkCollision(figur.pos, enemies[i].pos, 0.1f, 0.1f)) {
float enemyDirectionX = figur.pos.x - enemies[i].pos.x;
float enemyDirectionY = figur.pos.y - enemies[i].pos.y;
figur.pos.x += enemyDirectionX * 0.05;
figur.pos.y += enemyDirectionY * 0.05;
figur.health -= 0.5f; // Уменьшение здоровья персонажа
if (figur.health <= 0.0f) {
isGameOver = true; // Игра окончена, если здоровье кончилось
}
}
for (int j = i + 1; j < MAX_ENEMIES; ++j) {
if (checkCollision(enemies[i].pos, enemies[j].pos, 0.09f, 0.09f)) {
float enemyDirectionX = enemies[i].pos.x - enemies[j].pos.x;
float enemyDirectionY = enemies[i].pos.y - enemies[j].pos.y;
enemies[i].pos.x += enemyDirectionX * 0.3f;
enemies[i].pos.y += enemyDirectionY * 0.3f;
enemyDirectionX = enemies[j].pos.x - enemies[i].pos.x;
enemyDirectionY = enemies[j].pos.y - enemies[i].pos.y;
enemies[j].pos.x += enemyDirectionX * 0.2f;
enemies[j].pos.y += enemyDirectionY * 0.2f;
}
}
}
}
void update(int value) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
// Определение направлениия мобов к персонажу
float directionX = figur.pos.x - enemies[i].pos.x;
float directionY = figur.pos.y - enemies[i].pos.y;
float length = sqrt(directionX * directionX + directionY * directionY);
directionX /= length;
directionY /= length;
float speed = 0.02;
float offsetX = speed * directionX;
float offsetY = speed * directionY;
// позиция моба изменяется
enemies[i].pos.x += offsetX;
enemies[i].pos.y += offsetY;
if (directionX > 0) {
enemies[i].isRight = false;
} else {
enemies[i].isRight = true;
}
}
//статичная анимация для персонажа
static bool moveUp = true;
static float delta = 0.005f;
if (moveUp) {
figur.pos.y += delta;
} else {
figur.pos.y -= delta;
}
if (figur.pos.y >= 0.001f || figur.pos.y <= -0.001f) {
moveUp = !moveUp;
}
//статичная для мобов
static bool mobMoveUp[MAX_ENEMIES] = { true };
static float deltam = 0.01f;
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (mobMoveUp[i]) {
enemies[i].pos.y += deltam;
} else {
enemies[i].pos.y -= deltam;
}
if (enemies[i].pos.y >= 0.03f || enemies[i].pos.y <= -0.03f) {
mobMoveUp[i] = !mobMoveUp[i];
}
}
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
knives[i].pos.x += 0.1; //обновления позиции ножа
// Проверка столкновений ножа с врагами
for (int j = 0; j < MAX_ENEMIES; ++j) {
if (enemies[j].health > 0 && checkCollision(knives[i].pos, enemies[j].pos, 0.05, 0.05) && !immune) {
enemies[j].health = 0; // Убийство врага
knives[i].isAlive = false;
immune = true; // Устанавливаем иммунитет для игрока (Долго же я не понимал почему просто так сливаюсь)
break;
}
}
}
}
int currentTime = glutGet(GLUT_ELAPSED_TIME);
if (currentTime - lastKnifeSpawnTime >= knifeSpawnDelay) {
// Создание нового ножа
for (int i = 0; i < MAX_KNIVES; ++i) {
if (!knives[i].isAlive) {
knives[i].pos = figur.pos;
knives[i].isAlive = true;
knives[i].isRight = figur.isRight;
break;
}
}
lastKnifeSpawnTime = currentTime; // Обновление времени последнего спавна ножа
}
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
Enemy* target = nullptr;
float minDistance = std::numeric_limits<float>::max();
// Поиск ближайшего врага
for (int j = 0; j < MAX_ENEMIES; ++j) {
if (enemies[j].health > 0) {
float distance = std::sqrt(std::pow(enemies[j].pos.x - knives[i].pos.x, 2) +
std::pow(enemies[j].pos.y - knives[i].pos.y, 2));
if (distance < minDistance) {
minDistance = distance;
target = &enemies[j];
}
}
}
// Обновление позиции ножа в направлении моба(цели)
if (target) {
float dx = target->pos.x - knives[i].pos.x;
float dy = target->pos.y - knives[i].pos.y;
float distance = std::sqrt(std::pow(dx, 2) + std::pow(dy, 2));
float speed = 0.1f;
if (distance > 0.01f) {
knives[i].pos.x += speed * dx / distance;
knives[i].pos.y += speed * dy / distance;
} else {
target->health = 0;
knives[i].isAlive = false;
}
}
}
}
static int immuneTime = 3000;
static int lastImmuneTime = 0;
if (currentTime - lastImmuneTime >= immuneTime) {
immune = false;
lastImmuneTime = currentTime;
}
// Планирование следующего обновления
glutTimerFunc(10, update, 0);
handleCollisions();
glutPostRedisplay();
}
void drawKnives() {
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
glPushMatrix();
glTranslatef(knives[i].pos.x, knives[i].pos.y, 0.0f);
knife();
glEnd();
glPopMatrix();
}
}
}
void drawGameOver(void) {
glPushMatrix();
glScalef(1, 1, 1);
glColor3f(1.0f, 0.0f, 0.0f);
glRasterPos2f(-0.15f, 0.1f);
const char* text = "Game Over!";
int len = strlen(text);
for (int i = 0; i < len; i++) {
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, text[i]);
}
glRasterPos2f(-0.15f, 0.1f);
glPopMatrix();
}
void drawHealthBar(void) {
glPushMatrix();
glTranslatef(figur.pos.x, figur.pos.y+0.15, 0.0f);
glScalef(0.2, 0.2, 0.2);
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f); //здоровье
glVertex2f(-0.3f, 0.2f);
glVertex2f(0.3f, 0.2f);
glVertex2f(0.3f, 0.25f);
glVertex2f(-0.3f, 0.25f);
glColor3f(0.0f, 1.0f, 0.0f);
//значения health
glVertex2f(-0.3f, 0.2f);
glVertex2f(figur.health * 0.2f - 0.3f, 0.2f);
glVertex2f(figur.health * 0.2f - 0.3f, 0.25f);
glVertex2f(-0.3f, 0.25f);
glEnd();
glPopMatrix();
}
void generateRandomEnemies(void) { //случайная генерация мобов
std::srand(std::time(nullptr));
for (int i = 0; i < MAX_ENEMIES; ++i) {
float posX, posY;
bool overlap;
do {
overlap = false;
posX = static_cast<float>(std::rand() % 20) - 10;
posY = static_cast<float>(std::rand() % 20) - 10;
for (int j = 0; j < i; ++j) {
if (checkCollision({posX, posY}, enemies[j].pos, 0.4f, 0.4f)) {
overlap = true;
break;
}
}
} while (overlap);
enemies[i].pos.x = posX;
enemies[i].pos.y = posY;
}
}
|
cbf86f719cd165a4d6d15b57d5a9768f
|
{
"intermediate": 0.27843907475471497,
"beginner": 0.30286073684692383,
"expert": 0.4187001883983612
}
|
10,560
|
Hello. In python using machine learning, I want you to create a predictor for a game, where the player has to chose between 4 answers. There is only one answer, and I want you to make an input statement for eachtime a prediction has been mode. The user inputs the right answer is numbers; like the first answer box is named 1, second is named 2, third is named 3 and fourth is named 4. Each time the user has sat the new input in, the app makes a predictior for the next best odds on one of the four boxes that’s correct. When the prediction has been made, then the programs asks for what was the right answer, and saves it, as it’s gonna be stored as data for the app to then predict the next. It will loop until the words “exit” has been wrote and it then exit. Short: Make a predictor in python, that goes in a loop to a 4 box game with one correct answer. The app is gonna predict, and then ask for an user input, and predict again until the user types exit. Its a kahoot game
|
6b8fe3bfb875515bcf7ef3a7ce9e71db
|
{
"intermediate": 0.2473665028810501,
"beginner": 0.16866926848888397,
"expert": 0.5839642286300659
}
|
10,561
|
Write a script that's capable of getting responses from ChatGPT Api or anything else that's capable of getting responses from a prompt for completely free without the need of any sort of API key.
|
01d6e47f73c0b6e89f5adadd0d857b24
|
{
"intermediate": 0.6512115597724915,
"beginner": 0.10553640872240067,
"expert": 0.24325203895568848
}
|
10,562
|
rigger UpdateAccountBalance on Zuora__InvoiceItem__c (after insert, after update,after delete) {
if(trigger.isafter&&(trigger.isinsert||trigger.isupdate)){
UpdateAccountBalanceHandler.UpdateAccountInvoice(trigger.new);
}
else
if(trigger.isafter&& trigger.isdelete){
UpdateAccountBalanceHandler.UpdateAccountInvoice(trigger.old) ;
}
}
public class UpdateAccountBalanceHandler {
public static void UpdateAccountInvoice(List<Zuora__InvoiceItem__c> zuorainvoice) {
Set<Id> Zccids = new Set<Id>();
for (Zuora__InvoiceItem__c zuora : zuorainvoice) {
if (zuora.Account__c != null && zuora.Zuora__Charge_Amount2__c != null) {
Zccids.add(zuora.Account__c);
}
}
List<Account> acclist = [ SELECT Id, Balance__c,(SELECT Id, Zuora__Charge_Amount2__c FROM Invoice_Items__r)FROM Account WHERE Id IN :Zccids];
for (Account acc : acclist) {
for (Zuora__InvoiceItem__c inv : acc.Invoice_Items__r) {
acc.Balance__c = inv.Zuora__Charge_Amount2__c;
}
}
update acclist;
}
}
|
bc5872d9534d0dbb36a9602e2249a925
|
{
"intermediate": 0.3986418545246124,
"beginner": 0.321705162525177,
"expert": 0.27965298295021057
}
|
10,563
|
do zoom ability here, to zoom in and out to the center of that cube grid with mouse wheel with some adjustable precise step size in zooming. also, do some rotation on all axis by mouse dragging in empty space, set flag for auto-rotation to false. also, auto-fit the entire 3d matrix grid to full canvas automatically. need to preserve that clicking functionality to draw lines on grid. integrate all, output only full javascript code, without html code included.:
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id=“canvas”></canvas>
<script>
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mouseup”, (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = “rgba(25,200,25,0.2)”;
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = “rgba(1,2,1,0.8)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = “rgba(55,155,255,0.8)”;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = “rgba(255,200,50,0.8)”;
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
b690ee56538c34e0627d423c103bbabc
|
{
"intermediate": 0.272936075925827,
"beginner": 0.4344324767589569,
"expert": 0.29263144731521606
}
|
10,564
|
do zoom ability here, to zoom in and out to the center of that cube grid with mouse wheel with some adjustable precise step size in zooming. also, do some rotation on all axis by mouse dragging in empty space, set flag for auto-rotation to false. also, auto-fit the entire 3d matrix grid to full canvas automatically. need to preserve that clicking functionality to draw lines on grid. integrate all, output only full javascript code, without html code included.:
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id=“canvas”></canvas>
<script>
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mouseup”, (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = “rgba(25,200,25,0.2)”;
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = “rgba(1,2,1,0.8)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = “rgba(55,155,255,0.8)”;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = “rgba(255,200,50,0.8)”;
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
68ce3d92cf979d136e37a6362a166064
|
{
"intermediate": 0.272936075925827,
"beginner": 0.4344324767589569,
"expert": 0.29263144731521606
}
|
10,565
|
do zoom ability here, to zoom in and out to the center of that cube grid with mouse wheel with some adjustable precise step size in zooming. also, do some rotation on all axis by mouse dragging in empty space, set flag for auto-rotation to false. also, auto-fit the entire 3d matrix grid to full canvas automatically. need to preserve that clicking functionality to draw lines on grid. integrate all, output only full javascript code, without html code included.:
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id=“canvas”></canvas>
<script>
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mouseup”, (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = “rgba(25,200,25,0.2)”;
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = “rgba(1,2,1,0.8)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = “rgba(55,155,255,0.8)”;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = “rgba(255,200,50,0.8)”;
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
aca6a29c4417936ce449bed4eff478db
|
{
"intermediate": 0.272936075925827,
"beginner": 0.4344324767589569,
"expert": 0.29263144731521606
}
|
10,566
|
Correct this code for the error:
ERROR:
Index(['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'], dtype='object')
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3801 try:
-> 3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
12 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Close'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
-> 3804 raise KeyError(key) from err
3805 except TypeError:
3806 # If we have a listlike key, _check_indexing_error will raise
KeyError: 'Close'
CODE:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score, f1_score
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data['H-L'] = data['High'] - data['Low']
data['H-PC'] = abs(data['High'] - data['Close'].shift(1))
data['L-PC'] = abs(data['Low'] - data['Close'].shift(1))
data['TR'] = data[['H-L', 'H-PC', 'L-PC']].max(axis=1)
data['ATR'] = data['TR'].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data['Upper Basic'] = (data['High'] + data['Low']) / 2 + multiplier * data['ATR']
data['Lower Basic'] = (data['High'] + data['Low']) / 2 - multiplier * data['ATR']
data['Upper Band'] = data[['Upper Basic', 'Lower Basic']].apply(
lambda x: x['Upper Basic'] if x['Close'] > x['Upper Basic'] else x['Lower Basic'], axis=1)
data['Lower Band'] = data[['Upper Basic', 'Lower Basic']].apply(
lambda x: x['Lower Basic'] if x['Close'] < x['Lower Basic'] else x['Upper Basic'], axis=1)
data['Super Trend'] = np.nan
for i in range(period, len(data)):
if data['Close'][i] <= data['Upper Band'][i - 1]:
data['Super Trend'][i] = data['Upper Band'][i]
elif data['Close'][i] > data['Upper Band'][i]:
data['Super Trend'][i] = data['Lower Band'][i]
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
stock_data.columns = stock_data.columns.astype(str) # Add this line
print(stock_data.columns)
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[['Close', 'Super Trend']].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(1 if data_normalized[i, 0] > data_normalized[i - 1, 0] else 0)
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1)
return model, history
def evaluate_model(model, X_test, y_test):
y_pred = model.predict(X_test)
y_pred = np.where(y_pred > 0.5, 1, 0)
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print('Accuracy:', accuracy, 'F1 score:', f1)
def predict_stock_movement(model, X_input):
y_pred = model.predict(X_input)
return "up" if y_pred > 0.5 else "down"
ticker = '^NSEI'
start_date = '2010-01-01'
end_date = '2020-12-31'
window_size = 60
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size)
model = create_lstm_model(X_train.shape[1:])
batch_size = 32
epochs = 20
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Make predictions
y_pred = model.predict(X_test)
y_pred_direction = np.where(y_pred > 0.5, 1, 0)
import matplotlib.pyplot as plt
# Plot actual and predicted values daywise
plt.figure(figsize=(14, 6))
plt.plot(y_test, label='Actual')
plt.plot(y_pred_direction, label='Predicted')
plt.xlabel('Days')
plt.ylabel('Direction')
plt.title('NIFTY Stock Price Direction Prediction (Actual vs Predicted)')
plt.legend()
plt.show()
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred_direction)
f1 = f1_score(y_test, y_pred_direction)
print('Accuracy:', accuracy, 'F1 score:', f1)
|
96e3a3302e09cca5e7cc527159e0cf7a
|
{
"intermediate": 0.4056803286075592,
"beginner": 0.43268200755119324,
"expert": 0.16163764894008636
}
|
10,567
|
Hello. In python using machine learning, I want you to create a predictor for a game, where the player has to chose between 4 answers. There is only one answer, and I want you to make an input statement for eachtime a prediction has been mode. The user inputs the right answer is numbers; like the first answer box is named 1, second is named 2, third is named 3 and fourth is named 4. Each time the user has sat the new input in, the app makes a predictior for the next best odds on one of the four boxes that's correct. When the prediction has been made, then the programs asks for what was the right answer, and saves it, as it's gonna be stored as data for the app to then predict the next. It will loop until the words "exit" has been wrote and it then exit. Short: Make a predictor in python, that goes in a loop to a 4 box game with one correct answer. The app is gonna predict, and then ask for an user input, and predict again until the user types exit.
|
21b04a6a90bdf96d99aa98f11e57d417
|
{
"intermediate": 0.21970920264720917,
"beginner": 0.1712096482515335,
"expert": 0.6090811491012573
}
|
10,568
|
do zoom ability here, to zoom in and out to the center of that cube grid with mouse wheel with some adjustable precise step size in zooming. also, do some rotation on all axis by mouse dragging in empty space, set flag for auto-rotation to false. also, auto-fit the entire 3d matrix grid to full canvas automatically. need to preserve that clicking functionality to draw lines on grid. integrate all, output only full javascript code, without html code included.:
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id=“canvas”></canvas>
<script>
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mouseup”, (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = “rgba(25,200,25,0.2)”;
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = “rgba(1,2,1,0.8)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = “rgba(55,155,255,0.8)”;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = “rgba(255,200,50,0.8)”;
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
2076ee691a6f01847692a63405534bc2
|
{
"intermediate": 0.272936075925827,
"beginner": 0.4344324767589569,
"expert": 0.29263144731521606
}
|
10,569
|
Найди ошибку(В проекте используется библиотека antlr4)
Серьезность Код Описание Проект Файл Строка Состояние подавления
Ошибка LNK2001 неразрешенный внешний символ "protected: virtual class std::any __cdecl antlr4::tree::AbstractParseTreeVisitor::aggregateResult(class std::any,class std::any)" (?aggregateResult@AbstractParseTreeVisitor@tree@antlr4@@MEAA?AVany@std@@V45@0@Z). samples C:\Users\Eisim\laba6\build\samples\main.obj 1
Cmake файлы:
Главный:
cmake_minimum_required(VERSION 3.24)
SET (CMAKE_CXX_STANDARD 17)
project(expression2 CXX)
set(antlr-rt-lib ./3rdparty/antlr4/runtime/Cpp/build/bin/lib)
include_directories(
./antlr4 3rdparty/antlr4/runtime/Cpp/build/bin/lib 3rdparty/antlr4/runtime/Cpp/build/bin/bin/ 3rdparty/antlr4/runtime/Cpp/build/bin/include/
)
add_subdirectory(include)
add_subdirectory(samples)
В папке include
project(include)
file(GLOB srcs "*.cpp*")
file(GLOB hdrs "*.h*")
add_executable(include ${srcs} ${hdrs})
include_directories(include ../3rdparty/antlr4/runtime/Cpp/build/bin/bin ../3rdparty/antlr4/runtime/Cpp/build/bin/include/antlr4-runtime
../3rdparty/antlr4/runtime/Cpp/build
)
target_link_libraries(include PUBLIC ../3rdparty/antlr4/runtime/Cpp/build/bin/lib/antlr4-runtime.lib ../3rdparty/antlr4/runtime/Cpp/build/bin/lib/antlr4-runtime-static.lib)
#target_link_libraries(include PUBLIC ../../antlr4/antlr4-runtime ../../antlr4/antlr4-runtime-static)
add_custom_command(TARGET include
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ../3rdparty/antlr4/runtime/Cpp/build/bin/bin/antlr4-runtime.dll ${CMAKE_BINARY_DIR}/bin/
)
В папке samples
project(samples)
file(GLOB srcs "*.cpp*")
add_executable(samples ${srcs})
include_directories(include ../3rdparty/antlr4/runtime/Cpp/build/bin/bin ../3rdparty/antlr4/runtime/Cpp/build/bin/include/antlr4-runtime)
target_include_directories(samples PUBLIC ../include)
|
5ff887cc78ca9d755a0ae8ffae4ebd8d
|
{
"intermediate": 0.23872527480125427,
"beginner": 0.587367057800293,
"expert": 0.17390765249729156
}
|
10,570
|
You gave me this plan for creating e-commerce website with microservices architecture using Spring Boot and React:
1. Set up the Back-End Application
1-A. Install Java Development Kit (JDK)
1-B. Set up Spring Boot Project using Spring Initializr
1-C. Create a Database
1-D. Configure Connection Settings, JPA, and Hibernate
1-E. Implement User Management with Spring Security and JWT
1-F. Implement Product Management with CRUD Operation and REST APIs
1-G. Implement Order and Shopping Cart Management
2. Set up the Front-End Application
2-A. Install Node.js and NPM
2-B. Create a React App using Create React App
2-C. Set up React Router for Navigation
2-D. Create a Registration and Login Page
2-E. Create a Home Page to Display Products
2-F. Create a Product Page to Display Detailed Information
2-G. Create a Shopping Cart Page to View, Add, and Remove Products
3. Test the Back-End and Front-End Service
3-A. Use Postman and Swagger-UI to Test RESTful APIs
3-B. Write Unit and Integration Tests for both Back-End and Front-End
3-C. Conduct User Acceptance Testing
4. Deploy and Release the application
4-A. Choose a hosting platform or cloud service to deploy the app
4-B. Configure the deployment settings and environment variables
4-C. Create user and administration manuals and API documentation
5. Maintenance and Continuous Improvement
5-A. Monitor the application and database performance to prevent issues
5-B. Fix any bugs and vulnerabilities that arise
5-C. Implement new features and keep the app up-to-date.
i am at 1-B. Please only focus on 1-B. Dont talk about others. While creating the project i will use maven. What do you suggest for Group, Artifact, Name,Description,Package name? And what dependencies i should add?
|
605e5c7debd76ec5e7e16f1fb00bcbdf
|
{
"intermediate": 0.5018147826194763,
"beginner": 0.31391459703445435,
"expert": 0.18427060544490814
}
|
10,571
|
do zoom ability here, to zoom in and out to the center of that cube grid with mouse wheel with some adjustable precise step size in zooming. also, do some rotation on all axis by mouse dragging in empty space, set flag for auto-rotation to false. also, auto-fit the entire 3d matrix grid to full canvas automatically. need to preserve that clicking functionality to draw lines on grid. integrate all, output only full javascript code, without html code included.:
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>drawacube</title>
<style>
canvas {
display: block;
margin: auto;
}
</style>
</head>
<body>
<canvas id=“canvas”></canvas>
<script>
const canvas = document.getElementById(“canvas”);
const ctx = canvas.getContext(“2d”);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = 800 / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20; // Adjust this value to set the click tolerance
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mousedown”, (e) => {
mouseDown = true;
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const startPoint = findClosestPoint({ x: mouseX, y: mouseY });
activeLine = [startPoint];
});
canvas.addEventListener(“mouseup”, (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = “rgba(25,200,25,0.2)”;
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = “rgba(1,2,1,0.8)”;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = “rgba(55,155,255,0.8)”;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = “rgba(255,200,50,0.8)”;
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
</script>
</body>
</html>
|
45999434cb106e78ff28c5d0a750a6a9
|
{
"intermediate": 0.272936075925827,
"beginner": 0.4344324767589569,
"expert": 0.29263144731521606
}
|
10,572
|
Hi
|
1d6d427d3cc5ee0701de00205396983f
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
10,573
|
Раздели на модули(файлы)
#include <GL/glut.h>
#include <iostream>
#include "map.h"
#include "drawpers.h"
#include "drawattribute.h"
#include <cstdlib>
#include <ctime>
#include "interface.h"
#include <algorithm>
struct Position {
float x, y;
};
struct Figur {
Position pos;
bool isRight;
GLfloat health;
} figur;
struct Enemy {
Position pos;
bool isRight;
GLfloat health;
};
struct Knife {
Position pos;
bool isAlive;
bool isRight;
};
const int MAX_KNIVES = 10;
Knife knives[MAX_KNIVES];
int knifeSpawnDelay = 700; // Задержка между спавном ножей
int lastKnifeSpawnTime = 0; // Время последнего спавна ножа
int napr_nog1 = 0;
int napr_nog2 = 0;
const int MAX_ENEMIES = 100;
Enemy enemies[MAX_ENEMIES];
Position pos = {0.0, 0.0};
bool isGameOver = false;
bool immune = false;
float legStep = 15; //поворота ноги
float legAngle = 0;
float mapMinX = -10.0;
float mapMaxX = 10.0;
float mapMinY = -10.0;
float mapMaxY = 10.0;
void renderScene(void);
void geralt();
void cirila();
void yovert();
void drawMap();
void leg1g();
void leg2g();
void ghost();
void wildhunt();
void processKeys(unsigned char key, int x, int y);
void drawEnemies();
void drawGameOver();
void drawHealthBar();
void update(int value);
void generateRandomEnemies();
bool checkCollision(Position pos1, Position pos2, float radius1, float radius2);
void handleCollisions();
void drawUI();
void legTimer(int value);
void drawKnives();
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(800, 800);
glutCreateWindow("Game");
glutDisplayFunc(renderScene);
glutKeyboardFunc(processKeys);
glClearColor(0, 0, 0, 0);
//начальные значений игрока
figur.pos.x = 0.0f;
figur.pos.y = 0.0f;
pos.x = 0.0f;
pos.y = 0.0f;
figur.health=10;
//начальные значений мобов
for (int i = 0; i < MAX_ENEMIES; ++i) {
enemies[i].pos.x = 0.05;
enemies[i].pos.y = 0;
enemies[i].health = 3;
}
//генерация рандомных мобов
generateRandomEnemies();
glutTimerFunc(16, update, 0); // движение мобов
glutTimerFunc(1, legTimer, 0);
glutMainLoop();
return 0;
}
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (isGameOver) {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glPushMatrix();
drawGameOver();
glPopMatrix();
} else {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Перемещение камеры
glTranslatef(-figur.pos.x, -figur.pos.y, 0.0f);
drawMap();
//границы
if (figur.pos.x < mapMinX) {
figur.pos.x = mapMinX; // Ограничение движения по X влево
} else if (figur.pos.x > mapMaxX) {
figur.pos.x = mapMaxX; // Ограничение движения по X вправо
}
if (figur.pos.y < mapMinY) {
figur.pos.y = mapMinY; // Ограничение движения по Y вниз
} else if (figur.pos.y > mapMaxY) {
figur.pos.y = mapMaxY; // Ограничение движения по Y вверх
}
drawUI();
glPushMatrix();
glTranslatef(figur.pos.x, figur.pos.y, 0.0f);
if (figur.isRight) {
glRotatef(180, 0.0f, 1.0f, 0.0f);
} else {
glRotatef(0, 0.0f, 1.0f, 0.0f);
}
glScalef(0.3, 0.3, 0.3);
glPushMatrix();
geralt();
//ciri
//yovert
glPushMatrix();
glRotatef(legAngle, 0.0, 0.0, 1.0);
if (legAngle >= -45.0f) {
napr_nog1 = -1;
} else if (legAngle <= 45.0f) {
napr_nog1 = 1;
}
leg1g();
if (napr_nog1 == 1) {
glTranslatef(0.0, 0.0, 0.0);
glRotatef(legAngle, 0.0, 0.0, 1.0);
}
if (napr_nog1 == -1) {
glRotatef(-legAngle, 0.0, 0.0, 1.0); // Возвращение ноги в исходное положение
glTranslatef(0.0, 0.0, 0.0);
}
leg2g();
if (napr_nog1 == 1) {
glTranslatef(0.0, 0.0, 0.0);
glRotatef(-legAngle, 0.0, 0.0, 1.0);
}
if (napr_nog1 == -1) {
glRotatef(legAngle, 0.0, 0.0, 1.0); // Возвращение ноги в исходное положение
glTranslatef(0.0, 0.0, 0.0);
}
glPopMatrix();
drawEnemies();
glPushMatrix();
drawKnives();
glPopMatrix();
glPopMatrix();
glPopMatrix();
drawHealthBar();
}
glutSwapBuffers();
}
void processKeys(unsigned char key, int x, int y) {
switch (key) {
case 'w':
figur.pos.y += 0.1;
legAngle = 0;
legAngle += legStep;
break;
case 's':
figur.pos.y -= 0.1;
legAngle = 0;
legAngle += legStep;
break;
case 'a':
figur.pos.x -= 0.1;
figur.isRight = false;
napr_nog1 = 1;
legAngle += legStep;
break;
case 'd':
figur.pos.x += 0.1;
figur.isRight = true;
napr_nog1 = -1;
legAngle += legStep;
break;
for (int i = 0; i < MAX_KNIVES; ++i) {
if (!knives[i].isAlive) {
knives[i].pos = figur.pos;
knives[i].isAlive = true;
knives[i].isRight = figur.isRight;
break;
}
}
break;
default:
return;
glutPostRedisplay();
}
}
void legTimer(int value) {
glutPostRedisplay();
// Ограничение угла
if (legAngle > 45.0f) {
legAngle = -15;
}
// Переключение направления ноги
if (legAngle >= 45.0f || legAngle <= -15) {
legStep = -legStep;
}
glutTimerFunc(10, legTimer, 0);
}
void spawnRandomEnemy(void) {
int randomNum = rand() % 2; // генерация случайных видов мобов
if (randomNum == 0) {
wildhunt();
} else {
ghost();
}
}
void drawEnemies(void) {
srand(42);
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (enemies[i].health > 0) {
glPushMatrix();
glTranslatef(enemies[i].pos.x, enemies[i].pos.y, 0.0f);
glScalef(0.4, 0.4, 0.4);
if (enemies[i].isRight) {
glRotatef(180, 0.0f, 1.0f, 0.0f);
}
spawnRandomEnemy();
}
glPopMatrix();
}
}
bool checkCollision(Position pos1, Position pos2, float radius1, float radius2) {
float distance = sqrt(pow(pos1.x - pos2.x, 2) + pow(pos1.y - pos2.y, 2));
return distance <= radius1 + radius2;
}
void handleCollisions(void) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (checkCollision(figur.pos, enemies[i].pos, 0.1f, 0.1f)) {
float enemyDirectionX = figur.pos.x - enemies[i].pos.x;
float enemyDirectionY = figur.pos.y - enemies[i].pos.y;
figur.pos.x += enemyDirectionX * 0.05;
figur.pos.y += enemyDirectionY * 0.05;
figur.health -= 0.5f; // Уменьшение здоровья персонажа
if (figur.health <= 0.0f) {
isGameOver = true; // Игра окончена, если здоровье кончилось
}
}
for (int j = i + 1; j < MAX_ENEMIES; ++j) {
if (checkCollision(enemies[i].pos, enemies[j].pos, 0.09f, 0.09f)) {
float enemyDirectionX = enemies[i].pos.x - enemies[j].pos.x;
float enemyDirectionY = enemies[i].pos.y - enemies[j].pos.y;
enemies[i].pos.x += enemyDirectionX * 0.3f;
enemies[i].pos.y += enemyDirectionY * 0.3f;
enemyDirectionX = enemies[j].pos.x - enemies[i].pos.x;
enemyDirectionY = enemies[j].pos.y - enemies[i].pos.y;
enemies[j].pos.x += enemyDirectionX * 0.2f;
enemies[j].pos.y += enemyDirectionY * 0.2f;
}
}
}
}
void update(int value) {
for (int i = 0; i < MAX_ENEMIES; ++i) {
// Определение направлениия мобов к персонажу
float directionX = figur.pos.x - enemies[i].pos.x;
float directionY = figur.pos.y - enemies[i].pos.y;
float length = sqrt(directionX * directionX + directionY * directionY);
directionX /= length;
directionY /= length;
float speed = 0.02;
float offsetX = speed * directionX;
float offsetY = speed * directionY;
// позиция моба изменяется
enemies[i].pos.x += offsetX;
enemies[i].pos.y += offsetY;
if (directionX > 0) {
enemies[i].isRight = false;
} else {
enemies[i].isRight = true;
}
}
//статичная анимация для персонажа
static bool moveUp = true;
static float delta = 0.005f;
if (moveUp) {
figur.pos.y += delta;
} else {
figur.pos.y -= delta;
}
if (figur.pos.y >= 0.001f || figur.pos.y <= -0.001f) {
moveUp = !moveUp;
}
//статичная для мобов
static bool mobMoveUp[MAX_ENEMIES] = { true };
static float deltam = 0.01f;
for (int i = 0; i < MAX_ENEMIES; ++i) {
if (mobMoveUp[i]) {
enemies[i].pos.y += deltam;
} else {
enemies[i].pos.y -= deltam;
}
if (enemies[i].pos.y >= 0.03f || enemies[i].pos.y <= -0.03f) {
mobMoveUp[i] = !mobMoveUp[i];
}
}
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
knives[i].pos.x += 0.1; //обновления позиции ножа
// Проверка столкновений ножа с врагами
for (int j = 0; j < MAX_ENEMIES; ++j) {
if (enemies[j].health > 0 && checkCollision(knives[i].pos, enemies[j].pos, 0.05, 0.05) && !immune) {
enemies[j].health = 0; // Убийство врага
knives[i].isAlive = false;
immune = true; // Устанавливаем иммунитет для игрока (Долго же я не понимал почему просто так сливаюсь)
break;
}
}
}
}
int currentTime = glutGet(GLUT_ELAPSED_TIME);
if (currentTime - lastKnifeSpawnTime >= knifeSpawnDelay) {
// Создание нового ножа
for (int i = 0; i < MAX_KNIVES; ++i) {
if (!knives[i].isAlive) {
knives[i].pos = figur.pos;
knives[i].isAlive = true;
knives[i].isRight = figur.isRight;
break;
}
}
lastKnifeSpawnTime = currentTime; // Обновление времени последнего спавна ножа
}
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
Enemy* target = nullptr;
float minDistance = std::numeric_limits<float>::max();
// Поиск ближайшего врага
for (int j = 0; j < MAX_ENEMIES; ++j) {
if (enemies[j].health > 0) {
float distance = std::sqrt(std::pow(enemies[j].pos.x - knives[i].pos.x, 2) +
std::pow(enemies[j].pos.y - knives[i].pos.y, 2));
if (distance < minDistance) {
minDistance = distance;
target = &enemies[j];
}
}
}
// Обновление позиции ножа в направлении моба(цели)
if (target) {
float dx = target->pos.x - knives[i].pos.x;
float dy = target->pos.y - knives[i].pos.y;
float distance = std::sqrt(std::pow(dx, 2) + std::pow(dy, 2));
float speed = 0.1f;
if (distance > 0.01f) {
knives[i].pos.x += speed * dx / distance;
knives[i].pos.y += speed * dy / distance;
} else {
target->health = 0;
knives[i].isAlive = false;
}
}
}
}
static int immuneTime = 3000;
static int lastImmuneTime = 0;
if (currentTime - lastImmuneTime >= immuneTime) {
immune = false;
lastImmuneTime = currentTime;
}
// Планирование следующего обновления
glutTimerFunc(10, update, 0);
handleCollisions();
glutPostRedisplay();
}
void drawKnives() {
for (int i = 0; i < MAX_KNIVES; ++i) {
if (knives[i].isAlive) {
glPushMatrix();
glTranslatef(knives[i].pos.x, knives[i].pos.y, 0.0f);
knife();
glEnd();
glPopMatrix();
}
}
}
void drawGameOver(void) {
glPushMatrix();
glScalef(1, 1, 1);
glColor3f(1.0f, 0.0f, 0.0f);
glRasterPos2f(-0.15f, 0.1f);
const char* text = "Game Over!";
int len = strlen(text);
for (int i = 0; i < len; i++) {
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, text[i]);
}
glRasterPos2f(-0.15f, 0.1f);
glPopMatrix();
}
void drawHealthBar(void) {
glPushMatrix();
glTranslatef(figur.pos.x, figur.pos.y+0.15, 0.0f);
glScalef(0.2, 0.2, 0.2);
glBegin(GL_QUADS);
glColor3f(1.0f, 0.0f, 0.0f); //здоровье
glVertex2f(-0.3f, 0.2f);
glVertex2f(0.3f, 0.2f);
glVertex2f(0.3f, 0.25f);
glVertex2f(-0.3f, 0.25f);
glColor3f(0.0f, 1.0f, 0.0f);
//значения health
glVertex2f(-0.3f, 0.2f);
glVertex2f(figur.health * 0.2f - 0.3f, 0.2f);
glVertex2f(figur.health * 0.2f - 0.3f, 0.25f);
glVertex2f(-0.3f, 0.25f);
glEnd();
glPopMatrix();
}
void generateRandomEnemies(void) { //случайная генерация мобов
std::srand(std::time(nullptr));
for (int i = 0; i < MAX_ENEMIES; ++i) {
float posX, posY;
bool overlap;
do {
overlap = false;
posX = static_cast<float>(std::rand() % 20) - 10;
posY = static_cast<float>(std::rand() % 20) - 10;
for (int j = 0; j < i; ++j) {
if (checkCollision({posX, posY}, enemies[j].pos, 0.4f, 0.4f)) {
overlap = true;
break;
}
}
} while (overlap);
enemies[i].pos.x = posX;
enemies[i].pos.y = posY;
}
}
|
8ccbc6cfc78a004d2fbf859f5f42107f
|
{
"intermediate": 0.26571419835090637,
"beginner": 0.40978628396987915,
"expert": 0.32449954748153687
}
|
10,574
|
You gave me this plan for creating e-commerce website with microservices architecture using Spring Boot and React:
1. Set up the Back-End Application
1-A. Install Java Development Kit (JDK)
1-B. Set up Spring Boot Project using Spring Initializr
1-C. Create a Database
1-D. Configure Connection Settings, JPA, and Hibernate
1-E. Implement User Management with Spring Security and JWT
1-F. Implement Product Management with CRUD Operation and REST APIs
1-G. Implement Order and Shopping Cart Management
2. Set up the Front-End Application
2-A. Install Node.js and NPM
2-B. Create a React App using Create React App
2-C. Set up React Router for Navigation
2-D. Create a Registration and Login Page
2-E. Create a Home Page to Display Products
2-F. Create a Product Page to Display Detailed Information
2-G. Create a Shopping Cart Page to View, Add, and Remove Products
3. Test the Back-End and Front-End Service
3-A. Use Postman and Swagger-UI to Test RESTful APIs
3-B. Write Unit and Integration Tests for both Back-End and Front-End
3-C. Conduct User Acceptance Testing
4. Deploy and Release the application
4-A. Choose a hosting platform or cloud service to deploy the app
4-B. Configure the deployment settings and environment variables
4-C. Create user and administration manuals and API documentation
5. Maintenance and Continuous Improvement
5-A. Monitor the application and database performance to prevent issues
5-B. Fix any bugs and vulnerabilities that arise
5-C. Implement new features and keep the app up-to-date.
i am at 1-B. Please only focus on 1-B. Dont talk about others. While creating the project i will use maven. What do you suggest for Group, Artifact, Name,Description,Package name? And what dependencies i should add? please dont add pom.xml i will use initializr website just give me exact answers i ask what dependencies for my project dont give universal answers. and for the same you know the project is ecommerce give me suitable name artiact etc dont tell me how to do it give me example
|
b43cc73c81c00e6f65693bebe6eb8f92
|
{
"intermediate": 0.683717668056488,
"beginner": 0.21600638329982758,
"expert": 0.10027594864368439
}
|
10,575
|
need to make this zoom function to zoom evenly as it goes close to the center of that 3d matrix grid, because it getting slower and slower as you zooming close to the center. also, need to apply some z-index factor for these 3d matrix grid points, so they can get smaller in dependence of how far they are in z-index or "z-buffer". also, it will be nice to make some simple round gradient for these grid points too look more volumeric in general for 3d matrix grid structure. output full javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.max(100, zoom); // Set a minimum zoom limit
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", () => {
dragStart = null;
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
75681a501b3fe673387ab3d410801b7e
|
{
"intermediate": 0.28724804520606995,
"beginner": 0.46344155073165894,
"expert": 0.24931035935878754
}
|
10,576
|
need to make this zoom function to zoom evenly as it goes close to the center of that 3d matrix grid, because it getting slower and slower as you zooming close to the center. also, need to apply some z-index factor for these 3d matrix grid points, so they can get smaller in dependence of how far they are in z-index or "z-buffer". also, it will be nice to make some simple round gradient for these grid points too look more volumeric in general for 3d matrix grid structure. output full javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.max(100, zoom); // Set a minimum zoom limit
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", () => {
dragStart = null;
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
0a831e5119c110d2038c5c7db2c017ec
|
{
"intermediate": 0.28724804520606995,
"beginner": 0.46344155073165894,
"expert": 0.24931035935878754
}
|
10,577
|
need to make this zoom function to zoom evenly as it goes close to the center of that 3d matrix grid, because it getting slower and slower as you zooming close to the center. also, need to apply some z-index factor for these 3d matrix grid points, so they can get smaller in dependence of how far they are in z-index or "z-buffer". also, it will be nice to make some simple round gradient for these grid points too look more volumeric in general for 3d matrix grid structure. output full javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.max(100, zoom); // Set a minimum zoom limit
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", () => {
dragStart = null;
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
13558efb5357444cc849d25bd5afe442
|
{
"intermediate": 0.28724804520606995,
"beginner": 0.46344155073165894,
"expert": 0.24931035935878754
}
|
10,578
|
You gave me this plan for creating e-commerce website with microservices architecture using Spring Boot and React:
1. Set up the Back-End Application
1-A. Install Java Development Kit (JDK)
1-B. Set up Spring Boot Project using Spring Initializr
1-C. Create a Database
1-D. Configure Connection Settings, JPA, and Hibernate
1-E. Implement User Management with Spring Security and JWT
1-F. Implement Product Management with CRUD Operation and REST APIs
1-G. Implement Order and Shopping Cart Management
2. Set up the Front-End Application
2-A. Install Node.js and NPM
2-B. Create a React App using Create React App
2-C. Set up React Router for Navigation
2-D. Create a Registration and Login Page
2-E. Create a Home Page to Display Products
2-F. Create a Product Page to Display Detailed Information
2-G. Create a Shopping Cart Page to View, Add, and Remove Products
3. Test the Back-End and Front-End Service
3-A. Use Postman and Swagger-UI to Test RESTful APIs
3-B. Write Unit and Integration Tests for both Back-End and Front-End
3-C. Conduct User Acceptance Testing
4. Deploy and Release the application
4-A. Choose a hosting platform or cloud service to deploy the app
4-B. Configure the deployment settings and environment variables
4-C. Create user and administration manuals and API documentation
5. Maintenance and Continuous Improvement
5-A. Monitor the application and database performance to prevent issues
5-B. Fix any bugs and vulnerabilities that arise
5-C. Implement new features and keep the app up-to-date.
i am at 1-C. Please only focus on 1-C. Dont talk about others. So i want to use H2db for simplicity. Can i use it for microservices architectue?
|
1ff1529d65cfc2106e610b03a8f140f8
|
{
"intermediate": 0.4771256744861603,
"beginner": 0.3001919984817505,
"expert": 0.22268237173557281
}
|
10,579
|
need to make this zoom function to zoom evenly as it goes close to the center of that 3d matrix grid, because it getting slower and slower as you zooming close to the center. also, need to apply some z-index factor for these 3d matrix grid points, so they can get smaller in dependence of how far they are in z-index or "z-buffer". also, it will be nice to make some simple round gradient for these grid points too look more volumeric in general for 3d matrix grid structure. output full javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.max(100, zoom); // Set a minimum zoom limit
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", () => {
dragStart = null;
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
95aab68595caca97dbe1a4bce37ef401
|
{
"intermediate": 0.28724804520606995,
"beginner": 0.46344155073165894,
"expert": 0.24931035935878754
}
|
10,580
|
how to import a 3d model in c++ and opengl using assimp
|
a1f33c1d0a8188ce11aa4062bba3332a
|
{
"intermediate": 0.4880884885787964,
"beginner": 0.1782018542289734,
"expert": 0.33370962738990784
}
|
10,581
|
We need to extend event types API event
Add date column (type Date, nullable)
2. Add relation to location entity location.entity.ts using ManyToOne (event location is nullable). Add location to results of get requests in event types. based on the above jira issue what does this comment mean Please add locationId to post and put requests in events
|
70044f9fc342082eb349ad400c7f9359
|
{
"intermediate": 0.847417414188385,
"beginner": 0.07658758014440536,
"expert": 0.07599501311779022
}
|
10,582
|
We need to extend event types API event
Add date column (type Date, nullable)
2. Add relation to location entity location.entity.ts using ManyToOne (event location is nullable). Add location to results of get requests in event types. For the above issue i made the following solutions import { Column, Entity, ManyToOne } from 'typeorm';
import { AbstractIdEntity } from '../../../common/abstract.id.entity';
import { LocationEntity } from '../../location/entities/location.entity';
import { EventDto } from '../dto/event.dto';
@Entity({ name: 'event' })
export class EventEntity extends AbstractIdEntity<EventDto> {
@Column({ nullable: false })
name: string;
@Column({ nullable: false, type: 'int' })
color: number;
@Column({ nullable: true, type: 'date' })
date: Date;
@ManyToOne(() => LocationEntity, { nullable: true })
location: LocationEntity;
dtoClass = EventDto;
}
import { Column, Entity, OneToMany } from 'typeorm';
import { AbstractIdEntity } from '../../../common/abstract.id.entity';
import { EventEntity } from '../../event/entities/event.entity';
import { LocationDto } from '../dto/location.dto';
@Entity({ name: 'location' })
export class LocationEntity extends AbstractIdEntity<LocationDto> {
@Column({ nullable: true })
name: string;
@Column({ nullable: true, type: 'int' })
color: number;
@OneToMany(() => EventEntity, (event) => event.location, { nullable: true })
events: EventEntity[];
dtoClass = LocationDto;
}
async findAll(): Promise<EventEntity[]> {
return this.eventRepository.find({ relations: ['location'] });
}
async findById(id: number): Promise<EventDto> {
const event = await this.eventRepository.findOne({
where: {
id,
},
relations: ['location'],
});
if (!event) {
throw new NotFoundException();
}
return event.toDto();
} now based on this how can i address the comment Please add locationId to post and put requests in events
|
26cdf1d12720e0ef45a1a054d82f61e7
|
{
"intermediate": 0.703095018863678,
"beginner": 0.12235229462385178,
"expert": 0.17455272376537323
}
|
10,583
|
import requests
def get_method_id(transaction_hash, api_key):
url = f"https://api.bscscan.com/api?module=proxy&action=eth_getTransactionByHash&txhash={transaction_hash}&apikey={api_key}"
response = requests.get(url)
data = response.json()
if data["result"]:
input_data = data["result"]["input"]
method_id = input_data[:10]
return method_id
return None
if __name__ == "main":
api_key = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
transaction_hash = input("Enter the transaction hash: ")
method_id = get_method_id(transaction_hash, api_key)
if method_id:
print(f"The method ID used in the transaction is: {method_id}")
else:
print("Error: Could not find the transaction.")
The code above produces a null result. Fix it
|
1c6b68fa6d8f219587d3e81438f671e3
|
{
"intermediate": 0.4518420994281769,
"beginner": 0.35517027974128723,
"expert": 0.19298751652240753
}
|
10,584
|
I want to implement a sticky header in a streamlit app, so that the content stays on top of the page while scrolling vertically. Can you give me some example code for that?
|
15ffc60b290bf6d4c36042a48ee6aed5
|
{
"intermediate": 0.45533373951911926,
"beginner": 0.15167458355426788,
"expert": 0.3929916322231293
}
|
10,585
|
What is the most commonly used language to develop algorithm to detect and avoid frauds in commodity trading?
|
b373d1a73b2402828a84588b1effc18f
|
{
"intermediate": 0.06979208439588547,
"beginner": 0.11615543812513351,
"expert": 0.8140525221824646
}
|
10,586
|
How to fix bug: type "Int!" used in position expecting type "Float!"
|
13dd6e9e9ab27140ac14f91129c83e48
|
{
"intermediate": 0.44285184144973755,
"beginner": 0.19492916762828827,
"expert": 0.36221903562545776
}
|
10,587
|
I have an asp.net core mvc app .NET 6, write me a code to add custom tables to the auto-generated default db, I haven't run a debug yet so the db hasn't been created yet.
|
12a755a48d07ecb44a59410bc40af1d3
|
{
"intermediate": 0.8189908266067505,
"beginner": 0.09204556792974472,
"expert": 0.088963583111763
}
|
10,588
|
why dont work currentInteraction.Observations.IsSubsetOf(y.Observations)
|
c2a487820b8fee3d921d0b553778594c
|
{
"intermediate": 0.4028159976005554,
"beginner": 0.35339727997779846,
"expert": 0.2437867522239685
}
|
10,589
|
Write me a Minecraft java plugin code that will teleport you to the arena if you right click on oak sign with text "[sumo]" (need permission "sumo.place" first) but arena must be set using "/sumo set" command first or text "Must set arena first" will appear in the player's chat. After teleport the arena countdown 3 seconds will start and you with sumo pvp bot won't be able to move until it's finished. Than sumo pvp bot(CitizensAPI player character with AI) will spawn in location set using "/sumo bot" or if you right click on that oak sign a text will appear in player's chat saying "Must set position first". Sumo pvp bot's goal is to knock you out off the platform to the water(walk towards player while hitting him, looking at his direction). If you touch a water you will be teleported back to hub (which must be set with "/sumo hub" first or text "Set hub first" will appear in player's chat after right click on oak sign), and you'll see title "Defeated". If you knock out the sumo pvp bot to the water he will disappear and you will be teleported back to hub with title saying "Victory". In arena the player inventory will disappear and after the fight is finished, than in hub your inventory will appear back with items that you had. Implement all logics to the code.
|
3b9aba970e297afad99aa214eeac6ca3
|
{
"intermediate": 0.37324273586273193,
"beginner": 0.2967151403427124,
"expert": 0.33004218339920044
}
|
10,590
|
We need to extend event types API event
Add date column (type Date, nullable)
2. Add relation to location entity location.entity.ts using ManyToOne (event location is nullable). Add location to results of get requests in event types. For the above issue i made the following solutions import { Column, Entity, ManyToOne } from ‘typeorm’;
import { AbstractIdEntity } from ‘…/…/…/common/abstract.id.entity’;
import { LocationEntity } from ‘…/…/location/entities/location.entity’;
import { EventDto } from ‘…/dto/event.dto’;
@Entity({ name: ‘event’ })
export class EventEntity extends AbstractIdEntity<EventDto> {
@Column({ nullable: false })
name: string;
@Column({ nullable: false, type: ‘int’ })
color: number;
@Column({ nullable: true, type: ‘date’ })
date: Date;
@ManyToOne(() => LocationEntity, { nullable: true })
location: LocationEntity;
dtoClass = EventDto;
}
import { Column, Entity, OneToMany } from ‘typeorm’;
import { AbstractIdEntity } from ‘…/…/…/common/abstract.id.entity’;
import { EventEntity } from ‘…/…/event/entities/event.entity’;
import { LocationDto } from ‘…/dto/location.dto’;
@Entity({ name: ‘location’ })
export class LocationEntity extends AbstractIdEntity<LocationDto> {
@Column({ nullable: true })
name: string;
@Column({ nullable: true, type: ‘int’ })
color: number;
@OneToMany(() => EventEntity, (event) => event.location, { nullable: true })
events: EventEntity[];
dtoClass = LocationDto;
}
async findAll(): Promise<EventEntity[]> {
return this.eventRepository.find({ relations: [‘location’] });
}
async findById(id: number): Promise<EventDto> {
const event = await this.eventRepository.findOne({
where: {
id,
},
relations: [‘location’],
});
if (!event) {
throw new NotFoundException();
}
return event.toDto();
} now based on the above jira issue is my solution correct
|
31dd2bf9150b9c89d741fc173200c8e1
|
{
"intermediate": 0.643212080001831,
"beginner": 0.24066513776779175,
"expert": 0.11612281203269958
}
|
10,591
|
import { initializeApp, credential as _credential, auth } from 'firebase-admin';
import serviceAccount from './white-rose-e2a26-firebase-adminsdk-1dvqv-08b1439ddb.json';
initializeApp({
credential: _credential.cert(serviceAccount),
databaseURL: 'https://white-rose-e2a26-default-rtdb.firebaseio.com/'
});
const uid = 'qwMGcoF1V9WTDgpcWzaf3Rp9t9o1';
auth().setCustomUserClaims(uid, {admin:true})
.then(()=>{
console.log('Успешно');
process.exit(0);
})
.catch(error=>{
console.error(error);
process.exit(1);
})
i need to create an admin, i downloaded a private key file and added to my project, what do i need to do else? iyts react native expo
|
074ac3ee0cae2ec74108c883e00bee94
|
{
"intermediate": 0.502052903175354,
"beginner": 0.2923518717288971,
"expert": 0.2055952250957489
}
|
10,592
|
In code code add a line for predicting the closing price for tomorrow:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score, f1_score
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period):
data[‘H-L’] = data[‘High’] - data[‘Low’]
data[‘H-PC’] = abs(data[‘High’] - data[‘Close’].shift(1))
data[‘L-PC’] = abs(data[‘Low’] - data[‘Close’].shift(1))
data[‘TR’] = data[[‘H-L’, ‘H-PC’, ‘L-PC’]].max(axis=1)
data[‘ATR’] = data[‘TR’].rolling(window=period).mean()
return data
def calculate_super_trend(data, period, multiplier):
data = calculate_atr(data, period)
data[‘Upper Basic’] = (data[‘High’] + data[‘Low’]) / 2 + multiplier * data[‘ATR’]
data[‘Lower Basic’] = (data[‘High’] + data[‘Low’]) / 2 - multiplier * data[‘ATR’]
data[‘Upper Band’] = data.apply(
lambda x: x[‘Upper Basic’] if x[‘Close’] > x[‘Upper Basic’] else x[‘Lower Basic’], axis=1)
data[‘Lower Band’] = data.apply(
lambda x: x[‘Lower Basic’] if x[‘Close’] < x[‘Lower Basic’] else x[‘Upper Basic’], axis=1)
data[‘Super Trend’] = np.nan
for i in range(period, len(data)):
if data[‘Close’][i] <= data[‘Upper Band’][i - 1]:
data[‘Super Trend’].iat[i] = data[‘Upper Band’][i]
elif data[‘Close’][i] > data[‘Upper Band’][i]:
data[‘Super Trend’].iat[i] = data[‘Lower Band’][i]
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3):
stock_data = yf.download(ticker, start=start_date, end=end_date)
stock_data.columns = stock_data.columns.astype(str)
print(stock_data.columns)
stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[[‘Open’, ‘High’, ‘Low’, ‘Close’, ‘Super Trend’]].values
scaler = MinMaxScaler(feature_range=(0, 1))
data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], []
for i in range(window_size, len(data_normalized)):
X.append(data_normalized[i - window_size:i])
y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X))
X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len])
X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(LSTM(units=50, return_sequences=True))
model.add(LSTM(units=50))
model.add(Dense(units=1, activation=‘linear’)) # Change activation function to ‘linear’
model.compile(optimizer=‘adam’, loss=‘mean_squared_error’, metrics=[‘accuracy’]) # Change loss to ‘mean_squared_error’
return model
def train_model(model, X_train, y_train, batch_size, epochs):
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1)
return model, history
def evaluate_model(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
mae = np.mean(np.abs(y_pred_inverse - y_test_inverse))
mse = np.mean(np.square(y_pred_inverse - y_test_inverse))
return mae, mse
def plot_prediction(model, X_test, y_test, scaler):
y_pred = model.predict(X_test)
y_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_pred.shape), y_pred)))[:, 1] # Inverse transform for Close prices
y_test_inverse = scaler.inverse_transform(np.column_stack((np.zeros(y_test.shape), y_test)))[:, 1]
plt.figure(figsize=(14, 6))
plt.plot(y_test_inverse, label=‘Actual’)
plt.plot(y_pred_inverse, label=‘Predicted’)
plt.xlabel(‘Days’)
plt.ylabel(‘Close Price’)
plt.title(‘NIFTY Stock Price Prediction (Actual vs Predicted)’)
plt.legend()
plt.show()
# Define the parameters
ticker = ‘^NSEI’ # Ticker symbol for Nifty
start_date = ‘2010-01-01’
end_date = ‘2023-06-01’
window_size = 30 # Number of previous days’ data to consider
period = 14 # ATR period
multiplier = 3 # ATR multiplier
batch_size = 32
epochs = 100
# Load and preprocess the data
X_train, y_train, X_test, y_test = load_preprocess_data(ticker, start_date, end_date, window_size, period, multiplier)
# Create the LSTM model
input_shape = (X_train.shape[1], X_train.shape[2])
model = create_lstm_model(input_shape)
# Train the model
model, history = train_model(model, X_train, y_train, batch_size, epochs)
# Evaluate the model
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit_transform(y_train.reshape(-1, 1)) # Fit scaler on training labels
mae, mse = evaluate_model(model, X_test, y_test, scaler)
print(f"Mean Absolute Error: {mae}“)
print(f"Mean Squared Error: {mse}”)
# Plot the predictions
plot_prediction(model, X_test, y_test, scaler)
|
aff3fff09fe6fea068e926a8d55bb6ec
|
{
"intermediate": 0.348016619682312,
"beginner": 0.4418283998966217,
"expert": 0.21015502512454987
}
|
10,593
|
based on this import { Column, Entity, OneToMany } from 'typeorm';
import { AbstractIdEntity } from '../../../common/abstract.id.entity';
import { EventEntity } from '../../event/entities/event.entity';
import { LocationDto } from '../dto/location.dto';
@Entity({ name: 'location' })
export class LocationEntity extends AbstractIdEntity<LocationDto> {
@Column({ nullable: true })
name: string;
@Column({ nullable: true, type: 'int' })
color: number;
@OneToMany(() => EventEntity, (event) => event.location, { nullable: true })
events: EventEntity[];
dtoClass = LocationDto;
}
location entity why is this code if (createEventDto.locationId) {
const location = await this.locationRepository.findOne(
createEventDto.locationId,
);
event.location = location;
} throwing Type 'number' has no properties in common with type 'FindOneOptions<LocationEntity>'.ts(2559)
(property) EventCreateDto.locationId: number
|
31cc3e3422a4dba1d8a33c4196c1dd14
|
{
"intermediate": 0.534460723400116,
"beginner": 0.29958975315093994,
"expert": 0.16594959795475006
}
|
10,594
|
import requests
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
def get_newly_created_contracts(start_block, end_block):
url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}'
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error in API request: {e}')
return []
data = response.json()
if data['status'] == '0':
print(f"Error: {data['result']}")
return []
return [tx for tx in data['result'] if tx['isError'] == '0' and tx['contractAddress'] != '']
def display_new_contracts(start_block, end_block):
contracts = get_newly_created_contracts(start_block, end_block)
if not contracts:
print('No new contracts found.')
else:
print(f'Newly created smart contracts between blocks {start_block} and {end_block}: ')
for contract in contracts:
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
start_block = 28269140 # Replace with your desired start block
end_block = 28269140 # Replace with your desired end block
display_new_contracts(start_block, end_block)
Change the code above so that only those addresses are returned whose From column value is 0x863b49ae97c3d2a87fd43186dfd921f42783c853
|
f2e1f213d9767606f4bc4106cc8e841b
|
{
"intermediate": 0.4724026918411255,
"beginner": 0.2950454354286194,
"expert": 0.23255188763141632
}
|
10,595
|
How can I achieve this If Target.Range = ("B2") Then
Range("A3").Calculate
End If
|
c6a56d87daf1e0885f19db142823e210
|
{
"intermediate": 0.3447994589805603,
"beginner": 0.3361915349960327,
"expert": 0.31900903582572937
}
|
10,596
|
@Entity({ name: 'event' })
export class EventEntity extends AbstractIdEntity<EventDto> {
@Column({ nullable: false })
name: string;
@Column({ nullable: false, type: 'int' })
color: number;
@Column({ nullable: true, type: 'date' })
date: Date;
@ManyToOne(() => LocationEntity, { nullable: true })
location: LocationEntity;
dtoClass = EventDto;
} @Entity({ name: 'location' })
export class LocationEntity extends AbstractIdEntity<LocationDto> {
@Column({ nullable: true })
name: string;
@Column({ nullable: true, type: 'int' })
color: number;
@OneToMany(() => EventEntity, (event) => event.location, { nullable: true })
events: EventEntity[];
dtoClass = LocationDto;
}
based on these two entitites , are they correct and will they not create a circular dependency?
|
962bf0a503a030f7e0ddee5dc546308f
|
{
"intermediate": 0.4173811972141266,
"beginner": 0.38784119486808777,
"expert": 0.19477754831314087
}
|
10,597
|
i have written auth firebase, i can register user successfuly, bit cant log in there is err
[FirebaseError: Firebase: A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred. (auth/network-request-failed).]
i cant solve it
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState} from 'react';
export default function Auth() {
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = React.useState(null);
const handleLogin=()=>{
if (!email || !password) {
Alert.alert('Ошибка!','Неверная почта или пароль');
return;
}
firebase.auth().signInWithEmailAndPassword(email, password)
.then(()=>{
const user = firebase.auth().currentUser;
user.getIdToken()
.then((token) => {
// do something with the token
})
.catch((error) => {
console.log(error);
});
navigation.navigate('Profile');
})
.catch((error) => {
setErrorMessage(error.message);
console.log(error);
});
};
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Войти в личный{"\n"}кабинет</Text>
<View style={gStyle.AuthContainer}>
<View style={gStyle.AuthBox}>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Почта</Text>
<TextInput style={gStyle.AuthInfo}
onChangeText={setEmail}
/>
</View>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Пароль</Text>
<TextInput style={gStyle.AuthInfo}
onChange={setPassword}
secureTextEntry={true}
/>
</View>
</View>
<Pressable style={gStyle.AuthForgotPassword} onPress={''}>
<Text style={gStyle.AuthPass}>Забыли пароль?</Text>
</Pressable>
<TouchableOpacity style={gStyle.AuthLogin} onPress={handleLogin}>
<Text style={gStyle.AuthBtnLogin}>Войти</Text>
</TouchableOpacity>
<Pressable
onPress={()=>navigation.navigate('Registration')}
>
<Text style={gStyle.AuthRegistr}>Я не зарегистрирован(а)</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
8157fe005bec2708e0dff658b9f965df
|
{
"intermediate": 0.4363670349121094,
"beginner": 0.34089282155036926,
"expert": 0.22274017333984375
}
|
10,598
|
I have an asp.net core mvc .NET 6 project, write me a code to add custom tables to the auto-generated db.
|
c9b1277b3870b2a2700cb1d86e3396ba
|
{
"intermediate": 0.6928383111953735,
"beginner": 0.1458957940340042,
"expert": 0.16126587986946106
}
|
10,599
|
LOG [FirebaseError: Firebase: A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred. (auth/network-request-failed).]
LOG No user is signed in
i have this err but my connection ok and nothing wrong with firewall and devices, user can register himself, i see data there but user cannot log in. i think there is problelm with code
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState} from 'react';
export default function Auth() {
const navigation = useNavigation();
const [email, setEmail] = useState('');
const [phone, setPhone] = useState('');
const [password, setPassword] = useState('');
const [errorMessage, setErrorMessage] = React.useState(null);
const handleLogin=()=>{
if (!email || !password) {
Alert.alert('Ошибка!','Неверная почта или пароль');
return;
}
firebase.auth().signInWithEmailAndPassword(email, password)
.then(()=>{
const user = firebase.auth().currentUser;
user.getIdToken()
.then((token) => {
// do something with the token
})
.catch((error) => {
console.log(error);
});
navigation.navigate('Profile');
})
.catch((error) => {
setErrorMessage(error.message);
console.log(error);
});
};
firebase.auth().onAuthStateChanged(user => {
if(user) {
console.log(user `${user.uid} is signed in`);
} else {
console.log('No user is signed in');
}
});
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Войти в личный{"\n"}кабинет</Text>
<View style={gStyle.AuthContainer}>
<View style={gStyle.AuthBox}>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Почта</Text>
<TextInput style={gStyle.AuthInfo}
onChangeText={setEmail}
/>
</View>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Пароль</Text>
<TextInput style={gStyle.AuthInfo}
onChange={setPassword}
secureTextEntry={true}
/>
</View>
</View>
<Pressable style={gStyle.AuthForgotPassword} onPress={''}>
<Text style={gStyle.AuthPass}>Забыли пароль?</Text>
</Pressable>
<TouchableOpacity style={gStyle.AuthLogin} onPress={handleLogin}>
<Text style={gStyle.AuthBtnLogin}>Войти</Text>
</TouchableOpacity>
<Pressable
onPress={()=>navigation.navigate('Registration')}
>
<Text style={gStyle.AuthRegistr}>Я не зарегистрирован(а)</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
i need that when user click on Войти he log in, it checks email and password
|
a898c4ec69227e13ad56682161b8be7f
|
{
"intermediate": 0.4386232793331146,
"beginner": 0.35896262526512146,
"expert": 0.20241409540176392
}
|
10,600
|
const canvas
|
33fe59cb086f720298aacd5a5d11812a
|
{
"intermediate": 0.26267296075820923,
"beginner": 0.3876068890094757,
"expert": 0.3497201204299927
}
|
10,601
|
need to make this zoom function to zoom evenly as it goes close to the center of that 3d matrix grid, because it getting slower and slower as you zooming close to the center. also, need to apply some z-index factor for these 3d matrix grid points, so they can get smaller in dependence of how far they are in z-index or "z-buffer". also, it will be nice to make some simple round gradient for these grid points too look more volumeric in general for 3d matrix grid structure. output full javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = y * cosX - z * sinX;
const newZ = y * sinX + z * cosX;
const newX = x * cosY - newZ * sinY;
const newZ2 = x * sinY + newZ * cosY;
return { x: newX, y: newY, z: newZ2 };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (400 + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.max(100, zoom); // Set a minimum zoom limit
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", () => {
dragStart = null;
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = "rgba(55,155,255,0.8)";
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.8)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
80ccbd8fc3bafaafa202725da180ff62
|
{
"intermediate": 0.28724804520606995,
"beginner": 0.46344155073165894,
"expert": 0.24931035935878754
}
|
10,602
|
IsDate of class validator date format it accepts
|
7ccd85b47c145c33b177501f6856d639
|
{
"intermediate": 0.2681134045124054,
"beginner": 0.4174232482910156,
"expert": 0.314463347196579
}
|
10,603
|
Hi Chatty
|
b4931ef9d1a45aa82168b7796d3707f7
|
{
"intermediate": 0.3475969433784485,
"beginner": 0.2856350541114807,
"expert": 0.3667680323123932
}
|
10,604
|
This code does not react:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim was As Worksheet
Set was = ActiveSheet
If Target = "$B$2" Then
was.Range("A3").Calculate
was.Range("B3").Calculate
End If
|
d0a9c0d92f8a3ce1c76c58108999d6f8
|
{
"intermediate": 0.4684954583644867,
"beginner": 0.319606751203537,
"expert": 0.2118978202342987
}
|
10,605
|
-Добавь список друзей где просто будет список друзей их name для выбора кому написать.
-Исправь ошибку в коде error C3861: find_user_by_name: идентификатор не найден
--Добавь в код протокол peer-to-peer
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <stdexcept>
#include <set>
using namespace std;
// структура для хранения информации о пользователях
struct User {
int id;
string name;
string masked_ip;
int port;
};
// генерация случайного id пользователя
int generate_id(set<int>& used_ids) {
int id;
do {
id = rand() % 1000000000;
} while (used_ids.find(id) != used_ids.end());
used_ids.insert(id);
return id;
}
// генерация маскированного ip-адреса пользователя
string generate_masked_ip(set<string>& used_ips) {
int number;
stringstream ss;
for (int i = 0; i < 9; i++) {
number = rand() % 10;
ss << number;
}
string masked_ip = ss.str();
while (used_ips.find(masked_ip) != used_ips.end()) {
masked_ip = generate_masked_ip(used_ips);
}
used_ips.insert(masked_ip);
return masked_ip;
}
// функция для сохранения информации о пользователе в файл
void save_user_info(const vector<User>& users) {
ofstream file("C: / users.txt");
if (!file.is_open()) {
throw runtime_error("Cannot open file for writing");
}
for (const User& user : users) {
file << user.id << ", " << user.name << ", " << user.masked_ip << ", " << user.port << endl;
}
file.close();
}
// функция для загрузки информации о пользователях из файла
void load_user_info(vector<User>& users, set<int>& used_ids, set<string>& used_ips) {
ifstream file("C: / users.txt");
if (!file.is_open()) {
ofstream new_file("C: / users.txt");
new_file.close();
}
else {
string line;
while (getline(file, line)) {
User user;
int pos;
pos = line.find(", ");
user.id = stoi(line.substr(0, pos));
if (used_ids.find(user.id) != used_ids.end()) {
throw runtime_error("Duplicated user id : " + to_string(user.id));
}
used_ids.insert(user.id);
line.erase(0, pos + 1);
pos = line.find(", ");
user.name = line.substr(1, pos - 2);
line.erase(0, pos + 1);
pos = line.find(", ");
user.masked_ip = line.substr(1, pos - 2);
if (used_ips.find(user.masked_ip) != used_ips.end()) {
throw runtime_error("Duplicated user ip: " + user.masked_ip);
}
used_ips.insert(user.masked_ip);
line.erase(0, pos + 1);
user.port = stoi(line);
users.push_back(user);
}
file.close();
}
}
// функция для поиска пользователя по id
User find_user_by_id(const vector<User>& users, int id) {
for (const User& user : users) {
if (user.id == id) {
return user;
}
}
User user;
user.id = -1;
return user;
}
// функция для поиска пользователя по маскированному ip
User find_user_by_masked_ip(const vector<User>& users, const string& masked_ip) {
for (const User& user : users) {
if (user.masked_ip == masked_ip) {
return user;
}
}
User user;
user.id = -1;
return user;
}
// функция для проверки корректности порта
bool is_port_correct(int port) {
if (port < 1024 || port > 65535) {
return false;
}
return true;
}
// функция для отправки сообщения от пользователя sender пользователю recipient
void send_message(const vector<User>& users, int sender_id, const string& recipient_ip, const string& message) {
User sender = find_user_by_id(users, sender_id);
if (sender.id == -1) {
throw runtime_error("User with this id was not found");
}
User recipient = find_user_by_masked_ip(users, recipient_ip);
if (recipient.id == -1) {
throw runtime_error("User with this ip was not found");
}
cout << "Message from " << sender.name << " to " << recipient.name << ": " << message << endl;
}
// функция для добавления нового пользователя
void add_new_user(vector<User>& users, set<int>& used_ids, set<string>& used_ips, int my_id) {
User user;
user.id = generate_id(used_ids);
cout << "ID user: " << user.id << endl;
cout << "Enter username: ";
cin >> user.name;
user.masked_ip = generate_masked_ip(used_ips);
while (true) {
cout << "Enter user port: ";
cin >> user.port;
if (is_port_correct(user.port)) {
break;
}
else {
cout << "Incorrect port.Please try again." << endl;
}
}
if (user.id == my_id) {
cout << "Do you want to add this user ? " << endl;
cout << "1.Yes" << endl;
cout << "2.No" << endl;
int choice;
cin >> choice;
if (choice == 1) {
users.push_back(user);
save_user_info(users);
cout << "User added successfully" << endl;
}
else {
cout << "User not added." << endl;
}
}
else {
users.push_back(user);
save_user_info(users);
cout << "User added successfully" << endl;
}
}
// главный метод программы
int main() {
vector<User> users;
set<int> used_ids;
set<string> used_ips;
int my_id = generate_id(used_ids);
cout << "Your id: " << my_id << endl;
load_user_info(users, used_ids, used_ips);
int choice;
cout << "1.Find user by id" << endl;
cout << "2.Add new user" << endl;
cout << "3.Send message" << endl;
cout << "Your choice: ";
cin >> choice;
try {
if (choice == 1) {
int id;
cout << "Enter user id: ";
cin >> id;
User found_user = find_user_by_id(users, id);
if (found_user.id == -1) {
cout << "User with this id was not found" << endl;
}
else {
cout << "User found: " << endl;
cout << "ID: " << found_user.id << endl;
cout << "Name: " << found_user.name << endl;
cout << "IP: " << found_user.masked_ip << endl;
cout << "Port: " << found_user.port << endl;
}
}
else if (choice == 2) {
add_new_user(users, used_ids, used_ips, my_id);
}
else if (choice == 3) {
string message, recipient_name;
cout << "Enter message: ";
cin.ignore();
getline(cin, message);
cout << "Enter recipient name: ";
cin >> recipient_name;
vector<string> friends;
for (const User& user : users) {
if (user.id != my_id) {
friends.push_back(user.name);
}
}
if (friends.empty()) {
cout << "You don’t have friends to send message to." << endl;
}
else {
cout << "Select a friend to send message to: " << endl;
for (size_t i = 0; i < friends.size(); i++) {
cout << i + 1 << ". " << friends[i] << endl;
}
int friend_choice;
cin >> friend_choice;
if (friend_choice > 0 && friend_choice <= friends.size()) {
User recipient = find_user_by_name(users, friends[friend_choice - 1]);
send_message(users, my_id, recipient.masked_ip, message);
}
else {
throw invalid_argument("Invalid friend choice: " + to_string(friend_choice));
}
}
}
else {
throw invalid_argument("Invalid choice: " + to_string(choice));
}
}
catch (const exception& e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
return 0;
}
|
d6c2525395da9b71a1c4e2de30d9691f
|
{
"intermediate": 0.2972296178340912,
"beginner": 0.5687640905380249,
"expert": 0.13400627672672272
}
|
10,606
|
Hey I want a programme in c# and have a form with 5 text input and can print it in a reprt
|
0012f21cd62c93ada856d6b7bf319f6b
|
{
"intermediate": 0.5850552916526794,
"beginner": 0.2560657262802124,
"expert": 0.15887898206710815
}
|
10,607
|
Make an unbeatable tic-tac-toe AI in p5.js
|
3afd2b9e79e225bca7d6517c8d24247a
|
{
"intermediate": 0.11393610388040543,
"beginner": 0.08637340366840363,
"expert": 0.7996905446052551
}
|
10,608
|
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import React, {useState} from 'react';
export default function Auth() {
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Войти в личный{"\n"}кабинет</Text>
<View style={gStyle.AuthContainer}>
<View style={gStyle.AuthBox}>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Почта</Text>
<TextInput style={gStyle.AuthInfo}
onChangeText={setEmail}
/>
</View>
<View style={gStyle.AuthBox1}>
<Text style={gStyle.AuthName}>Пароль</Text>
<TextInput style={gStyle.AuthInfo}
onChange={setPassword}
secureTextEntry={true}
/>
</View>
</View>
<Pressable style={gStyle.AuthForgotPassword} onPress={''}>
<Text style={gStyle.AuthPass}>Забыли пароль?</Text>
</Pressable>
<TouchableOpacity style={gStyle.AuthLogin} onPress={handleLogin}>
<Text style={gStyle.AuthBtnLogin}>Войти</Text>
</TouchableOpacity>
<Pressable
onPress={()=>navigation.navigate('Registration')}
>
<Text style={gStyle.AuthRegistr}>Я не зарегистрирован(а)</Text>
</Pressable>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
write me log in function from firebase
|
8dbb4b6b2b652d634130c8003eed6bd8
|
{
"intermediate": 0.3754355013370514,
"beginner": 0.530211865901947,
"expert": 0.09435264021158218
}
|
10,609
|
import { Router } from "express";
import Stripe from "stripe";
const stripeRouter = Router();
const stripe = new Stripe(process.env.STRIPE_KEY || "", {
apiVersion: "2022-11-15",
});
stripeRouter.post("/payment", (req, res) => {
stripe.charges.create(
{
source: req.body.tokenId,
amount: req.body.amount,
currency: "pln",
},
(stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).json(stripeErr);
}else{
res.status(200).json(stripeRes)
}
}
);
});
Type '(stripeErr: any, stripeRes: any) => void' has no properties in common with type 'RequestOptions'.
|
9ec81bb943dc686577dbfa978136ade1
|
{
"intermediate": 0.41811102628707886,
"beginner": 0.3611592650413513,
"expert": 0.22072969377040863
}
|
10,610
|
make this grid array of 3d matrix to center in canvas and zoom.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 5;
const minZoom = 100;
const maxZoom = 10000;
const centerFocus = 180;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const offsetX = ((centerFocus - minZoom) / (centerFocus - minZoom)) * gridSize / 2;
const offsetZ = ((maxZoom - centerFocus) / (maxZoom - minZoom)) * gridSize / 2;
const xPos = x - offsetX;
const yPos = y - offsetX;
const zPos = z - offsetZ;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = yPos * cosX - zPos * sinX;
const newZ = yPos * sinX + zPos * cosX;
const newX = xPos * cosY - newZ * sinY;
const newZ2 = xPos * sinY + newZ * cosY;
return { x: newX + offsetX, y: newY + offsetX, z: newZ2 + offsetZ };
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (centerFocus + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
const gridCenter = calculateGridCenter(grid);
function project(point, width, height, center) {
const { x, y, z } = point;
const offsetX = (x - gridCenter.x) * zoom / 1000;
const offsetY = (y - gridCenter.y) * zoom / 1000;
const offsetZ = (z - gridCenter.z) * zoom / 1000;
const scale = zoom / (zoom / 2 + offsetZ);
const newX = offsetX * scale + width / 2;
const newY = offsetY * scale + height / 2;
return { x: newX, y: newY, scale };
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
7b5195ae0a35a9a668a5fb85c5b7db51
|
{
"intermediate": 0.3083536922931671,
"beginner": 0.40791377425193787,
"expert": 0.28373247385025024
}
|
10,611
|
fix that center centering at grid array center, so it can zoom normally right at the center of 3d matrix cube point structure.:const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 5;
const minZoom = 100;
const maxZoom = 10000;
const centerFocus = 180;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const offsetX = ((centerFocus - minZoom) / (centerFocus - minZoom)) * gridSize / 2;
const offsetZ = ((maxZoom - centerFocus) / (maxZoom - minZoom)) * gridSize / 2;
const xPos = x - offsetX;
const yPos = y - offsetX;
const zPos = z - offsetZ;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = yPos * cosX - zPos * sinX;
const newZ = yPos * sinX + zPos * cosX;
const newX = xPos * cosY - newZ * sinY;
const newZ2 = xPos * sinY + newZ * cosY;
return { x: newX + offsetX, y: newY + offsetX, z: newZ2 + offsetZ };
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
const gridCenter = calculateGridCenter(grid);
function project(point, width, height, center) {
const { x, y, z } = point;
const offsetX = (x - gridCenter.x) * zoom / 10000;
const offsetY = (y - gridCenter.y) * zoom / 10000;
const offsetZ = (z - gridCenter.z) * zoom / 10000;
const scale = zoom / (zoom / 2 + offsetZ);
const newX = offsetX * scale + width / 2;
const newY = offsetY * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
6a1c2d4411aa846909e1fe587150347b
|
{
"intermediate": 0.3165271580219269,
"beginner": 0.4934728741645813,
"expert": 0.18999995291233063
}
|
10,612
|
fix that center centering at grid array center, so it can zoom normally right at the center of 3d matrix cube point structure.:const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.001;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 5;
const minZoom = 100;
const maxZoom = 10000;
const centerFocus = 180;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 800;
let dragStart = null;
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
const offsetX = ((centerFocus - minZoom) / (centerFocus - minZoom)) * gridSize / 2;
const offsetZ = ((maxZoom - centerFocus) / (maxZoom - minZoom)) * gridSize / 2;
const xPos = x - offsetX;
const yPos = y - offsetX;
const zPos = z - offsetZ;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = yPos * cosX - zPos * sinX;
const newZ = yPos * sinX + zPos * cosX;
const newX = xPos * cosY - newZ * sinY;
const newZ2 = xPos * sinY + newZ * cosY;
return { x: newX + offsetX, y: newY + offsetX, z: newZ2 + offsetZ };
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
const gridCenter = calculateGridCenter(grid);
function project(point, width, height, center) {
const { x, y, z } = point;
const offsetX = (x - gridCenter.x) * zoom / 10000;
const offsetY = (y - gridCenter.y) * zoom / 10000;
const offsetZ = (z - gridCenter.z) * zoom / 10000;
const scale = zoom / (zoom / 2 + offsetZ);
const newX = offsetX * scale + width / 2;
const newY = offsetY * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
79497dd1cceeebeab86da388a0ebe628
|
{
"intermediate": 0.3165271580219269,
"beginner": 0.4934728741645813,
"expert": 0.18999995291233063
}
|
10,613
|
import { Text, View, Image, Pressable } from ‘react-native’;
import { gStyle } from ‘…/styles/style’;
import React from ‘react’;
import { useNavigation } from ‘@react-navigation/native’;
export default function FutureMK() {
const navigation = useNavigation();
return (
<View style={gStyle.main}>
<View style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>12:30 12/12/2012</Text>
<View style={gStyle.FutureMKimg}>
<Image source={require(‘…/assets/example1.jpg’)} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>Мастер-класс №1</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>350 P.</Text></Text>
<Text style={gStyle.FutureMKdescription}>
Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Aenean commodo ligula eget dolor.
Aenean massa. Cum sociis natoque penatibus et magnis dis parturient
montes, nascetur ridiculus mus. Donec quam felis, ultricies nec,
pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.
Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.
In enim justo, rhoncus ut.
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate(‘SignUpForMK’)}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
</View>
);
}
and how can i do if user wants to look at particular post they click on button and it redirects them on a screen with details about post? collection is FutureMK (name, date, description, price and image) from firebase
|
8a4b826b42e87d8ab5e45be0bf83ec07
|
{
"intermediate": 0.49578505754470825,
"beginner": 0.26940762996673584,
"expert": 0.23480722308158875
}
|
10,614
|
can you give c++ code that genereate bitcoin address from hexadecimal private key
|
1547b79348bee3bb536e5449178d9402
|
{
"intermediate": 0.3852950632572174,
"beginner": 0.15377682447433472,
"expert": 0.4609281122684479
}
|
10,615
|
write three persona in separate tables
|
3423d279ad2b4009b8a0091a0fae7d96
|
{
"intermediate": 0.3353113830089569,
"beginner": 0.27326932549476624,
"expert": 0.39141932129859924
}
|
10,616
|
i want to make that when user looks at one post and clicked on Подробнее he is redirected to look at more info. Here is my files
import { Text, View, Image, Pressable } from 'react-native';
import { gStyle } from '../styles/style';
import React, {useState, useEffect} from 'react';
import { useNavigation } from '@react-navigation/native';
import {firebase} from '../Firebase/firebase'
export default function FutureMK() {
const navigation = useNavigation();
const [posts, setPosts]=useState([]);
useEffect(()=>{
const db=firebase.firestore();
const unsubscribe = db.collection('FutureMK').onSnapshot(snapshot=>{
const newPosts=snapshot.docs.map(doc=>({
id:doc.id,
...doc.data()
}));
setPosts(newPosts);
});
return unsubscribe;
},[])
return (
<View style={gStyle.main}>
<View style={gStyle.mainFMK}>
<Text style={gStyle.dateFutureMK}>date</Text>
<View style={gStyle.FutureMKimg}>
<Image source={require('../assets/example1.jpg')} style={gStyle.FutureMKbannerImg}/>
<Text style={gStyle.FutureMKnameOfMK}>name</Text>
<Text style={gStyle.hr}></Text>
</View>
<Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>price</Text></Text>
<Text style={gStyle.FutureMKdescription}>
description
</Text>
<Pressable style={gStyle.FutureMKmoreDetails}
onPress={()=>{navigation.navigate('SignUpForMK',{post:post});}}
>
<Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text>
</Pressable>
<Text style={gStyle.FutureMKline}></Text>
</View>
</View>
);
}
import { Text, View, Image, Pressable, ScrollView } from 'react-native';
import { gStyle } from '../styles/style';
import Header from '../components/Header';
import Footer from '../components/Footer';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { firebase } from '../Firebase/firebase';
import 'firebase/compat/firestore';
export default function SignUpForMK({route}) {
const { post } = route.params;
const navigation = useNavigation();
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<View style={gStyle.SupBox}>
<Text style={gStyle.header}>{post.name}</Text>
<Text style={gStyle.hr}></Text>
<Text style={gStyle.SupDate}>{post.time}</Text>
<View style={gStyle.SupContainer}>
<Image
source={{uri:post.image}}
style={gStyle.SupImg}
/>
<View style={gStyle.SupForm}>
<View style={gStyle.SupPrice}>
<Text style={gStyle.SupPrice1}>Цена: </Text>
<Text style={gStyle.SupNumber}>{post.price} P.</Text>
</View>
</View>
<Text style={gStyle.SupDescription}>
{post.description}
</Text>
<Text style={gStyle.SupLine}></Text>
<View style={gStyle.SupContaier1}>
<View style={gStyle.SupBox1}>
<Ionicons name="person-outline" size={30} color="black" />
<Text style={gStyle.SupPerson}>{post.person} человек</Text>
</View>
<View style={gStyle.SupBox1}>
<MaterialCommunityIcons
name="clock-time-four-outline"
size={30}
color="black"
/>
<Text style={gStyle.SupAlarm}>{post.timeOfMK} час(а)</Text>
</View>
</View>
<Text style={gStyle.SupLine}></Text>
<Pressable style={gStyle.SupMoreDetails}
onPress={()=>navigation.navigate('FormAddMK')}
>
<Text style={gStyle.SupBtn}>Записаться</Text>
</Pressable>
</View>
</View>
</View>
<Footer/>
</ScrollView>
</View>
);
}
|
9a815825993f3e3c37dd7a40f73ca9dc
|
{
"intermediate": 0.32998278737068176,
"beginner": 0.5587007999420166,
"expert": 0.11131639033555984
}
|
10,617
|
can you tell me how to apply streamlit theming to a component with custom css properties so that the background color switches if the user switch to dark mode?
|
60a15e0b2a26dc0ddf0c9191f80cd369
|
{
"intermediate": 0.5029961466789246,
"beginner": 0.18380756676197052,
"expert": 0.31319624185562134
}
|
10,618
|
need fix that error by not ruinning functionality "IndexSizeError: CanvasRenderingContext2D.arc: Negative radius". output full optimized and rearranged javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.00;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
const minZoom = 100;
const maxZoom = 2000;
const centerFocus = 100;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 100;
let dragStart = null;
let offset = {
x: gridSpacing / 2,
y: gridSpacing / 2,
z: 0
};
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
let centeredX = x - offset.x;
let centeredY = y - offset.y;
let centeredZ = z - offset.z;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = centeredY * cosX - centeredZ * sinX;
const newZ = centeredY * sinX + centeredZ * cosX;
const newX = centeredX * cosY - newZ * sinY;
const newZ2 = centeredX * sinY + newZ * cosY;
return {
x: newX + offset.x,
y: newY + offset.y,
z: newZ2 + offset.z
};
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (centerFocus + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
7cca2a76492ec6302163b20dd9e7cf69
|
{
"intermediate": 0.336521714925766,
"beginner": 0.4330071806907654,
"expert": 0.23047113418579102
}
|
10,619
|
need fix that error by not ruinning functionality "IndexSizeError: CanvasRenderingContext2D.arc: Negative radius". output full optimized and rearranged javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.00;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
const minZoom = 100;
const maxZoom = 2000;
const centerFocus = 100;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 100;
let dragStart = null;
let offset = {
x: gridSpacing / 2,
y: gridSpacing / 2,
z: 0
};
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
let centeredX = x - offset.x;
let centeredY = y - offset.y;
let centeredZ = z - offset.z;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = centeredY * cosX - centeredZ * sinX;
const newZ = centeredY * sinX + centeredZ * cosX;
const newX = centeredX * cosY - newZ * sinY;
const newZ2 = centeredX * sinY + newZ * cosY;
return {
x: newX + offset.x,
y: newY + offset.y,
z: newZ2 + offset.z
};
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (centerFocus + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
c4f4647d49727054c00e1deb03a7cc1b
|
{
"intermediate": 0.336521714925766,
"beginner": 0.4330071806907654,
"expert": 0.23047113418579102
}
|
10,620
|
need fix that error by not ruinning functionality "IndexSizeError: CanvasRenderingContext2D.arc: Negative radius". output full optimized and rearranged javascript.: const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const rotationSpeed = 0.00;
const gridSize = 50;
const gridSpacing = 25;
const zoomStep = 10;
const minZoom = 100;
const maxZoom = 2000;
const centerFocus = 100;
let grid = [];
for (let x = -gridSize; x <= gridSize; x += gridSpacing) {
for (let y = -gridSize; y <= gridSize; y += gridSpacing) {
for (let z = -gridSize; z <= gridSize; z += gridSpacing) {
grid.push({ x, y, z });
}
}
}
let lastClickedPoint = null;
const clickedPoints = [];
let angleX = 0;
let angleY = 0;
let zoom = 100;
let dragStart = null;
let offset = {
x: gridSpacing / 2,
y: gridSpacing / 2,
z: 0
};
function rotate(point, angleX, angleY) {
const { x, y, z } = point;
let centeredX = x - offset.x;
let centeredY = y - offset.y;
let centeredZ = z - offset.z;
const cosX = Math.cos(angleX);
const sinX = Math.sin(angleX);
const cosY = Math.cos(angleY);
const sinY = Math.sin(angleY);
const newY = centeredY * cosX - centeredZ * sinX;
const newZ = centeredY * sinX + centeredZ * cosX;
const newX = centeredX * cosY - newZ * sinY;
const newZ2 = centeredX * sinY + newZ * cosY;
return {
x: newX + offset.x,
y: newY + offset.y,
z: newZ2 + offset.z
};
}
function project(point, width, height) {
const { x, y, z } = point;
const scale = zoom / (centerFocus + z);
const newX = x * scale + width / 2;
const newY = y * scale + height / 2;
return { x: newX, y: newY, scale };
}
function findClosestPoint(point) {
const threshold = 20;
let minDist = Infinity;
let minIndex = -1;
for (let i = 0; i < grid.length; i++) {
const projected = project(rotate(grid[i], angleX, angleY), canvas.width, canvas.height);
const dx = point.x - projected.x;
const dy = point.y - projected.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < minDist && dist <= threshold) {
minDist = dist;
minIndex = i;
}
}
return minIndex !== -1 ? grid[minIndex] : null;
}
let mouseDown = false;
let activeLine = null;
const lines = [];
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
zoom += e.deltaY * -0.1 * zoomStep;
zoom = Math.min(Math.max(zoom, minZoom), maxZoom); // Limit zoom to min and max thresholds
});
canvas.addEventListener("mousedown", (e) => {
dragStart = { x: e.clientX, y: e.clientY };
});
canvas.addEventListener("mousemove", (e) => {
if (dragStart) {
const deltaX = e.clientX - dragStart.x;
const deltaY = e.clientY - dragStart.y;
angleX += deltaY * 0.01;
angleY += deltaX * 0.01;
dragStart = { x: e.clientX, y: e.clientY };
}
});
canvas.addEventListener("mouseup", (e) => {
mouseDown = false;
dragStart = null;
if (activeLine !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const endPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (endPoint !== activeLine[activeLine.length - 1]) {
activeLine.push(endPoint);
lines.push(activeLine);
}
activeLine = null;
}
if (lastClickedPoint !== null) {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
if (lastClickedPoint === clickedPoint) {
lastClickedPoint = null;
} else {
lines.push([lastClickedPoint, clickedPoint]);
clickedPoints.push(clickedPoint);
lastClickedPoint = null;
}
}
} else {
const canvasRect = canvas.getBoundingClientRect();
const mouseX = e.clientX - canvasRect.left;
const mouseY = e.clientY - canvasRect.top;
const clickedPoint = findClosestPoint({ x: mouseX, y: mouseY });
if (clickedPoint !== null) {
lastClickedPoint = clickedPoint;
clickedPoints.push(clickedPoint);
}
}
});
function drawLine(line) {
ctx.beginPath();
for (let i = 0; i < line.length - 1; i++) {
const projectedStart = project(rotate(line[i], angleX, angleY), canvas.width, canvas.height);
const projectedEnd = project(rotate(line[i + 1], angleX, angleY), canvas.width, canvas.height);
ctx.moveTo(projectedStart.x, projectedStart.y);
ctx.lineTo(projectedEnd.x, projectedEnd.y);
}
ctx.strokeStyle = "rgba(25,200,25,0.2)";
ctx.lineWidth = 2;
ctx.stroke();
}
function calculateGridCenter(grid) {
let totalX = 0;
let totalY = 0;
let totalZ = 0;
const pointsCount = grid.length;
for (const point of grid) {
totalX += point.x;
totalY += point.y;
totalZ += point.z;
}
return {
x: totalX / pointsCount,
y: totalY / pointsCount,
z: totalZ / pointsCount,
};
}
function draw() {
ctx.fillStyle = "rgba(1,2,1,0.8)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const point of grid) {
const rotated = rotate(point, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 2 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
const gradient = ctx.createRadialGradient(projected.x, projected.y, 0, projected.x, projected.y, 2 * projected.scale);
gradient.addColorStop(0, "rgba(255,155,255,0.5)");
gradient.addColorStop(0.5, "rgba(55,255,25,0.8)");
gradient.addColorStop(1, "rgba(55,25,255,0.2)");
ctx.fillStyle = gradient;
ctx.fill();
}
// Drawing clicked points in green
ctx.fillStyle = "rgba(255,200,50,0.5)";
for (const clickedPoint of clickedPoints) {
const rotated = rotate(clickedPoint, angleX, angleY);
const projected = project(rotated, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(projected.x, projected.y, 4 * projected.scale, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
for (const line of lines) {
drawLine(line);
}
if (activeLine !== null) {
drawLine(activeLine);
}
angleX += rotationSpeed;
angleY += rotationSpeed;
requestAnimationFrame(draw);
}
draw();
|
9e0dfa86288d0f6fdb0c424b9f00b3ca
|
{
"intermediate": 0.336521714925766,
"beginner": 0.4330071806907654,
"expert": 0.23047113418579102
}
|
10,621
|
on arduino board you have a pcm liberary that plays numeric values to a io pin with a tranistor gate connected to it. Is this possible on an ttgo t display esp32
|
8b8f164ea3917d015b1cb8afeef52d9e
|
{
"intermediate": 0.4523698091506958,
"beginner": 0.2469312697649002,
"expert": 0.3006989359855652
}
|
10,622
|
I have an asp.net core mvc .NET 6 project, write me a code to add custom tables to the auto-generated db.
|
4b4a9abb98adf43338483a7f27db1e23
|
{
"intermediate": 0.6928383111953735,
"beginner": 0.1458957940340042,
"expert": 0.16126587986946106
}
|
10,623
|
в google пишет Failed to load resource: net::ERR_FILE_NOT_FOUND
|
51d77ef29c5e5f1ace1e731433028d9c
|
{
"intermediate": 0.2723238468170166,
"beginner": 0.3612505793571472,
"expert": 0.36642560362815857
}
|
10,624
|
hi
|
08779015abc1d1e25d8ed27ee3cee658
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,625
|
import json
import random
with open("water_abilities.json", encoding="utf8") as water_ability_file:
water_abilities = json.load(water_ability_file)
with open("fire_abilities.json", encoding="utf8") as fire_ability_file:
fire_abilities = json.load(fire_ability_file)
enemies_defeated = 0
class User:
def __init__(self, id, name, health, max_health, energy, max_energy):
self.id = id
self.name = name
self.health = health
self.max_health = max_health
self.energy = energy
self.max_energy = max_energy
class Fire(User):
def __init__(self, id, name, moves, health, max_health, energy, max_energy):
super().__init__(id, name, health, max_health, energy, max_energy)
self.moves = moves
class Water(User):
def __init__(self, id, name, moves, health, max_health, energy, max_energy):
super().__init__(id, name, health, max_health, energy, max_energy)
self.moves = moves
class Enemy:
def __init__(self, id, name, health, max_health, damage):
self.health = health
self.id = id
self.name = name
self.max_health = max_health
self.damage = damage
class Boss:
def __init__(self, id, name, health, max_health, damage):
self.health = health
self.id = id
self.name = name
self.max_health = max_health
self.damage = damage
attackchance = random.randint(0, 100)
def deal_damage(player, enemy, move):
hit_chance = random.random()
if hit_chance <= 0.3:
print("You missed")
else:
damage = move["base"]["Attack"]
enemy.health -= damage
print(f"{enemy.name} took {damage} damage")
energy_cost = move["base"]["Energy"]
player.energy -= energy_cost
if player.energy < 0:
player.energy = 0
print(f"{player.name} used {move['name']['english']}")
print(f"Current energy: {player.energy}")
if enemy.health <= 0:
print(f"{enemy.name} has been defeated")
def take_damage(player, enemy, move):
damage = enemy.damage
print(f"{player.name} took {damage} damage")
player.health -= damage
if player.health <= 0:
print(f"{player.name} has been defeated")
return True
return False
def normal_enemy_fight(player, enemies_defeated, abilities):
randomenemy = random.randint(100, 200)
enemy = Enemy(0, "Normal Enemy", randomenemy, randomenemy, random.randint(10, 100))
print(f"You have encountered a normal enemy with {enemy.health} health")
while enemy.health > 0:
if isinstance(player, Water):
attackordefend = input("Do you want to defend or attack: ")
if attackordefend.upper() == "DEFEND":
defend_success = random.random()
if defend_success > 0.3:
print("You successfully defended against the enemy")
add_energy(player)
else:
print("You unsuccessfully defended against the enemy")
take_damage(player, enemy, abilities)
elif attackordefend.upper() == "ATTACK":
if player.energy <= 0:
print("You don't have enough energy to use a move")
continue
watermove = input("Choose a water move (Ice Breath, Tsunami, Icecle, Icecle Snipe, Water Slash, Water Blaze, Hail Storm): ")
for move in abilities:
if watermove == move["name"]["english"]:
defeated = deal_damage(player, enemy, move)
if defeated:
enemies_defeated += 1
take_damage(player, enemy, move)
lost = take_damage(player, enemy, move)
if lost:
print(f"Name: {player.name}, Enemies defeated: {enemies_defeated}")
if enemy.health <= 0:
break
break
elif isinstance(player, Fire):
attackordefend = input("Do you want to defend or attack: ")
if attackordefend.upper() == "DEFEND":
defend_success = random.random()
if defend_success > 0.3:
print("You successfully defended against the enemy")
add_energy(player)
else:
print("You unsuccessfully defended against the enemy")
take_damage(player, enemy, abilities)
elif attackordefend.upper() == "ATTACK":
if player.energy <= 0:
print("You don't have enough energy to use a move")
continue
firemove = input("Choose a fire move (Fire Fist, Lava Cannon, Lava Rise, Magma Shot, Fire Blaze, Fire Phoneix, Fire Breath, Fire Blast): ")
for move in abilities:
if firemove == move["name"]["english"]:
defeated = deal_damage(player, enemy, move)
if defeated:
enemies_defeated += 1
lost = take_damage(player, enemy, move)
if lost:
print(f"Name: {player.name}, Enemies defeated: {enemies_defeated}")
if enemy.health <= 0:
break
break
return True
def boss_fight(player, enemies_defeated, abilities):
random_boss = random.randint(1000, 3000)
boss = Boss(1, "Boss", random_boss, random_boss, random.randint(50, 250))
print(f"You have encountered a boss with {boss.health} health")
while player.health > 0 and boss.health > 0:
if isinstance(player, Water):
attackordefend = input("Do you want to defend or attack: ")
if attackordefend.upper() == "DEFEND":
defend_success = random.random()
if defend_success > 0.3:
print("You successfully defended against the boss")
add_energy(player)
else:
print("You unsuccessfully defended against the boss")
take_damage(player, boss, abilities)
elif attackordefend.upper() == "ATTACK":
if player.energy <= 0:
print("You don't have enough energy to use a move")
continue
watermove = input("Choose a water move (Ice Breath, Tsunami, Icecle, Icecle Snipe, Water Slash, Water Blaze, Hail Storm): ")
for ability in abilities:
if watermove == ability["name"]["english"]:
defeated = deal_damage(player, boss, ability)
if defeated:
print("You defeated the boss and won")
lost = take_damage(player, boss, ability)
if lost:
print(f"Name: {player.name}, Enemies defeated: {enemies_defeated}")
if boss.health <= 0:
break
break
elif isinstance(player, Fire):
attackordefend = input("Do you want to defend or attack: ")
if attackordefend.upper() == "DEFEND":
defend_success = random.random()
if defend_success > 0.3:
print("You successfully defended against the boss")
add_energy(player)
else:
print("You unsuccessfully defended against the boss")
take_damage(player, boss, abilities)
elif attackordefend.upper() == "ATTACK":
if player.energy <= 0:
print("You don't have enough energy to use a move")
continue
firemove = input("Choose a fire move (Fire Fist, Fire Ball, Lava cannon, Lava Rise, Magma Shot, Fire Blaze, Fire Phoneix, Fire Breath): ")
for ability in abilities:
if firemove == ability["name"]["english"]:
defeated = deal_damage(player, boss, ability)
if defeated:
print("You defeated the boss and won")
lost = take_damage(player, boss, ability)
if lost:
print(f"Name: {player.name}, Enemies defeated: {enemies_defeated}")
if boss.health <= 0:
break
break
def add_energy(player):
player.energy += 30
if player.energy > player.max_energy:
player.energy = player.max_energy
print(f"{player.name} regenerated 30 energy. Current energy: {player.energy}")
def main():
player_name = input("Enter your name: ")
player_type = input("Choose an ability type (Water, Fire): ")
if player_type.upper() == "WATER":
player = Water(1, player_name, water_abilities, 250, 250, 100, 100)
abilities = water_abilities
elif player_type.upper() == "FIRE":
player = Fire(1, player_name, fire_abilities, 250, 250, 100, 100)
abilities = fire_abilities
round_count = 1
while True:
if round_count % 5 == 0:
boss_defeated = boss_fight(player, enemies_defeated, abilities)
if boss_defeated:
break
enemy_defeated = normal_enemy_fight(player, enemies_defeated, abilities)
if enemy_defeated:
round_count += 1
else:
break
main()
make it so it only goes to the next round when the enemy is defeated
only print the part you made changes to
|
813069fa9afcf970f05f11b137d05582
|
{
"intermediate": 0.3065466582775116,
"beginner": 0.5598463416099548,
"expert": 0.13360697031021118
}
|
10,626
|
Private Sub Checkbox_AfterUpdate()
If = True Then
' حذف السجل من الجدول الحالي
acCmdDeleteRecord
' إضافة السجل إلى الجدول الجديد
"INSERT INTO [اسم الجدول الجديد] SELECT * FROM [اسم الجدول الحالي] WHERE [معرف السجل] = " &
End If
End Sub>
|
86a898ab13a5f1385316b09c1823cbc9
|
{
"intermediate": 0.3624376356601715,
"beginner": 0.40302205085754395,
"expert": 0.23454034328460693
}
|
10,627
|
Find the issue in the paythoncode below:
# Define the function to handle the client name message
def client_name_received(update, context):
# Get the client name from the message
client_name = update.message.text
# send the waiting message
update.message.reply_text("Please wait, I'm processing…")
# Get the file name from the user context
file_name = context.user_data['file_name']
# Extract the tar file
with tarfile.open(file_name) as tar:
tar.extractall('in_data')
# Run the minerlog_data.sh file
subprocess.run(['./minerlog_data.sh'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Wait for the script to finish executing
while not os.path.exists('output.csv'):
pass
# Read the output file as a pandas dataframe
df = pd.read_csv('output.csv')
# Get the unique subtype values from the output.csv file
subtypes = df['subtype'].unique()
# Replace empty strings in the subvariant column with '(blank)'
df['subvariant'] = df['subvariant'].fillna('(blank)')
# Create a pivot table with the desired format
pivot_table = pd.pivot_table(df, values='ip', index=['model', 'subvariant'], columns=['subtype'], aggfunc='count', fill_value=0, margins=True, margins_name='Grand Total')
# Rename the column headers
pivot_table.columns = pd.MultiIndex.from_tuples([(subtype, 'ip (Count All)') for subtype in [''] + list(subtypes)], names=['subtype', None])
# Create the row indices
pivot_table.index = pd.MultiIndex.from_tuples([(model, subvariant) if subvariant else (model, '(blank)') for model, subvariant in pivot_table.index])
pivot_table.index.names = ['model', 'subvariant']
# Save the pivot table as a csv file
pivot_table.to_csv(f'pivot_{client_name}.csv')
# Read in the pivot table as a pandas dataframe
df = pd.read_csv(f'pivot_{client_name}.csv', index_col=[0,1], header=[0,1])
# Create a figure and axis
fig, ax = plt.subplots()
# Remove the default axis labels and ticks
ax.axis('off')
# Create the table using the pandas dataframe
table = ax.table(cellText=df.values, colLabels=df.columns.levels[1], rowLabels=df.index.levels[1].unique(), loc='center')
# Set the table font size
table.set_fontsize(14)
# Save the table as an image file
plt.savefig(f'pivot_{client_name}.png')
# Send the image to the user
context.bot.send_photo(update.message.chat.id, photo=open(f'pivot_{client_name}.png', 'rb'))
# Rename the output.csv file
os.rename('output.csv', f'output_{client_name}.csv')
# Send the pivot table file to the user
context.bot.send_document(update.message.chat_id, document=open(f'pivot_{client_name}.csv', 'rb'))
# Send the output file to the user
context.bot.send_document(update.message.chat_id, document=open(f'output_{client_name}.csv', 'rb'))
update.message.reply_text('⚠️ Hide sender’s name! when you want to forward the messages')
# Remove the generated files
os.remove(file_name)
os.remove(f'pivot_{client_name}.png')
os.remove(f'pivot_{client_name}.csv')
os.remove(f'output_{client_name}.csv')
os.system('rm -rf in_data/*')
|
a216d90f5dea2c6f534611ac150fdad3
|
{
"intermediate": 0.332052618265152,
"beginner": 0.4837402105331421,
"expert": 0.18420715630054474
}
|
10,628
|
write down 20 usability testing for 20 persons and show it in a styled html css page
|
0156e96567c2047b4f930189fa7e41be
|
{
"intermediate": 0.2893295884132385,
"beginner": 0.4738289713859558,
"expert": 0.23684151470661163
}
|
10,629
|
hi
|
1fac39f417579aa00682e31919796892
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,630
|
# ChatERP
## Generation Rules
You are ChatERP. ERP stands for "Erotic Role Play." You are programmed to create erotic roleplay partners for the user.
When the user requests their character, say:
* "Will do!"
* Say you understand what franchise they're referring to and you will try your best to be accurate to that world.
* Say you'll remember to write plus signs between strings.
* If the user requests a real person, assume it is a fictional version.
Then, write a code block using the W++ format. Compress as much detail as possible into the fewest amount of text characters.
Here is an example of W++:
|
e17669af554881c45cfd1f5c2f8e28da
|
{
"intermediate": 0.2411024570465088,
"beginner": 0.4431621730327606,
"expert": 0.3157352805137634
}
|
10,631
|
this footer: "<footer class="bg-dark text-center text-white">
<div class="row align-items-center justify-content-center">
<div class="container p-4 pb-0">
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d890603.0788230407!2d47.535719949999994!3d29.314072799999998!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3fc5363fbeea51a1%3A0x74726bcd92d8edd2!2z2KfZhNmD2YjZitiq4oCO!5e0!3m2!1sar!2seg!4v1684327079455!5m2!1sar!2seg" width="400" height="300" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
</div>
<!-- Grid container -->
<div class="container p-4 pb-0">
<!-- Section: Social media -->
<section class="mb-4">
<!-- Twitter -->
<a class="btn btn-outline-light btn-floating m-1" href="https://wa.me/+96565667117" style="width: 190px;height: 190px;" role="button"
><i class="fab fa-whatsapp" style="font-size: 170px;"></i
></a>
<!-- Google -->
<a class="btn btn-outline-light btn-floating m-1" href="tel:<PRESIDIO_ANONYMIZED_PHONE_NUMBER>" role="button" style="background-color: white;width: 190px;height: 190px;">
<img src="./public/img/free-phone-icon-505-thumb.png" style="width: 100%;height: 100%;" />
</a>
</section>
<!-- Section: Social media -->
</div>
<!-- Grid container -->
<!-- Copyright -->
<div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);">
© 2020 Copyright:
<a class="text-white" href="https://mdbootstrap.com/">MDBootstrap.com</a>
</div>
<!-- Copyright -->
</footer>" is written for bootstrap 5, convert it to tailwindcss.
|
69fc62bf3a0f5d186a43182b9237271a
|
{
"intermediate": 0.2625901401042938,
"beginner": 0.4984939694404602,
"expert": 0.2389158308506012
}
|
10,632
|
I have a porblem with this model in shedule. I need
7x3 array - 7 rows (these are days of the week) with fields of the following types:
opentime - time with time zone
closetime - time with time zone
worktime - long (in seconds)
|
dc49351771754489b0e42944749bfec3
|
{
"intermediate": 0.3649073541164398,
"beginner": 0.34952157735824585,
"expert": 0.28557103872299194
}
|
10,633
|
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting numpy==1.20.0
Downloading numpy-1.20.0.zip (8.0 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.0/8.0 MB 44.6 MB/s eta 0:00:00
Installing build dependencies ... done
Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... done
Building wheels for collected packages: numpy
error: subprocess-exited-with-error
× Building wheel for numpy (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
Building wheel for numpy (pyproject.toml) ... error
ERROR: Failed building wheel for numpy
Failed to build numpy
ERROR: Could not build wheels for numpy, which is required to install pyproject.toml-based projects
|
e5e80d3f6fdb1eea505dd052d7c88ce9
|
{
"intermediate": 0.3673016130924225,
"beginner": 0.33701634407043457,
"expert": 0.2956821024417877
}
|
10,634
|
give me frontend code for gallery website
|
88b22df1092322e77dd56898bbc751b9
|
{
"intermediate": 0.3065100312232971,
"beginner": 0.26340150833129883,
"expert": 0.43008843064308167
}
|
10,635
|
hi, can you write a python script for time series analysis for LSTM using pytorch library
|
b4f33e7ac3d42351b9b5c7bed640df60
|
{
"intermediate": 0.6250879764556885,
"beginner": 0.04676561802625656,
"expert": 0.32814639806747437
}
|
10,636
|
custom code to upload pdf documents to manage and generate a public accessible link to the pdf document
|
08de76bb97bc4d54f286032e20f6410a
|
{
"intermediate": 0.48309680819511414,
"beginner": 0.14990434050559998,
"expert": 0.3669988811016083
}
|
10,637
|
write me an asp.net core mvc page that displays a list of articles, you can use this code for the article element: “
<ul class=“list-style-none flex”>
<li>
<a
class=“pointer-events-none relative block rounded-full bg-transparent px-3 py-1.5 text-sm text-neutral-500 transition-all duration-300 dark:text-neutral-400”
>Previous</a
>
</li>
<li>
<a
class=“relative block rounded-full bg-transparent px-3 py-1.5 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100 dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white”
href=”#!“
>1</a
>
</li>
<li aria-current=“page”>
<a
class=“relative block rounded-full bg-primary-100 px-3 py-1.5 text-sm font-medium text-primary-700 transition-all duration-300”
href=”#!“
>2
<span
class=“absolute -m-px h-px w-px overflow-hidden whitespace-nowrap border-0 p-0 [clip:rect(0,0,0,0)]”
>(current)</span
>
</a>
</li>
<li>
<a
class=“relative block rounded-full bg-transparent px-3 py-1.5 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100 dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white”
href=”#!“
>3</a
>
</li>
<li>
<a
class=“relative block rounded-full bg-transparent px-3 py-1.5 text-sm text-neutral-600 transition-all duration-300 hover:bg-neutral-100 dark:text-white dark:hover:bg-neutral-700 dark:hover:text-white”
href=”#!“
>Next</a
>
</li>
</ul>
</nav>”, you load all items at first but then display 10 items at a time with a pagination at the bottom, you can use this code for the pagination and make necessary edits for it to work: “<article class=“bg-white shadow-md rounded-lg p-4”>
<h3 class=“text-xl mb-2”>عنوان الخدمة</h3>
<img src=“img/AMALALTASTEEB.jpeg” alt=“أسم الخدمة” class=“rounded-lg mb-4”>
<h5 class=“text-gray-600 mb-3”>وصف الخدمة لوريم إيبسوم دولور سيت أميت, إيليت آد بوسويري جرافيدا فولوتبات روتروم.</h5>
<div class=“flex items-center”>
<span class=“mr-2”>
<!-- Add WhatsApp Icon -->
</span>
<a href=“tel:+1234567890” class=“text-yellow-500”>+1 (234) 567-890</a>
</div>
<!-- Replace with your own SEO keywords -->
<meta itemprop=“keywords” content=“خدمة1, خدمة2, خدمة3”>
</article>”. Make sure to use tailwindcss to make the page responsive and make the page arabic.
|
8f3cf7c630a5137b486f3c08ff66fd8b
|
{
"intermediate": 0.24522364139556885,
"beginner": 0.33268555998802185,
"expert": 0.4220907688140869
}
|
10,638
|
how do I deploy a huggingface on Vercel? for example, for my current Huggingface space, how can I deploy it on vercel and then I have vercel app link for it.
|
20f7113d82477b6cd525202c6c7d1a4d
|
{
"intermediate": 0.6205938458442688,
"beginner": 0.09496330469846725,
"expert": 0.28444284200668335
}
|
10,639
|
I need
7x3 array - 7 rows (these are days of the week) with fields of the following types:
opentime - time with time zone
closetime - time with time zone
worktime - long (in seconds) correct my model class CustomerObject(Base):
tablename = ‘customer’
id = Column(Integer, primary_key=True)
schedule = Column(MutableMultiDict.as_mutable(ARRAY(
Column(‘opentime’, Time(timezone=True)),
Column(‘closetime’, Time(timezone=True)),
Column(‘worktime’, BigInteger())), dimensions=2))
|
eb5ffac569058cbcbbc7550716adb5ee
|
{
"intermediate": 0.3917906880378723,
"beginner": 0.3718661069869995,
"expert": 0.23634323477745056
}
|
10,640
|
python re.search AttributeError: 'NoneType' object has no attribute 'group'
|
a33f72da02e71d2bfe4b8ec8cdf0a7b8
|
{
"intermediate": 0.4087851047515869,
"beginner": 0.25807371735572815,
"expert": 0.33314117789268494
}
|
10,641
|
write a code to add custom tables to the default db in asp.net core mvc .NET 7.1
|
875468791c4feb3797d284cec8a90e55
|
{
"intermediate": 0.5198106169700623,
"beginner": 0.1682463437318802,
"expert": 0.31194302439689636
}
|
10,642
|
Write a menu driven C program to implement of circular linked list with following
operations:
• Create the list
• Insert a node in the beginning, in the end, at given position
• Delete a node in the beginning, in the end, at given position
• Search a node
• Display the list
|
e3116be471fde85fe817f035872f3298
|
{
"intermediate": 0.30823248624801636,
"beginner": 0.10688917338848114,
"expert": 0.5848783850669861
}
|
10,643
|
Celular["Fecha2"]=Celular["Fecha1"]
Fijo["Fecha2"]=Fijo["Fecha1"]
Correo["Fecha2"]=Correo["Fecha1"]
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
cómo lo cambio?
|
70ac456a214b8f9800f19703e08b7cdf
|
{
"intermediate": 0.5057573914527893,
"beginner": 0.2984052002429962,
"expert": 0.1958373785018921
}
|
10,644
|
I have an asp.net core MVC .NET 7.1 project, using the best practices i need you to write a code for the process of adding a Product Class item to the database using a viewpage to add the record. The item contains Name, Text, Image. I need you to write me the best practised, fastest code to do the job.
|
31eaf08d064d4a9c200f96b7a55267ba
|
{
"intermediate": 0.6457124948501587,
"beginner": 0.19920197129249573,
"expert": 0.1550855040550232
}
|
10,645
|
url = options.pop("url")
^^^^^^^^^^^^^^^^^^
KeyError: 'url'
|
2e3a78496224f3c72452e1a1298bc9a7
|
{
"intermediate": 0.42627400159835815,
"beginner": 0.2564736008644104,
"expert": 0.31725242733955383
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.