row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
10,044
|
how to preprocess this data set TransactionID isFraud TransactionDT TransactionAmt ProductCD card1 card2 card3 card4 card5 card6 addr1 addr2 dist1 dist2 P_emaildomain R_emaildomain C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 D14 D15 M1 M2 M3 M4 M5 M6 M7 M8 M9 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36 V37 V38 V39 V40 V41 V42 V43 V44 V45 V46 V47 V48 V49 V50 V51 V52 V53 V54 V55 V56 V57 V58 V59 V60 V61 V62 V63 V64 V65 V66 V67 V68 V69 V70 V71 V72 V73 V74 V75 V76 V77 V78 V79 V80 V81 V82 V83 V84 V85 V86 V87 V88 V89 V90 V91 V92 V93 V94 V95 V96 V97 V98 V99 V100 V101 V102 V103 V104 V105 V106 V107 V108 V109 V110 V111 V112 V113 V114 V115 V116 V117 V118 V119 V120 V121 V122 V123 V124 V125 V126 V127 V128 V129 V130 V131 V132 V133 V134 V135 V136 V137 V138 V139 V140 V141 V142 V143 V144 V145 V146 V147 V148 V149 V150 V151 V152 V153 V154 V155 V156 V157 V158 V159 V160 V161 V162 V163 V164 V165 V166 V167 V168 V169 V170 V171 V172 V173 V174 V175 V176 V177 V178 V179 V180 V181 V182 V183 V184 V185 V186 V187 V188 V189 V190 V191 V192 V193 V194 V195 V196 V197 V198 V199 V200 V201 V202 V203 V204 V205 V206 V207 V208 V209 V210 V211 V212 V213 V214 V215 V216 V217 V218 V219 V220 V221 V222 V223 V224 V225 V226 V227 V228 V229 V230 V231 V232 V233 V234 V235 V236 V237 V238 V239 V240 V241 V242 V243 V244 V245 V246 V247 V248 V249 V250 V251 V252 V253 V254 V255 V256 V257 V258 V259 V260 V261 V262 V263 V264 V265 V266 V267 V268 V269 V270 V271 V272 V273 V274 V275 V276 V277 V278 V279 V280 V281 V282 V283 V284 V285 V286 V287 V288 V289 V290 V291 V292 V293 V294 V295 V296 V297 V298 V299 V300 V301 V302 V303 V304 V305 V306 V307 V308 V309 V310 V311 V312 V313 V314 V315 V316 V317 V318 V319 V320 V321 V322 V323 V324 V325 V326 V327 V328 V329 V330 V331 V332 V333 V334 V335 V336 V337 V338 V339
2987000 0 86400 68.5 W 13926 150 discover 142 credit 315 87 19 1 1 0 0 0 1 0 0 1 0 2 0 1 1 14 13 13 13 0 T T T M2 F T 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 117 0 0 0 0 0 117 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 117 0 0 0 0 0 0 0 0 0 117 0 0 0 0
2987001 0 86401 29 W 2755 404 150 mastercard 102 credit 325 87 gmail.com 1 1 0 0 0 1 0 0 0 0 1 0 1 1 0 0 0 0 M0 T T 0 0 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987002 0 86469 59 W 4663 490 150 visa 166 debit 330 87 287 outlook.com 1 1 0 0 0 1 0 0 1 0 1 0 1 1 0 0 0 315 315 T T T M0 F F F F F 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987003 0 86499 50 W 18132 567 150 mastercard 117 debit 476 87 yahoo.com 2 5 0 0 0 4 0 0 1 0 1 0 25 1 112 112 0 94 0 84 111 M0 T F 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 1 48 28 0 10 4 1 38 24 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 50 1758 925 0 354 135 50 1404 790 0 0 0 1 28 0 0 0 0 10 0 4 0 0 1 1 1 1 38 24 0 0 0 0 0 0 0 0 0 1 50 1758 925 0 354 0 135 0 0 0 50 1404 790 0 0 0
2987004 0 86506 50 H 4497 514 150 mastercard 102 credit 420 87 gmail.com 1 1 0 0 0 1 0 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 18 140 0 0 0 0 1803 49 64 0 0 0 0 0 0 15557.99023 169690.7969 0 0 0 515 5155 2840 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987005 0 86510 49 W 5937 555 150 visa 226 debit 272 87 36 gmail.com 1 1 0 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 0 T T T M1 F T 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987006 0 86522 159 W 12308 360 150 visa 166 debit 126 87 0 yahoo.com 1 1 0 0 0 1 0 0 1 0 1 0 1 1 0 0 0 0 0 T T T M0 F F T T T 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987007 0 86529 422.5 W 12695 490 150 visa 226 debit 325 87 mail.com 1 1 0 0 0 1 0 0 0 0 1 0 1 1 0 0 0 0 M0 F F 0 0 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987008 0 86535 15 H 2803 100 150 visa 226 debit 337 87 anonymous.com 1 1 0 0 0 1 0 1 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 18 140 0 0 0 0 1804 49 64 0 0 0 0 0 0 15607.99023 169740.7969 0 0 0 515 5155 2840 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2987009 0 86536 117 W 17399 111 150 mastercard 224 debit 204 87 19 yahoo.com 2 2 0 0 0 3 0 0 3 0 1 0 12 2 61 61 30 318 30 40 302 318 T T T M0 T T 1 1 1 1 1 1 1 1 1 0 0 1 1 1 0 0 0 0 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1 0 0 1 1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 2 0 0 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 495 0 0 0 0 0 0 0
2987010 0 86549 75.887 C 16496 352 117 mastercard 134 credit gmail.com gmail.com 1 4 0 1 0 1 1 1 0 1 2 2 2 1 1 1 0 0 0 0 0 83 0 0 0 0 0 0 M0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 0 0 4 4 1 1 1 1 1 1 1 2 2 0 0 1 2 2 0 0 4 4 1 1 1 1 1 1 1 1 1 2 2 0 0 0 1 1 2 2 0 0 3 3 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 4 4 2 1 2 2 4 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 166.2153931 166.2153931 166.2153931 90.32790375 31.84129906 90.32790375 90.32790375 90.32790375 90.32790375 0 0 0 75.88749695 75.88749695 75.88749695 3 3 3 3 4 4 2 2 2 0 2 4 4 4 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 166.2153931 166.2153931 166.2153931 90.32790375 90.32790375 90.32790375 0 90.32790375 90.32790375 90.32790375 0 0 0 75.88749695 75.88749695 75.88749695 3 3 3 4 4 2 2 1 2 2 2 4 4 4 0 0 0 1 1 1 1 1 1 1 1 1 1 166.2153931 166.2153931 166.2153931 90.32790375 90.32790375 31.84129906 90.32790375 90.32790375 90.32790375 90.32790375 0 0 0 75.88749695 75.88749695 75.88749695
|
479bc8fdef6fdb0a9d6214cf326dc9e8
|
{
"intermediate": 0.34841957688331604,
"beginner": 0.2703438699245453,
"expert": 0.38123661279678345
}
|
10,045
|
Make a game name that has a minecraft theme with stumble guys characters
|
6f7e86cac76382de2c1d563b8f1f23ab
|
{
"intermediate": 0.3240259289741516,
"beginner": 0.32642391324043274,
"expert": 0.34955018758773804
}
|
10,046
|
I builded an model to predict handwritten word but it it does not work well this is my code can you give some improvement:
import numpy as np
import pandas as pd
import os
import cv2
import imutils
import random
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from sklearn.preprocessing import LabelBinarizer
from keras.layers import Flatten, Dense,Dropout
from keras.layers import Conv2D, MaxPooling2D
dir = "Final-state-Total"
dir2 = "dataset1"
df = pd.read_csv(os.path.join(dir2,"english.csv"))
df['label'] = df['label'].str.upper()
data = []
img_size = 32
non_chars = ["#","$","&","@"]
for i in os.listdir(dir):
if i in non_chars:
continue
listeToAdd = df[ df['label'] == i]
listeToAdd = listeToAdd['image'].tolist()
for j in listeToAdd:
img = cv2.imread(os.path.join(dir2,j),0)
img = cv2.resize(img,(img_size,img_size))
data.append([img,i])
count = 0
sub_directory = os.path.join(dir,i)
for j in os.listdir(sub_directory):
count+=1
if count > 4000:
break
img = cv2.imread(os.path.join(sub_directory,j),0)
img = cv2.resize(img,(img_size,img_size))
data.append([img,i])
random.shuffle(data)
len(data) # 21174
dataX = []
dataY = []
for feautures,label in data:
dataX.append(feautures)
dataY.append(label)
nb_classes = len(np.unique(dataY)) # 64 classes
LB = LabelBinarizer()
dataY = LB.fit_transform(dataY)
dataX = np.array(dataX)/255.0
dataX = dataX.reshape(-1,img_size,img_size,1)
X_train, X_val, y_train, y_val = train_test_split(dataX, dataY, test_size=0.2, random_state=42) # (16939, 32, 32, 1) (4235, 32, 32, 1) (16939, 64) (4235, 64)
model = Sequential()
model.add(Conv2D(32, (3, 3), padding = "same", activation='relu', input_shape=(32,32,1)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(64, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
history = model.fit(X_train,y_train, epochs=50, batch_size=32, validation_data = (X_val, y_val), verbose=1)
def sort_contours(cnts, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b:b[1][i], reverse=reverse))
# return the list of sorted contours and bounding boxes
return (cnts, boundingBoxes)
def get_letters(img):
letters = []
image = cv2.imread(img)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret,thresh1 = cv2.threshold(gray ,127,255,cv2.THRESH_BINARY_INV)
dilated = cv2.dilate(thresh1, None, iterations=2)
cnts = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sort_contours(cnts, method="left-to-right")[0]
# loop over the contours
for c in cnts:
if cv2.contourArea(c) > 10:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
roi = gray[y:y + h, x:x + w]
thresh = cv2.threshold(roi, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
thresh = cv2.resize(thresh, (32, 32), interpolation = cv2.INTER_CUBIC)
thresh = thresh.astype("float32") / 255.0
thresh = np.expand_dims(thresh, axis=-1)
thresh = thresh.reshape(1,32,32,1)
ypred = model.predict(thresh)
ypred = LB.inverse_transform(ypred)
[x] = ypred
letters.append(x)
return letters, image
def get_word(letter):
word = "".join(letter)
return word
letter,image = get_letters("brother.jpg")
word = get_word(letter)
print(word)
plt.imshow(image) # what it supposed to give BROTHER ## what give FFQFFFF
|
2df84ac71cfbc82cc6fcbe36478fea32
|
{
"intermediate": 0.31867551803588867,
"beginner": 0.31165146827697754,
"expert": 0.3696730434894562
}
|
10,047
|
hi
|
5131f8b4ce6cb60d5f10642b56a96b2b
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,048
|
Fivem scripting how to trigger an event for people in a radius of 30 meters from a vector3
|
4c7ce99585f2b1473a1c84da3f5f05bf
|
{
"intermediate": 0.23192700743675232,
"beginner": 0.1845160871744156,
"expert": 0.5835568904876709
}
|
10,049
|
Fivem scripting how to trigger an event for people in a radius of 30 meters from a vector3
|
a0beb4d991154c36b91ec7169ac568ac
|
{
"intermediate": 0.23192700743675232,
"beginner": 0.1845160871744156,
"expert": 0.5835568904876709
}
|
10,050
|
Fivem scripting how to trigger an event all players in a radius of 30 meters from a vector3
|
498e7c75c735cf162d5c1dc3e59d7bd1
|
{
"intermediate": 0.271634578704834,
"beginner": 0.23959405720233917,
"expert": 0.48877137899398804
}
|
10,051
|
Fivem scripting how to trigger an event all players in a radius of 30 meters from a vector3
|
6163fb28dbf7b9d8dd29231fe5bbcaa3
|
{
"intermediate": 0.271634578704834,
"beginner": 0.23959405720233917,
"expert": 0.48877137899398804
}
|
10,052
|
preprocess this data to improve accuracy TransactionID,isFraud,TransactionDT,TransactionAmt,ProductCD,card1,card2,card3,card4,card5,card6,addr1,addr2,dist1,dist2,P_emaildomain,R_emaildomain,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10,C11,C12,C13,C14,D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,D11,D12,D13,D14,D15,M1,M2,M3,M4,M5,M6,M7,M8,M9,V1,V2,V3,V4,V5,V6,V7,V8,V9,V10,V11,V12,V13,V14,V15,V16,V17,V18,V19,V20,V21,V22,V23,V24,V25,V26,V27,V28,V29,V30,V31,V32,V33,V34,V35,V36,V37,V38,V39,V40,V41,V42,V43,V44,V45,V46,V47,V48,V49,V50,V51,V52,V53,V54,V55,V56,V57,V58,V59,V60,V61,V62,V63,V64,V65,V66,V67,V68,V69,V70,V71,V72,V73,V74,V75,V76,V77,V78,V79,V80,V81,V82,V83,V84,V85,V86,V87,V88,V89,V90,V91,V92,V93,V94,V95,V96,V97,V98,V99,V100,V101,V102,V103,V104,V105,V106,V107,V108,V109,V110,V111,V112,V113,V114,V115,V116,V117,V118,V119,V120,V121,V122,V123,V124,V125,V126,V127,V128,V129,V130,V131,V132,V133,V134,V135,V136,V137,V138,V139,V140,V141,V142,V143,V144,V145,V146,V147,V148,V149,V150,V151,V152,V153,V154,V155,V156,V157,V158,V159,V160,V161,V162,V163,V164,V165,V166,V167,V168,V169,V170,V171,V172,V173,V174,V175,V176,V177,V178,V179,V180,V181,V182,V183,V184,V185,V186,V187,V188,V189,V190,V191,V192,V193,V194,V195,V196,V197,V198,V199,V200,V201,V202,V203,V204,V205,V206,V207,V208,V209,V210,V211,V212,V213,V214,V215,V216,V217,V218,V219,V220,V221,V222,V223,V224,V225,V226,V227,V228,V229,V230,V231,V232,V233,V234,V235,V236,V237,V238,V239,V240,V241,V242,V243,V244,V245,V246,V247,V248,V249,V250,V251,V252,V253,V254,V255,V256,V257,V258,V259,V260,V261,V262,V263,V264,V265,V266,V267,V268,V269,V270,V271,V272,V273,V274,V275,V276,V277,V278,V279,V280,V281,V282,V283,V284,V285,V286,V287,V288,V289,V290,V291,V292,V293,V294,V295,V296,V297,V298,V299,V300,V301,V302,V303,V304,V305,V306,V307,V308,V309,V310,V311,V312,V313,V314,V315,V316,V317,V318,V319,V320,V321,V322,V323,V324,V325,V326,V327,V328,V329,V330,V331,V332,V333,V334,V335,V336,V337,V338,V339
2987000,0,86400,68.5,W,13926,,150.0,discover,142.0,credit,315.0,87.0,19.0,,,,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,2.0,0.0,1.0,1.0,14.0,,13.0,,,,,,,13.0,13.0,,,,0.0,T,T,T,M2,F,T,,,,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,117.0,0.0,0.0,0.0,0.0,0.0,117.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,117.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,117.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,
2987001,0,86401,29.0,W,2755,404.0,150.0,mastercard,102.0,credit,325.0,87.0,,,gmail.com,,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,,,0.0,,,,,,0.0,,,,,0.0,,,,M0,T,T,,,,,,,,,,,,,,,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,
2987002,0,86469,59.0,W,4663,490.0,150.0,visa,166.0,debit,330.0,87.0,287.0,,outlook.com,,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,,,0.0,,,,,,0.0,315.0,,,,315.0,T,T,T,M0,F,F,F,F,F,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,
2987003,0,86499,50.0,W,18132,567.0,150.0,mastercard,117.0,debit,476.0,87.0,,,yahoo.com,,2.0,5.0,0.0,0.0,0.0,4.0,0.0,0.0,1.0,0.0,1.0,0.0,25.0,1.0,112.0,112.0,0.0,94.0,0.0,,,,,84.0,,,,,111.0,,,,M0,T,F,,,,,,,,,,,,,,,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,48.0,28.0,0.0,10.0,4.0,1.0,38.0,24.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,50.0,1758.0,925.0,0.0,354.0,135.0,50.0,1404.0,790.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,1.0,28.0,0.0,0.0,0.0,0.0,10.0,0.0,4.0,0.0,0.0,1.0,1.0,1.0,1.0,38.0,24.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,50.0,1758.0,925.0,0.0,354.0,0.0,135.0,0.0,0.0,0.0,50.0,1404.0,790.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,
2987004,0,86506,50.0,H,4497,514.0,150.0,mastercard,102.0,credit,420.0,87.0,,,gmail.com,,1.0,1.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,6.0,18.0,140.0,0.0,0.0,0.0,0.0,1803.0,49.0,64.0,0.0,0.0,0.0,0.0,0.0,0.0,15557.990234375,169690.796875,0.0,0.0,0.0,515.0,5155.0,2840.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
2987005,0,86510,49.0,W,5937,555.0,150.0,visa,226.0,debit,272.0,87.0,36.0,,gmail.com,,1.0,1.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,1.0,0.0,,,0.0,,,,,,0.0,0.0,,,,0.0,T,T,T,M1,F,T,,,,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,,,,,,,,,,,,,,,,,,
|
cacaebd837d20031d22333a017472d7e
|
{
"intermediate": 0.3728322982788086,
"beginner": 0.35851502418518066,
"expert": 0.26865270733833313
}
|
10,053
|
Fivem Scripting lua
how do i enable gta 5 stock police and set a wanted level so the police chase me
|
cfcef243270318b981f5f519bb4d4eec
|
{
"intermediate": 0.2912776470184326,
"beginner": 0.4211307764053345,
"expert": 0.2875915765762329
}
|
10,054
|
Fivem Scripting lua
how do i enable gta 5 stock police and set a wanted level so the police chase me
|
77d293299014520d3dbc685e05efe0a8
|
{
"intermediate": 0.2912776470184326,
"beginner": 0.4211307764053345,
"expert": 0.2875915765762329
}
|
10,055
|
Way to use this without using std::random_device, and the random header? #pragma once
#include <typeindex>
#include <functional>
#include <array>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <random>
class Event
{
public:
virtual ~Event() {}
};
class CollisionEvent : public Event
{
public:
// Event data and methods
CollisionEvent(size_t value, float p) : value{ value }, p{ p } {}
size_t value = 10;
float p = 10;
const void Update() const {
std::cout << "Entity Id: " << value << " | X-position: " << p << std::endl;
}
};
class EventBus
{
public:
using CallbackID = uint64_t;
//template <typename EventType>
//using Callback = std::function<void(const EventType&)>;
template <typename EventType, typename Callable>
CallbackID Subscribe(Callable&& callback);
template <typename EventType>
void Unsubscribe(CallbackID id);
template <typename EventType>
void Dispatch(const EventType& event);
private:
typedef std::vector<std::pair<CallbackID, std::function<void(const Event*)>>> CallbackVector;
std::unordered_map<std::type_index, CallbackVector> callbacks_;
std::random_device rd_;
};
template <typename EventType, typename Callable>
EventBus::CallbackID EventBus::Subscribe(Callable&& callback)
{
std::uniform_int_distribution<CallbackID> dist;
CallbackID id = dist(rd_);
auto wrapper = [callback](const Event* eventPtr)
{
callback(static_cast<const EventType&>(*eventPtr));
};
callbacks_[typeid(EventType)].emplace_back(id, wrapper);
return id;
}
template <typename EventType>
void EventBus::Dispatch(const EventType& event)
{
auto it = callbacks_.find(typeid(EventType));
if (it != callbacks_.end())
{
for (const auto& [_, callback] : it->second)
{
callback(&event);
}
}
}
template <typename EventType>
void EventBus::Unsubscribe(CallbackID id)
{
auto& vec = callbacks_[typeid(EventType)];
vec.erase(std::remove_if(vec.begin(), vec.end(),
[id](const auto& pair) { return pair.first == id; }), vec.end());
}
|
962e876ecaca80b8242598abce23fc36
|
{
"intermediate": 0.267434686422348,
"beginner": 0.5765995383262634,
"expert": 0.15596576035022736
}
|
10,056
|
Is there a VBA code to change a range of row heights
|
9578143786bf3ad317734b091ebd914d
|
{
"intermediate": 0.39620500802993774,
"beginner": 0.21342431008815765,
"expert": 0.3903706669807434
}
|
10,057
|
import socket
import threading
import tkinter as tk
import subprocess
from PIL import ImageTk, Image
from tkinter import Tk, Label
import sys
from tkinter import messagebox
from tkinter import ttk
import random
import string
import socket
from tkinter import simpledialog
root = tk.Tk()
root.title("Client")
root.configure(bg="#63bdea")
image = Image.open("vit.png")
image = image.resize((490, 150))
# Create an instance of the ImageTk class to display the image in the window
image_tk = ImageTk.PhotoImage(image)
# Create a Label widget to display the image
image_label = Label(root, image=image_tk)
# Place the label in the window
image_label.pack(pady=50)
frame = tk.Frame(root)
frame.pack()
text_label = tk.Label(root, text="Computer Network Project 2023 (BITE203P)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=25, y=50)
text_label = tk.Label(root, text="Fall Semester 2023-2024", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=25, y=75)
text_label = tk.Label(root, text="Faculty: Shunmuga P Sir", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=25, y=100)
text_label = tk.Label(root, text="Team Members:", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=50)
text_label = tk.Label(root, text="Omkar (21BIT0530)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=75)
text_label = tk.Label(root, text="Aditaya K (21BIT0583)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=100)
text_label = tk.Label(root, text="Malay Shau (21BIT0594)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=125)
text_label = tk.Label(root, text="Diti Jain (21BIT0311)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=150)
text_label = tk.Label(root, text="Tarunika Agarwal (21BIT0442)", bg="#63bdea")
text_label.config(font=("Arial", 18))
text_label.place(x=1125, y=175)
output_box = tk.Text(root)
output_box.place(x=800,y=300)
root.attributes('-fullscreen', True)
def display_message(message):
output_box.insert(tk.END, message + '\n')
output_box.see(tk.END)
def createAcc():
CAGUI()
def Login():
LNGUI()
def LNGUI():
window1 = tk.Tk()
window1.configure(bg="#63bdea")
def create_profile():
email = email_entry.get()
password = password_entry.get()
if not email:
messagebox.showwarning("Warning", "Email can't be Empty")
window1.destroy()
return
elif not password:
messagebox.showwarning("Warning", "Please Enter the Password")
window1.destroy()
return
message = "LI"+" email: "+email+" password: "+password
client_socket.sendall(message.encode('utf-8'))
window1.destroy()
window1.title("Blockchain Crypto Login!")
window1.geometry("400x200")
email_label = tk.Label(window1, text="Email:",bg="#63bdea", font=("Arial", 12))
email_label.pack()
email_entry = tk.Entry(window1)
email_entry.pack()
password_label = tk.Label(window1, text="Password:",bg="#63bdea", font=("Arial", 12))
password_label.pack()
password_entry = tk.Entry(window1, show="*")
password_entry.pack()
create_profile_button = tk.Button(window1, text="Login", command=create_profile,bg="#57ffd1", font=("Arial", 12))
create_profile_button.pack(pady=20)
window1.mainloop()
def CAGUI():
def create_profile():
name = name_entry.get()
email = email_entry.get()
password = password_entry.get()
if not name:
messagebox.showwarning("Warning", "Filed(s) can't be Empty")
window.destroy()
return
if not email:
messagebox.showwarning("Warning", "Filed(s) can't be Empty")
window.destroy()
return
if not password:
messagebox.showwarning("Warning", "Filed(s) can't be Empty")
window.destroy()
return
DATA = "CA"+" name: "+name+" email: "+email+" password: "+password
client_socket.sendall(DATA.encode('utf-8'))
window.destroy()
window = tk.Tk()
window.configure(bg="#63bdea")
window.title("Blockchain Crypto Profile Creation")
window.geometry("400x200")
name_label = tk.Label(window, text="Name:",bg="#63bdea", font=("Arial", 12))
name_label.pack()
name_entry = tk.Entry(window)
name_entry.pack()
email_label = tk.Label(window, text="Email:",bg="#63bdea", font=("Arial", 12))
email_label.pack()
email_entry = tk.Entry(window)
email_entry.pack()
password_label = tk.Label(window, text="Password:",bg="#63bdea", font=("Arial", 12))
password_label.pack()
password_entry = tk.Entry(window, show="*")
password_entry.pack()
create_profile_button = tk.Button(window, text="Create Profile", command=create_profile,bg="#57ffd1", font=("Arial", 12))
create_profile_button.pack(pady=20)
window.mainloop()
def start_client():
button1.pack_forget()
global client_socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('192.168.219.219', 8000) # Replace with the server IP address
client_socket.connect(server_address)
print("Connected to the server.")
receive_thread = threading.Thread(target=receive_data, args=(client_socket,))
receive_thread.start()
button1.destroy()
display_message("Successfully Connected to Server!")
display_message("Please Choose Anyone from the Given Options")
button_create = tk.Button(root, text="Create Account",width=20, height=2, font=("Arial", 12), command=createAcc,bg="#00a38e")
button_create.place(x=300,y=300)
# Login button
button_login = tk.Button(root, text="Login into Existing Account",width=20, height=2, font=("Arial", 12), command=Login,bg="#aac6ff")
button_login.place(x=300,y=380)
button1 = tk.Button(root, text="Click To Connect to Server",width=20, height=2, font=("Arial", 12), command=start_client,bg="#57ffd1")
button1.place(x=250,y=250)
def call_another_gui_program():
window = tk.Tk()
window.configure(bg="#63bdea")
label1_transfer = tk.Label(window, text="Waiting For Conformation",font=("Arial", 20), fg="blue", bg="yellow")
label2_transfer = tk.Label(window, text="Transfer Successful",font=("Arial", 20), fg="white", bg="green")
label3_transfer = tk.Label(window, text="Transfer Unsuccessful",font=("Arial", 20), fg="white", bg="red")
def remove_items():
label1_transfer.place_forget()
label2_transfer.place_forget()
label3_transfer.place_forget()
def generate_random_number():
number = random.uniform(0, 10)
increment = random.choice([0.1, 0.2, 0.3])
decrement = random.choice([-0.1, -0.2, -0.3])
number += increment
number += decrement
return round(number, 2)
number_label = tk.Label(window, text="",font=("Arial", 20))
def update_number_label():
number = generate_random_number()
number_label.place(x=1100,y=10)
number_label.config(text="Current Bitcoin: "+str((3+number*0.001)),bg="#63bdea")
window.after(2000, update_number_label)
token_label = tk.Label(window,bg="#63bdea")
def generate_token():
update_number_label()
generate_button.pack_forget()
token = ''.join(random.choices(string.ascii_letters + string.digits, k=16))
token_label.config(text="Token: " + token)
transfer_button.place(x=500,y=250)
deposit_button.place(x=700,y=250)
check_currency_button.place(x=900,y=250)
def transfer():
remove_items()
label1_transfer.place(x=500,y=350)
def transfer_amount():
token_number = token_entry.get()
amount = amount_entry.get()
root.destroy()
client_socket.sendall(f"TF {token_number} {amount}".encode('utf-8'))
result = client_socket.recv(1024).decode('utf-8')
# label2_transfer.configure(text=result)
if(result=='Approved'):
label1_transfer.place_forget()
label3_transfer.place_forget()
label2_transfer.configure(text="Transfer Successful")
label2_transfer.place(x=500,y=350)
elif(result[0:6]=='Denied'):
label1_transfer.place_forget()
label2_transfer.place_forget()
label3_transfer.configure(text=f"Transfer Unsuccessful with reason: "+result[7:])
label3_transfer.place(x=500,y=350)
root = tk.Tk()
root.title("Token Transfer")
root.configure(bg="#63bdea")
# Set window size
window_width = 400
window_height = 200
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_coordinate = int((screen_width/2) - (window_width/2))
y_coordinate = int((screen_height/2) - (window_height/2))
root.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")
token_label = tk.Label(root, text="Desired Token Number:", font=("Arial", 12),bg="#63bdea")
token_label.pack(pady=10)
token_entry = tk.Entry(root)
token_entry.pack()
amount_label = tk.Label(root, text="Amount:", font=("Arial", 12),bg="#63bdea")
amount_label.pack()
amount_entry = tk.Entry(root)
amount_entry.pack()
transfer_button = tk.Button(root, text="Transfer", command=transfer_amount, font=("Arial", 13),bg="#57ddf1")
transfer_button.pack(pady=10)
root.mainloop()
def deposit():
remove_items()
# Create a label for displaying the selected option
label = tk.Label(window, text="Selected Option: ",font=("Arial", 20),bg="#63bdea")
label.place(x=650,y=350)
options = ["--Click Here--", "Via Bitcoin", "Via Bank Account"]
selected_option = tk.StringVar(window)
selected_option.set(options[0]) # Set the initial selected option
def on_option_selected(*args):
global select
selected = selected_option.get()
select = selected
label.config(text="Selected Option: " + selected,bg="#63bdea")
proceed_button.config(state=tk.NORMAL)
def run():
label1_transfer.place(x=500,y=350)
if(select == 'Via Bitcoin'):
label.place_forget()
option_menu.place_forget()
proceed_button.place_forget()
def deposit_button_click():
token_id = token_id_entry.get()
token_amount = token_amount_entry.get()
token_id_entry.delete(0, tk.END)
token_amount_entry.delete(0, tk.END)
window.destroy()
Data = "DP "+token_id+" "+token_amount
client_socket.sendall(Data.encode('utf-8'))
result = client_socket.recv(1024).decode('utf-8')
label2_transfer.configure(text=result)
if(result=='Approved'):
label1_transfer.place_forget()
label3_transfer.place_forget()
label2_transfer.configure(text="Deposit Successful")
label2_transfer.place(x=500,y=350)
elif(result[0:6]=='Denied'):
label1_transfer.place_forget()
label2_transfer.place_forget()
label3_transfer.configure(text=f"Deposit Unsuccessful with reason: "+result[7:])
label3_transfer.place(x=500,y=350)
window = tk.Tk()
window.configure(bg="#63bdea")
window.title("Deposit")
window.geometry("400x200")
token_id_label = tk.Label(window, text="Token ID:", font=("Arial", 12),bg="#63bdea")
token_id_label.pack()
token_id_entry = tk.Entry(window)
token_id_entry.pack()
token_amount_label = tk.Label(window, text="Token Amount:", font=("Arial", 12),bg="#63bdea")
token_amount_label.pack()
token_amount_entry = tk.Entry(window)
token_amount_entry.pack()
deposit_button = tk.Button(window, text="Deposit", command=deposit_button_click, font=("Arial", 12),bg="#57ffd1")
deposit_button.pack(pady=10)
window.mainloop()
elif(select == 'Via Bank Account'):
label.place_forget()
option_menu.place_forget()
proceed_button.place_forget()
def deposit_button_click():
token_id_entry.delete(0, tk.END)
token_amount_entry.delete(0, tk.END)
label.place_forget()
option_menu.place_forget()
proceed_button.place_forget()
token_id = token_id_entry.get()
token_amount = token_amount_entry.get()
window.destroy()
Data = "DP "+token_id+" "+token_amount
client_socket.sendall(Data.encode('utf-8'))
window = tk.Tk()
window.configure(bg="#63bdea")
window.title("Deposit")
window.geometry("400x200")
token_id_label = tk.Label(window, text="Bank ID:", font=("Arial", 12),bg="#63bdea")
token_id_label.pack()
token_id_entry = tk.Entry(window)
token_id_entry.pack()
token_amount_label = tk.Label(window, text="Token Amount:", font=("Arial", 12),bg="#63bdea")
token_amount_label.pack()
token_amount_entry = tk.Entry(window)
token_amount_entry.pack()
deposit_button = tk.Button(window, text="Deposit", command=deposit_button_click, font=("Arial", 12),bg="#57ffd1")
deposit_button.pack(pady=10)
window.mainloop()
option_menu = tk.OptionMenu(window, selected_option, *options, command=on_option_selected)
option_menu.place(x=650,y=400)
proceed_button = tk.Button(window, text="Proceed", state=tk.DISABLED,width=12, font=("Arial", 12), command=run,bg="#57ffd1")
proceed_button.place(x=800,y=400)
def check_currency():
pass
window.title("Blockchain Transaction")
window.geometry("430x400") # Set the window size
token_label.configure(font=("TkDefaultFont", 24))
token_label.place(x=550,y=10)
token_label.pack_forget()
generate_button = tk.Button(window, text="Generate Token",width=30, height=2, font=("Arial", 15), command=generate_token,bg="#57ffd1")
generate_button.pack(padx=700,pady=300)
transfer_button = tk.Button(window, text="Transfer",width=13, height=2, font=("Arial", 15), command=transfer,bg="#ffdead")
deposit_button = tk.Button(window, text="Deposit",width=13, height=2, font=("Arial", 15), command=deposit,bg="#ffdead")
check_currency_button = tk.Button(window, text="Check Currency",width=13, height=2, font=("Arial", 15), command=check_currency,bg="#ffdead")
style = ttk.Style()
style.configure('TButton', padding=5, relief="flat", background="#ccc")
window.attributes('-fullscreen', True)
def close_program():
window.destroy()
exit_button = tk.Button(window, text="Log Out",width=13, height=2, font=("Arial", 8), command=close_program,bg="#ffad9f")
exit_button.place(x=window.winfo_screenwidth() - 100, y=50)
window.mainloop()
def receive_data(sock):
while True:
data = "Message from server --> "+sock.recv(1024).decode('utf-8')
if not data:
break
display_message(data)
if(data == "Message from server --> Login Successful!"):
call_another_gui_program()
def send_data(event=None):
print("Sending Data")
def close_program():
root.destroy()
exit_button = tk.Button(root, text="Exit",width=10, height=2, font=("Arial", 8), command=close_program,bg="#ffad9f")
exit_button.place(x=root.winfo_screenwidth() - 80, y=50)
root.bind('<Return>', send_data)
root.mainloop()
optimize the code
|
3a7a21e64291c128c5ba069bc92fd6c0
|
{
"intermediate": 0.3701712191104889,
"beginner": 0.3990160822868347,
"expert": 0.23081260919570923
}
|
10,058
|
Fivem Scripting lua
how do i enable gta 5 stock police and set a wanted level so the police chase me
|
b4d1264688ea253eda8b6f6d5993fde6
|
{
"intermediate": 0.2912776470184326,
"beginner": 0.4211307764053345,
"expert": 0.2875915765762329
}
|
10,059
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import 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
}
})
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_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
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):
# 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
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
price = binance_futures.fetch_ticker(symbol)['askPrice'] # remove rounding here
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
price = binance_futures.fetch_ticker(symbol)['bidPrice'] # remove rounding here
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Set take profit and stop loss prices
if signal == 'buy':
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
return
else:
take_profit_price = None
stop_loss_price = None
else:
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
return
else:
take_profit_price = None
stop_loss_price = None
# Place order
order_params = {
"symbol": symbol,
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": 125
}
try:
response = binance_futures.fapiPrivatePostOrder(**order_params)
print(f"Order details: {response}")
except BinanceAPIException as e:
print(f"Error in order_execution: {e}")
time.sleep(1)
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)
time.sleep(0.1)
But I getting ERROR: 06/04/2023 07:53:24
BTC/USDT found in the market
The signal time is: 2023-06-04 07:53:32 :
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 237, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 196, in order_execution
if price is not None:
^^^^^
UnboundLocalError: cannot access local variable 'price' where it is not associated with a value
|
8b4b0ddba582d4ca2fbfb2493f946210
|
{
"intermediate": 0.5031484961509705,
"beginner": 0.33535489439964294,
"expert": 0.1614965945482254
}
|
10,060
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040' or method_id[-4:] == '5dda' or method_id[-4:] == '80f2'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
if contract_address:
print(f'New contract creation: Contract Address: {contract_address}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28269139 # Replace with your desired starting block number
block_end = 28269141 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Modify the code above so that it also looks for contracts in which the To column displays not only Null, but also UNCX Network
|
8bb03c0caf952bc7c662abd3831c6c44
|
{
"intermediate": 0.3325138986110687,
"beginner": 0.4363502860069275,
"expert": 0.23113584518432617
}
|
10,061
|
#pragma once
class EventSystemBase
{
public:
virtual ~EventSystemBase() {}
}
template<typename... Events>
class EventSystem : public EventSystemBase
{
}
class EventBus
{
};
class EventBase
{
public:
virtual ~ComponentBase() {}
virtual void DestroyData(unsigned char* data) const = 0;
virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0;
virtual void ConstructData(unsigned char* data) const = 0;
virtual std::size_t GetSize() const = 0;
};
class Component : public ComponentBase
{
public:
virtual void DestroyData(unsigned char* data) const override;
virtual void MoveData(unsigned char* source, unsigned char* destination) const override;
virtual void ConstructData(unsigned char* data) const override;
virtual size_t GetSize() const override;
static size_t GetTypeID();
};
struct onCollisionEvent {
float x;
float y;
}; Can you finish creating an event system that integrates with an event bus? This is a very rough outline.
|
3da5706319f9f811322b621a82954d00
|
{
"intermediate": 0.310278981924057,
"beginner": 0.5181774497032166,
"expert": 0.17154361307621002
}
|
10,062
|
make discord bot write a message in server channel
|
65b776104d89b3da658dbd45a53a4518
|
{
"intermediate": 0.39329496026039124,
"beginner": 0.21349181234836578,
"expert": 0.3932132124900818
}
|
10,063
|
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_transaction_by_hash(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionByHash&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result']
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] == '0x863b49ae97c3d2a87fd43186dfd921f42783c853':
token_tx = await get_transaction_by_hash(tx['hash'])
if token_tx:
print(f"New token transfer: Token Address: {token_tx['from']}")
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28269139 # Replace with your desired starting block number
block_end = 28269141 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Change the code above so that instead of the address that is in the From line, it displays the addresses of token contracts that are located on the Tokens Transferred tab under the For link
|
7b055ae98ae8c9bdbb77f97c5605929b
|
{
"intermediate": 0.29634958505630493,
"beginner": 0.5299841165542603,
"expert": 0.1736663281917572
}
|
10,064
|
Write a program code that will return transactions from processed blocks on the site https://bscscan.com/. Use APIKey. Transactions are in the Contract Internal Transactions tab
|
fa73e153a079aacad8244c60727ad305
|
{
"intermediate": 0.5622023940086365,
"beginner": 0.15228411555290222,
"expert": 0.2855135202407837
}
|
10,065
|
make discord bot loop on checking if a twitch channel is live, if so, send a message in a discord channel in python
|
4c5bcd36babeb1c4c0ef57a7e6a433d2
|
{
"intermediate": 0.3041926920413971,
"beginner": 0.410946249961853,
"expert": 0.28486108779907227
}
|
10,066
|
Unable to resolve "./components/FutureMK" from "app\Navigation.js" react native, why is that? i have all imported
|
77996771f77f299188d6fccb923dc6bb
|
{
"intermediate": 0.5101862549781799,
"beginner": 0.2793916165828705,
"expert": 0.21042214334011078
}
|
10,067
|
Write a program code that will return a set of transactions from processed blocks on the site https://bscscan.com/, which are located in the Contract Internal Transactions tab. Must return contracts from the To column where the value of the Type column is create. Use APIKey.
|
dfe817ffa4e873c3592e97e9a3e7f55e
|
{
"intermediate": 0.6093191504478455,
"beginner": 0.12706194818019867,
"expert": 0.2636188268661499
}
|
10,068
|
Create animated progress bar with gradient in react native
|
bdb8564353e4452f54fce7f825db4dc5
|
{
"intermediate": 0.38024523854255676,
"beginner": 0.1483602076768875,
"expert": 0.4713945686817169
}
|
10,069
|
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном диапазоне блоков (Обрабатывет множество блоков)
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
if contract_address:
print(f'New contract creation: Contract Address: {contract_address}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Change the code above so that instead of the async def get_external_transactions(block_number) method, which returns the addresses in the Transactions tab, it returns the addresses that are in the Contract Internal Transactions tab
|
2c969d879970273204a6eb830348fbc2
|
{
"intermediate": 0.39617377519607544,
"beginner": 0.4186747372150421,
"expert": 0.18515151739120483
}
|
10,070
|
import { Text, View, Pressable, TextInput, Alert, ScrollView} from ‘react-native’;
import Header from ‘…/components/Header’;
import Footer from ‘…/components/Footer’;
import { gStyle } from ‘…/styles/style’;
import React, {useState} from ‘react’;
export default function Registration() {
const [name, setName] = useState(‘’);
const [surname, setSurname]=useState(‘’);
const [email, setEmail] = useState(‘’);
const [phone, setPhone] = useState(‘’);
const [password, setPassword] = useState(‘’);
const [confirmPassword, setConfirmPassword]=useState(‘’);
return (
<View>
<ScrollView>
<Header/>
<View style={gStyle.main}>
<Text style={gStyle.header}>Зарегистрироваться</Text>
<Text style={gStyle.RegLine}></Text>
<View style={gStyle.RegContainer}>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Имя</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setName(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Фамилия</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setSurname(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Электронная почта</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setEmail(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Номер телефона</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setPhone(text)}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Пароль</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setPassword(text)}
secureTextEntry={true}/>
</View>
<View style={gStyle.RegBox}>
<Text style={gStyle.RegName}>Подтверждение пароля</Text>
<TextInput style={gStyle.RegInfo}
onChangeText={text => setConfirmPassword(text)}
secureTextEntry={true}/>
</View>
</View>
<Pressable style={gStyle.RegRegistrBtn} onPress={()=>{}}>
<Text style={gStyle.RegRegistration}>Зарегистрироваться</Text>
</Pressable>
<Text style={gStyle.RegConf}>Нажимая на кнопку, Вы соглашаетесь с{‘\n’}Политикой конфиденциальности</Text>
<Text style={gStyle.RegLine}></Text>
</View>
<Footer/>
</ScrollView>
</View>
);
}
i have this code in my Registration.js so i need to write function to register user in db firebase, but also it must contain not only email and password but name, surname, phone and confirm password as well, and if password is not like confirm password there will be alert and if some field null there will be also alert. Can u help me with this, please?
|
b2d5cc5c24bd3f3d90777710c117cf74
|
{
"intermediate": 0.35568690299987793,
"beginner": 0.3765946924686432,
"expert": 0.26771843433380127
}
|
10,071
|
Error: You attempted to use a firebase module that's not installed on your Android project by calling firebase.app().
Ensure you have:
1) imported the 'io.invertase.firebase.app.ReactNativeFirebaseAppPackage' module in your 'MainApplication.java' file.
2) Added the 'new ReactNativeFirebaseAppPackage()' line inside of the RN 'getPackages()' method list.
See http://invertase.link/android for full setup instructions., js engine: hermes
what should i do? i installed firebase as u told
|
5d3849b46d648bc72fc9f4387cede19a
|
{
"intermediate": 0.6283185482025146,
"beginner": 0.19336003065109253,
"expert": 0.17832142114639282
}
|
10,072
|
Unable to resolve "firebase/app" from "App.js"
What do i need to do? I just prebuilt my project and this err came
|
d50934d39d539968a3ba9ba8d96dec85
|
{
"intermediate": 0.6283945441246033,
"beginner": 0.20058071613311768,
"expert": 0.17102468013763428
}
|
10,073
|
how to change regular type def input_spec():
return (
tf.TensorSpec([None, X_train.shape[1]], tf.float64),
tf.TensorSpec([None], tf.int64)
)
def build_model():
final_model = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=(X_train.shape[1],)),
tf.keras.layers.Dense(100, activation='relu',kernel_regularizer=regularizers.l1(0.01)),
tf.keras.layers.Dense(64, activation='relu',kernel_regularizer=regularizers.l1(0.01)),
tf.keras.layers.Dense(32, activation='relu',kernel_regularizer=regularizers.l1(0.01)),
tf.keras.layers.Dense(16, activation='relu',kernel_regularizer=regularizers.l1(0.01)),
tf.keras.layers.Dense(1, activation='sigmoid'),
])
|
47be0da507a04823efce92ca678ea945
|
{
"intermediate": 0.2736887037754059,
"beginner": 0.18978706002235413,
"expert": 0.5365241765975952
}
|
10,074
|
#include <stdio.h> #include<stdlib.h> #include<time.h> void input(int *&a,int & n); void output(int *a,int n); void HeapAdjust(int* a,int s,int m) ; void HeapSort(int *a,int n); int main () { int i,n,m; int *a = NULL; input (a,n); HeapSort (a,n) ; free(a); return 0; }void input(int *&a,int & n) { int i; scanf("%d",&n); if((a=(int *) malloc (n*sizeof(int)))==NULL) { printf("不能成功分配内存单元\n"); exit(0); } for(i=0;i<n;i++) { scanf("%d",&a[i]); } } void output(int *a,int n) { int i; for(i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); }void swap(int &a, int &b) { int t; t=a;a=b;b=t; } /**********定义函数**********/ /********** Begin **********/ void HeapAdjust(int* a,int s,int m){ int j,rc=a[s]; for(j=2*s;j<=m;j*=2) { if(j<m&&a[j]<a[j+1]) ++j; if(rc>=a[j]) break; a[s]=a[j]; s=j; } a[s]=rc; for(j=0;j<m;j++){ printf("%d ",a[j]); } printf("\n"); }void HeapSort(int *a,int n){ int i; for(i=n/2;i>0;--i){ HeapAdjust(a,i,n); }}/********** End **********/问题是什么?
|
dc1309dd99a29c67bf6627679c92c7e6
|
{
"intermediate": 0.3199606239795685,
"beginner": 0.5299344062805176,
"expert": 0.15010496973991394
}
|
10,075
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Here is a portion of code from Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandBuffers();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
I am getting the following error:
Calling vkBeginCommandBufferà
vkBeginCommandBuffer calledà
UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer(ERROR / SPEC): msgNum: 653100552 - Validation Error: [ UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer ] Object 0: handle = 0x3fbcd60000000028, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xb12fb2000000002c, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; Object 2: handle = 0x144f08a6d40, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x26ed8608 | You are adding vkCmdEndRenderPass to VkCommandBuffer 0x144f08a6d40[] that is invalid because bound VkBuffer 0x3fbcd60000000028[] was destroyed.
Objects: 3
[0] 0x3fbcd60000000028, type: 9, name: NULL
[1] 0xb12fb2000000002c, type: 23, name: NULL
[2] 0x144f08a6d40, type: 6, name: NULL
Do you know what could be causing it and how to adjust the code to fix it?
|
71f0a4cb62e45424e4726cdf7642e287
|
{
"intermediate": 0.44641023874282837,
"beginner": 0.3242754340171814,
"expert": 0.22931434214115143
}
|
10,076
|
I need to write a vba code That will cut the following file 'Due Checks.csv' from this address
C:\Users\HP\Downloads\Due Checks.csv
and paste into this folder
G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS
automatically overwriting any same named file, without any prompts
|
cc8b134ec67ba88be48b5f16dcaf62ee
|
{
"intermediate": 0.45070454478263855,
"beginner": 0.23783598840236664,
"expert": 0.3114594519138336
}
|
10,077
|
i want you to look at this code below and see if this code address these issues now
"For example, community 7 in HTTML is a 'nan community In addition, I can not find the total number of nodes in the whole graph to compare it with the number of unique edges The Eigenvector Centrality is given for nodes not in the main list (100 users) while it is my target
below is the code
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import community as community_louvain
data = pd.read_csv("cleaned_data.csv")
# Select the first 15 users as main users
main_users = data["User"][:15]
G = nx.DiGraph()
for user in main_users:
G.add_node(user, main_user=True)
for i in range(len(data)):
user = data.iloc[i]["User"]
followers = data.iloc[i]["Followers"].split(",")
following = data.iloc[i]["Following"].split(",")
if followers[0] != 'nan' and followers[0] != '':
for follower in followers:
G.add_edge(follower, user)
if not G.has_node(follower):
G.add_node(follower, main_user=False)
else:
G.add_node(f"user_{i}", main_user=False)
if following[0] != 'nan' and following[0] != '':
for follow in following:
G.add_edge(user, follow)
if not G.has_node(follow):
G.add_node(follow, main_user=False)
else:
G.add_node(f"user_{i+len(data)}", main_user=False)
# Check if 'nan' node exists before removing
if 'nan' in G:
G.remove_node('nan')
# Create a PNG visualization of the main graph
plt.figure(figsize=(30, 20))
pos = nx.circular_layout(G)
node_colors = ['red' if 'main_user' in G.nodes[node] and G.nodes[node]['main_user'] else 'skyblue' for node in G.nodes]
nx.draw_networkx(G, pos, with_labels=True, node_color=node_colors, edge_color='gray', node_size=24000, font_size=12)
plt.tight_layout()
plt.savefig("graph.png")
plt.close()
# Calculate Eigenvector Centrality for the main users
eigenvector_centrality = nx.eigenvector_centrality(G)
# Remove the temporary nodes and edges
for i in range(len(data)):
if G.has_node(f"user_{i}"):
G.remove_node(f"user_{i}")
if G.has_node(f"user_{i+len(data)}"):
G.remove_node(f"user_{i+len(data)}")
# Perform community detection using Louvain algorithm
partition = community_louvain.best_partition(G.to_undirected())
main_user_communities = set(partition[user] for user in main_users)
# Visualize subgraphs by community
graphs_data = []
for community_num in main_user_communities:
subgraph_nodes = [node for node in G.nodes if partition[node] == community_num]
subgraph = G.subgraph(subgraph_nodes)
plt.figure(figsize=(25, 15))
pos = nx.kamada_kawai_layout(subgraph)
node_colors = ['red' if 'main_user' in subgraph.nodes[node] and subgraph.nodes[node]['main_user'] else 'skyblue' for node in subgraph.nodes]
nx.draw_networkx(subgraph, pos, with_labels=True, node_color=node_colors, edge_color='gray', node_size=19000, font_size=11)
plt.tight_layout()
plt.savefig(f"graph_community_{community_num}.png")
plt.close()
graph_data = {
'Community': community_num,
'Nodes': subgraph.number_of_nodes(),
'Edges': subgraph.number_of_edges(),
'Density': nx.density(subgraph),
}
graphs_data.append(graph_data)
# Calculate graph metrics
total_nodes = G.number_of_nodes()
number_of_edges = G.number_of_edges()
unique_edges = G.size(weight="weight")
eigenvector_centrality_main_users = {node: centrality for node, centrality in eigenvector_centrality.items() if node in main_users}
# Print graph metrics
print("Total Number of Nodes:", total_nodes)
print("Number of Edges:", number_of_edges)
print("Unique Edges:", unique_edges)
print("Eigenvector Centrality (Main Users):", eigenvector_centrality_main_users)
# Save graphs and metrics data to CSV files
graphs_df = pd.DataFrame(graphs_data)
graphs_df.to_csv('graphs_data.csv', index=False)
metrics_data = {
'Total Number of Nodes': total_nodes,
'Number of Edges': number_of_edges,
'Unique Edges': unique_edges,
'Eigenvector Centrality (Main Users)': eigenvector_centrality_main_users,
}
metrics_df = pd.DataFrame([metrics_data])
metrics_df.to_csv('metrics_data.csv', index=False)
|
5a581459b94bc8a1ce4abd31ae547e9d
|
{
"intermediate": 0.3158065676689148,
"beginner": 0.35623490810394287,
"expert": 0.32795849442481995
}
|
10,078
|
Android Bundling failed 69ms
Unable to resolve "firebase/app" from "App.js"
|
335b6b19ace8322a970f1f668920bbd7
|
{
"intermediate": 0.4821840822696686,
"beginner": 0.2971130609512329,
"expert": 0.2207028567790985
}
|
10,079
|
I have tried -8 times ssh key but Git Bash is giving this error: Load key "/c/Users/user/.ssh/id_rsa.pub": invalid format
<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>: Permission denied (publickey,gssapi-keyex,gssapi-with-mi
c).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
|
5b63f63111440abd92894640d9c7410c
|
{
"intermediate": 0.3627576231956482,
"beginner": 0.32090193033218384,
"expert": 0.31634044647216797
}
|
10,080
|
thats my app.js
import firebase from ‘firebase/app’;
import { Navigation } from ‘./app/Navigation’;
import * as Font from ‘expo-font’;
import { useState } from ‘react’;
import AppLoading from ‘expo-app-loading’;
import ‘@react-native-firebase/auth’;
import ‘@react-native-firebase/database’;
import { firebaseConfig } from ‘./app/DB/FirebaseConfig’;
import { SafeAreaView } from ‘react-native’;
firebase.initializeApp(firebaseConfig);
const fonts = ()=> Font.loadAsync({
‘multi’:require(‘./app/assets/fonts/MultiroundPro.otf’),
‘yu-reg’:require(‘./app/assets/fonts/YuGothicUIRegular.ttf’),
‘yu-semibold’:require(‘./app/assets/fonts/YuGothicUISemibold.ttf’)
});
export default function App() {
const [font, setFont]=useState(false);
if(font){
return (
<SafeAreaView style={{ flex: 1 }}>
<Navigation/>
</SafeAreaView>
);
}else{
return(
<AppLoading startAsync={fonts} onFinish={()=>setFont(true)} onError={console.warn}/>
)
}
};
thats FirebaseConfig
import firebase from “firebase/app”
import “firebase/auth”;
import “firebase/database”;
import ‘firebase/firestore’;
const firebaseConfig = {
apiKey: ‘AIzaSyD3x41FYcVOfyzfrb93gODDTHSgNa0Yq40’,
authDomain: ‘whiterose-6b31f.firebaseapp.com’,
projectId: ‘whiterose-6b31f’,
storageBucket: “whiterose-6b31f.appspot.com”,
messagingSenderId: ‘6427461933’,
appId: ‘1:6427461933:ios:012616b0414b2ac36c6ba4’,
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
thats app.json
{
“expo”: {
“name”: “whiteRose”,
“slug”: “whiteRose”,
“version”: “1.0.0”,
“orientation”: “portrait”,
“icon”: “./app/assets/icon.png”,
“userInterfaceStyle”: “light”,
“splash”: {
“image”: “./app/assets/splash.png”,
“resizeMode”: “contain”,
“backgroundColor”: “#ffffff”
},
“assetBundlePatterns”: [
“**/*”
],
“ios”: {
“googleServicesFile”: “./GoogleService-Info.plist”,
“supportsTablet”: true,
“bundleIdentifier”: “white.rose”
},
“android”: {
“googleServicesFile”: “google-services.json”,
“adaptiveIcon”: {
“foregroundImage”: “./app/assets/adaptive-icon.png”,
“backgroundColor”: “#ffffff”
},
“package”: “white.rose”
},
“web”: {
“favicon”: “./app/assets/favicon.png”
},
“plugins”: [
“@react-native-firebase/app”,
[
“expo-build-properties”,
{
“ios”: {
“useFrameworks”: “static”
}
}
]
],
“extra”: {
“eas”: {
“projectId”: “098b744d-d49b-4f2c-91fd-8e04e64ca6c2”
}
}
}
}
|
d2cbe12270b7ac6f24cdd1e89ea63554
|
{
"intermediate": 0.2939542531967163,
"beginner": 0.4737054705619812,
"expert": 0.2323402464389801
}
|
10,081
|
I have a range of columns that are continously being added to.
The range is column B to E.
Row 1 is my Header
Column B is for date entries.
Is there a VBA code that can sort the table range below the header
so that the Date value is from Oldest to Newest
|
2f3e46722b5fbc42fffa6d89aaeb21c9
|
{
"intermediate": 0.4661654829978943,
"beginner": 0.2350628823041916,
"expert": 0.29877161979675293
}
|
10,082
|
hi
|
3a8339367692d68148ba626d4af2d558
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
10,083
|
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 = 28496140 # Replace with your desired start block
end_block = 28496140 # Replace with your desired end block
display_new_contracts(start_block, end_block)
Modify the above code to display addresses in the To column that have a type column equal to create
|
1494a073488dfeb5f7250544d466aff0
|
{
"intermediate": 0.4645857512950897,
"beginner": 0.33941057324409485,
"expert": 0.19600366055965424
}
|
10,084
|
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
}
})
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_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
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', 133920)
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', 133920)
def order_execution(symbol, signal, step_size, leverage):
# 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
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)
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)
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
# Round the price variable
try:
price = round_step_size(price, step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
return
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Set take profit and stop loss prices
# Set take profit and stop loss prices
if signal == 'buy':
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
else:
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
# Place order
order_params = {
"symbol": symbol,
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": 100
}
try:
response = binance_futures.fapiPrivatePostOrder(**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', 133920) # 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)
time.sleep(0.1)
But I getting ERROR: BTC/USDT found in the market
The signal time is: 2023-06-04 13:02:22 :
Error rounding price: cannot access local variable 'price' where it is not associated with a value
|
91ac2bcd4f31a580faf0c6ae9a6b3326
|
{
"intermediate": 0.5100780129432678,
"beginner": 0.3374444544315338,
"expert": 0.15247753262519836
}
|
10,085
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Here is a portion of code from Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandBuffers();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
I am getting the following error:
VUID-vkFreeCommandBuffers-pCommandBuffers-00048(ERROR / SPEC): msgNum: 515182009 - Validation Error: [ VUID-vkFreeCommandBuffers-pCommandBuffers-00048 ] Object 0: handle = 0x2c39c604970, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x1eb50db9 | Invalid VkCommandBuffer 0x2c39c604970[]. The Vulkan spec states: pCommandBuffers must be a valid pointer to an array of commandBufferCount VkCommandBuffer handles, each element of which must either be a valid handle or NULL (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkFreeCommandBuffers-pCommandBuffers-00048)
Objects: 1
Do you know what could be causing it and how to adjust the code to fix it?
|
f401e05bb413c0b4e619982961373207
|
{
"intermediate": 0.4101669192314148,
"beginner": 0.33082178235054016,
"expert": 0.25901132822036743
}
|
10,086
|
"TimeLabel = importTime('Book1.xlsx');
Data = importData('Book1.xlsx');
nDays = 38064;
TimeLabel = TimeLabel(1:nDays);
Data = Data(1:nDays);"
expand the code to create time series data from TimeLabel and Data
|
57b53166b97e445fee5a045e425d58b6
|
{
"intermediate": 0.5888614654541016,
"beginner": 0.22210125625133514,
"expert": 0.1890372931957245
}
|
10,087
|
The argument type 'QrImage' can't be assigned to the parameter type 'Widget? flutter
|
12995bf2543b54c81b05aa55edc3b67a
|
{
"intermediate": 0.5014796853065491,
"beginner": 0.21921880543231964,
"expert": 0.2793015241622925
}
|
10,088
|
java code to detect number of tracks in a midi file and delete all tracks except the first , using java midi
|
721221de7ac20c89bdc38a65001fb1b9
|
{
"intermediate": 0.5250117778778076,
"beginner": 0.09577146917581558,
"expert": 0.3792167901992798
}
|
10,089
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Here is a portion of code from Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1cb94a23410, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_IMAGE; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1cb94a23410[], VkImage 0xb097c90000000027[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1cb94a23410, type: 3, name: NULL
[1] 0xb097c90000000027, type: 10, name: NULL
Do you know what could be causing it and how to adjust the code to fix it?
|
6dae68451f914fe0864cc88b30c2c950
|
{
"intermediate": 0.4101669192314148,
"beginner": 0.33082178235054016,
"expert": 0.25901132822036743
}
|
10,090
|
Make a c# .net framework web api that retrieves data from an ms crm, the name of the entity is alfa_shipmentorder, the names of the fields in the crm start with alfa_
CRMAccountId long Yes CustomerID of
your corporate
PickupType Int Yes
0 client will give items
himself to POS
1 to be picked up
RequestTypeId Int Yes
Request delivery
type of package
(returned or not)
Package Delivery = 1,
Reverse Logistic = 2
CustomerName String Yes
The receiver name
who will receive
the items
Max Length = 50
CustomerMobileNumber String Yes
The receiver
mobile who will
receive the items
Max Length = 15
Min Length = 10
(numbers only)
SenderName String Yes
The person
delegated by your
corporate to send
these items
Max Length = 50
SenderMobileNumber String Yes
The person
delegated by your
corporate to send
these items
Max Length = 15
Min Length = 10
(numbers only)
Items List<UPDSItem> Yes
List of UPDSItem
with address
details of each one
(from where and
to where)
1.2.1. UPDSItem properties:
Property Name Type Mandatory Description Comment
ReferenceId String Yes
Your item identifier
Unique value per
CRMAccountId Attribute
PaymentType int Yes
Cash on delivery or not
If PickupType = 0
PaymentType must be = 1
1 paid
2 Cash on delivery
ContentPrice decimal Yes Price of the content Maxlength = 6
Decimal(8,3)
ContentDescription String Yes Description of the content
UPDS Integration Services (APIs) Guide Page 7
Weight decimal Yes
decimal (8,3) in
GM Maximum 30
KG
BoxLength int No Mandatory in case of Item
Type is parcel only Centimetre (cm)
BoxWidth int No Mandatory in case of Item
Type is parcel only Centimetre (cm)
BoxHeight int No Mandatory in case of Item
Type is parcel only Centimetre (cm)
DeliveryCost decimal No decimal(8,3) cost of delivery
cost in SAR
maximum is
99999.999
TotalAmount decimal Conditional
Mandatory if
PaymentType = 2
decimal(8,3)
Total amount of
COD in SAR,
maximum is
99999.999
SenderAddressDetail object Yes Object of
ItemCustomerDetails
Where to pick
from
Review 1.2.2
ReceiverAddressDetail object Yes Object of
ItemCustomerDetails
Where to deliver
Review 1.2.2
PiecesCount int No
Number of pieces in the
same item which related to
each other
mandatory when
you send data in
ItemPieces List
ItemPieces List<ItemPiece> No list of pieces related to the
item
mandatory when
you send data in
PiecesCount and
ItemPieces list
count should be
(PiecesCount - 1)
UPDS Integration Services (APIs) Guide Page 8
1.2.2. ItemCustomerDetails properties: (Address details of (from) and (to))
Property Name Type Mandatory Description Comment
AddressTypeID string Yes
1- NationalAddress = 2
ParcelStation = 3
Office = 4
InternationalAddress=5
InternalDescriptive = 6
MapCoordinates = 7
ShortAddress = 10
For required fields per
AddressType
Latitude string Conditional
Longitude string Conditional
BuildingNo int Conditional
Building Number
Mandatory if
AddressTypeID = 2
Must be 4 numbers
UnitNo int Conditional
Unit Number
Mandatory if
AddressTypeID = 2
Max = 4 numbers
AdditionalNo int Conditional
Additional Number
Mandatory if
AddressTypeID = 2
Must be 4 numbers
ZipCode int Conditional
Zip Code
Mandatory if
AddressTypeID = 2
Must be 5 numbers
FinalOfficeID int Conditional Mandatory If
AddressTypeID = 3 or 4
API:
Address Type = Office:
[URL]/ServiceProvider/GetPostalO
fficeByCity
Address Type = Parcel Station:
[URL]/ServiceProvider/GetParcelSt
ationByCity
LocationId string Yes City ID API: [URL]/GIS/GetCitiesByRegion
DistrictID Int No District ID API: [URL]/GIS/GetDistricts
AddressLine1 string Conditional Mandatory if
AddressTypeID = 6 Max = 100
AddressLine2 string Conditional Mandatory if
AddressTypeID = 6 Max = 100
CountryID int Conditional Mandatory if
AddressTypeID = 5 API: [URL]/Location/GetCountries
ShortAddress String Conditional Mandatory if
AddressTypeID = 10
DistributionDirectorateId Int Optional Posta distribution point ID
UPDS Integration Services (APIs) Guide Page 9
1.2.3. ItemPiece properties:
Property Name Type Mandatory Description Comment
PieceWeight decimal Yes Piece weight must be greater than 0 and less than
or equal 30
PiecePrice decimal No Piece price can’t be negative number
decimal (8,3)
PieceBarcode string No Barcode of piece will be filled
in the response don’t set it.
PieceDescription string Yes Piece description PieceDescription is required and must
be less than 500 charachter
1.3. Output Response
Property Name Type Mandatory Description Comment
Items List Yes List of UPDSItemResponse
Status Int Yes 1 success 2 an error occurred
Message String Yes success or an error occurred
1.3.1. UPDSItemResponse properties:
Property Name Type Mandatory Description Comment
ReferenceId string Yes
ItemStatus int Yes 1 success else types of errors
Message string Yes
Barcode string Yes
1.3.2. Address Types for the Sender with the required fields
AddressTypeID AddressTypeName Required Fields
2 National Address
BuildingNo
UnitNo
AdditionalNo
ZipCode
UPDS Integration Services (APIs) Guide Page 10
LocationID
3 Parcel Station
FinalOfficeID
LocationID
4 Office
FinalOfficeID
LocationID
6 InternalDescriptive
AddressLine1
AddressLine2
LocationID
7 MapCoordinates
Latitude
Longitude
LocationID
1.3.3. Address Types for the Receiver with the required fields
AddressTypeID AddressTypeName Required Fields
2 National Address
BuildingNo
UnitNo
AdditionalNo
ZipCode
LocationID
3 Parcel Station
FinalOfficeID
LocationID
4 Office
FinalOfficeID
LocationID
6 InternalDescriptive
AddressLine1
AddressLine2
LocationID
7 MapCoordinates
Latitude
Longitude
LocationID
5 InternationalAddress
AddressLine1
AddressLine2
CountryID
UPDS Integration Services (APIs) Guide Page 11
10 Short Address ShortAddress
1.3.4. Message Validations
Status Message
0 Unfortunately, Number of valid items is 0
1 success
2 an error occurred
3 invalid object
4 No items sent
5 property is required
6 property length is more than max length
7 mail syntax error
8
mobile syntax error
enter valid mobile number: numerical, maximum 15 and minimum 10
9 Pick Type should be 0 for POS or 1 for getting Picked by System
10 failure to commit valid items
11 N items accepted and committed out of N, [N Failed N Already Exists N are invalid]
12 Invalid CRMAccountID: Unregistered Client CRM Account ID
13 Invalid CRMAccountID: inactivated Client Request Account
ItemStatus Message
1 Success
4 Customer locationId Unrecognized
5 Sender OfficeId Unrecognized
5 Country Id is required with External Items
5 Country Id should not be 21 for External items
5 Decimal value has max length 3 digit after point
5 ZipCode is required and length should be 5
5 BuildingNumber is required and length should be 4
5 AdditionalNumber is required and length should be 4
5 UnitNumber is required with maximum length 4
5 OfficeID is required
5 AddressLine1 is required with max length 100
5 AddressLine2 is required with max length 100
5 Sender address cannot be International
UPDS Integration Services (APIs) Guide Page 12
5 LocationID is required
5 Item ReferenceId is null(required) or Duplicated among same Request
5 Item Weight range must be more than 0 and maximum is 30 kg
5 Item RequestAccountCustomerDetail is null(required)
5
Item.RequestAccountCustomerDetail.AddressTypeId:NationalAddress = 2, ParcelStation =
3, Office = 4, InternalDescriptive = 6
5 Item.ItemCustomerDetail is null (required)
5
Item.ItemCustomerDetail.AddressTypeID:NationalAddress = 2, ParcelStation = 3, Office =
4, InternationalAddress = 5, InternalDescriptive = 6
5 Payment Type should be 1 for Paid or 2 for CashOnDelivery
5 suspended temporarily
5 Payment type Cash on delivery not allowed with external Item
5 Payment type Cash on delivery not allowed with POS Items
5 Latitude is required with max length 50
5 Longitude is required with max length 50
5 Item referenceId is null(required) or Duplicated among same Request
5 ItemBarcode is required (if store is allowed to in setting)
5
ItemBarcode does not match the barcode store pattern (if store is allowed to pass
barcode)
5 ItemBarcode duplicated among the request (if store is allowed to pass barcode in setting)
5
Sending a predefined barcode is not allowed with external item (if store is allowed to
pass)
5 (Return denied) Item.ReceiverAddressDetail.AddressTypeId : NationalAddress = 2
5 (Return denied) Item.SenderAddressDetail.AddressTypeId: Office = 4
6 Item ContentPriceVAT maximum length is 99999.999
6 Item DeliveryCost maximum length is 99999.999
6 Item DeliveryCostVAT maximum length is 99999.999
6 Item TotalAmount maximum length is 99999.999
6 Item CustomerVAT maximum length is 99999.999
6 Item SaudiPostVAT maximum length is 99999.999
6 Receiver OfficeId Unrecognized
8 Receiver locationId Unrecognized
9 Duplicate Referenceid, succeeded for same CRMAccountId before.
10 Receiver Country locationId Unrecognized
11 Receiver OfficeId type is not parcel station
12 Sender OfficeId type is not parcel station
13 Receiver OfficeId(parcel) does not belong to Receiver location id
14 Sender OfficeId(parcel) does not belong to Sender location id
15 Sender OfficeId with addressTypeID = 4 shouldn’t be parcel station
UPDS Integration Services (APIs) Guide Page 13
16 Receiver OfficeId with addressTypeID = 4 shouldn’t be parcel station
17 Sender OfficeId(Office) does not belong to Sender location id
18 Receiver OfficeId(Office) does not belong to Receiver location id
19 Item Couldnot be inserted at PreAdvice (MsgCode: "MsgCode", MsgDesc: "MsgDesc")
32 (Return denied) Receiver national address doesn't match with account national address.
UPDS Integration Services (APIs) Guide Page 14
1.4. Example
Request payload
{
"CRMAccountId": 123456,
"PickupType": 1,
"RequestTypeId": 1,
"CustomerName": "Customer Name",
"CustomerMobileNumber": "0543941021",
"SenderName": "Sender Name",
"SenderMobileNumber": "0543941021",
"Items": [{
"ReferenceId": "1234",
"PaymentType": 1,
"ContentPrice": 123.123,
"ContentDescription": "No Description",
"Weight": 11.25,
"BoxLength": 10.56,
"BoxWidth": 12.44,
"BoxHeight": 13.3,
"DeliveryCost": 10,
"TotalAmount": 123.132,
"SenderAddressDetail": {
"AddressTypeID": 2,
"LocationId": 3,
"buildingNo": 3957,
"unitNo": 1,
"additionalNo": 7414,
"zipCode": 13253,
},
"ReceiverAddressDetail": {
"AddressTypeID": 6,
"LocationId": 3,
"AddressLine1": "sample string 10",
"AddressLine2": "sample string 11",
“DistrictId”:540
}
}]
}
UPDS Integration Services (APIs) Guide Page 15
Response
{
"Items": [{
"ReferenceId": "1234",
"ItemStatus": 1,
"Message": "Success",
"Barcode": "CRDSAL0000117419",
"ItemPiecesResponse": null
}],
"Status": 11,
"Message": "Success"
}
1.4.1. Address Details Example
NationalAddress "ReceiverAddressDetail": {
"AddressTypeID": 2,
"BuildingNo": 4000,
"UnitNo": 20,
"AdditionalNo": 3000,
"ZipCode": 12345,
"LocationId": 3,
}
InternalDescriptive "ReceiverAddressDetail": {
"AddressTypeID": 6,
"LocationId": 3,
“DistrictId”: 540
"AddressLine1": "sample string 10",
"AddressLine2": "sample string 11",
}
MapCoordinates "ReceiverAddressDetail": {
"AddressTypeID": 7,
"Latitude": "24.6544212",
"Longitude": "48.254425",
"LocationId": 3
}
Office "ReceiverAddressDetail": {
"AddressTypeID": 4,
"LocationId": 3,
"FinalOfficeID": 20300
}
ParcelStation "ReceiverAddressDetail": {
"AddressTypeID": 3,
"LocationId": 1,
"FinalOfficeID": 220723
}
InternationalAddress "ReceiverAddressDetail": {
"AddressTypeID": "5",
UPDS Integration Services (APIs) Guide Page 16
"CountryID": 3,
"AddressLine1": "sample string 10",
"AddressLine2": "sample string 11"
}
ShortAddress "ReceiverAddressDetail": {
"AddressTypeID": 10,
"ShortAddress": "RUMD3957"
}
|
6381f994682cdabea598502a8eb4747c
|
{
"intermediate": 0.3635196089744568,
"beginner": 0.3379993438720703,
"expert": 0.2984810769557953
}
|
10,091
|
what is front arena by FIS
|
4adf6e13932739a004d2be67d8addaf1
|
{
"intermediate": 0.3289248049259186,
"beginner": 0.2283129096031189,
"expert": 0.4427623450756073
}
|
10,092
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Here is a portion of code from Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1cb94a23410, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_IMAGE; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1cb94a23410[], VkImage 0xb097c90000000027[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1cb94a23410, type: 3, name: NULL
[1] 0xb097c90000000027, type: 10, name: NULL
Do you know what could be causing it and how to adjust the code to fix it?
|
ff005d00ba696354fe5721f67d2dbae5
|
{
"intermediate": 0.4101669192314148,
"beginner": 0.33082178235054016,
"expert": 0.25901132822036743
}
|
10,093
|
i have an err with import file FirebaseConfig
import firebase from 'firebase/app';
import { Navigation } from './app/Navigation';
import * as Font from 'expo-font';
import { useState } from 'react';
import AppLoading from 'expo-app-loading';
import '@react-native-firebase/auth';
import '@react-native-firebase/database';
import { firebaseConfig } from './app/DB/FirebaseConfig';
import { SafeAreaView } from 'react-native';
firebase.initializeApp(firebaseConfig);
const fonts = ()=> Font.loadAsync({
'multi':require('./app/assets/fonts/MultiroundPro.otf'),
'yu-reg':require('./app/assets/fonts/YuGothicUIRegular.ttf'),
'yu-semibold':require('./app/assets/fonts/YuGothicUISemibold.ttf')
});
export default function App() {
const [font, setFont]=useState(false);
if(font){
return (
<SafeAreaView style={{ flex: 1 }}>
<Navigation/>
</SafeAreaView>
);
}else{
return(
<AppLoading startAsync={fonts} onFinish={()=>setFont(true)} onError={console.warn}/>
)
}
};
import firebase from "firebase/app"
import "firebase/auth";
import "firebase/database";
import 'firebase/firestore';
const firebaseConfig = {
apiKey: 'AIzaSyD3x41FYcVOfyzfrb93gODDTHSgNa0Yq40',
authDomain: 'whiterose-6b31f.firebaseapp.com',
projectId: 'whiterose-6b31f',
databaseURL: 'https://whiterose-6b31f-default-rtdb.europe-west1.firebasedatabase.app/',
storageBucket: "whiterose-6b31f.appspot.com",
messagingSenderId: '6427461933',
appId: '1:6427461933:ios:012616b0414b2ac36c6ba4',
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
{
"project_info": {
"project_number": "640952084004",
"project_id": "white-rose-27cf0",
"storage_bucket": "white-rose-27cf0.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:640952084004:android:da40b1fcce2addacee5ab1",
"android_client_info": {
"package_name": "white.rose"
}
},
"oauth_client": [
{
"client_id": "640952084004-u4neobkpfmmnag69jp9a4s2120qice5v.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyBX-fPula3jANgTAbZ3qN475uZIbzArzYs"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "640952084004-u4neobkpfmmnag69jp9a4s2120qice5v.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
|
d9539e3313eca933491c882861c42657
|
{
"intermediate": 0.407375305891037,
"beginner": 0.42288216948509216,
"expert": 0.16974250972270966
}
|
10,094
|
huggingface.co/spaces/yuntian-deng/ChatGPT API
|
604d03459e554be8df95d1ccddeb66e3
|
{
"intermediate": 0.44852614402770996,
"beginner": 0.2555980384349823,
"expert": 0.2958758473396301
}
|
10,095
|
I want to create a brand new and unique social media platform that will attract young people and teens. It will be fully open source on GitHub. Please create a full file structure for the GitHub repo that will host the platform. Don't leave any folder or file out.
|
ebfd8bf42f2d8bf2b8d6c10c6e5917cc
|
{
"intermediate": 0.3355869650840759,
"beginner": 0.2208871692419052,
"expert": 0.4435258209705353
}
|
10,096
|
do you know what is front arena by fIS?
|
4ba0d232e3b8c24d82927e4504cae8c9
|
{
"intermediate": 0.27110597491264343,
"beginner": 0.2283228635787964,
"expert": 0.5005711913108826
}
|
10,097
|
I want to create a brand new and unique social media platform that will attract young people and teens. It will be fully open source on GitHub. Please create a. a unique, memorable name for the platform and the repo, and b. a full possible file structure for the GitHub repo that will host the platform. Don't leave any folder or file out, include EVERYTHING.
|
25aedbb4ce102ed0870c5f3c738d5dd3
|
{
"intermediate": 0.3550368547439575,
"beginner": 0.23847821354866028,
"expert": 0.4064849317073822
}
|
10,098
|
OOP C++: Kaguya có rất nhiều bạn: bao gồm bạn thân (BestFriend), bạn trai (BoyFriend) và các bạn trai khác (OtherBoy). Tất cả những người bạn đều cần lưu thông tin bao gồm tên (name, không có khoảng trắng) và độ tuổi (age, từ 0 đến 100).
Bạn thân (loại 1) cần lưu thêm số điện thoại (phone), thời gian dành cho bạn thân là 5h / tuần.
Bạn trai (loại 2) lưu thêm mức thu nhập (income), thời gian dành cho bạn trai là 5 * income / 10000000.0 / tuần.
Bạn trai khác (loại 3) thì là độ hấp dẫn (attractiveness, có giá trị từ 0 đến 1), thời gian dành cho bạn trai khác là độ hấp dẫn * 20 / tổng số bạn.
Viết chương trình nhập vào thông tin của n người bạn, mỗi người bạn sẽ nhập trên cùng một dòng lần lượt:
[tên] [tuổi] [thông tin phụ: số điện thoại, mức thu nhập hoặc độ hấp dẫn]
Sau đó xuất ra thống kê thời gian dành cho mỗi loại bạn / tuần theo định dạng của sample test case (lưu ý giả sử nếu không có bạn trai khác, thì không cần thống kê thời gian dành ra cho bạn trai khác, tương tự với những loại bạn khác). Cuối cùng là xuất ra thông tin người bạn quan trọng nhất (dành nhiều thời gian nhất, nếu k người có thời gian bằng nhau thì xuất k người theo thứ tự đã nhập), với mỗi người theo định dạng:
Ten: [name], tuoi: [age], so dien thoai: [phone]
hoặc:
Ten: [name], tuoi: [age], thu nhap: [income]d
hoặc:
Ten: [name], tuoi: [age], do thu hut: [level]* (level = 'cao' nếu độ thu hút >= 0.7, 'trung binh' nếu độ thu hút >= 0.4 và < 0.7, 'thap' nếu độ thu hút < 0.4)
Xuất ra kết quả tính tính với định dạng:
Thong ke:
-Thoi gian cho ban than: ... h
-Thoi gian cho ban trai: ... h
-Thoi gian cho ban trai khac: ... h
Nguoi ban quan trong nhat:
[Ten: [name], tuoi: [age], ...]Input Format
int
[string int ...]
Constraints
No constraint
Output Format
string
Sample Input 0
4
1 banthan 23 012345
2 bantrai 23 15000000
3 bantrai1 23 0.5
3 bantrai2 24 0.7
Sample Output 0
Thong ke:
-Thoi gian cho ban than: 5 h
-Thoi gian cho ban trai: 7.5 h
-Thoi gian cho ban trai khac: 6 h
Nguoi ban quan trong nhat:
Ten: bantrai, tuoi: 23, thu nhap: 15000000d
|
474d5c011260908c8f9d503bf87bd24f
|
{
"intermediate": 0.2216140627861023,
"beginner": 0.6105071902275085,
"expert": 0.1678786724805832
}
|
10,099
|
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'] == '1':
print(f"Error: {data['result']}")
return []
return [tx for tx in data['result']]
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:
if contract['from'] == '0x863b49ae97c3D2A87Fd43186dfd921F42783C853':
print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}")
start_block = 28645722 # Replace with your desired start block
end_block = 28645722 # Replace with your desired end block
display_new_contracts(start_block, end_block)
The code above prints all transactions in the specified block. Change it so that it only prints transactions where the address in the From column is 0x863b49ae97c3d2a87fd43186dfd921f42783c853
|
ce4670bdaaada822963e3e5e14245739
|
{
"intermediate": 0.4997616708278656,
"beginner": 0.3501095473766327,
"expert": 0.15012884140014648
}
|
10,100
|
I need a python programm to draw a phase portrait of system of differential equations
|
02b9a9aed288966ddca3bc21b82ed9be
|
{
"intermediate": 0.3861175775527954,
"beginner": 0.16841167211532593,
"expert": 0.44547075033187866
}
|
10,101
|
Heres a roblox script to play an animation when the player presses E, is there anything wrong with this code?
|
7eed6d25a5322efeefd2e931e21699fb
|
{
"intermediate": 0.4696862995624542,
"beginner": 0.19175487756729126,
"expert": 0.3385588526725769
}
|
10,102
|
I need a script, in whatever coding language it works best, that lets me select a pdf, splits it into 100 pages max, translates each split, and then merges it back up into 1 pdf
|
3abd5e68d17b9b55c593579387223fe7
|
{
"intermediate": 0.496889591217041,
"beginner": 0.22234979271888733,
"expert": 0.28076067566871643
}
|
10,103
|
I want to create a brand new and unique social media platform that will attract young people and teens. It will be fully open source on GitHub. Please create a. a unique, memorable name for the platform and the repo, and b. a full possible file structure for the GitHub repo that will host the platform. Don't leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
a17a88bd9d8a6ad968f9dc29f07e1ba0
|
{
"intermediate": 0.3625689148902893,
"beginner": 0.24940219521522522,
"expert": 0.3880288302898407
}
|
10,104
|
I need a script, in any language, that will select a pdf and will translate it. The pdf can be very big ( 800 pages + ). Make sure it translates the whole pdf
|
805faeb01ffea7bdd702e2bfe96820f9
|
{
"intermediate": 0.33002936840057373,
"beginner": 0.17968899011611938,
"expert": 0.4902816712856293
}
|
10,105
|
crossover_point = 7
population_size = 100
num_generations = 100
tournament_size = 2
probability = 0.09
penalty = 1
parents = mutate(pop_init, position_vectors,1.0)
nrows=100
global_best = pop_init[1, :]
global_best_value = target(global_best)
# Main loop
for gen in 1:num_generations
# Parent population
parent_pop = create_ones_dataframe(n_rows, length(position_vectors))
parent_pop= parent_pop[1:(n_rows), :]
for c in 1:population_size
parent_pop[c, :] = tournament_selection(parents, tournament_size, penalty)
end
#parent_pop = fill!(parent_pop, missing)
# Generate offspring
offspring_temp = create_ones_dataframe(n_rows, length(position_vectors))
offspring_temp=offspring_temp[1:(n_rows), :]
for c in 1:2:population_size
offsprings = crossover(parent_pop[c, :], parent_pop[c + 1, :], crossover_point)
offspring_temp = vcat(offspring_temp, offsprings)
end
offspring_temp = offspring_temp[nrows+1:end, :]
#print(offspring_temp)
#offspring_temp = offspring_temp[2:end, :]
#offspring_temp = fill!(offspring_temp, missing)
parents = mutate(offspring_temp, position_vectors, 0.09)
# Evaluate solutions
solutions = [target(parent) for parent in eachrow(parents)]
#print(solutions)
idx_sol = argmin(solutions)
temp_best = parents[idx_sol, :]
temp_target_value = solutions[idx_sol]
if temp_target_value <= global_best_value
global_best = temp_best
global_best_value = temp_target_value
end
end
Change that into a function callded GA that returns global_best and global_best_value.
|
ca4cf2b9a4b0355ecb2f917be8a370af
|
{
"intermediate": 0.31339937448501587,
"beginner": 0.39473024010658264,
"expert": 0.2918703556060791
}
|
10,106
|
I want to create a brand new, useful and unique piece of software for web and Windows aimed at developers. It will be fully open source on GitHub. Please create a. a unique, memorable name for the platform and the repo, and b. a full possible file structure for the GitHub repo that will host the platform. Don't leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
35eeb9a888a04db8c2115ae1169594e3
|
{
"intermediate": 0.36585527658462524,
"beginner": 0.27017444372177124,
"expert": 0.3639703094959259
}
|
10,107
|
I want to create a brand new, useful and unique piece of software for Windows aimed at developers. It will be fully open source on GitHub. Please create a. a unique, memorable name for the platform and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the platform. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
58d0dffe11c0a6ca61baa4991c37b27b
|
{
"intermediate": 0.35654670000076294,
"beginner": 0.29584917426109314,
"expert": 0.34760409593582153
}
|
10,108
|
I want to create a brand new, extremely useful and VERY unique, niche and specific piece of software with a lot of potential, for Windows only, aimed at developers. IT SHOULD NOT BE GENERIC OR ALREADY EXIST. It will be fully open source on GitHub. Please create a. a unique, memorable name for the platform and the repo, b. a description for the repo and c. a full possible file structure for the GitHub repo that will host the platform. Don’t leave any folder or file out, include EVERYTHING, down to each individual file. Do not leave any folders empty.
|
d0c1555bb93be956102e7153d2671688
|
{
"intermediate": 0.3062431514263153,
"beginner": 0.3243385851383209,
"expert": 0.36941826343536377
}
|
10,109
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(glm::vec3(0.0f, 0.0f, 0.0f)), rotation(glm::vec3(0.0f, 0.0f, 0.0f)), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
SetScale(glm::vec3(1.0f));
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
/* VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;*/
//BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
// sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
// VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
// mvpBuffer, mvpBufferMemory);
auto [mvpBuffer, mvpBufferMemory] = renderer.RequestMvpBuffer();
material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP));
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
/* vkDeviceWaitIdle(device);
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);*/
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
vkDeviceWaitIdle(*renderer.GetDevice());
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Here is a portion of code from Renderer.cpp:
Renderer::Renderer() : currentFrame(0), shutdownInProgress(false)
{
}
Renderer::~Renderer()
{
Shutdown();
}
void Renderer::Initialize(GLFWwindow* window)
{
this->window = window;
CreateInstance();
CreateSurface();
ChoosePhysicalDevice();
CreateDevice();
// Create the MVP buffers
mvpBuffers.resize(kMvpBufferCount);
mvpBufferMemory.resize(kMvpBufferCount);
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
BufferUtils::CreateBuffer(device, *GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffers[i], mvpBufferMemory[i]);
}
CreateSwapchain();
CreateRenderPass();
CreateCommandPool();
CreateFramebuffers();
CreateSyncObjects();
}
void Renderer::Shutdown()
{
if (isShutDown) {
return;
}
if (shutdownInProgress) {
return;
}
shutdownInProgress = true;
if (device != VK_NULL_HANDLE) {
vkDeviceWaitIdle(device);
}
CleanupFramebuffers();
CleanupRenderPass();
CleanupSyncObjects();
CleanupCommandPool();
CleanupImageViews();
CleanupSwapchain();
// Destroy the MVP buffers
for (uint32_t i = 0; i < kMvpBufferCount; ++i)
{
vkDestroyBuffer(device, mvpBuffers[i], nullptr);
vkFreeMemory(device, mvpBufferMemory[i], nullptr);
}
if (device != VK_NULL_HANDLE) {
CleanupDevice();
}
DestroySurface();
CleanupInstance();
shutdownInProgress = false;
isShutDown = true;
}
void Renderer::BeginFrame()
{
// Wait for any previous work on this swapchain image to complete
vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// Acquire an image from the swapchain, then begin recording commands for the current frame.
VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (acquireResult != VK_SUCCESS && acquireResult != VK_SUBOPTIMAL_KHR) {
throw std::runtime_error("Failed to acquire next swapchain image.");
}
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
//currentCommandBuffer = commandBuffers[currentFrame];
currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2;
currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex];
// Add debug message before vkBeginCommandBuffer
std::cout << "Current Frame: " << currentFrame << " | Cmd Buffer Index: " << currentCmdBufferIndex << " | Image Index: " << imageIndex << "\n";
std::cout << "Calling vkBeginCommandBuffer…\n";
vkBeginCommandBuffer(currentCommandBuffer, &beginInfo);
std::cout << "vkBeginCommandBuffer called…\n";
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[imageIndex];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = swapChainExtent;
// Set the clear color to black
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(currentCommandBuffer, &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void Renderer::EndFrame()
{
vkCmdEndRenderPass(currentCommandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &imageAvailableSemaphores[currentFrame];
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = ¤tCommandBuffer;
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &renderFinishedSemaphores[currentFrame];
vkEndCommandBuffer(currentCommandBuffer);
vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences[currentFrame]);
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &renderFinishedSemaphores[currentFrame];
VkSwapchainKHR swapChains[] = { swapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VkResult queuePresentResult = vkQueuePresentKHR(presentQueue, &presentInfo);
std::cout << "Frame rendered: " << currentFrame << "\n";
if (queuePresentResult == VK_ERROR_OUT_OF_DATE_KHR || queuePresentResult == VK_SUBOPTIMAL_KHR) {
// Handle swapchain recreation if needed, e.g., due to resizing the window or other swapchain properties changes
}
else if (queuePresentResult != VK_SUCCESS) {
throw std::runtime_error("Failed to present the swapchain image.");
}
currentFrame = (currentFrame + 1) % kMaxFramesInFlight;
}
void Renderer::CleanupFramebuffers()
{
for (auto framebuffer : framebuffers)
{
if (framebuffer != VK_NULL_HANDLE)
{
vkDestroyFramebuffer(device, framebuffer, nullptr);
framebuffer = VK_NULL_HANDLE;
}
}
framebuffers.clear(); // Make sure to clear the framebuffers vector after destroying each framebuffer
}
void Renderer::CleanupRenderPass()
{
vkDestroyRenderPass(device, renderPass, nullptr);
}
void Renderer::CleanupSyncObjects()
{
for (size_t i = 0; i < kMaxFramesInFlight; ++i)
{
if (renderFinishedSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
if (imageAvailableSemaphores[i] != VK_NULL_HANDLE)
vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
if (inFlightFences[i] != VK_NULL_HANDLE)
vkDestroyFence(device, inFlightFences[i], nullptr);
}
}
void Renderer::CleanupCommandPool()
{
// Clean up Vulkan command pool
CleanupCommandBuffers(); // Add this line to clean up command buffers before destroying the command pool
vkDestroyCommandPool(device, commandPool, nullptr);
}
void Renderer::CleanupCommandBuffers()
{
vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
}
void Renderer::CleanupImageViews()
{
for (auto imageView : swapChainImageViews)
{
vkDestroyImageView(device, imageView, nullptr);
}
swapChainImageViews.clear();
}
void Renderer::CleanupSwapchain()
{
// Clean up Vulkan swapchain
if (swapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, swapchain, nullptr);
swapchain = VK_NULL_HANDLE;
}
}
void Renderer::CleanupDevice()
{
// Destroy the logical device
vkDestroyDevice(device, nullptr);
}
Here is a portion of code from Texture.cpp:
exture::Texture()
: device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE)
{
}
Texture::~Texture()
{
}
void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
this->physicalDevice = physicalDevice;
this->commandPool = commandPool;
this->graphicsQueue = graphicsQueue;
this->initialized = true;
// Load image from file using stb_image
int width, height, channels;
stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha);
if (!pixels)
{
throw std::runtime_error("Failed to load texture image!");
}
// Calculate the number of mip levels
uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1;
// Create a buffer to store the image data
VkDeviceSize imageSize = width * height * 4;
VkBuffer stagingBuffer;
VkDeviceMemory stagingBufferMemory;
// Create the staging buffer for transferring image data
BufferUtils::CreateBuffer(device, physicalDevice, imageSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory);
// Copy image data to the buffer
void* bufferData;
vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData);
memcpy(bufferData, pixels, static_cast<size_t>(imageSize));
vkUnmapMemory(device, stagingBufferMemory);
// Free the stb_image buffer
stbi_image_free(pixels);
// Create vkImage, copy buffer to image, and create imageView and sampler
// …
CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL,
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels);
CreateSampler(mipLevels);
TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels, VK_SAMPLE_COUNT_1_BIT); // Add this call
CopyBufferToImage(stagingBuffer, width, height);
// Cleanup the staging buffer and staging buffer memory
// …
// Destroy the staging buffer and free the staging buffer memory
vkDestroyBuffer(device, stagingBuffer, nullptr);
vkFreeMemory(device, stagingBufferMemory, nullptr);
}
void Texture::Cleanup(Texture* texture)
{
// Put the content of the old Cleanup() method here
// Make sure to replace this with texture keyword
// …
}
VkImageView Texture::GetImageView() const
{
return imageView;
}
VkSampler Texture::GetSampler() const
{
return sampler;
}
void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties)
{
VkImageCreateInfo imageInfo{};
imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
imageInfo.imageType = VK_IMAGE_TYPE_2D;
imageInfo.extent.width = width;
imageInfo.extent.height = height;
imageInfo.extent.depth = 1;
imageInfo.mipLevels = mipLevels;
imageInfo.arrayLayers = 1;
imageInfo.format = format;
imageInfo.tiling = tiling;
imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
imageInfo.usage = usage;
imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageInfo.samples = numSamples;
imageInfo.flags = 0;
if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create image!");
}
VkMemoryRequirements memRequirements;
vkGetImageMemoryRequirements(device, image, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate image memory!");
}
vkBindImageMemory(device, image, imageMemory, 0);
}
I am getting the following error in Renderer::CleanupDevice:
VUID-vkDestroyDevice-device-00378(ERROR / SPEC): msgNum: 1901072314 - Validation Error: [ VUID-vkDestroyDevice-device-00378 ] Object 0: handle = 0x1cb94a23410, type = VK_OBJECT_TYPE_DEVICE; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_IMAGE; | MessageID = 0x71500fba | OBJ ERROR : For VkDevice 0x1cb94a23410[], VkImage 0xb097c90000000027[] has not been destroyed. The Vulkan spec states: All child objects created on device must have been destroyed prior to destroying device (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkDestroyDevice-device-00378)
Objects: 2
[0] 0x1cb94a23410, type: 3, name: NULL
[1] 0xb097c90000000027, type: 10, name: NULL
Do you know what could be causing it and how to adjust the code to fix it?
|
ec287a9b0906c2d45be6e5bade1d7656
|
{
"intermediate": 0.4101669192314148,
"beginner": 0.33082178235054016,
"expert": 0.25901132822036743
}
|
10,110
|
检查这段html代码的意图以及存在的错误,然后改正它:
<html>
<head>
<meta charest="UTF-8">
<title>美好的一天</title>
</head>
<body>
<h1 style="background-color:gold;">计算机和时钟养成记</h1>
作者:<b><i>邓旻昕</i></b><sup>*</sup>时间:<i>2023年5月19日</i> <h2>发明前</h2>
<div>
<p>在发明前,我也不知道自己能不能做成。</p>
<br/>
<hr/>
<div/>
<h2>发明中</h2>
<p>过程中,查了好多资料,好累但很快乐。</p>
<br/>
<hr/>
<h2>发明后</h2>
<p>终于做好了,虽然很粗糙,那也是亲儿子</p>
<table border="1">
表:艰难历程表
<tr>
<td>事件</td><td>感悟</td>
</tr>
<tr>
<td>看CSS语法</td><td>一天没睡</td>
</tr>
<tr>
<td>看HTML语法</td><td>还是没睡</td>
</tr>
<tr>
<td>看JS语法</td><td>还是Go香</td>
</tr>
</table>
列表:王小二的动机
<ol>
<li>学习CSS</li>
<li>学习HTML</li>
<li>学习JS</li>
<li>写计算器和时钟</li>
</ol>
<form>
操作数1: <input type="text" id="op1"><br/>
操作数2: <input type="text" id="op2">
<br/>
<input type="radio" name="op">加
<input type="radio" name="op">减
<input type="radio" name="op">乘
<input type="radio" name="op">除
<input type="radio" name="op">模
<br/>
结果:<span id="result">xxxx</span><br/>
<input type="button" value="计算" onclick="run_cal()">
</form>
<script>
function add(x,y){return x+y;}
function sub(x,y){return x-y;}
function mul(x,y){return x*y;}
function div(x,y){return x/y;}
function mod(x,y){return x%y;}
function run_cal(){
var function_array=[add,sub,mul,div,mod];
var options=document.getElementsByName("op");
var z;
for(var i=0;i<function_array.length;i++){
if(options[i].checked==true){
z=function_array[i](op1,op2);
break;
}
}
document.getElementById('result').innerHTML=z;
}
</script>
</body>
</html>
|
1ff2dbeb740282ca0871063874f93413
|
{
"intermediate": 0.3112667202949524,
"beginner": 0.41500425338745117,
"expert": 0.27372899651527405
}
|
10,111
|
Write a program code that, when entering the address of a token, will determine whether liquidity has been added to this one and whether it has been blocked. Token on Binance Smart Chain. Use APIKey
|
f6e8184ccd0bbee407bbb2d4600afc75
|
{
"intermediate": 0.6781594753265381,
"beginner": 0.06426409631967545,
"expert": 0.25757643580436707
}
|
10,112
|
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
}
})
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_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
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', 133920)
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', 133920)
def order_execution(symbol, signal, step_size, leverage):
# 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
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
# Round the price variable
try:
price = round_step_size(price, step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
return
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Set take profit and stop loss prices
# Set take profit and stop loss prices
if signal == 'buy':
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
else:
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
# Place order
order_params = {
"symbol": symbol,
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": 100
}
try:
response = binance_futures.fapiPrivatePostOrder(**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', 133920) # 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)
time.sleep(0.1)
But I getting ERROR: The signal time is: 2023-06-04 16:43:44 :buy
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 260, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 247, in order_execution
response = binance_futures.fapiPrivatePostOrder(**order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol'
|
861fc99c1b59888c7421f2ea5e544d2e
|
{
"intermediate": 0.5100780129432678,
"beginner": 0.3374444544315338,
"expert": 0.15247753262519836
}
|
10,113
|
function GA2(crossover_point=7, population_size=100, num_generations=10, tournament_size=2, probability=0.09, weight1=0.15,
weight2=0.6,
weight3=0.3,
contraint_1=250000000,
constraint2=250000,
contraint_3=1.2)
nrows=population_size
parents = mutate(pop_init, position_vectors, 1.0)
global_best = pop_init[1, :]
global_best_value = target2(global_best,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
penalty=1
# Main loop
for gen in 1:num_generations
# Parent population
parent_pop = create_ones_dataframe(n_rows, length(position_vectors))
parent_pop = parent_pop[1:n_rows, :]
for c in 1:population_size
parent_pop[c, :] = tournament_selection2(parents, tournament_size, penalty,weight1,weight2,weight3,contraint_1,constraint2,contraint_3)
end
# Generate offspring
offspring_temp = create_ones_dataframe(n_rows, length(position_vectors))
offspring_temp = offspring_temp[1:n_rows, :]
for c in 1:2:population_size
offsprings = crossover(parent_pop[c, :], parent_pop[c + 1, :], crossover_point)
offspring_temp = vcat(offspring_temp, offsprings)
end
offspring_temp = offspring_temp[nrows+1:end, :]
parents = mutate(offspring_temp, position_vectors, 0.09)
# Evaluate solutions
solutions = [target2(parent,6,weight1,weight2,weight3,contraint_1,constraint2,contraint_3) for parent in eachrow(parents)]
idx_sol = argmin(solutions)
temp_best = parents[idx_sol, :]
temp_target_value = solutions[idx_sol]
if penalty==4
penalty=0
else
penalty+0.5
end
if temp_target_value <= global_best_value
global_best = temp_best
global_best_value = temp_target_value
end
end
return global_best, global_best_value
end
I want to iterate over diffrent
weight1=0.05:0.05:0.2,
weight2=0:1:0:1:0:9 and
weight3=0.1:0.1:0.9
For each of those combinations I need DataFrame of global_best and global_best_value. I also need to know exactly for which combination of weight1,weigh2 and weight3 the output of GA2 are.
|
7a91ba1674a7c25f4177d2514755414e
|
{
"intermediate": 0.35266900062561035,
"beginner": 0.376441091299057,
"expert": 0.27088984847068787
}
|
10,114
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
faa43ffc00faaf18e6dec78af6b7dce2
|
{
"intermediate": 0.26680880784988403,
"beginner": 0.4191991686820984,
"expert": 0.3139919936656952
}
|
10,115
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
c4bf76cd0b022ec96644d778c3ff24ea
|
{
"intermediate": 0.26680880784988403,
"beginner": 0.4191991686820984,
"expert": 0.3139919936656952
}
|
10,116
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
c25c018e7d6a8993d88b1a429704b8db
|
{
"intermediate": 0.26680880784988403,
"beginner": 0.4191991686820984,
"expert": 0.3139919936656952
}
|
10,117
|
I want that:
function iterate_weights()
weight1_range = 0.05:0.05:0.2
weight2_range = 0:0.1:1.0
weight3_range = 0.1:0.1:0.9
results = DataFrame(weight1=[], weight2=[], weight3=[], global_best=DataFrame([]), global_best_value=[])
for weight1 in weight1_range
for weight2 in weight2_range
for weight3 in weight3_range
global_best, global_best_value = GA2(7, 100, 10, 2, 0.09, weight1,weight2,weight3,250000000,250000,1.2)
global_best_df = DataFrame(global_best)
push!(results, (weight1=weight1, weight2=weight2, weight3=weight3, global_best=global_best_df, global_best_value=global_best_value))
print(results)
end
end
end
return results
end
# Call the iterate_weights function to get the results
results_df = iterate_weights()
to be done in multiprocessing using @everywhere or something like that.
|
249c9e1deb00b11582ffea3475917d3d
|
{
"intermediate": 0.536117434501648,
"beginner": 0.28796523809432983,
"expert": 0.1759173572063446
}
|
10,118
|
Change that:
weight1_range = 0.05:0.05:0.2
weight2_range = 0:0.1:1.0
weight3_range = 0.1:0.1:0.9
for weight1 in weight1_range
for weight2 in weight2_range
for weight3 in weight3_range
@async begin
global_best, global_best_value = GA2(7, 100, 10, 2, 0.09, weight1,weight2,weight3,250000000,250000,1.2)
global_best_df = DataFrame(global_best)
put!(results, (weight1=weight1, weight2=weight2, weight3=weight3, global_best=global_best_df, global_best_value=global_best_value))
print(results)
end
end
end
end
close(results)
df_results = DataFrame(weight1 = Float64[], weight2 = Float64[], weight3 = Float64[], global_best = Any[], global_best_value = Any[])
for r in results
push!(df_results, r)
end
return df_results
into pararell processing in julia.
|
698cb7dadbf81df910330a5fc2d3e26b
|
{
"intermediate": 0.34705591201782227,
"beginner": 0.28705859184265137,
"expert": 0.36588549613952637
}
|
10,119
|
Give complete solution with code for the below project stepwise in docker and docker compose (Automate everything) As a user, I should be able to access APIs associated with any model (Please tell me how it is done in solution):
Project:
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future. It abstracts the dirty details of how a model works similar to Huggingface and gives a clean API that you can orchestrate at aenter code here BFF level.
Features to be implemented
Abstract the layer of deployment for AI Tools. Anyone should be easily add a new model to the stack without thinking about deployments. We should be able to deploy AI Tools in such a way where each model (every model can be packaged as a container) should be independently scalable. As a user, I should be able to access APIs associated with any model.
Product Set Up
https://github.com/Samagra-Development/ai-tools#setup
Github Information:
ReadME:
AI Toolchain
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future.
How to Run
To deploy all models, simply execute the deploy.sh script located in the root folder. This script calls the deployment files of each model. Note that the toolchain may switch to using Docker in the future for deployment.
To create a new model class, use the template_batch_model.py file as a starting point. Your new model class should implement the method mentioned in the template file.
To create a new request class, use the template_model_request.py file as a starting point. This class is used to map the incoming request to the data needed by the model.
To add your new model and request to the API, modify the repository dictionary in api.py.
Repository
The repository is structured as follows
Setup
To set up the AI Toolchain environment, follow these steps:
python3 -m venv venv
source venv/bin/activate
pip install poetry
poetry install
quart --app api --debug run
Poetry Fixes
poetry lock --no-update
Contributing
Contributions to AI Toolchain are welcome! To contribute, please follow these guidelines:
Fork the repository and create a new branch for your feature or bug fix.
Write tests for your changes.
Submit a pull request describing your changes and why they are needed.
Thank you for considering contributing to AI Toolchain!
Files:
.github/workflows
Lower case repo name for GH Packages
2 months ago
benchmarks
Fix add test
3 weeks ago
flake8
Fix: module/folder names
2 months ago
src
Merge pull request #100 from rishav-eulb/rishav-eulb-patch-2
last week
.flake8
Fixes: #29
2 months ago
.gitignore
Initial Commit
2 months ago
.gitpod.Dockerfile
Included installation of Git
last week
.gitpod.yml
Corrected .gitpod.yml
last week
Dockerfile
Added Gitpod
last week
README.md
docs: readme updated
last month
api.py
Moved restart and watch functions to separate file
last week
contribution.md
Corrected Gitpod button
last week
deploy.sh
deploy.sh_error
last month
docker-compose.yml
Added Gitpod
last week
poetry.lock
Feat: Reload debug server on changes to src folder
last week
prometheus.yml
add prometheus.yml
2 weeks ago
pyproject.toml
Feat: Reload debug server on changes to src folder
last week
repository_data.json
Feat: Azure translation
3 weeks ago
sample.env
Fix: Add sample env
2 months ago
template_batch_model.py
added repo structure and translation model
2 months ago
template_model_request.py
added repo structure and translation model
2 months ago
test.py
Fix add test
3 weeks ago
watch_folder.py
Moved resta
Dockercompose file:
version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
restart: always
environment:
- PYTHONUNBUFFERED=1
- PYTHONDONTWRITEBYTECODE=1
- OPENAI_API_KEY=${OPENAI_API_KEY}
- AUTH_HEADER=${AUTH_HEADER}
- AUTH_HEADER_KEY=${AUTH_HEADER_KEY}
prometheus:
image: prom/prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
gitpod:
image: gitpod/workspace-full
ports:
- "8888:8888"
volumes:
- ./workspace:/workspace
|
316b0a9e4f69358ab3f91b1d7bcece84
|
{
"intermediate": 0.45972713828086853,
"beginner": 0.29506298899650574,
"expert": 0.24520979821681976
}
|
10,120
|
Give complete solution with code for the below project stepwise in docker and docker compose (Automate everything) As a user, I should be able to access APIs associated with any model (Please tell me how it is done in solution):
Project:
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future. It abstracts the dirty details of how a model works similar to Huggingface and gives a clean API that you can orchestrate at aenter code here BFF level.
Features to be implemented
Abstract the layer of deployment for AI Tools. Anyone should be easily add a new model to the stack without thinking about deployments. We should be able to deploy AI Tools in such a way where each model (every model can be packaged as a container) should be independently scalable. As a user, I should be able to access APIs associated with any model.
Product Set Up
https://github.com/Samagra-Development/ai-tools#setup
Github Information:
ReadME:
AI Toolchain
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future.
How to Run
To deploy all models, simply execute the deploy.sh script located in the root folder. This script calls the deployment files of each model. Note that the toolchain may switch to using Docker in the future for deployment.
To create a new model class, use the template_batch_model.py file as a starting point. Your new model class should implement the method mentioned in the template file.
To create a new request class, use the template_model_request.py file as a starting point. This class is used to map the incoming request to the data needed by the model.
To add your new model and request to the API, modify the repository dictionary in api.py.
Repository
The repository is structured as follows
Setup
To set up the AI Toolchain environment, follow these steps:
python3 -m venv venv
source venv/bin/activate
pip install poetry
poetry install
quart --app api --debug run
Poetry Fixes
poetry lock --no-update
Contributing
Contributions to AI Toolchain are welcome! To contribute, please follow these guidelines:
Fork the repository and create a new branch for your feature or bug fix.
Write tests for your changes.
Submit a pull request describing your changes and why they are needed.
Thank you for considering contributing to AI Toolchain!
|
ff3fafec49b82ddc468842b3bc17da20
|
{
"intermediate": 0.6782860159873962,
"beginner": 0.18161873519420624,
"expert": 0.14009523391723633
}
|
10,121
|
test
|
307a97be66702cf130fdadd0fe7b9397
|
{
"intermediate": 0.3229040801525116,
"beginner": 0.34353747963905334,
"expert": 0.33355844020843506
}
|
10,122
|
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
}
})
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_time()
return server_time
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
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', 44640)
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', 44640)
def order_execution(symbol, signal, step_size, leverage):
# 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
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
# Round the price variable
try:
price = round_step_size(price, step_size=step_size)
except Exception as e:
print(f"Error rounding price: {e}")
return
# Reduce quantity if opposite position exists
if opposite_position is not None:
if abs(opposite_position['positionAmt']) < quantity:
quantity = abs(opposite_position['positionAmt'])
# Set take profit and stop loss prices
# Set take profit and stop loss prices
if signal == 'buy':
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
else:
if price is not None:
try:
price = round_step_size(price, step_size=step_size)
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}")
take_profit_price = None
stop_loss_price = None
else:
take_profit_price = None
stop_loss_price = None
# Place order
order_params = {
"side": "BUY" if signal == "buy" else "SELL",
"type": order_type,
"positionSide": position_side,
"quantity": quantity,
"price": price,
"stopPrice": stop_loss_price if signal == "buy" else take_profit_price,
"reduceOnly": False,
"newOrderRespType": "RESULT",
"workingType": "MARK_PRICE",
"priceProtect": False,
"leverage": 100
}
try:
response = binance_futures.fapiPrivatePostOrder(symbol=symbol, **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', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Error rounding price: cannot access local variable 'price' where it is not associated with a value
The signal time is: 2023-06-04 17:00:03 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 259, in <module>
order_execution(symbol, signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 246, in order_execution
response = binance_futures.fapiPrivatePostOrder(symbol=symbol, **order_params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Entry.__init__.<locals>.unbound_method() got an unexpected keyword argument 'symbol'
|
295f7eb4827c34dddf5eefb3c9138572
|
{
"intermediate": 0.5100780129432678,
"beginner": 0.3374444544315338,
"expert": 0.15247753262519836
}
|
10,123
|
import requests
# Replace YOUR_APIKEY with your actual BscScan API key.
APIKEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
# Method signatures
LOCK_TOKENS_SIGNATURE = "0x6167aa61"
ADD_LIQUIDITY_ETH_SIGNATURE = "0xf305d719"
LOCK_SIGNATURE = "0x07279357"
def is_signature_present(address, signature, start_block=0, end_block="latest"):
url = f"https://api.bscscan.com/api?module=account&action=txlist&address={address}&startblock={start_block}&endblock={end_block}&sort=asc&apikey={APIKEY}"
response = requests.get(url)
data = response.json()
for tx in data["result"]:
if tx["input"].startswith(signature):
return True
return False
def is_liquidity_added_and_locked(token_address):
lock_tokens_present = is_signature_present(token_address, LOCK_TOKENS_SIGNATURE)
add_liquidity_eth_present = is_signature_present(token_address, ADD_LIQUIDITY_ETH_SIGNATURE)
lock_present = is_signature_present(token_address, LOCK_SIGNATURE)
return add_liquidity_eth_present and (lock_tokens_present or lock_present)
token_address = "0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e"
print(is_liquidity_added_and_locked(token_address))
The code above determines the presence of the specified method signatures directly on the transaction, which does not mean that this will be the address of the token. Fix the code so that it can determine the presence of the specified method signatures exactly when entering the address of the token itself
|
5870653a5436c8182f606a9474314784
|
{
"intermediate": 0.46948373317718506,
"beginner": 0.3497673273086548,
"expert": 0.18074892461299896
}
|
10,124
|
Can you program
|
e913458340b802684ea0ca62f524f80d
|
{
"intermediate": 0.2628566324710846,
"beginner": 0.2704368233680725,
"expert": 0.4667064845561981
}
|
10,125
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
369d4df8f9d8a8fc5cedcf34ea21fc8c
|
{
"intermediate": 0.26680880784988403,
"beginner": 0.4191991686820984,
"expert": 0.3139919936656952
}
|
10,126
|
Write a program code that will analyze all transactions on the site https://bscscan.com/token/0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e in the Transfers tab and detect method signatures
Lock Tokens 0x6167aa61
Add Liquidity ETH 0xf305d719
Lock 0x07279357.
Token on Binance Smart Chain. Use APIKey
|
95973015f88c20505f517ec9aaee1b27
|
{
"intermediate": 0.543624997138977,
"beginner": 0.1400260478258133,
"expert": 0.31634896993637085
}
|
10,127
|
на widnows запускаю и получаю ошибку fATAL: data directory “/var/lib/postgresql/data/pgdata” has invalid permissions
|
303dbbdbe7435be9816524bbc936ec5c
|
{
"intermediate": 0.3690183162689209,
"beginner": 0.27059730887413025,
"expert": 0.36038440465927124
}
|
10,128
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! vmc menu should appear on every grid point intersection mouse hover, and disappear when out of grid attachment points, to be able to add new lines to actual 3dwireframe matrix model. output only full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
b4e77a9167f3c26d28dd85a3f0c5f4df
|
{
"intermediate": 0.2741520404815674,
"beginner": 0.3953407108783722,
"expert": 0.3305072486400604
}
|
10,129
|
я запускаю docker compose через windows
btms-postgres-1 | 2023-06-04 15:08:51.443 UTC [83] FATAL: data directory "/var/lib/postgresql/data/pgdata" has invalid permissions
btms-postgres-1 | 2023-06-04 15:08:51.443 UTC [83] DETAIL: Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).
|
e0dd66c5054daa49d701769042cbce4c
|
{
"intermediate": 0.40214264392852783,
"beginner": 0.29258835315704346,
"expert": 0.3052690029144287
}
|
10,130
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! vmc menu should appear on every grid point intersection mouse hover, and disappear when out of grid attachment points, to be able to add new lines to actual 3dwireframe matrix model. output only full properre modified and optimized code: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const greenDotContainer = document.createElement('div');
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement('div');
dot.className = 'green-dot';
dot.style.left = (i - 2) + 'px';
dot.style.top = (j - 2) + 'px';
dot.style.display = displayGrid ? '' : 'none';
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = '#0F0';
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement('button');
gridToggleButton.innerText = 'Toggle Grid';
vmcMenu.insertBefore(gridToggleButton, document.getElementById('add-edge'));
gridToggleButton.addEventListener('click', () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = 'block';
} else {
greenDotContainer.style.display = 'none';
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
edf0274ea76167b7246a3d7831f3a85d
|
{
"intermediate": 0.2741520404815674,
"beginner": 0.3953407108783722,
"expert": 0.3305072486400604
}
|
10,131
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code. (and don't forget to analyze your shits before outputs!): const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
2ec3b20087cc299fbde8ba6953f08e84
|
{
"intermediate": 0.27949637174606323,
"beginner": 0.3869239389896393,
"expert": 0.3335796594619751
}
|
10,132
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code. (and don't forget to analyze your shits before outputs!): const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
6e062815f670d476c506eae7f6f4257d
|
{
"intermediate": 0.27949637174606323,
"beginner": 0.3869239389896393,
"expert": 0.3335796594619751
}
|
10,133
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code. (and don't forget to analyze your shits before outputs!): const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
55cdc5ccec6526d513c6a4feec4f72af
|
{
"intermediate": 0.27949637174606323,
"beginner": 0.3869239389896393,
"expert": 0.3335796594619751
}
|
10,134
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize);
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
//CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkBuffer uniformBuffer, VkDeviceSize bufferSize)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, [device](Texture* textureToDelete) {
textureToDelete->Cleanup();
delete textureToDelete;
});
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<VkWriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[0].dstSet = descriptorSet;
descriptorWrites[0].dstBinding = 0;
descriptorWrites[0].dstArrayElement = 0;
descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
descriptorWrites[0].descriptorCount = 1;
descriptorWrites[0].pBufferInfo = &bufferInfo;
descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrites[1].dstSet = descriptorSet;
descriptorWrites[1].dstBinding = 1;
descriptorWrites[1].dstArrayElement = 0;
descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrites[1].descriptorCount = 1;
descriptorWrites[1].pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
void Cleanup();
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
Shader.h:
#pragma once
#include <vulkan/vulkan.h>
#include <string>
class Shader
{
public:
Shader();
~Shader();
void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage);
VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const;
static void Cleanup(Shader* shader);
private:
VkDevice device;
VkShaderModule shaderModule;
VkShaderStageFlagBits stage;
};
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
std::pair<VkBuffer, VkDeviceMemory> RequestMvpBuffer();
private:
bool isShutDown = false;
static const uint32_t kMvpBufferCount = 3;
std::vector<VkBuffer> mvpBuffers;
std::vector<VkDeviceMemory> mvpBufferMemory;
uint32_t currentMvpBufferIndex = 0;
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
The Material::Cleanup method is currently incomplete. Based on the provided code, can you complete the code for this method?
|
628f1ff3512deca2e3608bf6c34e869c
|
{
"intermediate": 0.4536263644695282,
"beginner": 0.4259277880191803,
"expert": 0.12044584006071091
}
|
10,135
|
есть код на языке R.нужно переименовать переменные, седалть рефакторинг кода matr=sample(c(0,1), #setting a random matr
size=students^2,
prob=c(0.1,0.9), #probability of occurrence 0 and 1
replace=T) #with repetitions
team <- function(students,
matr=sample(c(0,1),
size=students^2,
prob=c(0.1,0.9),
replace=T)){
# set the vector of students
n <- sample(1:students) # write down the numbers from 1 to 20 in different order
# reshape vector matr into matrix
know <- matrix(matr,
nrow=length(n),ncol=length(n)) #the matrix must be symmetrical
for ( i in 1:nrow(know) ){ # for each student i check symmetry and create symmetric matrix
j <- 1
while ( j < i ){
know[i,j] <- know[j,i]
j <- j+1 #should be 1 on the diagonal since 1 knows 1, 2 knows the second...
}
know[i,i] <- 1
}
print(know)
# include those who know everyone
team_4 <- c() #the students themselves
r <- c() #student index
for ( i in 1:length(n) ){ # for each student (select his index from vector n)
e <- 0
for ( j in 1:length(n) ){ # calculate the number of students he knows
if ( know[n[i],n[j]] == 1 ){
e <- e+1 #if the student knows
}
}
if ( e == length(n) ){ # if he knows everyone -> include in team_4
team_4 <- c(team_4,n[i])
r <- c(r,i) # save the index of student in vector n
}
}
if ( length(r) != 0 & length(r) == length(n) ){ # all students know everyone
if ( length(n)%%2 == 0 ){ # split on 2 groups equally if n even
team_1 <- c(n[1:(length(n)/2)])
team_2 <- c(n[(length(n)/2+1):length(n)])
print(team_1)
print(team_2)
}else{ # split by 2 groups
team_1 <- c(n[1:(length(n)/2+0.5)])
team_2 <- c(n[(length(n)/2+1.5):length(n)])
print(team_1)
print(team_2)
}
}
else{
if ( length(r) != 0 ){ # if we have students who know everyone
n <- n[-r] # drop them from the vector n
}
# split students into 2 teams
vector <- n[-1]
team_1 <- c(n[1]) # put the first student from vector n in group 1 as a starting point
team_2 <- c()
l <- c()
u <- 1
while ( (length(team_1)+length(team_2)) < length(n) ){
for ( i in 1:length(team_1) ){ # for each student in team_1
for ( j in 1:length(n) ){ # for students from 1 to 20
e <- 0
if ( is.null(team_2) == FALSE ){
for ( k in 1:length(team_2) ){
if ( n[j] == team_2[k] ){ # if a student already in team_2 , then e = 1
e <- 1
}
}
}
if ( know[team_1[i],n[j]] == 0 & e == 0 ){ # if student i doesn't know the student j and student j not in team 2 -> put student j in team 2
team_2 <- c(team_2,n[j])
if ( length(vector) != 0 ){
for ( k in 1:length(vector) ){ # for each element of the vector, check if student j is equal to it and drop him out of vector
if ( vector[k] == n[j] ){
vector <- vector[-k]
break # stop when first true
}
}
}
}
}
}
o <- c()
for ( i in 1:length(team_2) ){ # for each student in team 2
for ( j in 1:length(n) ){ # for all other students
e <- 0
for ( k in 1:length(team_1) ){ # check if a user in team 1
if ( n[j] == team_1[k] ){
e <- 1
}
}
if ( know[team_2[i],n[j]] == 0 & e == 0 ){ # if j and i don't know each other -> put j into team_1
team_1 <- c(team_1,n[j])
o <- c(o,n[j]) # save the number of this student j in vector o
if ( length(vector) != 0 ){
for ( k in 1:length(vector) ){ # drop j from vector
if ( vector[k] == n[j] ){
vector <- vector[-k]
break
}
}
}
}
}
}
l <- c(l,length(team_1)+length(team_2)) # save the length of 2 teams
if ( u > 1 ){
if ( l[u] == l[u-1] ){ # if the sizes of the teams in 2 consecutive elements are same
if ( length(team_1) < length(team_2) ){
team_2 <- c(team_2,vector[1]) # include the first student from vector to team 2
vector <- vector[-1]
}else{
team_1 <- c(team_1,vector[1]) # else to team 1
vector <- vector[-1]
}
}
}
u <- u+1
}
#???????? ?? ???????????? ????????
# double check for relationships of users from team_1
w <- c()
if ( length(o) > 0 ){ # o is a vector with students in team1 , who don't know anyone in team 2 and were added in previous step
for ( i in 1:length(o) ){ # for each such student check whether he knows anyone of 20
for ( j in 1:length(n) ){
if ( know[o[i],n[j]] == 0 ){ # if no -> create vector w with all students he doesn't know
w <- c(w,n[j])
}
}
}
team_2 <- c(team_2,w) # add these users to team_2
}
e <- 0
for ( i in 1:length(team_1) ){ # if team_1 and team_2 include the same students -> break -> "?????????? ??????? ?? ??? ??????"
for ( j in 1:length(team_2) ){
if ( team_1[i] == team_2[j] ){
e <- 1
break
}
}
if ( e == 1 ){
print("Same students in the teams")
break
}
}
if ( e == 0 ){ # if teams are different
if ( length(o) != 0 ){ # if vector o with students from team 1 is not 0
team_2 <- team_2[1:(length(team_2)-length(w))] # drop w from team_2
}
if ( length(team_1) < length(team_2) ){ # if teams are of different sizeand team 1 is smaller change the order of teams
team_3 <- team_1
team_1 <- team_2
team_2 <- team_3
}
if ( length(team_4) == 0 ){ # team_4 includes students, who know everyone. If it is 0 then print the teams
if ( length(team_1)/length(team_2) <= 2 & length(team_1)/length(team_2) >= 1/2 ){
print(team_1)
print(team_2)
}else{
print(team_1)
print(team_2)
print("Everyone doesn't know at least someone: Conditions of task are not satisfied")
}
}else{ # if team 4 includes some users
while ( length(team_4) > 0 & length(team_1) > length(team_2) ){
team_2 <- c(team_2,team_4[1]) # include members of team 4 into team 2 while conditions are true
team_4 <- team_4[-1]
}
if ( length(team_4) != 0 ){ # if we still have some students in team_4
while ( length(team_4) > 0 ){
team_1 <- c(team_1,team_4[1]) # include them in team_1 and team_2 consecutively , start with team 1
team_4 <- team_4[-1]
if ( length(team_4) != 0 ){
team_2 <- c(team_2,team_4[1])
team_4 <- team_4[-1]
}
}
print(team_1) # print two teams
print(team_2)
}else{ # if no students in team_4 -> print teams (again strange part part)
if ( length(team_1)/length(team_2) <= 2 & length(team_1)/length(team_2) >= 1/2 ){
print(team_1)
print(team_2)
}else{
print(team_1)
print(team_2)
print("At least someone knows everyone: Conditions of task are not satisfied")
}
}
}
}
}
}
team(20)
|
86fd9b7707452d85b47df54b7c250ba6
|
{
"intermediate": 0.29096758365631104,
"beginner": 0.5480158925056458,
"expert": 0.16101647913455963
}
|
10,136
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code. (and don't forget to analyze your shits before outputs!): const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
f7be5dbf33c767a87b95d83463e4b8fb
|
{
"intermediate": 0.27949637174606323,
"beginner": 0.3869239389896393,
"expert": 0.3335796594619751
}
|
10,137
|
need to make normal snapability from 3dwireframe matrix model to grid, from grid to grid, from grid to 3dwfireframe matrix model and from 3dwireframe matrix model to 3dwireframe matrix model on mouse click to start-end snap points and making new 3dwireframe matrix lines that way. grid should not interline itself on its own, only by user mouse clicks! try output full properre modified and optimized code. (and don’t forget to analyze your shits before outputs!): const canvas = document.createElement(‘canvas’);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext(‘2d’);
const vmcMenu = document.getElementById(‘vmc-menu’);
const greenDotContainer = document.createElement(‘div’);
document.body.appendChild(greenDotContainer);
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById(‘red-dot’);
// Add Edge
document.getElementById(‘add-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById(‘remove-edge’).addEventListener(‘click’, () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = ‘#FFF’;
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = ‘hsla(’ + (angleX + offsetX + angleY + offsetY) * 55 + ‘, 100%, 30%, 0.8)’;
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener(‘mousedown’, (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener(‘mouseup’, () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener(‘mousemove’, (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = ‘block’;
vmcMenu.style.left = mousePos.x + ‘px’;
vmcMenu.style.top = mousePos.y + ‘px’;
document.getElementById(‘vmc-vertex-x’).value = vertices[bestIndex][0];
document.getElementById(‘vmc-vertex-y’).value = vertices[bestIndex][1];
document.getElementById(‘vmc-vertex-z’).value = vertices[bestIndex][2];
document.getElementById(‘vmc-vertex-x’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-y’).dataset.vertexIndex = bestIndex;
document.getElementById(‘vmc-vertex-z’).dataset.vertexIndex = bestIndex;
redDot.style.display = ‘block’;
redDot.style.left = projectedVertices[bestIndex][0] - 3 + ‘px’;
redDot.style.top = projectedVertices[bestIndex][1] - 3 + ‘px’;
} else {
vmcMenu.style.display = ‘none’;
redDot.style.display = ‘none’;
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById(‘vmc-vertex-x’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 0);
});
document.getElementById(‘vmc-vertex-y’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 1);
});
document.getElementById(‘vmc-vertex-z’).addEventListener(‘input’, (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
// Grid related variables
const gridSpacing = 50; // Spacing between grid lines (in px)
const gridPoints = []; // Array to store grid points
let displayGrid = true; // A flag to toggle grid display on and off
for (let i = 0; i < canvas.width; i += gridSpacing) {
for (let j = 0; j < canvas.height; j += gridSpacing) {
gridPoints.push({ x: i, y: j });
const dot = document.createElement(‘div’);
dot.className = ‘green-dot’;
dot.style.left = (i - 2) + ‘px’;
dot.style.top = (j - 2) + ‘px’;
dot.style.display = displayGrid ? ‘’ : ‘none’;
greenDotContainer.appendChild(dot);
}
}
// Renders grid lines
function renderGrid() {
if (!displayGrid) return;
ctx.strokeStyle = ‘#0F0’;
ctx.lineWidth = 1;
for (let i = 0; i <= canvas.width; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.stroke();
}
for (let i = 0; i <= canvas.height; i += gridSpacing) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.stroke();
}
}
// Adds a button to toggle the grid display
const gridToggleButton = document.createElement(‘button’);
gridToggleButton.innerText = ‘Toggle Grid’;
vmcMenu.insertBefore(gridToggleButton, document.getElementById(‘add-edge’));
gridToggleButton.addEventListener(‘click’, () => {
displayGrid = !displayGrid;
if (displayGrid) {
greenDotContainer.style.display = ‘block’;
} else {
greenDotContainer.style.display = ‘none’;
}
});
renderGrid();
requestAnimationFrame(render);
window.addEventListener(“resize”, () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
29a68c90cefab577561ba371a2691486
|
{
"intermediate": 0.2819575369358063,
"beginner": 0.3762917220592499,
"expert": 0.3417508006095886
}
|
10,138
|
i want to make a evaluation metrics, which takes into account the r2_score, mean_squared_error and mean_absolute error of the train data and test data each of the many trained ml models. Give a code to sort these models according to the new evaluation metrics
|
1dc644bcf3efb55655f14295f879fd07
|
{
"intermediate": 0.31925347447395325,
"beginner": 0.08734913170337677,
"expert": 0.5933974385261536
}
|
10,139
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
5e953af457fd8a1fed1791df19598ced
|
{
"intermediate": 0.30002614855766296,
"beginner": 0.36309120059013367,
"expert": 0.33688271045684814
}
|
10,140
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
8cb63d36cde0beb87a91bd350eaa4378
|
{
"intermediate": 0.30002614855766296,
"beginner": 0.36309120059013367,
"expert": 0.33688271045684814
}
|
10,141
|
Hi,
I have this code:
%%cu
#include <stdio.h>
#include <stdlib.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include "/content/common.h"
#define MATRIX_SIZE 1024
#define THREADS_PER_BLOCK 32
// Bitonic sort implementation
__device__ void bitonicSort(int* data, int k, int j, int dir) {
int i, temp;
if ((k & j) == 0) {
i = threadIdx.x / k;
if ((i & j) == 0) {
if (dir == 1) {
if (data[i * k + j] > data[i * k + j + k / 2]) {
temp = data[i * k + j];
data[i * k + j] = data[i * k + j + k / 2];
data[i * k + j + k / 2] = temp;
}
} else {
if (data[i * k + j] < data[i * k + j + k / 2]) {
temp = data[i * k + j];
data[i * k + j] = data[i * k + j + k / 2];
data[i * k + j + k / 2] = temp;
}
}
}
}
}
__global__ void sortKernel(int* data, int width, int height) {
int row = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height) {
// Sort the subsequence of integers using bitonic sort
for (int k = 2; k <= width; k *= 2) {
for (int j = k / 2; j > 0; j /= 2) {
bitonicSort(data + row * width, k, j, 1);
}
}
}
}
__global__ void mergeKernel(int* data, int width, int height, int iteration) {
int row = blockIdx.x * blockDim.x + threadIdx.x;
if (row < height) {
// Calculate the indices for merging the previously sorted halves
int blockSize = width / (1 << iteration);
int blockIndex = row / blockSize;
int indexInBlock = row % blockSize;
// Calculate the starting indices for the two halves to be merged
int leftStart = blockIndex * blockSize;
int rightStart = leftStart + blockSize / 2;
// Merge the two sorted halves into a single sorted subsequence
for (int k = blockSize / 2; k >= 1; k /= 2) {
int j = indexInBlock % k;
int leftIndex = leftStart + indexInBlock - j;
int rightIndex = rightStart + indexInBlock - j;
if (leftIndex < width && rightIndex < width) {
if (data[leftIndex] > data[rightIndex]) {
int temp = data[leftIndex];
data[leftIndex] = data[rightIndex];
data[rightIndex] = temp;
}
} else {
printf("Invalid memory access in mergeKernel.\n");
}
__syncthreads();
}
} else {
printf("Invalid memory access in mergeKernel.\n");
}
}
bool isSorted(int* data, int size) {
for (int i = 0; i < size - 1; i++) {
if (data[i] > data[i + 1])
return false;
}
return true;
}
int main() {
const int dataSize = MATRIX_SIZE * MATRIX_SIZE;
/* set up the device */
int dev = 0;
cudaDeviceProp deviceProp;
CHECK(cudaGetDeviceProperties(&deviceProp, dev));
printf("Using Device %d: %s\n", dev, deviceProp.name);
CHECK(cudaSetDevice(dev));
// Read the input data from file
FILE* inputFile = fopen("/content/datSeq1M.bin", "rb");
int* hostData = (int*)malloc(dataSize * sizeof(int));
fseek(inputFile, sizeof(int), SEEK_SET); // Skip the first integer
fread(hostData, sizeof(int), dataSize, inputFile);
fclose(inputFile);
// Print the sorted data
for (int i = 0; i < dataSize; i++) {
printf("%d ", hostData[i]);
if( i == 10 ) break;
}
printf("\n");
// Allocate memory on GPU
int* deviceData;
CHECK(cudaMalloc((void**)&deviceData, dataSize * sizeof(int)));
// Copy data to GPU
CHECK(cudaMemcpy(deviceData, hostData, dataSize * sizeof(int), cudaMemcpyHostToDevice));
/* run the computational kernel */
unsigned int gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ;
blockDimX = THREADS_PER_BLOCK;
blockDimY = 1;
blockDimZ = 1;
gridDimX = (dataSize + blockDimX - 1) / blockDimX;
gridDimY = 1;
gridDimZ = 1;
dim3 grid(gridDimX, gridDimY, gridDimZ);
dim3 block(blockDimX, blockDimY, blockDimZ);
// Launch the sorting kernels in iterations
int width = MATRIX_SIZE;
int height = MATRIX_SIZE;
for (int iteration = 1; iteration <= 10; iteration++) {
sortKernel<<<grid, block>>>(deviceData, width, height);
CHECK (cudaDeviceSynchronize ()); // wait for kernel to finish
CHECK (cudaGetLastError ()); // check for kernel errors
// Merge the previously sorted halves
mergeKernel<<<grid, block>>>(deviceData, width, height, iteration);
CHECK (cudaDeviceSynchronize ()); // wait for kernel to finish
CHECK (cudaGetLastError ()); // check for kernel errors
// Update the width and height for the next iteration
width *= 2;
height /= 2;
}
// Copy sorted data back to CPU
cudaMemcpy(hostData, deviceData, dataSize * sizeof(int), cudaMemcpyDeviceToHost);
// Check if the array is sorted
bool isOrdered = isSorted(hostData, dataSize);
// Print the sorted data
for (int i = 0; i < dataSize; i++) {
printf("%d ", hostData[i]);
if( i == 10 ) break;
}
printf("\n");
// Print the result of the ordering check
if (isOrdered) {
printf("The array is ordered.\n");
} else {
printf("The array is not ordered.\n");
}
// Free GPU memory
cudaFree(deviceData);
// Free CPU memory
free(hostData);
return 0;
}
And it is supposed to do this:
The kernels to be written should sort the contents of the file datSeq1M.bin in 10 iteration
steps. In iteration 1, 1024 subsequences of 1024 integer values are to be sorted in parallel. In
iteration 2, 512 subsequences of 2048 integer values are to be sorted in parallel based on the
merging of the previously sorted halves. And so on and so forth, until iteration 10 is reached,
where 2 previously sorted subsequences of 512K values are merged, yielding the whole sorted
sequence.
Assume that the values of the whole sequence, when stored in memory, are organized as the
elements of 1024 X 1024 matrix. The threads in a block thread process successive matrix rows.
But im getting this error:
Error: /tmp/tmp2rhhmu8n/208c30b5-68a7-4c2b-881c-f2b5913f6acd.cu:135, code: 700, reason: an illegal memory access was encountered
Fix it and give me the full code please
|
9b7edb84433881d69bbc586658760e6f
|
{
"intermediate": 0.36709389090538025,
"beginner": 0.38975971937179565,
"expert": 0.2431463599205017
}
|
10,142
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
60c49c800c7d3efef1bc010734a609ff
|
{
"intermediate": 0.30002614855766296,
"beginner": 0.36309120059013367,
"expert": 0.33688271045684814
}
|
10,143
|
make some attachment points on which new edges-vertices can be snapped. spread all these attachment points all over canvas through the center of 3d matrix model. make this mvc menu appear and disappear when pointing throughou these attachmen point grid, to be able to press that addedge button and draw a new line to extend the actual wireframe. output only full properre modified and optimized code, without any shortages and cutoffs. analyze all possible functions extremely careful and if need optimize or adapt them appropriately and accordingly, by not ruinning the transformation animations and deviations. (if need make your own version of absolutely new code but with the same similar functionalities.): <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
20ba2b4446f9f5d086105c2ca470525e
|
{
"intermediate": 0.30002614855766296,
"beginner": 0.36309120059013367,
"expert": 0.33688271045684814
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.