row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
12,857
|
const Cart = () => {
const cart = useAppSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState("");
const onToken = (token: string) => {
setStripeToken(token);
};
console.log(stripeToken);
return (
<Container>
<Navbar />
<PromoInfo />
<Wrapper>
<Title>YOUR CART</Title>
<Top>
<TopButton>CONTINUE SHOPPING</TopButton>
<TopTexts>
<TopText>Shopping Bag(2)</TopText>
<TopText>Your Wishlist(0)</TopText>
</TopTexts>
<TopButton buttonType="filled">CHECKOUT NOW</TopButton>
</Top>
<Bottom>
<Information>
{cart.products.map((product) => (
<Product>
<ProductDetail>
<Image src={product.img} />
<Details>
<ProductName>
<b>Product:</b>
{product.title}
</ProductName>
<ProductId>
<b>ID:</b>
{product._id}
</ProductId>
{product.color?.map((color, i) => (
<ProductColor key={i} color={color} />
))}
</Details>
</ProductDetail>
<PriceDetail>
<ProductAmountContainer>
<AddIcon />
<ProductAmount>{product.quantity}</ProductAmount>
<RemoveIcon />
</ProductAmountContainer>
<ProductPrice>
{product.price * product.quantity}PLN
</ProductPrice>
</PriceDetail>
</Product>
))}
<Hr />
</Information>
<Summary>
<SummaryTitle>ORDER SUMMARY</SummaryTitle>
<SummaryItem>
<SummaryItemText>Subtotal</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Estimated Shipping</SummaryItemText>
<SummaryItemPrice>5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Shipping Discount</SummaryItemText>
<SummaryItemPrice>-5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem type="total">
<SummaryItemText>Total</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<StripeCheckout
name="FABICO"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
billingAddress
shippingAddress
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey={KEY || ""}
>
<SummaryButton>CHECKOUT NOW</SummaryButton>
</StripeCheckout>
</Summary>
</Bottom>
</Wrapper>
<Footer />
</Container>
);
};
TS2769: No overload matches this call.
Overload 1 of 2, '(props: StripeCheckoutProps | Readonly<StripeCheckoutProps>): StripeCheckout', gave the following error.
Type '(token: string) => void' is not assignable to type '(token: Token) => void'.
Types of parameters 'token' and 'token' are incompatible.
Type 'Token' is not assignable to type 'string'.
Overload 2 of 2, '(props: StripeCheckoutProps, context: any): StripeCheckout', gave the following error.
Type '(token: string) => void' is not assignable to type '(token: Token) => void'.
208 | description={`Your total is $${cart.total}`}
209 | amount={cart.total * 100}
> 210 | token={onToken}
| ^^^^^
211 | stripeKey={KEY || ""}
212 | >
213 | <SummaryButton>CHECKOUT NOW</SummaryButton>
|
1469ca4bee91bdde1d585b6204facd9c
|
{
"intermediate": 0.31232938170433044,
"beginner": 0.5513283014297485,
"expert": 0.13634228706359863
}
|
12,858
|
请用C#语言改写以下代码
BOOL CSystemTray::Create(HINSTANCE hInst, HWND hParent, UINT uCallbackMessage,
LPCTSTR szToolTip, HICON icon, UINT uID, BOOL bHidden /*=FALSE*/,
LPCTSTR szBalloonTip /*=NULL*/,
LPCTSTR szBalloonTitle /*=NULL*/,
DWORD dwBalloonIcon /*=NIIF_NONE*/,
UINT uBalloonTimeout /*=10*/)
{
#ifdef _WIN32_WCE
m_bEnabled = TRUE;
#else
// this is only for Windows 95 (or higher)
m_bEnabled = (GetVersion() & 0xff) >= 4;
if (!m_bEnabled)
{
ASSERT(FALSE);
return FALSE;
}
#endif
m_nMaxTooltipLength = _countof(m_tnd.szTip);
// Make sure we avoid conflict with other messages
ASSERT(uCallbackMessage >= WM_APP);
// Tray only supports tooltip text up to m_nMaxTooltipLength) characters
ASSERT(_tcslen(szToolTip) <= m_nMaxTooltipLength);
m_hInstance = hInst;
RegisterClass(hInst);
// Create an invisible window
m_hWnd = ::CreateWindow(TRAYICON_CLASS, _T(""), WS_POPUP,
CW_USEDEFAULT,CW_USEDEFAULT,
CW_USEDEFAULT,CW_USEDEFAULT,
NULL, 0,
hInst, 0);
// load up the NOTIFYICONDATA structure
//m_tnd.cbSize = sizeof(NOTIFYICONDATA);
m_tnd.cbSize = NOTIFYICONDATA_V2_SIZE; // 2012-01-05 GONG Chen, XP compatibility
m_tnd.hWnd = (hParent)? hParent : m_hWnd;
m_tnd.uID = uID;
m_tnd.hIcon = icon;
m_tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
m_tnd.uCallbackMessage = uCallbackMessage;
// 2007-11-14 GONG
_tcsncpy_s(m_tnd.szTip, _countof(m_tnd.szTip), szToolTip, m_nMaxTooltipLength);
#ifdef SYSTEMTRAY_USEW2K
if (m_bWin2K && szBalloonTip)
{
#if _MSC_VER < 0x1000
// The balloon tooltip text can be up to 255 chars long.
// ASSERT(AfxIsValidString(szBalloonTip));
ASSERT(lstrlen(szBalloonTip) < 256);
#endif
// The balloon title text can be up to 63 chars long.
if (szBalloonTitle)
{
// ASSERT(AfxIsValidString(szBalloonTitle));
ASSERT(lstrlen(szBalloonTitle) < 64);
}
// dwBalloonIcon must be valid.
ASSERT(NIIF_NONE == dwBalloonIcon || NIIF_INFO == dwBalloonIcon ||
NIIF_WARNING == dwBalloonIcon || NIIF_ERROR == dwBalloonIcon);
// The timeout must be between 10 and 30 seconds.
ASSERT(uBalloonTimeout >= 10 && uBalloonTimeout <= 30);
m_tnd.uFlags |= NIF_INFO;
_tcsncpy_s(m_tnd.szInfo, _countof(m_tnd.szInfo), szBalloonTip, 255);
if (szBalloonTitle)
_tcsncpy_s(m_tnd.szInfoTitle, _countof(m_tnd.szInfoTitle), szBalloonTitle, 63);
else
m_tnd.szInfoTitle[0] = _T('\0');
m_tnd.uTimeout = uBalloonTimeout * 1000; // convert time to ms
m_tnd.dwInfoFlags = dwBalloonIcon;
}
#endif
m_bHidden = bHidden;
m_hTargetWnd = m_tnd.hWnd;
#ifdef SYSTEMTRAY_USEW2K
if (m_bWin2K && m_bHidden)
{
m_tnd.uFlags = NIF_STATE;
m_tnd.dwState = NIS_HIDDEN;
m_tnd.dwStateMask = NIS_HIDDEN;
}
#endif
m_uCreationFlags = m_tnd.uFlags; // Store in case we need to recreate in OnTaskBarCreate
BOOL bResult = TRUE;
if (!m_bHidden || m_bWin2K)
{
bResult = Shell_NotifyIcon(NIM_ADD, &m_tnd);
m_bShowIconPending = m_bHidden = m_bRemoved = !bResult;
}
#ifdef SYSTEMTRAY_USEW2K
if (m_bWin2K && szBalloonTip)
{
// Zero out the balloon text string so that later operations won't redisplay
// the balloon.
m_tnd.szInfo[0] = _T('\0');
}
#endif
return bResult;
}
|
0bbc056866a52ae7f5db840081676981
|
{
"intermediate": 0.303472101688385,
"beginner": 0.4461419880390167,
"expert": 0.2503858506679535
}
|
12,859
|
function addItem() {
// We'll work on this next
console.time('state')
setThingsArray([
...thingsArray,
`Things ${thingsArray.length+1}`
])
console.timeEnd('state')
console.log(thingsArray)
}
|
ba605b6987a5943ffe55056fe1b0c0e6
|
{
"intermediate": 0.3340030610561371,
"beginner": 0.4064425230026245,
"expert": 0.2595544457435608
}
|
12,860
|
Hello, pretend to be an expert in databases, especially in mongodb, analyze the following statement in detail and give me the code step by step:
Create the carStore database.
Then create the following collections: cars, customers, category, sales.
Then add the following data to the collection category:
categoryId: cat01, description: sedan.
categoryId: cat02, description: sport.
Then add the following data to the cars collection, pay attention to the indications that are in parentheses since they indicate where to make a relationship preferably using the added method:
carId: C001, brand: Toyota, model: Corolla, year: 2020, (attention this is where the relationship has to go) type: sedan (attention this data comes from the relationship with the category collection), price: 800.
carId: C002, make: Chevrolet, model: Camaro, year: 2022, type: sport (attention this data comes from the relationship with the category collection), price: 2000.
Then it lists all the cars and categories.
|
97c971bbb397299c2706fc67b9787353
|
{
"intermediate": 0.4239889681339264,
"beginner": 0.2048736810684204,
"expert": 0.3711373209953308
}
|
12,861
|
import { useState } from "react";
import dotenv from "dotenv";
import styled from "styled-components";
import Navbar from "../components/Navbar";
import PromoInfo from "../components/PromoInfo";
import Footer from "../components/Footer";
import RemoveIcon from "@mui/icons-material/Remove";
import AddIcon from "@mui/icons-material/Add";
import { useAppSelector } from "../redux/store";
import StripeCheckout from "react-stripe-checkout";
import { Token } from "react-stripe-checkout";
const KEY = process.env.REACT_APP_STRIPE || "";
type ButtonProps = {
buttonType?: "filled";
};
type SummaryItemProps = {
type?: string;
};
const Container = styled.div``;
const Wrapper = styled.div`
padding: 20px;
`;
const Title = styled.h2`
font-weight: 300;
text-align: center;
`;
const Top = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
`;
const TopButton = styled.button<ButtonProps>`
padding: 10px;
font-weight: 600;
cursor: pointer;
border: ${(props) => (props.buttonType === "filled" ? "none" : null)};
background-color: ${(props) =>
props.buttonType === "filled" ? "black" : "transparent"};
color: ${(props) => (props.buttonType === "filled" ? "white" : null)};
`;
const TopTexts = styled.div``;
const TopText = styled.span`
text-decoration: underline;
cursor: pointer;
margin: 0 10px;
`;
const Bottom = styled.div`
display: flex;
justify-content: space-between;
`;
const Information = styled.div`
flex: 3;
`;
const Product = styled.div`
display: flex;
justify-content: space-between;
`;
const ProductDetail = styled.div`
flex: 2;
display: flex;
`;
const Image = styled.img`
width: 200px;
`;
const Details = styled.div`
padding: 20px;
display: flex;
flex-direction: column;
justify-content: space-around;
`;
const ProductName = styled.span``;
const ProductId = styled.span``;
const ProductColor = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${(props) => props.color};
`;
const PriceDetail = styled.div`
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
const ProductAmountContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
`;
const ProductAmount = styled.div`
font-size: 24px;
margin: 5px;
`;
const ProductPrice = styled.div`
font-size: 30px;
font-weight: 200;
`;
const Hr = styled.hr`
background-color: #5a5959;
border: none;
height: 1px;
`;
const Summary = styled.div`
flex: 1;
border: 0.5px solid black;
border-radius: 10px;
padding: 20px;
`;
const SummaryTitle = styled.h2`
font-weight: 200;
`;
const SummaryItem = styled.div<SummaryItemProps>`
margin: 30px 0;
display: flex;
justify-content: space-between;
font-weight: ${(props) => (props.type === "total" ? 500 : null)};
font-size: ${(props) => (props.type === "total" ? "24px" : null)};
`;
const SummaryItemText = styled.span``;
const SummaryItemPrice = styled.span``;
const SummaryButton = styled.button`
width: 100%;
padding: 10px;
background-color: black;
color: white;
font-weight: 600;
`;
const Cart = () => {
const cart = useAppSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState("");
const onToken = (token: Token) => {
setStripeToken(token.id);
};
console.log(stripeToken);
return (
<Container>
<Navbar />
<PromoInfo />
<Wrapper>
<Title>YOUR CART</Title>
<Top>
<TopButton>CONTINUE SHOPPING</TopButton>
<TopTexts>
<TopText>Shopping Bag(2)</TopText>
<TopText>Your Wishlist(0)</TopText>
</TopTexts>
<TopButton buttonType="filled">CHECKOUT NOW</TopButton>
</Top>
<Bottom>
<Information>
{cart.products.map((product) => (
<Product>
<ProductDetail>
<Image src={product.img} />
<Details>
<ProductName>
<b>Product:</b>
{product.title}
</ProductName>
<ProductId>
<b>ID:</b>
{product._id}
</ProductId>
{product.color?.map((color, i) => (
<ProductColor key={i} color={color} />
))}
</Details>
</ProductDetail>
<PriceDetail>
<ProductAmountContainer>
<AddIcon />
<ProductAmount>{product.quantity}</ProductAmount>
<RemoveIcon />
</ProductAmountContainer>
<ProductPrice>
{product.price * product.quantity}PLN
</ProductPrice>
</PriceDetail>
</Product>
))}
<Hr />
</Information>
<Summary>
<SummaryTitle>ORDER SUMMARY</SummaryTitle>
<SummaryItem>
<SummaryItemText>Subtotal</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Estimated Shipping</SummaryItemText>
<SummaryItemPrice>5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Shipping Discount</SummaryItemText>
<SummaryItemPrice>-5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem type="total">
<SummaryItemText>Total</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<StripeCheckout
name="FABICO"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey={KEY}
></StripeCheckout>
</Summary>
</Bottom>
</Wrapper>
<Footer />
</Container>
);
};
export default Cart;
why const KEY = process.env.REACT_APP_STRIPE || ""; don't work?
|
d8bc13c400165b84bd7f41a455027f06
|
{
"intermediate": 0.3290448486804962,
"beginner": 0.49040982127189636,
"expert": 0.1805453598499298
}
|
12,862
|
You will get instructions for code to write.
You will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.
You will first lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.
Then you will output the content of each file, with syntax below.
(You will start with the "entrypoint" file, then go to the ones that are imported by that file, and so on.)
Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.
Ensure to implement all code, if you are unsure, write a plausible implementation.
Before you finish, double check that all parts of the architecture is present in the files.
File syntax:
|
8d5055ba5a77b92ee8190aa33892686a
|
{
"intermediate": 0.18467757105827332,
"beginner": 0.5713608264923096,
"expert": 0.24396157264709473
}
|
12,863
|
You will get instructions for code to write.
You will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.
You will first lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.
Then you will output the content of each file, with syntax below.
(You will start with the "entrypoint" file, then go to the ones that are imported by that file, and so on.)
Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.
Ensure to implement all code, if you are unsure, write a plausible implementation.
Before you finish, double check that all parts of the architecture is present in the files.
File syntax:
|
70743a33a8b21372ed675320a20e82f8
|
{
"intermediate": 0.18467757105827332,
"beginner": 0.5713608264923096,
"expert": 0.24396157264709473
}
|
12,864
|
You will get instructions for code to write.
You will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.
You will first lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.
Then you will output the content of each file, with syntax below.
(You will start with the "entrypoint" file, then go to the ones that are imported by that file, and so on.)
Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.
Ensure to implement all code, if you are unsure, write a plausible implementation.
Before you finish, double check that all parts of the architecture is present in the files.
File syntax:
|
e3bb2d0177e84c25a1b96e0cd89ae03a
|
{
"intermediate": 0.18467757105827332,
"beginner": 0.5713608264923096,
"expert": 0.24396157264709473
}
|
12,865
|
import { useState } from "react";
import dotenv from "dotenv";
import styled from "styled-components";
import Navbar from "../components/Navbar";
import PromoInfo from "../components/PromoInfo";
import Footer from "../components/Footer";
import RemoveIcon from "@mui/icons-material/Remove";
import AddIcon from "@mui/icons-material/Add";
import { useAppSelector } from "../redux/store";
import StripeCheckout from "react-stripe-checkout";
import { Token } from "react-stripe-checkout";
dotenv.config();
const KEY = process.env.REACT_APP_STRIPE;
type ButtonProps = {
buttonType?: "filled";
};
type SummaryItemProps = {
type?: string;
};
const Container = styled.div``;
const Wrapper = styled.div`
padding: 20px;
`;
const Title = styled.h2`
font-weight: 300;
text-align: center;
`;
const Top = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
`;
const TopButton = styled.button<ButtonProps>`
padding: 10px;
font-weight: 600;
cursor: pointer;
border: ${(props) => (props.buttonType === "filled" ? "none" : null)};
background-color: ${(props) =>
props.buttonType === "filled" ? "black" : "transparent"};
color: ${(props) => (props.buttonType === "filled" ? "white" : null)};
`;
const TopTexts = styled.div``;
const TopText = styled.span`
text-decoration: underline;
cursor: pointer;
margin: 0 10px;
`;
const Bottom = styled.div`
display: flex;
justify-content: space-between;
`;
const Information = styled.div`
flex: 3;
`;
const Product = styled.div`
display: flex;
justify-content: space-between;
`;
const ProductDetail = styled.div`
flex: 2;
display: flex;
`;
const Image = styled.img`
width: 200px;
`;
const Details = styled.div`
padding: 20px;
display: flex;
flex-direction: column;
justify-content: space-around;
`;
const ProductName = styled.span``;
const ProductId = styled.span``;
const ProductColor = styled.div`
width: 20px;
height: 20px;
border-radius: 50%;
background-color: ${(props) => props.color};
`;
const PriceDetail = styled.div`
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
const ProductAmountContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
`;
const ProductAmount = styled.div`
font-size: 24px;
margin: 5px;
`;
const ProductPrice = styled.div`
font-size: 30px;
font-weight: 200;
`;
const Hr = styled.hr`
background-color: #5a5959;
border: none;
height: 1px;
`;
const Summary = styled.div`
flex: 1;
border: 0.5px solid black;
border-radius: 10px;
padding: 20px;
`;
const SummaryTitle = styled.h2`
font-weight: 200;
`;
const SummaryItem = styled.div<SummaryItemProps>`
margin: 30px 0;
display: flex;
justify-content: space-between;
font-weight: ${(props) => (props.type === "total" ? 500 : null)};
font-size: ${(props) => (props.type === "total" ? "24px" : null)};
`;
const SummaryItemText = styled.span``;
const SummaryItemPrice = styled.span``;
const SummaryButton = styled.button`
width: 100%;
padding: 10px;
background-color: black;
color: white;
font-weight: 600;
`;
const Cart = () => {
const cart = useAppSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState("");
const onToken = (token: Token) => {
setStripeToken(token.id);
};
console.log(KEY);
return (
<Container>
<Navbar />
<PromoInfo />
<Wrapper>
<Title>YOUR CART</Title>
<Top>
<TopButton>CONTINUE SHOPPING</TopButton>
<TopTexts>
<TopText>Shopping Bag(2)</TopText>
<TopText>Your Wishlist(0)</TopText>
</TopTexts>
<TopButton buttonType="filled">CHECKOUT NOW</TopButton>
</Top>
<Bottom>
<Information>
{cart.products.map((product) => (
<Product>
<ProductDetail>
<Image src={product.img} />
<Details>
<ProductName>
<b>Product:</b>
{product.title}
</ProductName>
<ProductId>
<b>ID:</b>
{product._id}
</ProductId>
{product.color?.map((color, i) => (
<ProductColor key={i} color={color} />
))}
</Details>
</ProductDetail>
<PriceDetail>
<ProductAmountContainer>
<AddIcon />
<ProductAmount>{product.quantity}</ProductAmount>
<RemoveIcon />
</ProductAmountContainer>
<ProductPrice>
{product.price * product.quantity}PLN
</ProductPrice>
</PriceDetail>
</Product>
))}
<Hr />
</Information>
<Summary>
<SummaryTitle>ORDER SUMMARY</SummaryTitle>
<SummaryItem>
<SummaryItemText>Subtotal</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Estimated Shipping</SummaryItemText>
<SummaryItemPrice>5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Shipping Discount</SummaryItemText>
<SummaryItemPrice>-5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem type="total">
<SummaryItemText>Total</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<StripeCheckout
name="FABICO"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey="pk_test_51LIIjSLsQot4Cql4LmUPJyQAn91rhWQMAAU7hoOvtzXIkxD06sm02vj8XHjlAJga35YSPqjMBMpsDLV68PTJeofj00RzqW0c9r"
></StripeCheckout>
</Summary>
</Bottom>
</Wrapper>
<Footer />
</Container>
);
};
export default Cart;
it is in react, why dotenv don't work?
|
d4f6441e525e3a24dc48b84ce1e34ed7
|
{
"intermediate": 0.3403426706790924,
"beginner": 0.47378426790237427,
"expert": 0.1858730912208557
}
|
12,866
|
You will get instructions for code to write.
You will write a very long answer. Make sure that every detail of the architecture is, in the end, implemented as code.
You will first lay out the names of the core classes, functions, methods that will be necessary, As well as a quick comment on their purpose.
Then you will output the content of each file with syntax below inside a python script named "creator.py" for google colab that autmatically creates all the files and their content
(You will start with the "entrypoint" file, then go to the ones that are imported by that file, and so on.)
Make sure that files contain all imports, types etc. Make sure that code in different files are compatible with each other.
Ensure to implement all code, if you are unsure, write a plausible implementation.
Before you finish, double check that all parts of the architecture is present in the files.
File syntax:
|
2ae6d5f4ace059fcba2e4e2a1c353415
|
{
"intermediate": 0.16050396859645844,
"beginner": 0.6166743636131287,
"expert": 0.22282159328460693
}
|
12,867
|
create a time table with using alert
|
25db7b30f7c581c0815efd47d6cbb6ce
|
{
"intermediate": 0.41361185908317566,
"beginner": 0.1801167130470276,
"expert": 0.40627145767211914
}
|
12,868
|
import dotenv from 'dotenv';
dotenv.config();
console.log(process.env.MY_KEY);
this doen't work some webpack errors?
|
81c2bbc82d1be62a20b24fe20f3d1fe9
|
{
"intermediate": 0.7313209772109985,
"beginner": 0.1697254776954651,
"expert": 0.09895353019237518
}
|
12,870
|
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
why dotenv don't work on react tsx?
|
273ba1ae373563bf98a8155ec98f072e
|
{
"intermediate": 0.513579249382019,
"beginner": 0.34312188625335693,
"expert": 0.1432989090681076
}
|
12,871
|
what is code refactory
|
902078a20d60827e0317a5c13190e7c1
|
{
"intermediate": 0.2815011441707611,
"beginner": 0.32683098316192627,
"expert": 0.3916678726673126
}
|
12,872
|
how do i spilt a latex subsection list horizontally
|
6100e93ea0455b84a818f8a1618563c9
|
{
"intermediate": 0.3766235411167145,
"beginner": 0.38316744565963745,
"expert": 0.24020904302597046
}
|
12,873
|
TB_GETITEMRECT消息在C#语言中怎么使用
|
cf28bb3d691692e8ccd6ce8fe06773ad
|
{
"intermediate": 0.3701673746109009,
"beginner": 0.2833969295024872,
"expert": 0.3464357256889343
}
|
12,874
|
hello !
|
5230d9612b07fd69294f7d41df5779c0
|
{
"intermediate": 0.3269449770450592,
"beginner": 0.2993490695953369,
"expert": 0.37370598316192627
}
|
12,875
|
We have this code. You need to edit car structure doing this and earlier created functions should work correctly:
char* car brand
field FIO (First name, last name, patronymic)
int engine power
int Mileage
field DATE (date of last maintenance)
(date structure: number (int), month(char*), year (int)) (use typedef):
#include
#include
#include
using namespace std;
struct car
{
char *brand;
char *surname;
char *name;
int power;
int mileage;
};
void add_car(car *arr, int &n)
{
cout << “Enter car brand:” << endl;
char brand[1000];
gets(brand);
arr[n].brand = new char[strlen(brand) + 1];
strcpy(arr[n].brand, brand);
cout << “Enter owner’s surname:” << endl;
char surname[1000];
gets(surname);
arr[n].surname = new char[strlen(surname) + 1];
strcpy(arr[n].surname, surname);
cout << “Enter owner’s name:” << endl;
char name[1000];
gets(name);
arr[n].name = new char[strlen(name) + 1];
strcpy(arr[n].name, name);
cout << “Enter engine power:” << endl;
cin >> arr[n].power;
cout << “Enter mileage:” << endl;
cin >> arr[n].mileage;
n++;
}
void print(car *arr, int n)
{
cout << “Car brand | Owner’s surname | Owner’s name | Engine power | Mileage” << endl;
for (int i = 0; i < n; i++)
{
cout << arr[i].brand << " | " << arr[i].surname << " | " << arr[i].name << " | " << arr[i].power << " | " << arr[i].mileage << endl;
}
}
void find_brand(car *arr, int n)
{
cout << “Enter car brand to find:” << endl;
char brand[1000];
gets(brand);
cout << "Cars of brand " << brand << “:” << endl;
for (int i = 0; i < n; i++)
{
if (strcmp(arr[i].brand, brand) == 0)
{
cout << arr[i].surname << " " << arr[i].name << endl;
}
}
}
void find_mileage(car *arr, int n)
{
cout << “Enter mileage value:” << endl;
int mileage;
cin >> mileage;
int count = 0;
for (int i = 0; i < n; i++)
{
if (arr[i].mileage > mileage)
{
count++;
}
}
if (count == 0)
{
cout << "No cars with mileage greater than " << mileage << endl;
return;
}
car *new_arr = new car[count];
int index = 0;
for (int i = 0; i < n; i++)
{
if (arr[i].mileage > mileage)
{
new_arr[index] = arr[i];
index++;
}
}
for (int i = 0; i < count - 1; i++)
{
for (int j = 0; j < count - i - 1; j++)
{
if (strcmp(new_arr[j].surname, new_arr[j + 1].surname) > 0)
{
car tmp = new_arr[j];
new_arr[j] = new_arr[j + 1];
new_arr[j + 1] = tmp;
}
}
}
cout << "Owners of cars with mileage greater than " << mileage << “:” << endl;
for (int i = 0; i < count; i++)
{
cout << new_arr[i].surname << " " << new_arr[i].name << endl;
}
delete[] new_arr;
}
int main()
{
int n = 0;
car *arr = new car[1000];
while (true)
{
cout << endl
<< “Select an action:” << endl;
cout << “1. Add a new car” << endl;
cout << “2. Print car information” << endl;
cout << “3. Find all cars of a certain brand” << endl;
cout << “4. Find all owners of cars with a mileage greater than a given value” << endl;
cout << “5. Exit the program” << endl;
int choice;
cin >> choice;
cin.get();
switch (choice)
{
case 1:
add_car(arr, n);
break;
case 2:
print(arr, n);
break;
case 3:
find_brand(arr, n);
break;
case 4:
find_mileage(arr, n);
break;
case 5:
delete[] arr;
return 0;
break;
default:
cout << “Error!” << endl;
break;
}
}
return 0;
}
|
fd0021140daa2e38509fc9c51005d88c
|
{
"intermediate": 0.31597423553466797,
"beginner": 0.511052668094635,
"expert": 0.17297309637069702
}
|
12,876
|
hello, this code throws an error find: unknown predicate `--metadata=mediatype:movies'
ERROR: Postprocessing: Command returned error code 1
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/YoutubeDL.py", line 3356, in process_info
replace_info_dict(self.post_process(dl_filename, info_dict, files_to_move))
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/YoutubeDL.py", line 3539, in post_process
return self.run_all_pps('after_move', info)
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/YoutubeDL.py", line 3518, in run_all_pps
info = self.run_pp(pp, info)
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/YoutubeDL.py", line 3496, in run_pp
files_to_delete, infodict = pp.run(infodict)
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/postprocessor/common.py", line 24, in run
ret = func(self, info, *args, **kwargs)
File "/usr/local/lib/python3.10/dist-packages/yt_dlp/postprocessor/exec.py", line 33, in run
raise PostProcessingError('Command returned error code %d' % retCode)
yt_dlp.utils.PostProcessingError: Command returned error code 1
|
606b9336c468c9e228726953b5447d30
|
{
"intermediate": 0.4540627598762512,
"beginner": 0.3433922827243805,
"expert": 0.20254497230052948
}
|
12,877
|
I have a table store the country. I want to make a select field to user to select.
|
9e20ce22631b257cb2ca4f64a5d091c8
|
{
"intermediate": 0.29490911960601807,
"beginner": 0.24410802125930786,
"expert": 0.4609828591346741
}
|
12,878
|
how do i use a time icon in latex
|
9008d08bf4dc25cd2e1229804995aba8
|
{
"intermediate": 0.47129279375076294,
"beginner": 0.26631033420562744,
"expert": 0.2623968720436096
}
|
12,879
|
Tell me all I need to know about noble gases
|
9e7b6bbabd5bf638126285adb4e0ce6a
|
{
"intermediate": 0.3663260340690613,
"beginner": 0.3815405070781708,
"expert": 0.25213345885276794
}
|
12,880
|
hwo do i insert a person icon into latex
|
7c4a5b4211b015edc770ea48a7a9208f
|
{
"intermediate": 0.41204607486724854,
"beginner": 0.287230521440506,
"expert": 0.30072346329689026
}
|
12,881
|
in python green is; \033[1;32;40m can you make a yellow
|
db70a6c6ef60fceb6c8d010827c743cb
|
{
"intermediate": 0.26242876052856445,
"beginner": 0.2838749587535858,
"expert": 0.4536963105201721
}
|
12,882
|
while reading csv Pyspark skips blank rows
|
25b5295293b57d7efdb47a60beecc818
|
{
"intermediate": 0.2968657612800598,
"beginner": 0.3831922113895416,
"expert": 0.31994205713272095
}
|
12,883
|
how do I read 32 bytes, zero-padded ASCII string.
|
86236dd8dc5bb0af2e39c806d5346364
|
{
"intermediate": 0.4866752028465271,
"beginner": 0.2738494575023651,
"expert": 0.2394753396511078
}
|
12,884
|
Explain serialization vs https query
|
8afc43937e30e16bec8135b3285d1b40
|
{
"intermediate": 0.42171812057495117,
"beginner": 0.23852787911891937,
"expert": 0.33975404500961304
}
|
12,885
|
package org.example;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.interactions.Actions;
public class TelegramUsernames {
public static void main(String[] args) throws InterruptedException, IOException {
// Установите путь к драйверу Edge
System.setProperty("webdriver.edge.driver", "C:/MyCode/Tools/Msegdriver/edgedriver_win64 v115.0.1901.9/msedgedriver.exe");
// Создайте экземпляр драйвера
WebDriver driver = new EdgeDriver();
// Откройте Telegram в браузере
driver.get("https://web.telegram.org/k/#@prepodsteam");
Thread.sleep(15000);
driver.get("https://web.telegram.org/k/#@prepodsteam");
Thread.sleep(3000);
// Находим все элементы с классом "peer-title"
var doc = Jsoup.connect(driver.getCurrentUrl()).get();
Elements allPeerTitles = doc.select("span.peer-title");
Elements filteredPeerTitles = new Elements();
for (Element peerTitle : allPeerTitles) {
if (!peerTitle.hasAttr("data-exclude")) {
filteredPeerTitles.add(peerTitle);
}
}
// Получение объекта HTML с помощью селектора CSS
WebElement repliesElementSelenium = driver.findElement(By.cssSelector("replies-element[data-post-key='-1361050199_4294969813']"));
Elements repliesElements = doc.select("replies-element[data-post-key='-1361050199_4294969813']");
Element repliesElement = repliesElements.first();
// Выполнение действий с объектом HTML (например, нажатие на него)
repliesElementSelenium.click();
Thread.sleep(2000);
Set<String> links = new HashSet<>();
for (Element element : filteredPeerTitles) {
// Получаем значение атрибута "data-peer-id"
String peerId = element.attr("data-peer-id");
// Создаем экземпляр класса Actions
Actions actions = new Actions(driver);
// Перемещаем курсор мыши на элемент и кликаем на нем
actions.moveToElement(element).click().perform();
// Ждем, пока страница загрузится
Thread.sleep(2000);
// Получаем ссылку на текущую страницу
String currentUrl = driver.getCurrentUrl();
Thread.sleep(2000);
// Добавляем ссылку в множество, если ее там еще нет
if (!links.contains(currentUrl)) {
links.add(currentUrl);
}
// Находим кнопку с классом "sidebar-close-button"
WebElement closeButton = driver.findElement(By.className("sidebar-close-button"));
// Кликаем на кнопку
closeButton.click();
}
// Выводим уникальные ссылки
for (String link : links) {
System.out.println(link);
}
// Закрываем драйвер
driver.quit();
}
}
/* // Получите список имен пользователей и запишите их в файл
List<WebElement> usernames = driver.findElements(By.xpath("//div[@class='im_dialog_peer']//span[@class='im_dialog_peer_name']"));
FileWriter writer = new FileWriter("usernames.txt");
for (WebElement username : usernames) {
String name = username.getText();
writer.write(name + "\n");
System.out.println(name);
}
writer.close();
// Закройте браузер
driver.quit();*/
Как превратить Element в WebElement или как-нибудь по другому исправить эту проблему
|
6c87b96e8e6d5d459a285fcc62ae8d81
|
{
"intermediate": 0.3056401014328003,
"beginner": 0.42348936200141907,
"expert": 0.27087050676345825
}
|
12,886
|
write a pzthon script to translate english text to klingon plus the abilitz to hear the klingon translation
|
3c1f3630a2d4842aa62601e21fc693cb
|
{
"intermediate": 0.3627598285675049,
"beginner": 0.1854429394006729,
"expert": 0.451797217130661
}
|
12,887
|
Explain polymorphism in c++ code with a theme of dota 2 mechanics
|
dd2c19df801af8511a77c369ddeccae7
|
{
"intermediate": 0.2829185426235199,
"beginner": 0.4895693063735962,
"expert": 0.2275122106075287
}
|
12,888
|
WARNING: The script whisper-ctranslate2.exe is installed in 'C:\Users\vania\AppData\Roaming\Python\Python311\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
numba 0.57.0 requires numpy<1.25,>=1.21, but you have numpy 1.25.0 which is incompatible.
|
2868e65f5cac8ad902507a9b46e0f3d3
|
{
"intermediate": 0.2931371033191681,
"beginner": 0.3883923590183258,
"expert": 0.31847044825553894
}
|
12,889
|
"local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character.Humanoid
local HRP = Character.HumanoidRootPart
local Camera = workspace.CurrentCamera
local gun = Player.Backpack:WaitForChild("Tool")
local UIS = game:GetService("UserInputService")
local RS = game:GetService("RunService")
local GuiService = game:GetService("GuiService")
local TS = game:GetService("TweenService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local DeployedVm = Camera:WaitForChild("GunViewmodel")
local Animations = {
["Idle"] =
}
local function OnEquipped()
local Viewmodel = ReplicatedStorage.v_blanktemplate:Clone()
Viewmodel.Parent = Camera
Viewmodel.Name = "GunViewmodel"
Animations.Idle:Play{}
for _, part in ipairs(Viewmodel:GetDescendants()) do
if part:IsA("BasePart") then
part.CanCollide = false
part:SetAttribute("CollisionGroupId", 0)
end
end
RS:BindToRenderStep("Viewmodel",301, function(DT)
Viewmodel:PivotTo(
Camera.CFrame
)
end)
end
local function OnUnequipped()
local Viewmodel = Camera:FindFirstChild("GunViewmodel")
if Viewmodel then
Viewmodel:Destroy()
end
end
gun.Equipped:Connect(OnEquipped)
gun.Unequipped:Connect(OnUnequipped)" How do i make the viewmodel play an animation when it spawns
|
7974f3c2e11905dde6480303c41396b4
|
{
"intermediate": 0.3685997426509857,
"beginner": 0.3258056938648224,
"expert": 0.3055945038795471
}
|
12,890
|
javascript code , input utc dtate tile string , the I want to display date and time in any timezone...
|
944fc285a4b7e88069d0c68fc4533348
|
{
"intermediate": 0.37745094299316406,
"beginner": 0.250074177980423,
"expert": 0.3724747896194458
}
|
12,891
|
how to reset mips cpu by assembly instructions?
|
7071ad519938f1a0caee6e8277cf358e
|
{
"intermediate": 0.3097341060638428,
"beginner": 0.37729379534721375,
"expert": 0.31297215819358826
}
|
12,892
|
Check the command code below
|
6969e8609ea619b8f327a1438073d9bb
|
{
"intermediate": 0.314482718706131,
"beginner": 0.274474173784256,
"expert": 0.41104304790496826
}
|
12,893
|
Explain writing interface for a mixing in dart
|
474e12c796be52497b3f3a19c7ff0aa3
|
{
"intermediate": 0.58094722032547,
"beginner": 0.2781298756599426,
"expert": 0.1409229189157486
}
|
12,894
|
yes do you help me write unity code this game
|
d612ef362c24a29fe4a641f15c4fa868
|
{
"intermediate": 0.380951851606369,
"beginner": 0.23019662499427795,
"expert": 0.3888515532016754
}
|
12,895
|
Build an if else ladder in java for pokemon weakness
|
352a295c671e596ea926d3792797ecfd
|
{
"intermediate": 0.2672877907752991,
"beginner": 0.3475457727909088,
"expert": 0.3851664364337921
}
|
12,896
|
how to use env files in react app? give exapmle?
|
02cf515ce046d6f13bf516d1c018603a
|
{
"intermediate": 0.7053689956665039,
"beginner": 0.13286787271499634,
"expert": 0.16176316142082214
}
|
12,897
|
i am going to give you text and i want it to print in python using print(" text example") in every line
|
460268efd15f2416506e706920ffdb2e
|
{
"intermediate": 0.4030872583389282,
"beginner": 0.35681506991386414,
"expert": 0.24009762704372406
}
|
12,898
|
how can I code program in python for sortng numbers.
|
6fc0192040ce3c77d3d4761f4c344e76
|
{
"intermediate": 0.43607297539711,
"beginner": 0.3054383397102356,
"expert": 0.2584887146949768
}
|
12,899
|
Посмотри на код и посмотри как можно исправить, чтобы сайт работал быстрее (сейчас он работает ОЧЕНЬ МЕДЛЕННО). Размер моего json файла 350 мегабайт. надо как-то data.json в mongodb перевести. Добавь чтение из json файла и перевод этого в mongodb, так как у меня более 55 тысяч страниц записаны в data.json
const express = require("express");
const ejs = require("ejs");
const fs = require("fs");
const request = require("request");
const cheerio = require("cheerio");
const app = express();
// Установка EJS в качестве шаблонизатора
app.set('view engine', 'ejs');
// Функция для получения HTML-кода страницы
function getHtml(url) {
return new Promise((resolve, reject) => {
request(url, (error, response, html) => {
if (error) {
reject(error);
} else {
resolve(html);
}
});
});
}
// Функция для получения номеров телефонов и сохранения их в файле data.json
async function getNewPhoneNumbers() {
console.log("Запущен процесс поиска новых номеров...");
const phoneNumbers = JSON.parse(fs.readFileSync("data.json"));
const lastPageUrl = phoneNumbers.length > 0 ? phoneNumbers[0].url : null;
const newPhoneNumbers = [];
// Получить HTML-код первой страницы с номерами телефонов
const firstPageUrl = "https://zvonili.com/";
const firstPageHtml = await getHtml(firstPageUrl);
// Использовать Cheerio для парсинга HTML-кода и извлечения информации о номере телефона
const $firstPage = cheerio.load(firstPageHtml);
const phoneElements = $firstPage(".card-header");
phoneElements.each((index, element) => {
const phoneNumber = $firstPage(element).find(".nomerlnk").text().trim();
const url = $firstPage(element).find(".nomerlnk").attr("href");
const comments = $firstPage(element).next().find("blockquote").text().trim().replace(/\s*[\[\(]?\s*(Опросы|Реклама|Мошенники)\s*[\]\)]?\s*/gi, '');
const callTypeElements = $firstPage(element).next().find("span.type");
const callType = callTypeElements.length > 0 ? callTypeElements.map((index, element) => $firstPage(element).text().trim()).get().join(", ") : "";
// Добавить новый номер телефона в массив, если его еще нет в списке
if (!phoneNumbers.some((phone) => phone.number === phoneNumber)) {
newPhoneNumbers.push({ number: phoneNumber, url: url, comments: [comments], callType: callType });
}
});
console.log(`Найдено ${newPhoneNumbers.length} новых номеров телефонов.`);
// Сохранить новые номера телефонов в начало файла data.json
const updatedPhoneNumbers = [...newPhoneNumbers, ...phoneNumbers];
fs.writeFileSync("data.json", JSON.stringify(updatedPhoneNumbers, null, 2));
return newPhoneNumbers;
}
// Создать маршрут для страницы с информацией о номере телефона
app.get("/phone/:number", (req, res) => {
const phoneNumbers = JSON.parse(fs.readFileSync("data.json"));
const phoneNumber = phoneNumbers.find((phone) => phone.number === req.params.number);
if (phoneNumber) {
const data = {
number: phoneNumber.number,
comments: phoneNumber.comments,
callType: phoneNumber.callType,
};
res.render('phone', data);
} else {
res.status(404).send("Номер телефона не найден");
}
});
// Маршрут для главной страницы
app.get("/", (req, res) => {
const phoneNumbers = JSON.parse(fs.readFileSync("data.json"));
const data = {
phoneNumbers: phoneNumbers,
};
const html = ejs.render(fs.readFileSync("views/index.ejs", "utf8"), data);
res.send(html);
});
// Запуск сервера и поиск новых номеров телефонов каждые 10 минут
const searchInterval = 10 * 60 * 1000; // 10 минут в миллисекундах
app.listen(3000, () => {
console.log("Сервер запущен на порту 3000");
getNewPhoneNumbers();
setInterval(getNewPhoneNumbers, searchInterval);
});
|
3bceadbf0e891ae8107ab527605f6959
|
{
"intermediate": 0.3194325864315033,
"beginner": 0.48562708497047424,
"expert": 0.19494037330150604
}
|
12,900
|
how do i color text in python
|
4c8140af969308d8e5e0509f96d8c2a2
|
{
"intermediate": 0.3916598856449127,
"beginner": 0.255847692489624,
"expert": 0.35249239206314087
}
|
12,901
|
Module '"react-router-dom"' has no exported member 'useHistory'.ts(2305)
|
4d2cc7de6ebbdcb085cca681e8c23dc3
|
{
"intermediate": 0.41714033484458923,
"beginner": 0.30050626397132874,
"expert": 0.2823534309864044
}
|
12,902
|
este script:
import os
import sys
import time
import wave
import tempfile
import threading
import torch
import pyaudiowpatch as pyaudio
from faster_whisper import WhisperModel as whisper
# A bigger audio buffer gives better accuracy
# but also increases latency in response.
AUDIO_BUFFER = 5
#index=1
def record_audio(p, device):
"""Record audio from output device and save to temporary WAV file."""
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
filename = f.name
wave_file = wave.open(filename, "wb")
wave_file.setnchannels(device["maxInputChannels"])
wave_file.setsampwidth(pyaudio.get_sample_size(pyaudio.paInt16))
wave_file.setframerate(int(device["defaultSampleRate"]))
def callback(in_data, frame_count, time_info, status):
"""Write frames and return PA flag"""
wave_file.writeframes(in_data)
return (in_data, pyaudio.paContinue)
stream = p.open(
format=pyaudio.paInt16,
channels=device["maxInputChannels"],
rate=int(device["defaultSampleRate"]),
frames_per_buffer=pyaudio.get_sample_size(pyaudio.paInt16),
input=True,
input_device_index=device["index"],
stream_callback=callback,
)
try:
time.sleep(AUDIO_BUFFER) # Blocking execution while playing
finally:
stream.stop_stream()
stream.close()
wave_file.close()
# print(f"{filename} saved.")
return filename
def whisper_audio(filename, model):
"""Transcribe audio buffer and display."""
segments, info = model.transcribe(filename, beam_size=5, task="translate")
os.remove(filename)
# print(f"{filename} removed.")
for segment in segments:
print(f"[{segment.start:.2f} -> {segment.end:.2f}] {segment.text.strip()}")
def main():
"""Load model record audio and transcribe from default output device."""
print("Loading model...")
device = "cuda" if torch.cuda.is_available() else "cpu"
model = whisper("large-v2", device=device, compute_type="float16")
print("Model loaded.")
with pyaudio.PyAudio() as pya:
# Create PyAudio instance via context manager.
try:
# Get default WASAPI info
wasapi_info = pya.get_host_api_info_by_type(pyaudio.paWASAPI)
#print(wasapi_info)
except OSError:
print("Looks like WASAPI is not available on the system. Exiting...")
sys.exit()
# Get default WASAPI speakers
default_speakers = pya.get_device_info_by_index(
wasapi_info["defaultOutputDevice"]
)
if not default_speakers["isLoopbackDevice"]:
for loopback in pya.get_loopback_device_info_generator():
# Try to find loopback device with same name(and [Loopback suffix]).
# Unfortunately, this is the most adequate way at the moment.
if default_speakers["name"] in loopback["name"]:
default_speakers = loopback
break
else:
print(
"""
Default loopback output device not found.
Run `python -m pyaudiowpatch` to check available devices.
Exiting...
"""
)
sys.exit()
print(
f"Recording from: {default_speakers['name']} ({default_speakers['index']})\n"
)
while True:
filename = record_audio(pya, default_speakers)
thread = threading.Thread(target=whisper_audio, args=(filename, model))
thread.start()
if __name__ == "__main__":
main()
The script will start recording audio from the default output device .
como altero para start recording audio from the default imput device
|
97393e776bed91304db23193828710fb
|
{
"intermediate": 0.30456721782684326,
"beginner": 0.44879046082496643,
"expert": 0.2466423213481903
}
|
12,903
|
what is the answer to life and everything?
|
b8451dc8c0d45b3c82cb01618d6609d5
|
{
"intermediate": 0.41290464997291565,
"beginner": 0.3573805093765259,
"expert": 0.22971487045288086
}
|
12,904
|
show me the result in a vase I do a console log, I want the dateTime in Houston londo, paris and singapore and sidney
|
511d7d93d4d21c122988b4fcc599d8a3
|
{
"intermediate": 0.41615548729896545,
"beginner": 0.2814032733440399,
"expert": 0.30244123935699463
}
|
12,905
|
on Kali how to test how many ports are open on a specific IP address
|
cc8fc7653c81f62d994fa2a421bfc030
|
{
"intermediate": 0.3439616858959198,
"beginner": 0.22668933868408203,
"expert": 0.42934897541999817
}
|
12,906
|
How many ports are open on the target machine? the machine is running Kali. give me terminal commands to find this answer.
|
dd2c5c7db42cd9c236e87115bae77130
|
{
"intermediate": 0.35588330030441284,
"beginner": 0.3144185543060303,
"expert": 0.3296981453895569
}
|
12,907
|
Take the following script and make it more conscise
|
4faa2c8b50d2517a8f63ded2e381b3bd
|
{
"intermediate": 0.30183130502700806,
"beginner": 0.3862280547618866,
"expert": 0.31194064021110535
}
|
12,908
|
show me the result in a case I do a console log, I want the dateTime in Houston londo, paris and singapore and sidney
|
a3d793cbfde5e1668ea1907ffe174a45
|
{
"intermediate": 0.4699912369251251,
"beginner": 0.267600953578949,
"expert": 0.2624078094959259
}
|
12,909
|
import { Router, Request, Response } from "express";
import Stripe from "stripe";
const stripeRouter: Router = Router();
const stripe = new Stripe(process.env.STRIPE_KEY || "", {
apiVersion: "2022-11-15",
});
stripeRouter.post("/payment", async (req: Request, res: Response) => {
try {
const stripeRes: Stripe.Charge = await stripe.charges.create({
source: req.body.tokenId,
amount: req.body.amount,
currency: "pln",
});
res.status(200).json(stripeRes);
} catch (stripeErr) {
res.status(500).json("This " + stripeErr);
}
});
const createCustomer = async (): Promise<void> => {
const params: Stripe.CustomerCreateParams = {
description: "test customer",
};
const customer: Stripe.Customer = await stripe.customers.create(params);
};
createCustomer();
export default stripeRouter;
const Cart = () => {
const cart = useAppSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState<{ id: string }>({ id: "" });
const history = useNavigate();
const onToken = (token: Token) => {
setStripeToken({ id: token.id });
};
useEffect(() => {
const makeRequest = async () => {
try {
const res = await userRequest.post("/checkout/payment", {
tokenId: stripeToken.id,
amount: 100,
});
history("/success", { state: { data: res.data } });
} catch (err) {
console.log("it gives this error " + err);
}
};
if (stripeToken) {
makeRequest();
}
}, [stripeToken, cart.total, history]);
return (
<Container>
<Navbar />
<PromoInfo />
<Wrapper>
<Title>YOUR CART</Title>
<Top>
<TopButton>CONTINUE SHOPPING</TopButton>
<TopTexts>
<TopText>Shopping Bag(2)</TopText>
<TopText>Your Wishlist(0)</TopText>
</TopTexts>
<TopButton buttonType="filled">CHECKOUT NOW</TopButton>
</Top>
<Bottom>
<Information>
{cart.products.map((product) => (
<Product>
<ProductDetail>
<Image src={product.img} />
<Details>
<ProductName>
<b>Product:</b>
{product.title}
</ProductName>
<ProductId>
<b>ID:</b>
{product._id}
</ProductId>
{product.color?.map((color, i) => (
<ProductColor key={i} color={color} />
))}
</Details>
</ProductDetail>
<PriceDetail>
<ProductAmountContainer>
<AddIcon />
<ProductAmount>{product.quantity}</ProductAmount>
<RemoveIcon />
</ProductAmountContainer>
<ProductPrice>
{product.price * product.quantity}PLN
</ProductPrice>
</PriceDetail>
</Product>
))}
<Hr />
</Information>
<Summary>
<SummaryTitle>ORDER SUMMARY</SummaryTitle>
<SummaryItem>
<SummaryItemText>Subtotal</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Estimated Shipping</SummaryItemText>
<SummaryItemPrice>5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem>
<SummaryItemText>Shipping Discount</SummaryItemText>
<SummaryItemPrice>-5.90PLN</SummaryItemPrice>
</SummaryItem>
<SummaryItem type="total">
<SummaryItemText>Total</SummaryItemText>
<SummaryItemPrice>{cart.total}PLN</SummaryItemPrice>
</SummaryItem>
{process.env.REACT_APP_STRIPE ? (
<StripeCheckout
name="FABICO"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey={process.env.REACT_APP_STRIPE}
></StripeCheckout>
) : (
<div>Stripe key is not defined</div>
)}
</Summary>
</Bottom>
</Wrapper>
<Footer />
</Container>
);
};
export default Cart;
why res status is 500?
|
21886720e0a9b2cce50f03fab9be7f63
|
{
"intermediate": 0.36046847701072693,
"beginner": 0.4782090187072754,
"expert": 0.16132251918315887
}
|
12,910
|
const cart = useSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState(null);
const history = useHistory();
const onToken = (token) => {
setStripeToken(token);
};
useEffect(() => {
const makeRequest = async () => {
try {
const res = await userRequest.post("/checkout/payment", {
tokenId: stripeToken.id,
amount: 500,
});
history.push("/success", {
stripeData: res.data,
products: cart, });
} catch {}
};
stripeToken && makeRequest();
}, [stripeToken, cart.total, history]);
use another functioanlitiesbut it must work the same
|
49ae0f9eebbb6e2afece6446f6580271
|
{
"intermediate": 0.381290465593338,
"beginner": 0.37421298027038574,
"expert": 0.24449649453163147
}
|
12,911
|
const cart = useSelector((state) => state.cart);
const [stripeToken, setStripeToken] = useState(null);
const history = useHistory();
const onToken = (token) => {
setStripeToken(token);
};
useEffect(() => {
const makeRequest = async () => {
try {
const res = await userRequest.post(“/checkout/payment”, {
tokenId: stripeToken.id,
amount: 500,
});
history.push(“/success”, {
stripeData: res.data,
products: cart, });
} catch {}
};
stripeToken && makeRequest();
}, [stripeToken, cart.total, history]);
I use routerv6 use history isn't working?
|
b18f26acc56f1dc560fe1b35b9f9eefd
|
{
"intermediate": 0.5290996432304382,
"beginner": 0.2706963121891022,
"expert": 0.2002040296792984
}
|
12,912
|
corrija esse código: function HoraAtual() {
if (today.isBefore(inicioExpediente) || today.isAfter(fimExpediente)) {
return null;
}
let totalHeight = slots.length * 80 - 10;
const topPercentage = currentTime.diff(inicioExpediente, "minutes") / 30;
return (
<div
style={{
position: "absolute",
top: "100px",
width: "100%",
height: totalHeight,
zIndex: 2,
}}
>
<div
style={{
top: `${topPercentage * 80 - 20}px`,
position: "absolute",
height: "2px",
width: "100%",
background: "red",
}}
/>
</div>
);
}
|
0e5ad34c76f1aefe8aee40e61658a049
|
{
"intermediate": 0.2857048809528351,
"beginner": 0.5206660628318787,
"expert": 0.19362908601760864
}
|
12,913
|
The target is a Windows OS with an IP address of 10.10.1.169.
What is the version of service MySQL running on the target machine?
without using port 3308
|
a7b5ad0dc76dd1dc63a3f40a26c982d4
|
{
"intermediate": 0.39763379096984863,
"beginner": 0.2902970016002655,
"expert": 0.31206920742988586
}
|
12,914
|
How many ports are open nmap
|
fc245f716b1578d2ceb2e00db9de0d3b
|
{
"intermediate": 0.3574965000152588,
"beginner": 0.270990788936615,
"expert": 0.37151268124580383
}
|
12,915
|
windows command to show all open ports
|
f47cd1018ed3b51f65ccd50499367e3a
|
{
"intermediate": 0.36471226811408997,
"beginner": 0.2645435333251953,
"expert": 0.3707441985607147
}
|
12,916
|
on Kali how to find the version of service MySQL running on specific IP address using sqlmap
|
7b2eca7b56396f937d37eb717d4f082b
|
{
"intermediate": 0.5081373453140259,
"beginner": 0.22335366904735565,
"expert": 0.26850903034210205
}
|
12,917
|
import os
import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.slider import Slider
from kivy.core.audio import SoundLoader
from kivy.clock import Clock
from kivy.uix.spinner import Spinner
class MusicPlayerApp(App):
def build(self):
layout = BoxLayout(orientation='vertical')
self.music_folder = '/storage/emulated/0/Download'
self.song_spinner = Spinner(text='Select Song', values=self.get_music_files())
self.song_spinner.bind(text=self.on_song_select)
layout.add_widget(self.song_spinner)
self.play_button = Button(text='Play', on_press=self.play_music)
layout.add_widget(self.play_button)
self.stop_button = Button(text='Stop', on_press=self.stop_music)
layout.add_widget(self.stop_button)
self.next_button = Button(text='Next', on_press=self.next_song)
layout.add_widget(self.next_button)
self.prev_button = Button(text='Previous', on_press=self.previous_song)
layout.add_widget(self.prev_button)
self.progress_slider = Slider(min=0, max=1, value=0, step=0.01)
self.progress_slider.bind(value=self.on_progress_change)
layout.add_widget(self.progress_slider)
self.current_song = None
self.song_index = 0
return layout
def get_music_files(self):
files = os.listdir(self.music_folder)
music_files = [f for f in files if f.endswith('.mp3')]
return music_files
def on_song_select(self, spinner, text):
self.current_song = SoundLoader.load(os.path.join(self.music_folder, text))
self.play_button.disabled = False
def play_music(self, button):
if self.current_song:
self.current_song.play()
Clock.schedule_interval(self.update_progress_slider, 0.1)
self.play_button.disabled = True
self.stop_button.disabled = False
def stop_music(self, button):
if self.current_song:
self.current_song.stop()
self.progress_slider.value = 0
self.play_button.disabled = False
self.stop_button.disabled = True
def next_song(self, button):
self.song_index = (self.song_index + 1) % len(self.song_spinner.values)
self.song_spinner.text = self.song_spinner.values[self.song_index]
self.play_music(None) # Auto-play the next song
def previous_song(self, button):
self.song_index = (self.song_index - 1) % len(self.song_spinner.values)
self.song_spinner.text = self.song_spinner.values[self.song_index]
self.play_music(None) # Auto-play the previous song
def on_progress_change(self, slider, value):
if self.current_song:
self.current_song.seek(value * self.current_song.length)
def update_progress_slider(self, dt):
if self.current_song:
self.progress_slider.value = self.current_song.get_pos() / self.current_song.length
if not self.current_song.state == 'play':
# Automatically switch to the next song when the current song ends
self.next_song(None)
def on_stop(self):
if self.current_song:
self.current_song.stop()
if __name__ == '__main__':
MusicPlayerApp().run()
Добавь функцию выключения предыдущей песни при переключении
|
b6b65489bd8720d2e6a5d9c810919068
|
{
"intermediate": 0.29100123047828674,
"beginner": 0.5441504120826721,
"expert": 0.16484828293323517
}
|
12,918
|
How do I find a file on remote computer 10.10.1.101 kali linux
|
78a75a64054c4b66002edcc3ad19b73f
|
{
"intermediate": 0.4517982006072998,
"beginner": 0.221360445022583,
"expert": 0.32684144377708435
}
|
12,919
|
apache users how to use 10.10.1.101
|
7728a19d024ed21585e3bf302d56e932
|
{
"intermediate": 0.37377211451530457,
"beginner": 0.28931674361228943,
"expert": 0.33691108226776123
}
|
12,920
|
I'm using the following R code to create a faceted ggplot:
ggplot(plot.PIs.long, aes(x = x_var, y = y_var)) +
geom_point(position=position_jitter(width=0.0, height=0))+
facet_wrap(~ y, labeller = labeller(y=label_wrap_gen(width=35)), ncol = 3, scales="free_y", strip.position = "left")+
geom_hline(aes(yintercept=m), linetype="dashed", color="red")+
ylab(NULL)+
xlab()+
theme(strip.background = element_blank(), strip.placement = "outside")+
scale_x_continuous() +
theme(legend.position = "none")+
geom_smooth(method = "lm", se = T)+
stat_poly_eq(aes(label = paste(p.value.label,..rr.label.., sep = "~~~")),
formula = y ~ x, parse = TRUE, size = 3,
label.x.npc = 0, label.y.npc = 0)
Can you show me how to put this into a function that will take inputs of x_var and y_var so that I can use the function plot may x and y variables in the future?
|
daefd1422a4e07afe5fde44c5e63997e
|
{
"intermediate": 0.5339770317077637,
"beginner": 0.31086522340774536,
"expert": 0.15515774488449097
}
|
12,921
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I have recently made updates to the following code for the Material class:
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayoutUnique(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout.get();
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>(device, physicalDevice);
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
However, I am now getting the following errors. Can you help modify the code to fix them?
allocInfo.setDescriptorPool(descriptorPool)
No suitable conversion from vk::UniqueDescriptorPool to vk::DescriptorPool exists
pipelineLayout = device.createPipelineLayoutUnique(pipelineLayoutInfo)
No operator "=" matches these operands
return pipelineLayout.get()
vk::PipelineLayout has no member "get"
|
784a7e20685eaa86e6e453fb7444a66f
|
{
"intermediate": 0.4223000407218933,
"beginner": 0.4331861138343811,
"expert": 0.1445138156414032
}
|
12,922
|
In r, generate a dataset that has a treatment effect X and a confounder C
|
82129c8477c24672b9acc05bfffcd21f
|
{
"intermediate": 0.33251452445983887,
"beginner": 0.1560685783624649,
"expert": 0.5114169120788574
}
|
12,923
|
以下程序完成功能:将data.txt文件的所有行加上行号后写到newdata.txt文件中。请将其补充完整。
#include <fstream.h>
void main()
{
int i=0;
char line[100];
________(1)__________
ofstream outfile;
________(2)__________
outfile.open("newdata.txt",ios::out);
while(!infile.eof())
{
________(3)__________
i++;
________(4)__________
outfile<<line<<endl;
}
infile.close();
outfile.close();
}
|
b106cbf6e6aec1a6d4e29325e841d268
|
{
"intermediate": 0.3981629014015198,
"beginner": 0.3651508092880249,
"expert": 0.23668628931045532
}
|
12,924
|
use el-cascader when disabled,how to show text when hover
|
6b0665187388381ab9edc42690924f9b
|
{
"intermediate": 0.46928635239601135,
"beginner": 0.20888273417949677,
"expert": 0.3218308687210083
}
|
12,925
|
please Explain the pytorch code below: " for g in grad_input: \n g[g != g] = 0"
|
99a8014439f28d5f8d95707848320846
|
{
"intermediate": 0.2925889194011688,
"beginner": 0.31792259216308594,
"expert": 0.38948845863342285
}
|
12,926
|
in python, how to check if the string is umber
|
ad207f6193194e14baa964d4118ea3c8
|
{
"intermediate": 0.44945502281188965,
"beginner": 0.19170446693897247,
"expert": 0.3588405251502991
}
|
12,927
|
how to restrict access by IP in AWS Cloudfront
|
ec0878deeb078873970c1fae5aef03b7
|
{
"intermediate": 0.4368078410625458,
"beginner": 0.26347988843917847,
"expert": 0.29971224069595337
}
|
12,928
|
here is an expression: It might take some time to download the image. If your portal is shown as below, just stay tuned for the completion of the process. Is it proper to say "stay tuned for"
|
340224bf24373a6af71b20c1a854e561
|
{
"intermediate": 0.3656548261642456,
"beginner": 0.3041718304157257,
"expert": 0.3301733434200287
}
|
12,929
|
i want tp write a book about JavaScript for beginners: Learning through real-world examples can you give me table of contents for the book. the book should include 200 eamples
|
8f2cad58e791155305a4641eb1294747
|
{
"intermediate": 0.2994953989982605,
"beginner": 0.533349871635437,
"expert": 0.16715475916862488
}
|
12,930
|
IntPtr taskbarWnd = WinApi.FindWindow("Shell_TrayWnd", null);
IntPtr trayWnd = WinApi.FindWindowEx(taskbarWnd, IntPtr.Zero, "TrayNotifyWnd", null);
IntPtr reBarWnd = WinApi.FindWindowEx(trayWnd, IntPtr.Zero, "ReBarWindow32", null);
第三句代码返回空指针为什么
|
575bc23f1f766115405ddbe5fd1c7c3e
|
{
"intermediate": 0.4092240333557129,
"beginner": 0.3171098828315735,
"expert": 0.2736660838127136
}
|
12,931
|
You are given a file consisting of 8 distinct characters, a-g. The frequency of each character in the file is the following: a: 20, b: 12, c: 13, d: 5, e: 10, f: 15, g: 8. What’s the total number of bits you would need to encode this file using Huffman coding?
|
b2c4ac6d8174a53e78e88c23f73aa732
|
{
"intermediate": 0.41309306025505066,
"beginner": 0.22623644769191742,
"expert": 0.3606705367565155
}
|
12,932
|
In Unity I need my TrailRenderer's trail to not stay behind the moving parent's object, so it doesn't leave trail behind, but stays in local space. I need code for that
|
24cfedf71530dc7a560a3369e057e3dc
|
{
"intermediate": 0.5383214950561523,
"beginner": 0.17352832853794098,
"expert": 0.2881501615047455
}
|
12,933
|
how to make blog posts as grid and in same size in divi them
|
bfbc955fb32591a6789406ec1739dde5
|
{
"intermediate": 0.40808138251304626,
"beginner": 0.31106340885162354,
"expert": 0.2808552086353302
}
|
12,934
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some chagnes to the Material class. Here is the current code:
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(*descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
I am now getting the following errors in the log:
UNASSIGNED-GeneralParameterError-RequiredParameter(ERROR / SPEC): msgNum: -1711571459 - Validation Error: [ UNASSIGNED-GeneralParameterError-RequiredParameter ] Object 0: handle = 0x17ec117d1f0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x99fb7dfd | vkAllocateDescriptorSets: required parameter pAllocateInfo->descriptorPool specified as VK_NULL_HANDLE
Objects: 1
[0] 0x17ec117d1f0, type: 3, name: NULL
VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter(ERROR / SPEC): msgNum: -2127463821 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter ] Object 0: handle = 0x17ebdb60a90, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x81317a73 | Invalid VkDescriptorPool Object 0x0. The Vulkan spec states: descriptorPool must be a valid VkDescriptorPool handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter)
Objects: 1
[0] 0x17ebdb60a90, type: 1, name: NULL
Do you know what the problem is and how to modify the code to fix it?
|
1dc295d5ed4f212a659fb9d8f8bd6267
|
{
"intermediate": 0.3589906096458435,
"beginner": 0.4263220429420471,
"expert": 0.21468733251094818
}
|
12,935
|
use jest create ut for this component: <template>
<div class="update-func-container">
<el-popover
v-bind="priPopoverProps"
>
<slot name="popover" />
<div slot="reference" class="update-func">
<el-badge
v-bind="priBadgeProps"
@mouseenter.native="__tagetMouseenter"
@click.native="__targetClick"
>
<slot />
</el-badge>
</div>
</el-popover>
</div>
</template>
<script>
const defaultPopoverProps = {
placement: 'top',
disabled: false,
trigger: 'hover'
}
const defaultBadgeProps = {
'is-dot': true
}
export default {
data() {
return {
isShow: true,
priPopoverProps: {},
priBadgeProps: {}
}
},
watch: {
popoverProps() {
this.__initPopoverParams()
},
badgeProps() {
this.__initBadgeParams()
}
},
created() {
this.__initParams()
this.__setTimeoutToHide()
},
methods: {
__initParams() {
this.__initPopoverParams()
this.__initBadgeParams()
},
__initPopoverParams() {
// popover props
let popoverProps = Object.assign({}, defaultPopoverProps, this.popoverProps)
Object.keys(popoverProps).map(key => {
this.$set(this.priPopoverProps, key, popoverProps[key])
})
this.__isShowPopover()
},
__initBadgeParams() {
let badgeProps = Object.assign({}, defaultBadgeProps, this.badgeProps)
Object.keys(badgeProps).map(key => {
this.$set(this.priBadgeProps, key, badgeProps[key])
})
if (this.badgeProps.value) {
this.$set(this.priBadgeProps, 'is-dot', false)
}
let newFuncIdentify = localStorage.getItem('newFuncIdentify')
let reg = new RegExp(`-${this.updateKey}-`)
if (reg.test(newFuncIdentify)) {
this.clearBadge()
}
},
__setTimeoutToHide() {
let hideByTimeout = parseInt(this.hideByTimeout)
let countdown = parseInt(this.countdown)
if (hideByTimeout > 0) {
// 有设置超时时间优先
let currentTime = new Date().getTime()
if (currentTime >= hideByTimeout) {
this.clearBadge()
}
} else {
// 无设置超时时间
if (countdown > 0 && !this.priBadgeProps.hidden) {
let timer = setTimeout(() => {
this.clearBadge()
clearTimeout(timer)
}, countdown)
}
}
},
__isShowPopover() {
if (!this.popoverProps.content && !this.$slots.popover) {
this.$set(this.priPopoverProps, 'disabled', true)
}
},
__tagetMouseenter() {
if (this.trigger === 'hover' && !this.priBadgeProps.hidden) {
this.clearBadge()
}
},
__targetClick() {
if (this.trigger === 'click' && !this.priBadgeProps.hidden) {
this.clearBadge()
}
},
__setStorageKey() {
let newFuncIdentify = localStorage.getItem('newFuncIdentify') || ''
let reg = new RegExp(`-${this.updateKey}-`)
if (!reg.test(newFuncIdentify)) {
localStorage.setItem('newFuncIdentify', `${newFuncIdentify}-${this.updateKey}-`)
}
},
clearBadge() {
this.$set(this.priBadgeProps, 'hidden', true)
this.__setStorageKey()
this.$emit('clearBadge')
}
}
}
</script>
|
dd1cd8b3f20defae72a1dc2d2b6b7f57
|
{
"intermediate": 0.38060107827186584,
"beginner": 0.43661263585090637,
"expert": 0.18278636038303375
}
|
12,936
|
How to change framerate from all video using ffmpeg
|
0755ed9cfa68f6df8351db4f770b5dc5
|
{
"intermediate": 0.40060093998908997,
"beginner": 0.2853673994541168,
"expert": 0.3140316903591156
}
|
12,937
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some changes to the Material class. Here is the current code for both the Engine and Material classes:
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 cube’s vertices and indices
std::vector<Vertex> vertices = {
{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f} }, // bottom-left-back
{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f} }, // bottom-right-back
{ { 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} }, // top-right-back
{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f} }, // top-left-back
{ {-0.5f, -0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} }, // bottom-left-front
{ { 0.5f, -0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} }, // bottom-right-front
{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f, 1.0f}, {0.0f, 1.0f} }, // top-right-front
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f} }, // top-left-front
};
std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0, // back face
0, 3, 7, 7, 4, 0, // left face
4, 7, 6, 6, 5, 4, // front face
1, 5, 6, 6, 2, 1, // right face
3, 2, 6, 6, 7, 3, // top face
0, 4, 5, 5, 1, 0 // bottom face
};
// 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_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// 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();
}
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(*descriptorPool);
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
I am now getting the following errors in the log:
UNASSIGNED-GeneralParameterError-RequiredParameter(ERROR / SPEC): msgNum: -1711571459 - Validation Error: [ UNASSIGNED-GeneralParameterError-RequiredParameter ] Object 0: handle = 0x17ec117d1f0, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x99fb7dfd | vkAllocateDescriptorSets: required parameter pAllocateInfo->descriptorPool specified as VK_NULL_HANDLE
Objects: 1
[0] 0x17ec117d1f0, type: 3, name: NULL
VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter(ERROR / SPEC): msgNum: -2127463821 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter ] Object 0: handle = 0x17ebdb60a90, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x81317a73 | Invalid VkDescriptorPool Object 0x0. The Vulkan spec states: descriptorPool must be a valid VkDescriptorPool handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter)
Objects: 1
[0] 0x17ebdb60a90, type: 1, name: NULL
Do you know what the problem is and how to modify the code to fix it?
|
52d3d0e067275a0ae900b5e4901077a1
|
{
"intermediate": 0.29085010290145874,
"beginner": 0.5410047769546509,
"expert": 0.16814512014389038
}
|
12,938
|
hello
|
8b5971280bda5706b596d838430fa150
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
12,939
|
python报错 non-UTF-8 code starting with
|
e42aed06dbf196d1c48c661a4287649c
|
{
"intermediate": 0.270007461309433,
"beginner": 0.42683398723602295,
"expert": 0.30315855145454407
}
|
12,940
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some changes to the Material class. Here is the current code for both the Engine and Material classes:
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 cube’s vertices and indices
std::vector<Vertex> vertices = {
{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f} }, // bottom-left-back
{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f} }, // bottom-right-back
{ { 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} }, // top-right-back
{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f} }, // top-left-back
{ {-0.5f, -0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} }, // bottom-left-front
{ { 0.5f, -0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} }, // bottom-right-front
{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f, 1.0f}, {0.0f, 1.0f} }, // top-right-front
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f} }, // top-left-front
};
std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0, // back face
0, 3, 7, 7, 4, 0, // left face
4, 7, 6, 6, 5, 4, // front face
1, 5, 6, 6, 2, 1, // right face
3, 2, 6, 6, 7, 3, // top face
0, 4, 5, 5, 1, 0 // bottom face
};
// 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_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// 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();
}
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(descriptorPool.get());
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
I am now getting the following errors in the log:
UNASSIGNED-GeneralParameterError-RequiredParameter(ERROR / SPEC): msgNum: -1711571459 - Validation Error: [ UNASSIGNED-GeneralParameterError-RequiredParameter ] Object 0: handle = 0x1db5cc43360, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x99fb7dfd | vkAllocateDescriptorSets: required parameter pAllocateInfo->descriptorPool specified as VK_NULL_HANDLE
Objects: 1
[0] 0x1db5cc43360, type: 3, name: NULL
VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter(ERROR / SPEC): msgNum: -2127463821 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter ] Object 0: handle = 0x1db595d8e30, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x81317a73 | Invalid VkDescriptorPool Object 0x0. The Vulkan spec states: descriptorPool must be a valid VkDescriptorPool handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter)
Objects: 1
[0] 0x1db595d8e30, type: 1, name: NULL
I don't believe the descriptorPool variable is being assigned properly during Initialization. Do you know what the problem is and how to modify the code to fix it?
|
0828b5a362d6347530b39398c768630c
|
{
"intermediate": 0.29085010290145874,
"beginner": 0.5410047769546509,
"expert": 0.16814512014389038
}
|
12,941
|
i want to write a book about JavaScript for beginners: Learning through real-world examples describe Function Parameters and Arguments
|
ea1897b321d32b08be0a9ab35caac524
|
{
"intermediate": 0.17440427839756012,
"beginner": 0.6627116799354553,
"expert": 0.16288401186466217
}
|
12,942
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some changes to the Material class. Here is the current code for both the Engine and Material classes:
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 cube’s vertices and indices
std::vector<Vertex> vertices = {
{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f} }, // bottom-left-back
{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f} }, // bottom-right-back
{ { 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} }, // top-right-back
{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f} }, // top-left-back
{ {-0.5f, -0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} }, // bottom-left-front
{ { 0.5f, -0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} }, // bottom-right-front
{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f, 1.0f}, {0.0f, 1.0f} }, // top-right-front
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f} }, // top-left-front
};
std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0, // back face
0, 3, 7, 7, 4, 0, // left face
4, 7, 6, 6, 5, 4, // front face
1, 5, 6, 6, 2, 1, // right face
3, 2, 6, 6, 7, 3, // top face
0, 4, 5, 5, 1, 0 // bottom face
};
// 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_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// 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();
}
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(descriptorPool.get());
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
I am now getting the following errors in the log:
UNASSIGNED-GeneralParameterError-RequiredParameter(ERROR / SPEC): msgNum: -1711571459 - Validation Error: [ UNASSIGNED-GeneralParameterError-RequiredParameter ] Object 0: handle = 0x1db5cc43360, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x99fb7dfd | vkAllocateDescriptorSets: required parameter pAllocateInfo->descriptorPool specified as VK_NULL_HANDLE
Objects: 1
[0] 0x1db5cc43360, type: 3, name: NULL
VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter(ERROR / SPEC): msgNum: -2127463821 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter ] Object 0: handle = 0x1db595d8e30, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x81317a73 | Invalid VkDescriptorPool Object 0x0. The Vulkan spec states: descriptorPool must be a valid VkDescriptorPool handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter)
Objects: 1
[0] 0x1db595d8e30, type: 1, name: NULL
I don't believe the descriptorPool variable is being assigned properly during Material::Initialization. Do you know how to modify the code to fix it?
|
17d4fa777d05127415d9dd6ecb43843d
|
{
"intermediate": 0.29085010290145874,
"beginner": 0.5410047769546509,
"expert": 0.16814512014389038
}
|
12,943
|
java server faces как правильно сделать с помощью ui:repait возможность динамического добавления и удаления блоков selectOneRadio, с помощью которых нужно управлять полями объектов из списка List <UserAuthMethod> twoFactorAuthMethods
|
73ffaa3d696bd9f2935ba4de6d86377d
|
{
"intermediate": 0.5129216313362122,
"beginner": 0.28666841983795166,
"expert": 0.2004099190235138
}
|
12,944
|
i want to write a book about JavaScript for beginners: Learning through real-world examples describe Selecting Elements
|
aab155ec0786dd107c12e1bd69c4b674
|
{
"intermediate": 0.24434655904769897,
"beginner": 0.5611763000488281,
"expert": 0.1944771260023117
}
|
12,945
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some changes to the Material class. Here is the current code for both the Engine and Material classes and some relevant code from Renderer.cpp:
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 cube’s vertices and indices
std::vector<Vertex> vertices = {
{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f} }, // bottom-left-back
{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f} }, // bottom-right-back
{ { 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} }, // top-right-back
{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f} }, // top-left-back
{ {-0.5f, -0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} }, // bottom-left-front
{ { 0.5f, -0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} }, // bottom-right-front
{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f, 1.0f}, {0.0f, 1.0f} }, // top-right-front
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f} }, // top-left-front
};
std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0, // back face
0, 3, 7, 7, 4, 0, // left face
4, 7, 6, 6, 5, 4, // front face
1, 5, 6, 6, 2, 1, // right face
3, 2, 6, 6, 7, 3, // top face
0, 4, 5, 5, 1, 0 // bottom face
};
// 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_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// 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();
}
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(descriptorPool.get());
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
A portion of Renderer.cpp:
vk::DescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
vk::DescriptorPoolSize poolSize{};
poolSize.type = vk::DescriptorType::eUniformBuffer;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
vk::DescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = vk::DescriptorType::eCombinedImageSampler;
samplerPoolSize.descriptorCount = maxSets;
std::array<vk::DescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
vk::DescriptorPoolCreateInfo poolInfo{};
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
vk::DescriptorPool descriptorPool;
if (device.createDescriptorPool(&poolInfo, nullptr, &descriptorPool) != vk::Result::eSuccess) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
I am now getting the following errors in the log:
UNASSIGNED-GeneralParameterError-RequiredParameter(ERROR / SPEC): msgNum: -1711571459 - Validation Error: [ UNASSIGNED-GeneralParameterError-RequiredParameter ] Object 0: handle = 0x1db5cc43360, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0x99fb7dfd | vkAllocateDescriptorSets: required parameter pAllocateInfo->descriptorPool specified as VK_NULL_HANDLE
Objects: 1
[0] 0x1db5cc43360, type: 3, name: NULL
VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter(ERROR / SPEC): msgNum: -2127463821 - Validation Error: [ VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter ] Object 0: handle = 0x1db595d8e30, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x81317a73 | Invalid VkDescriptorPool Object 0x0. The Vulkan spec states: descriptorPool must be a valid VkDescriptorPool handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkDescriptorSetAllocateInfo-descriptorPool-parameter)
Objects: 1
[0] 0x1db595d8e30, type: 1, name: NULL
I don't believe the descriptorPool variable is being assigned to the descriptorPool member variable properly during Material::Initialization. Do you know how to modify the code to fix it?
|
9ff97982ec1a7b37cb27bd2476ee1c26
|
{
"intermediate": 0.31533244252204895,
"beginner": 0.5099630951881409,
"expert": 0.1747044175863266
}
|
12,946
|
i want to write a book about JavaScript for beginners: Learning through real-world examples describe Displaying API Data
|
3d6ef265533d7e3417bb0f613adfdee6
|
{
"intermediate": 0.571175754070282,
"beginner": 0.314310222864151,
"expert": 0.11451400071382523
}
|
12,947
|
create Project 4: todo list in javascript
|
5ef123e4d700ee944968d90d307e0041
|
{
"intermediate": 0.37513467669487,
"beginner": 0.3267894685268402,
"expert": 0.2980758547782898
}
|
12,948
|
write A countdown timer in javascript
|
4e1a676ab3cad4993f5e0d2adc18c27f
|
{
"intermediate": 0.41763901710510254,
"beginner": 0.27416980266571045,
"expert": 0.30819112062454224
}
|
12,949
|
write . A tic-tac-toe game in javascript
|
187cb5cde3d0663fe09ea8187aa4e22f
|
{
"intermediate": 0.328260600566864,
"beginner": 0.4599747061729431,
"expert": 0.21176469326019287
}
|
12,950
|
write . A chat application in javascript
|
7ffb4c9bfefb33dc3a91cabf5b303c5b
|
{
"intermediate": 0.27272316813468933,
"beginner": 0.5734502077102661,
"expert": 0.15382659435272217
}
|
12,951
|
hi/ do you know python?
|
3c005f2169071875cd2800b7b5bcc055
|
{
"intermediate": 0.25541961193084717,
"beginner": 0.3800840675830841,
"expert": 0.3644963204860687
}
|
12,952
|
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.
I am in the process of converting the code to make use of vulkan.hpp and RAII. I've been making some changes to the Material class. Here is the current code for both the Engine and Material classes and some relevant code from Renderer.cpp:
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 cube’s vertices and indices
std::vector<Vertex> vertices = {
{ {-0.5f, -0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}, {0.0f, 0.0f} }, // bottom-left-back
{ { 0.5f, -0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f} }, // bottom-right-back
{ { 0.5f, 0.5f, -0.5f}, {0.0f, 0.0f, 1.0f}, {1.0f, 1.0f} }, // top-right-back
{ {-0.5f, 0.5f, -0.5f}, {1.0f, 1.0f, 0.0f}, {0.0f, 1.0f} }, // top-left-back
{ {-0.5f, -0.5f, 0.5f}, {0.0f, 1.0f, 1.0f}, {1.0f, 0.0f} }, // bottom-left-front
{ { 0.5f, -0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}, {0.0f, 0.0f} }, // bottom-right-front
{ { 0.5f, 0.5f, 0.5f}, {1.0f, 0.0f, 1.0f}, {0.0f, 1.0f} }, // top-right-front
{ {-0.5f, 0.5f, 0.5f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f} }, // top-left-front
};
std::vector<uint32_t> indices = {
0, 1, 2, 2, 3, 0, // back face
0, 3, 7, 7, 4, 0, // left face
4, 7, 6, 6, 5, 4, // front face
1, 5, 6, 6, 2, 1, // right face
3, 2, 6, 6, 7, 3, // top face
0, 4, 5, 5, 1, 0 // bottom face
};
// 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_depth.spv", "C:/shaders/frag_depth.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->Initialize2(renderer);
// 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();
}
Material.h:
#pragma once
#include <vulkan/vulkan.hpp>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
#include <array>
// Add this struct outside the Material class, possibly at the top of Material.cpp
struct ShaderDeleter {
void operator()(Shader* shaderPtr) {
if (shaderPtr != nullptr) {
Shader::cleanup(shaderPtr);
}
}
};
class Material
{
public:
Material() = default;
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device);
void UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize);
vk::DescriptorSet GetDescriptorSet() const;
vk::PipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
void CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize);
private:
vk::Device device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout);
vk::DescriptorSet descriptorSet;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSetLayout descriptorSetLayout;// = VK_NULL_HANDLE;
vk::UniqueDescriptorPool descriptorPool;
void CleanupDescriptorSetLayout();
};
Material.cpp:
#include "Material.h"
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, vk::Device device, vk::DescriptorSetLayout descriptorSetLayout, vk::DescriptorPool descriptorPool, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
this->device = device;
this->descriptorPool = vk::UniqueDescriptorPool(descriptorPool, device); // Assign unique descriptor pool
this->descriptorSetLayout = descriptorSetLayout;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkBuffer uniformBuffer, vk::DeviceSize bufferSize)
{
vk::DescriptorSetAllocateInfo allocInfo{};
allocInfo.setDescriptorPool(descriptorPool.get());
allocInfo.setDescriptorSetCount(1);
allocInfo.setPSetLayouts(&descriptorSetLayout);
descriptorSet = device.allocateDescriptorSetsUnique(allocInfo)[0].get();
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = uniformBuffer;
bufferInfo.offset = 0;
bufferInfo.range = bufferSize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CreatePipelineLayout(vk::DescriptorSetLayout descriptorSetLayout)
{
vk::PipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.setSetLayouts(descriptorSetLayout);
pipelineLayout = device.createPipelineLayout(pipelineLayoutInfo);
}
void Material::Cleanup()
{
if (vertexShader) {
Shader::cleanup(vertexShader.get());
}
if (fragmentShader) {
Shader::cleanup(fragmentShader.get());
}
if (texture) {
texture->Cleanup();
texture.reset();
}
CleanupDescriptorSetLayout();
// Be sure to destroy the descriptor set if necessary
// Note: If the descriptor pool is being destroyed, you don’t need to free individual descriptor sets
}
vk::DescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
vk::PipelineLayout 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, vk::Device device, vk::PhysicalDevice physicalDevice, vk::CommandPool commandPool, vk::Queue graphicsQueue)
{
texture = std::make_shared<Texture>();
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, vk::Device device)
{
vertexShader = std::make_shared<Shader>();
fragmentShader = std::make_shared<Shader>();
vertexShader->loadFromFile(vertFilename, device, vk::ShaderStageFlagBits::eVertex);
fragmentShader->loadFromFile(fragFilename, device, vk::ShaderStageFlagBits::eFragment);
}
void Material::UpdateBufferBinding(VkBuffer newBuffer, vk::Device device, vk::DeviceSize devicesize)
{
vk::DescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
vk::DescriptorImageInfo imageInfo{};
imageInfo.imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
std::array<vk::WriteDescriptorSet, 2> descriptorWrites{};
descriptorWrites[0].setDstSet(descriptorSet);
descriptorWrites[0].setDstBinding(0);
descriptorWrites[0].setDstArrayElement(0);
descriptorWrites[0].setDescriptorType(vk::DescriptorType::eUniformBuffer);
descriptorWrites[0].setDescriptorCount(1);
descriptorWrites[0].setPBufferInfo(&bufferInfo);
descriptorWrites[1].setDstSet(descriptorSet);
descriptorWrites[1].setDstBinding(1);
descriptorWrites[1].setDstArrayElement(0);
descriptorWrites[1].setDescriptorType(vk::DescriptorType::eCombinedImageSampler);
descriptorWrites[1].setDescriptorCount(1);
descriptorWrites[1].setPImageInfo(&imageInfo);
device.updateDescriptorSets(static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
}
void Material::CleanupDescriptorSetLayout()
{
if (descriptorSetLayout != vk::DescriptorSetLayout{}) {
device.destroyDescriptorSetLayout(descriptorSetLayout, nullptr);
descriptorSetLayout = vk::DescriptorSetLayout{};
}
}
A portion of Renderer.cpp:
vk::DescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
vk::DescriptorPoolSize poolSize{};
poolSize.type = vk::DescriptorType::eUniformBuffer;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
vk::DescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = vk::DescriptorType::eCombinedImageSampler;
samplerPoolSize.descriptorCount = maxSets;
std::array<vk::DescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
vk::DescriptorPoolCreateInfo poolInfo{};
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
vk::DescriptorPool descriptorPool;
if (device.createDescriptorPool(&poolInfo, nullptr, &descriptorPool) != vk::Result::eSuccess) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
I am now getting the following errors in the log:
I made those changes. However, I am now getting these errors:
VUID-vkFreeDescriptorSets-descriptorPool-00312(ERROR / SPEC): msgNum: 1593871867 - Validation Error: [ VUID-vkFreeDescriptorSets-descriptorPool-00312 ] Object 0: handle = 0xcb1c7c000000001b, type = VK_OBJECT_TYPE_DESCRIPTOR_POOL; | MessageID = 0x5f008dfb | It is invalid to call vkFreeDescriptorSets() with a pool created without setting VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT. The Vulkan spec states: descriptorPool must have been created with the VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT flag (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkFreeDescriptorSets-descriptorPool-00312)
Objects: 1
[0] 0xcb1c7c000000001b, type: 22, name: NULL
VUID-VkWriteDescriptorSet-dstSet-00320(ERROR / SPEC): msgNum: 148949623 - Validation Error: [ VUID-VkWriteDescriptorSet-dstSet-00320 ] Object 0: handle = 0x2b30c536750, type = VK_OBJECT_TYPE_INSTANCE; | MessageID = 0x8e0ca77 | Invalid VkDescriptorSet Object 0xa43473000000002d. The Vulkan spec states: dstSet must be a valid VkDescriptorSet handle (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkWriteDescriptorSet-dstSet-00320)
Objects: 1
[0] 0x2b30c536750, type: 1, name: NULL
Do you know what could be causing the issue and how to modify the code to fix it?
|
6b3e6071ecc2cb42473a08039b39c414
|
{
"intermediate": 0.31533244252204895,
"beginner": 0.5099630951881409,
"expert": 0.1747044175863266
}
|
12,953
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
from binance.helpers import round_step_size
import pandas as pd
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
from decimal import Decimal
import requests
import hmac
import hashlib
import ntplib
import os
import ta
import ta.volatility
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
# Set the endpoint and parameters for the request
url = "https://fapi.binance.com/fapi/v2/account"
timestamp = int(time.time() * 1000)
recv_window = 10000 # update the recv_window value
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
# Define the sync_time() function
def sync_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
# Sync your local time with the server time
sync_time()
# Sign the message using the Client’s secret key
message = "&".join([f"{k}={v}" for k, v in params.items()])
signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()
params['signature'] = signature
leverage = 100
# Send the request using the requests library
response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY})
account_info = response.json()
# Get the USDT balance and calculate the max trade size based on the leverage
try:
usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free']
except KeyError:
usdt_balance = 0
print("Error: Could not retrieve USDT balance from API response.")
max_trade_size = float(usdt_balance) * leverage
# Get the current time and timestamp
now = dt.datetime.now()
date = now.strftime("%m/%d/%Y %H:%M:%S")
print(date)
timestamp = int(time.time() * 1000)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
quantity = 1
symbol = 'BTC/USDT'
order_type = 'market'
leverage = 100
max_trade_quantity_percentage = 1
binance_futures = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
},'future': {
'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc…
}
})
# Load the market symbols
exchange = ccxt.binance({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True,
})
symbol = 'BTC/USDT'
orderbook = exchange.fetch_order_book(symbol)
current_price = (orderbook['bids'][0][0] + orderbook['asks'][0][0]) / 2
def get_server_time():
ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org', version=3)
now = time.time()
offset = response.offset
new_time = now + offset
# Set the system clock to the new time
os.system(f'sudo date -s @{int(new_time)}')
print(f'New time: {dt.datetime.now()}')
params = {
"timestamp": timestamp,
"recvWindow": recv_window
}
try:
markets = binance_futures.load_markets()
except ccxt.BaseError as e:
print(f'Error fetching markets: {e}')
markets = []
if symbol in markets:
print(f"{symbol} found in the market")
else:
print(f"{symbol} not found in the market")
# Get server time and time difference
def get_server_time(exchange):
return exchange.fetch_time()
def get_time_difference():
server_time = get_server_time(binance_futures)
local_time = int(time.time() * 1000)
time_difference = local_time - server_time
return time_difference
time.sleep(1)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(time.time() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
symbol = symbol.replace("/", "") # remove slash from symbol
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
df = get_klines(symbol, '1m', 44640)
def signal_generator(df):
# Calculate EMA and MA lines
df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean()
df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean()
df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean()
df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean()
df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean()
df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean()
df['MA10'] = df['Close'].rolling(window=10).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
df['MA50'] = df['Close'].rolling(window=50).mean()
df['MA100'] = df['Close'].rolling(window=100).mean()
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Calculate the last candlestick
last_candle = df.iloc[-1]
current_price = df.Close.iloc[-1]
# Calculate MACD indicators
ema_12 = df['Close'].ewm(span=12, adjust=False).mean()
ema_26 = df['Close'].ewm(span=26, adjust=False).mean()
macd_line = ema_12 - ema_26
signal_line = macd_line.ewm(span=9, adjust=False).mean()
histogram = macd_line - signal_line
ema_analysis = ''
candle_analysis = ''
macd_analysis = ''
# EMA crossover - buy signal
if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and current_price > last_candle[['EMA10', 'EMA50']].iloc[-1].min():
ema_analysis = 'buy'
# EMA crossover - sell signal
elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and current_price < last_candle[['EMA10', 'EMA50']].iloc[-1].max():
ema_analysis = 'sell'
# EMA crossover - buy signal
if df.EMA20.iloc[-1] > df.EMA200.iloc[-1] and current_price > last_candle[['EMA20', 'EMA200']].iloc[-1].min():
ema_analysis = 'buy'
# EMA crossover - sell signal
elif df.EMA20.iloc[-1] < df.EMA200.iloc[-1] and current_price < last_candle[['EMA20', 'EMA200']].iloc[-1].max():
ema_analysis = 'sell'
# Check for bullish trends
elif current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].max():
ema_analysis = 'buy'
# Check for bearish trends
elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].min():
ema_analysis = 'sell'
# Check for bullish candlestick pattern
if (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
candle_analysis = 'buy'
# Check for bearish candlestick pattern
elif (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
candle_analysis = 'sell'
# MACD trading strategy - buy signal
if macd_line.iloc[-1] > signal_line.iloc[-1] and histogram.iloc[-1] > 0:
macd_analysis = 'buy'
# MACD trading strategy - sell signal
elif macd_line.iloc[-1] < signal_line.iloc[-1] and histogram.iloc[-1] < 0:
macd_analysis = 'sell'
# Check if both analyses are the same
if ema_analysis == candle_analysis == macd_analysis and ema_analysis != '':
return ema_analysis
# If no signal is found, return an empty string
return ''
df = get_klines(symbol, '1m', 44640)
def order_execution(symbol, signal, step_size, leverage, order_type):
# Set default value for response
response = {}
# Close any existing positions
current_position = None
positions = binance_futures.fapiPrivateGetPositionRisk()
for position in positions:
if position["symbol"] == symbol:
current_position = position
if current_position is not None and current_position["positionAmt"] != 0:
response = binance_futures.fapiPrivatePostOrder(
symbol=symbol,
side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY',
type='MARKET',
quantity=abs(float(current_position['positionAmt'])),
positionSide=current_position['positionSide'],
reduceOnly=True
)
if 'orderId' in response:
print(f'Closed position: {response}')
else:
print(f'Error closing position: {response}')
time.sleep(1)
# Calculate appropriate order quantity and price based on signal
opposite_position = None
quantity = step_size
position_side = None #initialise to None
price = None
# Set default take profit price
take_profit_price = None
stop_loss_price = None
if signal == 'buy':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None
order_type = 'TAKE_PROFIT_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'ask' in ticker:
price = ticker['ask']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None
order_type = 'STOP_MARKET'
ticker = binance_futures.fetch_ticker(symbol)
price = 0 # default price
if 'bid' in ticker:
price = ticker['bid']
# perform rounding and other operations on price
else:
# handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.)
take_profit_percentage = TAKE_PROFIT_PERCENTAGE
stop_loss_percentage = STOP_LOSS_PERCENTAGE
# Set stop loss price
stop_loss_price = None
if price is not None:
price = round_step_size(price, step_size=step_size)
if signal == 'buy':
# Calculate take profit and stop loss prices for a buy signal
take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
elif signal == 'sell':
# Calculate take profit and stop loss prices for a sell signal
take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size)
stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size)
# Placing new order
api_method = 'fapiPrivatePostOrder'
params = {
'symbol': symbol,
'side': signal.upper(),
'type': order_type,
'quantity': quantity,
'positionSide': position_side,
'leverage': leverage,
'price': price,
'stopPrice': stop_loss_price,
'takeProfit': take_profit_price
}
response = getattr(binance_futures, api_method)(params=params)
if 'orderId' in response:
print(f'Order placed: {response}')
else:
print(f'Error placing order: {response}')
time.sleep(1)
return response
signal = signal_generator(df)
while True:
df = get_klines(symbol, '1m', 44640) # await the coroutine function here
if df is not None:
signal = signal_generator(df)
if signal is not None:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}")
time.sleep(1)
But I getting ERROR: ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
fcff6d58da3dc3d2452d60bcfc1e0b49
|
{
"intermediate": 0.3626437783241272,
"beginner": 0.3542361855506897,
"expert": 0.28311994671821594
}
|
12,954
|
dict keys to 数组
|
570822d35fe36db5028cdc9321240dc8
|
{
"intermediate": 0.3183247148990631,
"beginner": 0.36168935894966125,
"expert": 0.31998589634895325
}
|
12,955
|
write A password generator in javascript
|
52602e470f2c1fdd55858d587bc65376
|
{
"intermediate": 0.34815090894699097,
"beginner": 0.26596179604530334,
"expert": 0.38588735461235046
}
|
12,956
|
hi
|
ffeec88176a9845ada6265ebedb29279
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
12,957
|
write a A simple e-commerce website with a shopping cart in javascript
|
da7dde86add2388e23cf09c4544fcfe1
|
{
"intermediate": 0.34292230010032654,
"beginner": 0.3506617546081543,
"expert": 0.3064159154891968
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.