row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
9,139
|
/*******************
* Napminimal Test *
*******************/
import { core, data, sound, util, visual, hardware } from './lib/psychojs-2023.1.1.js';
const { PsychoJS } = core;
const { TrialHandler, MultiStairHandler } = data;
const { Scheduler } = util;
//some handy aliases as in the psychopy scripts;
const { abs, sin, cos, PI: pi, sqrt } = Math;
const { round } = util;
// store info about the experiment session:
let expName = 'NAPminimal'; // from the Builder filename that created this script
let expInfo = {
'participant': `${util.pad(Number.parseFloat(util.randint(0, 999999)).toFixed(0), 6)}`,
'session': '001',
};
// Start code blocks for 'Before Experiment'
// Generate random samples of distorted images
function generateImages(numSamples, numImages) {
var chunkSize = Math.floor(numSamples / 3);
var imgsChunk1 = getRandomSample(1, Math.floor(numImages / 3) + 1, chunkSize);
var imgsChunk2 = getRandomSample(Math.floor(numImages / 3) + 1, Math.floor(2 * numImages / 3) + 1, chunkSize);
var imgsChunk3 = getRandomSample(Math.floor(2 * numImages / 3) + 1, numImages + 1, chunkSize);
var imgs = imgsChunk1.concat(imgsChunk2, imgsChunk3);
var distortions = ['_jpeg_70', '_jpeg_80', '_jpeg_90', '_blur_70', '_blur_80', '_blur_90', '_contrast_70', '_contrast_80', '_contrast_90', '_original'];
var numDistortions = distortions.length;
var numChunks = 3;
var letters = [];
var repetitions = Math.floor(numSamples / (numDistortions * numChunks));
for (var i = 0; i < repetitions; i++) {
letters = letters.concat(distortions);
}
var test = [];
for (var j = 0; j < numChunks; j++) {
letters = shuffleArray(letters);
test = test.concat(letters);
}
// Check that each chunk has the same number of letters
var stims = [];
for (var k = 0; k < numSamples; k++) {
stims.push({ imgs: imgs[k], test: String(imgs[k]) + test[k] });
}
return stims;
}
// Helper function to generate a random sample within a range
function getRandomSample(min, max, size) {
var sample = [];
var nums = [];
for (var i = min; i < max; i++) {
nums.push(i);
}
for (var j = 0; j < size; j++) {
var index = Math.floor(Math.random() * nums.length);
sample.push(nums.splice(index, 1)[0]);
}
return sample;
}
// Helper function to shuffle an array
function shuffleArray(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Usage example
var numSamples = 30;
var numImages = 100;
var stims = generateImages(numSamples, numImages);
console.log(stims);
var resource_list = [];
// Append generated images to resource_list and set download to true
for (var i = 0; i < numSamples; i++) {
var imageName = stims[i].imgs + '.png'; // Assuming the image extension is PNG
var imagePath = 'path/to/images/' + imageName; // Replace 'path/to/images/' with the actual path
resource_list.push({
name: imageName,
path: imagePath,
download: true
});
}
// init psychoJS:
const psychoJS = new PsychoJS({
debug: true
});
// open window:
psychoJS.openWindow({
fullscr: true,
color: new util.Color([0,0,0]),
units: 'height',
waitBlanking: true
});
// schedule the experiment:
psychoJS.schedule(psychoJS.gui.DlgFromDict({
dictionary: expInfo,
title: expName
}));
const flowScheduler = new Scheduler(psychoJS);
const dialogCancelScheduler = new Scheduler(psychoJS);
psychoJS.scheduleCondition(function() { return (psychoJS.gui.dialogComponent.button === 'OK'); }, flowScheduler, dialogCancelScheduler);
// flowScheduler gets run if the participants presses OK
flowScheduler.add(updateInfo); // add timeStamp
flowScheduler.add(experimentInit);
const trialsLoopScheduler = new Scheduler(psychoJS);
flowScheduler.add(trialsLoopBegin(trialsLoopScheduler));
flowScheduler.add(trialsLoopScheduler);
flowScheduler.add(trialsLoopEnd);
flowScheduler.add(quitPsychoJS, '', true);
// quit if user presses Cancel in dialog box:
dialogCancelScheduler.add(quitPsychoJS, '', false);
psychoJS.start({
expName: expName,
expInfo: expInfo,
resources: [
// resources:
{'name': 'Balancing/observer_1.csv', 'path': 'Balancing/observer_1.csv'},
]
});
psychoJS.experimentLogger.setLevel(core.Logger.ServerLevel.EXP);
var currentLoop;
var frameDur;
async function updateInfo() {
currentLoop = psychoJS.experiment; // right now there are no loops
expInfo['date'] = util.MonotonicClock.getDateStr(); // add a simple timestamp
expInfo['expName'] = expName;
expInfo['psychopyVersion'] = '2023.1.1';
expInfo['OS'] = window.navigator.platform;
// store frame rate of monitor if we can measure it successfully
expInfo['frameRate'] = psychoJS.window.getActualFrameRate();
if (typeof expInfo['frameRate'] !== 'undefined')
frameDur = 1.0 / Math.round(expInfo['frameRate']);
else
frameDur = 1.0 / 60.0; // couldn't get a reliable measure so guess
// add info from the URL:
util.addInfoFromUrl(expInfo);
psychoJS.experiment.dataFileName = (("." + "/") + `data/${expInfo["participant"]}_${expName}_${expInfo["date"]}`);
return Scheduler.Event.NEXT;
}
var trialClock;
var image;
var key_resp;
var globalClock;
var routineTimer;
async function experimentInit() {
// Initialize components for Routine "trial"
trialClock = new util.Clock();
image = new visual.ImageStim({
win : psychoJS.window,
name : 'image', units : undefined,
image : (("images/" + (trials.thisTrialN + 1).toString()) + "_original.jpg"), mask : undefined,
anchor : 'center',
ori : 0.0, pos : [0, 0], size : [0.5, 0.5],
color : new util.Color([1,1,1]), opacity : undefined,
flipHoriz : false, flipVert : false,
texRes : 128.0, interpolate : true, depth : 0.0
});
key_resp = new core.Keyboard({psychoJS: psychoJS, clock: new util.Clock(), waitForStart: true});
// Create some handy timers
globalClock = new util.Clock(); // to track the time since experiment started
routineTimer = new util.CountdownTimer(); // to track time remaining of each (non-slip) routine
return Scheduler.Event.NEXT;
}
var trials;
function trialsLoopBegin(trialsLoopScheduler, snapshot) {
return async function() {
TrialHandler.fromSnapshot(snapshot); // update internal variables (.thisN etc) of the loop
// set up handler to look after randomisation of conditions etc
trials = new TrialHandler({
psychoJS: psychoJS,
nReps: 420, method: TrialHandler.Method.RANDOM,
extraInfo: expInfo, originPath: undefined,
trialList: undefined,
seed: undefined, name: 'trials'
});
psychoJS.experiment.addLoop(trials); // add the loop to the experiment
currentLoop = trials; // we're now the current loop
// Schedule all the trials in the trialList:
for (const thisTrial of trials) {
snapshot = trials.getSnapshot();
trialsLoopScheduler.add(importConditions(snapshot));
trialsLoopScheduler.add(trialRoutineBegin(snapshot));
trialsLoopScheduler.add(trialRoutineEachFrame());
trialsLoopScheduler.add(trialRoutineEnd(snapshot));
trialsLoopScheduler.add(trialsLoopEndIteration(trialsLoopScheduler, snapshot));
}
return Scheduler.Event.NEXT;
}
}
async function trialsLoopEnd() {
// terminate loop
psychoJS.experiment.removeLoop(trials);
// update the current loop from the ExperimentHandler
if (psychoJS.experiment._unfinishedLoops.length>0)
currentLoop = psychoJS.experiment._unfinishedLoops.at(-1);
else
currentLoop = psychoJS.experiment; // so we use addData from the experiment
return Scheduler.Event.NEXT;
}
function trialsLoopEndIteration(scheduler, snapshot) {
// ------Prepare for next entry------
return async function () {
if (typeof snapshot !== 'undefined') {
// ------Check if user ended loop early------
if (snapshot.finished) {
// Check for and save orphaned data
if (psychoJS.experiment.isEntryEmpty()) {
psychoJS.experiment.nextEntry(snapshot);
}
scheduler.stop();
} else {
psychoJS.experiment.nextEntry(snapshot);
}
return Scheduler.Event.NEXT;
}
};
}
var t;
var frameN;
var continueRoutine;
var _key_resp_allKeys;
var trialComponents;
function trialRoutineBegin(snapshot) {
return async function () {
TrialHandler.fromSnapshot(snapshot); // ensure that .thisN vals are up to date
//--- Prepare to start Routine 'trial' ---
t = 0;
trialClock.reset(); // clock
frameN = -1;
continueRoutine = true; // until we're told otherwise
// update component parameters for each repeat
key_resp.keys = undefined;
key_resp.rt = undefined;
_key_resp_allKeys = [];
// keep track of which components have finished
trialComponents = [];
trialComponents.push(image);
trialComponents.push(key_resp);
for (const thisComponent of trialComponents)
if ('status' in thisComponent)
thisComponent.status = PsychoJS.Status.NOT_STARTED;
return Scheduler.Event.NEXT;
}
}
function trialRoutineEachFrame() {
return async function () {
//--- Loop for each frame of Routine 'trial' ---
// get current time
t = trialClock.getTime();
frameN = frameN + 1;// number of completed frames (so 0 is the first frame)
// update/draw components on each frame
// *image* updates
if (t >= 0.2 && image.status === PsychoJS.Status.NOT_STARTED) {
// keep track of start time/frame for later
image.tStart = t; // (not accounting for frame time here)
image.frameNStart = frameN; // exact frame index
image.setAutoDraw(true);
}
// *key_resp* updates
if (t >= 0.2 && key_resp.status === PsychoJS.Status.NOT_STARTED) {
// keep track of start time/frame for later
key_resp.tStart = t; // (not accounting for frame time here)
key_resp.frameNStart = frameN; // exact frame index
// keyboard checking is just starting
psychoJS.window.callOnFlip(function() { key_resp.clock.reset(); }); // t=0 on next screen flip
psychoJS.window.callOnFlip(function() { key_resp.start(); }); // start on screen flip
psychoJS.window.callOnFlip(function() { key_resp.clearEvents(); });
}
if (key_resp.status === PsychoJS.Status.STARTED) {
let theseKeys = key_resp.getKeys({keyList: ['1', '2', '3', '4', '5'], waitRelease: false});
_key_resp_allKeys = _key_resp_allKeys.concat(theseKeys);
if (_key_resp_allKeys.length > 0) {
key_resp.keys = _key_resp_allKeys[_key_resp_allKeys.length - 1].name; // just the last key pressed
key_resp.rt = _key_resp_allKeys[_key_resp_allKeys.length - 1].rt;
// a response ends the routine
continueRoutine = false;
}
}
// check for quit (typically the Esc key)
if (psychoJS.experiment.experimentEnded || psychoJS.eventManager.getKeys({keyList:['escape']}).length > 0) {
return quitPsychoJS('The [Escape] key was pressed. Goodbye!', false);
}
// check if the Routine should terminate
if (!continueRoutine) { // a component has requested a forced-end of Routine
return Scheduler.Event.NEXT;
}
continueRoutine = false; // reverts to True if at least one component still running
for (const thisComponent of trialComponents)
if ('status' in thisComponent && thisComponent.status !== PsychoJS.Status.FINISHED) {
continueRoutine = true;
break;
}
// refresh the screen if continuing
if (continueRoutine) {
return Scheduler.Event.FLIP_REPEAT;
} else {
return Scheduler.Event.NEXT;
}
};
}
function trialRoutineEnd(snapshot) {
return async function () {
//--- Ending Routine 'trial' ---
for (const thisComponent of trialComponents) {
if (typeof thisComponent.setAutoDraw === 'function') {
thisComponent.setAutoDraw(false);
}
}
// update the trial handler
if (currentLoop instanceof MultiStairHandler) {
currentLoop.addResponse(key_resp.corr, level);
}
psychoJS.experiment.addData('key_resp.keys', key_resp.keys);
if (typeof key_resp.keys !== 'undefined') { // we had a response
psychoJS.experiment.addData('key_resp.rt', key_resp.rt);
routineTimer.reset();
}
key_resp.stop();
// the Routine "trial" was not non-slip safe, so reset the non-slip timer
routineTimer.reset();
// Routines running outside a loop should always advance the datafile row
if (currentLoop === psychoJS.experiment) {
psychoJS.experiment.nextEntry(snapshot);
}
return Scheduler.Event.NEXT;
}
}
function importConditions(currentLoop) {
return async function () {
psychoJS.importAttributes(currentLoop.getCurrentTrial());
return Scheduler.Event.NEXT;
};
}
async function quitPsychoJS(message, isCompleted) {
// Check for and save orphaned data
if (psychoJS.experiment.isEntryEmpty()) {
psychoJS.experiment.nextEntry();
}
psychoJS.window.close();
psychoJS.quit({message: message, isCompleted: isCompleted});
return Scheduler.Event.QUIT;
}
Returns:
Error
Unfortunately we encountered the following error:
TypeError: Cannot read properties of undefined (reading 'thisTrialN')
Try to run the experiment again. If the error persists, contact the experiment designer.
|
b5ee2ec7328fbdc438eafc90b1cfbafd
|
{
"intermediate": 0.3429770767688751,
"beginner": 0.43570634722709656,
"expert": 0.22131659090518951
}
|
9,140
|
how to download google doc as a pdf file
|
823a76856c48175b4ff9de8ba6fcead6
|
{
"intermediate": 0.32640719413757324,
"beginner": 0.2243417203426361,
"expert": 0.44925108551979065
}
|
9,141
|
How escape % sign in django raw sql query?
|
44b96d814243ec9214625f396435ec19
|
{
"intermediate": 0.6908746361732483,
"beginner": 0.12561394274234772,
"expert": 0.18351146578788757
}
|
9,142
|
Write 10 strong argument why I must use spark instead of write my custom code in kotlin for transfer data
|
ff4efc706f48525d071ab08162c1e656
|
{
"intermediate": 0.7449144124984741,
"beginner": 0.06433090567588806,
"expert": 0.19075463712215424
}
|
9,143
|
I need a rust function that adds a hashset to another hashset and returns that new hashset
|
78a02b6b10fb0b8fc3e75c63724098df
|
{
"intermediate": 0.3306950330734253,
"beginner": 0.3272722065448761,
"expert": 0.342032790184021
}
|
9,144
|
7 solutions to copy sublime's Build Results into a string variable. Requirements: solutions with minimal viable code example in rust that can do this, strictly using only std library in rust. Starting with one most efficient solution, proceeding through several most sophisticated ones and, finally, to the several completely different approaches to achieve this regardless of any mentioned requirements.
|
4a4be3b2a7bfe837e5defb0833f2a8d1
|
{
"intermediate": 0.3741579055786133,
"beginner": 0.4172670841217041,
"expert": 0.20857496559619904
}
|
9,145
|
<html> <head> <title>Калькулятор расчета щебня фракции 10-20 мм.</title> <style> h1 { text-align: center; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 20px; }
form {
max-width: 500px;
margin: 0 auto;
}
input[type="text"],
input[type="email"],
input[type="number"],
label,
output {
font-family: Arial, sans-serif;
font-size: 16px;
color: black;
}
input[type="text"],
input[type="email"],
input[type="number"] {
border-radius: 10px;
border: 2px solid orange;
padding: 5px;
margin-bottom: 10px;
width: 100%;
}
input[type="submit"] {
margin-top: 20px;
padding: 10px;
background-color: orange;
color: white;
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
border-radius: 10px;
border: none;
}
input[type="submit"]:hover {
cursor: pointer;
}
label {
display: block;
margin-bottom: 5px;
}
output {
font-weight: bold;
margin-bottom: 10px;
}
/* Скрыть элемент cost_w_vat при выборе самовывоза */
#cost_w_vat {
display: none;
}
</style>
</head> <body> <h1>Расчет стоимости щебня фракции 10-20 мм:</h1> <form> <label for="tons">Введите количество тонн:<br></label> <input type="number" name="tons" min="0" required /><br /><br /> <label for="delivery">Выберите способ получения: </label><br /> <input type="radio" name="delivery" value="self" checked /> Самовывоз<br /> <input type="radio" name="delivery" value="delivery" /> Рассчитать доставку<br /><br />
<div id="delivery-options" style="display:none">
<h2>Расчет доставки щебня:</h2>
<label for="distance_km">Укажите удаленность от карьера в километрах:<br></label>
<input type="number" name="distance_km" min="0" /><br /><br />
</div>
<label>Количество м3:</label>
<output name="volume"></output><br /><br />
<label>Расчет стоимости щебня:</label>
<output name="cost_wo_vat"></output><br /><br />
<label>Расчет стоимости с учетом способа получения:</label>
<output id="cost_w_vat" name="cost_w_vat"></output><br /><br />
<label for="name">Введите Ваше имя:</label><br />
<input type="text" name="name" required /><br /><br />
<label for="phone">Введите номер телефона:<br /></label>
<input type="text" name="phone" required /><br /><br />
<label for="email">Введите E-mail:<br /></label>
<input type="email" name="email" /><br /><br />
<input type="submit" id="submit-btn" value="Отправить" />
</form>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const price_per_ton = 560;
const price_per_km = new Map([
[100, 5.5],
[150, 5.1],
[200, 4.5],
[300, 4.2],
[400, 4.0],
[Infinity, 3.8],
]);
const vat_rate = 20;
function sendEmail(values) {
const formData = new FormData();
formData.append('service_id', 'service_zzlkjgr');
formData.append('template_id', 'template_3y6qnq3');
formData.append('user_id', 'bSTMJweuEiI90I3Uk');
formData.append('to_email', 'kv.sheben@yandex.ru');
formData.append('tons', values.tons);
formData.append('delivery', values.delivery);
formData.append('distance_km', values.distance_km);
formData.append('volume', values.volume);
formData.append('cost_wo_vat', values.cost_wo_vat);
formData.append('cost_w_vat', values.cost_w_vat);
formData.append('name', values.name);
formData.append('phone', values.phone);
formData.append('email', values.email);
$.ajax('https://api.emailjs.com/api/v1.0/email/send-form', {
type: 'POST',
data: formData,
contentType: false,
processData: false,
})
.done(function () {
alert('Ваше письмо успешно отправлено!');
})
.fail(function (error) {
alert('Упс... ' + JSON.stringify(error));
});
}
function calculate() {
const tons = Number(document.getElementsByName('tons')[0].value);
const volume = tons / 1.27;
const cost_wo_vat = tons * price_per_ton;
const delivery = document.querySelector('input[name="delivery"]:checked').value;
const distance_km = Number(document.getElementsByName('distance_km')[0].value);
let cost_w_vat = 0;
if (delivery === 'delivery') {
const price_per_km_array = [...price_per_km.entries()];
const [distance, price] = price_per_km_array.find(([distance, _]) => distance >= distance_km);
cost_w_vat = tons * price * distance + cost_wo_vat;
} else {
cost_w_vat = cost_wo_vat;
}
const cost_w_vat_formatted = cost_w_vat.toLocaleString('ru-RU', { style: 'currency', currency: 'RUB' });
const values = {
tons: tons,
delivery: delivery,
distance_km: distance_km,
volume: volume.toFixed(2),
cost_wo_vat: cost_wo_vat.toLocaleString('ru-RU', { style: 'currency', currency: 'RUB' }),
cost_w_vat: cost_w_vat_formatted,
name: document.getElementsByName('name')[0].value,
phone: document.getElementsByName('phone')[0].value,
email: document.getElementsByName('email')[0].value,
};
document.getElementsByName('volume')[0].textContent = `${values.volume} м3`;
document.getElementsByName('cost_wo_vat')[0].textContent = values.cost_wo_vat;
document.getElementsByName('cost_w_vat')[0].textContent = values.cost_w_vat;
if (delivery === 'self') {
document.getElementById('delivery-options').style.display = 'none';
document.getElementById('cost_w_vat').style.display = 'block';
} else {
document.getElementById('delivery-options').style.display = 'block';
document.getElementById('cost_w_vat').style.display = 'block';
}
}
document.getElementsByName('tons')[0].addEventListener('input', calculate);
document.getElementsByName('delivery').forEach((el) => {
el.addEventListener('change', () => {
if (el.value === 'self') {
document.getElementById('delivery-options').style.display = 'none';
document.getElementById('cost_w_vat').style.display = 'block';
} else {
document.getElementById('delivery-options').style.display = 'block';
document.getElementById('cost_w_vat').style.display = 'block';
}
calculate();
});
});
document.getElementsByName('distance_km')[0].addEventListener('input', calculate);
document.querySelector('form').addEventListener('submit', (event) => {
event.preventDefault();
sendEmail({
tons: Number(document.getElementsByName('tons')[0].value),
delivery: document.querySelector('input[name="delivery"]:checked').value,
distance_km: Number(document.getElementsByName('distance_km')[0].value),
volume: Number(document.getElementsByName('volume')[0].textContent),
cost_wo_vat: document.getElementsByName('cost_wo_vat')[0].textContent,
cost_w_vat: document.getElementsByName('cost_w_vat')[0].textContent,
name: document.getElementsByName('name')[0].value,
phone: document.getElementsByName('phone')[0].value,
email: document.getElementsByName('email')[0].value,
});
});
</script>
</body> </html>
КОД ЧЕТЫРЕ:
<html> <head> <title>Калькулятор расчета щебня фракции 10-20 мм.</title> <style> h1 { text-align: center; font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif"; font-size: 20px; } form { max-width: 500px; margin: 0 auto; }
input[type="text"],
input[type="email"],
input[type="number"],
label,
output {
font-family: Arial, sans-serif;
font-size: 16px;
color: black;
}
input[type="text"],
input[type="email"],
input[type="number"] {
border-radius: 10px;
border: 2px solid orange;
padding: 5px;
margin-bottom: 10px;
width: 100%;
}
input[type="submit"] {
margin-top: 20px;
padding: 10px;
background-color: orange;
color: white;
font-family: Arial, sans-serif;
font-size: 16px;
font-weight: bold;
border-radius: 10px;
border: none;
}
input[type="submit"]:hover {
cursor: pointer;
}
label {
display: block;
margin-bottom: 5px;
}
output {
font-weight: bold;
margin-bottom: 10px;
}
/* Скрыть элемент cost_w_vat при выборе самовывоза */
#cost_w_vat {
display: none;
}
</style>
</head> <body> <h1>Расчет стоимости щебня фракции 10-20 мм:</h1> <form> <label for="tons">Введите количество тонн:<br></label> <input type="number" name="tons" min="0" required /><br /><br /> <label for="delivery">Выберите способ получения: </label><br /> <input type="radio" name="delivery" value="self" checked /> Самовывоз<br /> <input type="radio" name="delivery" value="delivery" /> Рассчитать доставку<br /><br />
<div id="delivery-options" style="display:none">
<h2>Расчет доставки щебня:</h2>
<label for="distance_km">Укажите удаленность от карьера в километрах:<br></label>
<input type="number" name="distance_km" min="0" /><br /><br />
</div>
<label>Количество м3:</label>
<output name="volume"></output><br /><br />
<label>Расчет стоимости щебня:</label>
<output name="cost_wo_vat"></output><br /><br />
<label>Расчет стоимости с учетом способа получения:</label>
<output id="cost_w_vat" name="cost_w_vat"></output><br /><br />
<label for="name">Введите Ваше имя:</label><br />
<input type="text" name="name" required /><br /><br />
<label for="phone">Введите номер телефона:<br /></label>
<input type="text" name="phone" required /><br /><br />
<label for="email">Введите E-mail:<br /></label>
<input type="email" name="email" /><br /><br />
<input type="submit" id="submit-btn" value="Отправить" />
</form>
<div id="popup" class="overlay">
<div class="popup">
<h2>Ваше сообщение было отправлено</h2>
<br />
<a class="close" href="#">×</a>
<div class="content">
<p>Спасибо за ваше сообщение!</p>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
const price_per_ton = 560;
const price_per_km = new Map([
[100, 5.5],
[150, 5.1],
[200, 4.5],
[300, 4.2],
[400, 4.0],
[Infinity, 3.8],
]);
const vat_rate = 20;
function sendEmail(values) {
const formData = new FormData();
formData.append('service_id', 'service_zzlkjgr');
formData.append('template_id', 'template_3y6qnq3');
formData.append('user_id', 'bSTMJweuEiI90I3Uk');
formData.append('to_email', 'kv.sheben@yandex.ru');
formData.append('tons', values.tons);
formData.append('delivery', values.delivery);
formData.append('distance_km', values.distance_km);
formData.append('volume', values.volume);
formData.append('cost_wo_vat', values.cost_wo_vat);
formData.append('cost_w_vat', values.cost_w_vat);
formData.append('name', values.name);
formData.append('phone', values.phone);
formData.append('email', values.email);
$.ajax('https://api.emailjs.com/api/v1.0/email/send-form', {
type: 'POST',
data: formData,
contentType: false,
processData: false,
})
.done(function () {
$('#popup').show();
})
.fail(function (error) {
$('#popup').show();
});
}
function calculate() {
const tons = Number(document.getElementsByName('tons')[0].value);
const volume = tons / 1.27;
const cost_wo_vat = tons * price_per_ton;
const delivery = document.querySelector('input[name="delivery"]:checked').value;
const distance_km = Number(document.getElementsByName('distance_km')[0].value);
let cost_w_vat = 0;
if (delivery === 'delivery') {
const price_per_km_array = [...price_per_km.entries()];
const [distance, price] = price_per_km_array.find(([distance, _]) => distance >= distance_km);
cost_w_vat = tons * price * distance + cost_wo_vat;
} else {
cost_w_vat = cost_wo_vat;
}
const cost_w_vat_formatted = cost_w_vat.toLocaleString('ru-RU', { style: 'currency', currency: 'RUB' });
const values = {
tons: tons,
delivery: delivery,
distance_km: distance_km,
volume: volume.toFixed(2),
cost_wo_vat: cost_wo_vat.toLocaleString('ru-RU', { style: 'currency', currency: 'RUB' }),
cost_w_vat: cost_w_vat_formatted,
name: document.getElementsByName('name')[0].value,
phone: document.getElementsByName('phone')[0].value,
email: document.getElementsByName('email')[0].value,
};
document.getElementsByName('volume')[0].textContent = `${values.volume} м3`;
document.getElementsByName('cost_wo_vat')[0].textContent = values.cost_wo_vat;
document.getElementsByName('cost_w_vat')[0].textContent = values.cost_w_vat;
if (delivery === 'self') {
document.getElementById('delivery-options').style.display = 'none';
document.getElementById('cost_w_vat').style.display = 'block';
} else {
document.getElementById('delivery-options').style.display = 'block';
document.getElementById('cost_w_vat').style.display = 'block';
}
}
document.getElementsByName('tons')[0].addEventListener('input', calculate);
document.getElementsByName('delivery').forEach((el) => {
el.addEventListener('change', () => {
if (el.value === 'self') {
document.getElementById('delivery-options').style.display = 'none';
document.getElementById('cost_w_vat').style.display = 'block';
} else {
document.getElementById('delivery-options').style.display = 'block';
document.getElementById('cost_w_vat').style.display = 'block';
}
calculate();
});
});
document.getElementsByName('distance_km')[0].addEventListener('input', calculate);
document.querySelector('form').addEventListener('submit', (event) => {
event.preventDefault();
sendEmail({
tons: Number(document.getElementsByName('tons')[0].value),
delivery: document.querySelector('input[name="delivery"]:checked').value,
distance_km: Number(document.getElementsByName('distance_km')[0].value),
volume: Number(document.getElementsByName('volume')[0].textContent),
cost_wo_vat: document.getElementsByName('cost_wo_vat')[0].textContent,
cost_w_vat: document.getElementsByName('cost_w_vat')[0].textContent,
name: document.getElementsByName('name')[0].value,
phone: document.getElementsByName('phone')[0].value,
email: document.getElementsByName('email')[0].value,
});
});
$('.close').click(function(){
$('#popup').hide();
});
$(document).mouseup(function (e) {
var popup = $('.popup');
if (!$('#submit-btn').is(e.target) && !popup.is(e.target) && popup.has(e.target).length === 0) {
$('#popup').hide();
}
});
</script>
</body> </html> запомни этот код с ним мы будем работать
|
3c3eff6cc91b6f6c4abfa462d445158f
|
{
"intermediate": 0.34308114647865295,
"beginner": 0.49804508686065674,
"expert": 0.15887384116649628
}
|
9,146
|
POST /resweb/asset/assetCheck.spr?method=startPD HTTP/1.1
Referer: http://10.35.35.43:7016/resweb/asset/assetCheck.spr?method=forwardStartAssetsPD
querystring :
method startPD
body:
processType ZCPD
roomId 000102080000000000009564
roomName 东方医院位置点
使用requests.post处理,给出代码
|
c50263f4afeba3a8b9b1bceb277b7238
|
{
"intermediate": 0.3588533401489258,
"beginner": 0.21016943454742432,
"expert": 0.4309772551059723
}
|
9,147
|
Can you write a function `generate_chunk` which takes `x` and `y` as parameters. Where a chunk is a square made up of 64 `tiles`. And returns the value as a list of lists containing position of tile inside the chunk, tile type and plant type in the following pattern: `[(x_pos, y_pos), tile_type, plant_type]`
Tile type is a value between (and including) 0 and 2 where, 0 is grass block, 1 is sand and 2 is water.
Plant type is a value of either 0, 1, 2 or None where None is no plant, 0 is grass plant, 1 is palm tree and 2 is cactus.
The terrain should be generated depending on two factors `altitude` and `temperature` which is generated from the `opensimplex` python module. The terrain should be divided into 4 biomes (ocean, beach, grassland and desert).
|
a531a27c7b976b35b191ee2849aa7ae4
|
{
"intermediate": 0.41182371973991394,
"beginner": 0.26185110211372375,
"expert": 0.3263251781463623
}
|
9,148
|
Can you split the addComponent function into smaller functions? template<class C, typename... Args>
C* ECS::AddComponent(const uint32_t entityId, Args&&... args) {
auto newComponentID = Component<C>::GetTypeID();
if (componentMasks[entityId].HasComponent(newComponentID)) {
return nullptr; // Component already exists for the entity
}
componentMasks[entityId].AddComponent(newComponentID);
Archetype* newArchetype = nullptr;
C* newComponent = nullptr;
Record& record = entityArchetypeMap[entityId];
Archetype* oldArchetype = record.archetype;
auto& newComponentMask = componentMasks[entityId];
newArchetype = GetArchetype(componentMasks[entityId]);
// if the entity already has components
if (oldArchetype) {
auto oldComponentMask = oldArchetype->componentMask;
std::size_t entityIndex = std::find(
oldArchetype->entityIds.begin(),
oldArchetype->entityIds.end() - 1,
entityId
) - oldArchetype->entityIds.begin();
std::size_t index = 0;
std::size_t j = 0;
for (std::size_t i = 0; i < newComponentMask.GetBitsetMask().size() - 1; ++i) {
if (newComponentMask.GetBitsetMask().test(i)) {
const ComponentBase* const componentBase = componentMap[i];
const std::size_t newComponentDataSize = componentBase->GetSize();
std::size_t currentSize = newArchetype->entityIds.size() * newComponentDataSize;
std::size_t newSize = currentSize + newComponentDataSize;
if (newSize > newArchetype->componentDataSize[index]) {
Reallocate(componentBase, newComponentDataSize, newArchetype, index);
}
if (oldComponentMask.HasComponent(i)) {
TransferComponentData(componentBase, oldArchetype, newArchetype, index, j, entityIndex);
++j;
}
else {
/*newComponent = */ new (&newArchetype->componentData[index][currentSize]) C(std::forward<Args>(args)...);
}
index++;
}
}
auto lastEntity = oldArchetype->entityIds.size() - 1;
// If the old archetype still has entities in
if (!oldArchetype->entityIds.empty() && entityIndex < oldArchetype->entityIds.size()) {
std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.begin() + lastEntity);
for (std::size_t i = 0, j = 0, index = 0; i < oldComponentMask.GetBitsetMask().size() - 1; ++i) {
if (oldComponentMask.GetBitsetMask().test(i)) {
const ComponentBase* const componentBase = componentMap[i];
SwapComponentData(componentBase, oldArchetype, index, entityIndex);
++index;
}
}
// swap the entity leaving the archetype with the one at the end of the list before deleting the leaving entity by popping
oldArchetype->entityIds.pop_back();
}
}
// If this is the first time we're adding a component to this entity
else
{
// Get size of the new component
const ComponentBase* const newComponentBase = componentMap[newComponentID];
const std::size_t& newComponentDataSize = newComponentBase->GetSize();
std::size_t currentSize = newArchetype->entityIds.size() * newComponentDataSize;
std::size_t newSize = currentSize + newComponentDataSize;
//Reallocate(newComponentBase, newArchetype, 0);
if (newSize > newArchetype->componentDataSize[0]) {
Reallocate(newComponentBase, newComponentDataSize, newArchetype, 0);
}
newComponent = new (&newArchetype->componentData[0][currentSize]) C(std::forward<Args>(args)...);
}
newArchetype->entityIds.push_back(entityId);
record.index = newArchetype->entityIds.size() - 1;
record.archetype = newArchetype;
return newComponent;
}void ECS::Reallocate(const ComponentBase* compbase, const size_t& newCompSize, Archetype* arch, size_t index) {
arch->componentDataSize[index] *= 2;
arch->componentDataSize[index] += newCompSize;
unsigned char* newData = new unsigned char[arch->componentDataSize[index]];
for (auto e = 0; e < arch->entityIds.size(); ++e) {
compbase->MoveData(&arch->componentData[index][e * newCompSize],
&newData[e * newCompSize]);
compbase->DestroyData(&arch->componentData[index][e * newCompSize]);
}
delete[] arch->componentData[index];
arch->componentData[index] = newData;
}
void ECS::TransferComponentData(const ComponentBase* compbase, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex) {
const std::size_t compSize = compbase->GetSize();
std::size_t currentSize = toArch->entityIds.size() * compSize;
compbase->MoveData(&fromArch->componentData[j][entityIndex * compSize],
&toArch->componentData[i][currentSize]);
compbase->DestroyData(&fromArch->componentData[j][entityIndex * compSize]);
}
#include "ComponentMask.h"
typedef unsigned char* ComponentData;
typedef std::vector<int> ArchetypeId;
struct Archetype
{
ComponentMask componentMask;
std::vector<ComponentData> componentData;
std::vector<uint32_t> entityIds;
std::vector<std::size_t> componentDataSize;
};
|
732bf732ed64e99bd90ca001d05f4e81
|
{
"intermediate": 0.4108835756778717,
"beginner": 0.3578696548938751,
"expert": 0.23124676942825317
}
|
9,149
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
How can I alter the code to fix this issue?
|
7253b84cc7f06d334894c6b0ecf15004
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,150
|
How to upgrade python to last version ?
|
09349c9382d81ac8322515d81f288ed8
|
{
"intermediate": 0.39015012979507446,
"beginner": 0.20973090827465057,
"expert": 0.40011900663375854
}
|
9,151
|
hi
|
d9170cd021ff35b66227252c4c1bad8a
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,152
|
代码注释package com.mindskip.xzs.controller.admin;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.configuration.property.SystemConfig;
import com.mindskip.xzs.service.FileUpload;
import com.mindskip.xzs.service.UserService;
import com.mindskip.xzs.viewmodel.admin.file.UeditorConfigVM;
import com.mindskip.xzs.viewmodel.admin.file.UploadResultVM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
@RequestMapping("/api/admin/upload")
@RestController("AdminUploadController")
public class UploadController extends BaseApiController {
private final FileUpload fileUpload;
private final SystemConfig systemConfig;
private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
private static final String IMAGE_UPLOAD = "imgUpload";
private static final String IMAGE_UPLOAD_FILE = "upFile";
private final UserService userService;
@Autowired
public UploadController(FileUpload fileUpload, SystemConfig systemConfig, UserService userService) {
this.fileUpload = fileUpload;
this.systemConfig = systemConfig;
this.userService = userService;
}
@ResponseBody
@RequestMapping("/configAndUpload")
public Object upload(HttpServletRequest request, HttpServletResponse response) {
String action = request.getParameter("action");
if (action.equals(IMAGE_UPLOAD)) {
try {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartHttpServletRequest.getFile(IMAGE_UPLOAD_FILE);
long attachSize = multipartFile.getSize();
String imgName = multipartFile.getOriginalFilename();
String filePath;
try (InputStream inputStream = multipartFile.getInputStream()) {
filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
}
String imageType = imgName.substring(imgName.lastIndexOf("."));
UploadResultVM uploadResultVM = new UploadResultVM();
uploadResultVM.setOriginal(imgName);
uploadResultVM.setName(imgName);
uploadResultVM.setUrl(filePath);
uploadResultVM.setSize(multipartFile.getSize());
uploadResultVM.setType(imageType);
uploadResultVM.setState("SUCCESS");
return uploadResultVM;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} else {
UeditorConfigVM ueditorConfigVM = new UeditorConfigVM();
ueditorConfigVM.setImageActionName(IMAGE_UPLOAD);
ueditorConfigVM.setImageFieldName(IMAGE_UPLOAD_FILE);
ueditorConfigVM.setImageMaxSize(2048000L);
ueditorConfigVM.setImageAllowFiles(Arrays.asList(".png", ".jpg", ".jpeg", ".gif", ".bmp"));
ueditorConfigVM.setImageCompressEnable(true);
ueditorConfigVM.setImageCompressBorder(1600);
ueditorConfigVM.setImageInsertAlign("none");
ueditorConfigVM.setImageUrlPrefix("");
ueditorConfigVM.setImagePathFormat("");
return ueditorConfigVM;
}
return null;
}
@RequestMapping("/image")
@ResponseBody
public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
long attachSize = multipartFile.getSize();
String imgName = multipartFile.getOriginalFilename();
try (InputStream inputStream = multipartFile.getInputStream()) {
String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
userService.changePicture(getCurrentUser(), filePath);
return RestResponse.ok(filePath);
} catch (IOException e) {
return RestResponse.fail(2, e.getMessage());
}
}
}
|
7f68bdceeec06b5fdec013840f7681bc
|
{
"intermediate": 0.2594969570636749,
"beginner": 0.5244630575180054,
"expert": 0.2160399705171585
}
|
9,153
|
import disnake
from disnake.ext import commands
import time
import threading
import requests
import random
import socks
botchannel = 1110877089374146621
logschannel = 1110877089374146621
moderators = [5418189181651561651]
intents = disnake.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
discord = disnake
x1 = "Bronze"
x2 = "Gold"
x5 = "Diamond"
x6 = "Silver"
x3 = "Premium"
x4 = "Premium +"
x5 = "Max"
x6 = "No Cooldown"
def get_username(channel_name):
json = {
"operationName": "ChannelShell",
"variables": {
"login": channel_name
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "580ab410bcd0c1ad194224957ae2241e5d252b2c5173d8e0cce9d32d5bb14efe"
}
}
}
headers = {
'Client-ID': 'kimne78kx3ncx6brgo4mv6wki5h1ko'
}
try:
r = requests.post('https://gql.twitch.tv/gql', json=json, headers=headers)
return r.json()['data']['userOrError']['id']
except Exception as e:
print(f"Error occurred while getting username: {e}")
return None
def follower(target_id):
global followsent
try:
i1 = open('tokens.txt', 'r').read().splitlines()
i2 = random.choice(i1)
headers = {
'Accept': 'application/vnd.twitchtv.v3+json',
'Accept-Language': 'en-us',
'api-consumer-type': 'mobile; Android/1404000',
'authorization': f'OAuth {i2}',
'client-id': 'kd1unb4b3q4t58fwlpcbzcbnm76a8fp',
'client-session-id': '7f4b1045-f52b-49da-bcef-a81394610476',
'connection': 'Keep-Alive',
'content-type': 'application/json',
'host': 'gql.twitch.tv',
'user-agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; vivo V3Max Build/LMY47V) tv.twitch.android.app/14.4.0/1404000',
'x-apollo-operation-id': 'cd112d9483ede85fa0da514a5657141c24396efbc7bac0ea3623e839206573b8',
'x-apollo-operation-name': 'FollowUserMutation',
'x-app-version': '14.4.0',
'x-device-id': 'e5c5e81ebfca405784e1da77aacca842'
}
data = {
"operationName": "FollowUserMutation",
"variables": {
"targetId": target_id,
"disableNotifications": False
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "cd112d9483ede85fa0da514a5657141c24396efbc7bac0ea3623e839206573b8"
}
}
}
response = requests.post('https://gql.twitch.tv/gql', json=data, headers=headers)
followsent += 1
except Exception as e:
print(f"Error occurred while sending follow request: {e}")
def followerraid(channel):
token = open('tokens.txt', 'r').read().splitlines()
tokens = random.choice(token)
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
'Authorization': f'OAuth {tokens}'
}
response = requests.get("https://id.twitch.tv/oauth2/validate", headers=headers).json()
token_name = response['login']
guser = get_username(token_name)
headers = {
'Accept': 'application/vnd.twitchtv.v3+json',
'Accept-Language': 'en-us',
'api-consumer-type': 'mobile; Android/1404000',
'authorization': f'OAuth {tokens}',
'client-id': 'kd1unb4b3q4t58fwlpcbzcbnm76a8fp',
'client-session-id': '7f4b1045-f52b-49da-bcef-a81394610476',
'connection': 'Keep-Alive',
'content-type': 'application/json',
'host': 'gql.twitch.tv',
'user-agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; vivo V3Max Build/LMY47V) tv.twitch.android.app/14.4.0/1404000',
'x-apollo-operation-id': '412f0fd1876b9fe3426cd726b00b4e4fff9ea3e027e03407de89b6dd0c8674e7',
'x-apollo-operation-name': 'CreateRaidMutation',
'x-app-version': '14.4.0',
'x-device-id': '6c2a973b192849fea684773a218e34f4'
}
data = {
"operationName": "CreateRaidMutation",
"variables": {
"input": {
"sourceID": guser,
"targetID": get_username(channel)
}
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "412f0fd1876b9fe3426cd726b00b4e4fff9ea3e027e03407de89b6dd0c8674e7"
}
}
}
r = requests.post('https://gql.twitch.tv/gql', headers=headers, json=data)
print(r.text)
time.sleep(20)
headersf = {
'Accept': 'application/vnd.twitchtv.v3+json',
'Accept-Language': 'en-us',
'api-consumer-type': 'mobile; Android/1404000',
'authorization': f'OAuth {tokens}',
'client-id': 'kd1unb4b3q4t58fwlpcbzcbnm76a8fp',
'client-session-id': '7f4b1045-f52b-49da-bcef-a81394610476',
'connection': 'Keep-Alive',
'content-type': 'application/json',
'host': 'gql.twitch.tv',
'user-agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; vivo V3Max Build/LMY47V) tv.twitch.android.app/14.4.0/1404000',
'x-apollo-operation-id': '54268306ec0b1e37d0cad4079ed4a0a057f3ff1dbc901580b6e09fa0fb8709c1',
'x-apollo-operation-name': 'GoRaidMutation',
'x-app-version': '14.4.0',
'x-device-id': '6c2a973b192849fea684773a218e34f4'
}
datag = {
"operationName": "GoRaidMutation",
"variables": {
"channelId": guser
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "54268306ec0b1e37d0cad4079ed4a0a057f3ff1dbc901580b6e09fa0fb8709c1"
}
}
}
r = requests.post('https://gql.twitch.tv/gql', headers=headersf, json=datag)
print(r.text)
def joinraidd(raidid):
t = open('tokens.txt', 'r').read().splitlines()
t1 = random.choice(t)
headers = {
'Accept': 'application/vnd.twitchtv.v3+json',
'Accept-Language': 'en-us',
'api-consumer-type': 'mobile; Android/1404000',
'authorization': f'OAuth {t1}',
'client-id': 'kd1unb4b3q4t58fwlpcbzcbnm76a8fp',
'client-session-id': '7f4b1045-f52b-49da-bcef-a81394610476',
'connection': 'Keep-Alive',
'content-type': 'application/json',
'host': 'gql.twitch.tv',
'user-agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; vivo V3Max Build/LMY47V) tv.twitch.android.app/14.4.0/1404000',
'x-apollo-operation-id': '412f0fd1876b9fe3426cd726b00b4e4fff9ea3e027e03407de89b6dd0c8674e7',
'x-apollo-operation-name': 'CreateRaidMutation',
'x-app-version': '14.4.0',
'x-device-id': '6c2a973b192849fea684773a218e34f4'
}
data = {
"operationName": "JoinRaidMutation",
"variables": {
"input": raidid
},
"extensions": {
"persistedQuery": {
"version": 1,
"sha256Hash": "7b56131e1c45db978b59d29e966280b1e32f43e5d1e2b2840f96109063826c49"
}
}
}
r = requests.post('https://gql.twitch.tv/gql', json=data, headers=headers)
def viewstart(channel):
lines = open("proxy.txt", "r").read().splitlines()
proxy = random.choice(lines)
proxies = {"http": "http://" + proxy, "https": "http://" + proxy}
token = "MTExMDg3NzM4MjA5MDQ0NDgzMQ.Gqx8Kj.uUXehT_fKfLoOQKRCU-07a5zQ54ozTKIMRMTXk"
headers = {
'Accept': '*/*',
'Accept-Language': 'en-US',
'Authorization': 'undefined',
'Client-ID': 'kimne78kx3ncx6brgo4mv6wki5h1ko',
'Connection': 'keep-alive',
'Content-Type': 'text/plain; charset=UTF-8',
'Device-ID': '6GsDKc6Jagdhp140DfRs7IjMgInpV5Iw',
'Origin': 'https://www.twitch.tv',
'Prefer': 'safe',
'Referer': 'https://www.twitch.tv/',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-site',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.50',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Microsoft Edge";v="100"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
}
data = '{"operationName":"PlaybackAccessToken_Template","query":"query PlaybackAccessToken_Template($login: String!, $isLive: Boolean!, $vodID: ID!, $isVod: Boolean!, $playerType: String!) { streamPlaybackAccessToken(channelName: $login, params: {platform: \\"web\\", playerBackend: \\"mediaplayer\\", playerType: $playerType}) @include(if: $isLive) { value signature __typename } videoPlaybackAccessToken(id: $vodID, params: {platform: \\"web\\", playerBackend: \\"mediaplayer\\", playerType: $playerType}) @include(if: $isVod) { value signature __typename }}","variables":{"isLive":true,"login":"'+channel+'","isVod":false,"vodID":"","playerType":"site"}}'
try:
r = requests.post('https://gql.twitch.tv/gql', headers=headers, data=data, proxies=proxies)
start = r.text.find('"value":"') + 9
end = r.text.find('","signature')
xtoken = r.text[start:end]
token = xtoken.replace('\\', '')
start = r.text.find('signature":"') + 12
end = r.text.find('","__typename')
sig = r.text[start:end]
linktoken = token.replace('{', '%7B').replace('}', '%7D').replace('"', "%22").replace(':', '%3A').replace(',', '%2C')
except:
pass
headers = {
'Accept': 'application/x-mpegURL, application/vnd.apple.mpegurl, application/json, text/plain',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36',
}
params = {
'allow_source': 'true',
'fast_bread': 'true',
'p': '3839592',
'play_session_id': '587e61679bcc5503d760eda271c30dc0',
'player_backend': 'mediaplayer',
'playlist_include_framerate': 'true',
'reassignments_supported': 'true',
'sig': sig,
'supported_codecs': 'avc1',
'token': token,
'cdm': 'wv',
'player_version': '1.10.0',
}
try:
response = requests.get(f'https://usher.ttvnw.net/api/channel/hls/{channel}.m3u8?allow_source=true&fast_bread=true&p=5725800&play_session_id=df4348c5caad4f981aba7aab8df7759a&player_backend=mediaplayer&playlist_include_framerate=true&reassignments_supported=true&sig={sig}&supported_codecs=avc1&token={linktoken}&cdm=wv&player_version=1.10.0', params=params, headers=headers, proxies=proxies)
start = response.text.find('https://video-weaver')
end = response.text.find('.m3u8') + 5
link = response.text[start:end]
except:
pass
headers = {
'Accept': 'application/x-mpegURL, application/vnd.apple.mpegurl, application/json, text/plain',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36',
}
try:
response = requests.get(link, headers=headers, proxies=proxies)
except Exception as e:
pass
@bot.slash_command(description='Sends twitch followers to a channel.')
@commands.cooldown(1, 120, commands.BucketType.user)
async def tfollow(interaction: disnake.ApplicationCommandInteraction, channel):
if interaction.channel_id == botchannel:
amunt = 0
exempt_role_ids = [1110907996994805874]
user_roles = [role.id for role in interaction.user.roles]
if any(role_id in user_roles for role_id in exempt_role_ids):
commands.cooldown(10, 0, commands.BucketType.user)
if interaction.user.get_role(1110907952333860874):
amunt += 99999999999
if interaction.user.get_role(1110907876521812008):
amunt += 1000
elif interaction.user.get_role(1110907753720971285):
amunt += 800
elif interaction.user.get_role(1110925896770138163):
amunt += 500
elif interaction.user.get_role(1110907622489600131):
amunt += 300
elif interaction.user.get_role(1110907676914892930):
amunt += 120
elif interaction.user.get_role(1110907293379338250):
amunt += 75
await interaction.response.defer(with_message=True, ephemeral=True)
embed = discord.Embed(
title='ID check',
description='Checking if twitch channel exists... Please wait.',
color=0x538ab1
)
await interaction.send(embed=embed)
channel_id = get_username(channel)
if channel_id is None:
embed = discord.Embed(
title='Failed',
description='The username you have entered is wrong. Double-check the spelling and try again.',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
else:
def start():
for i in range(amunt):
follower(channel_id)
embed = discord.Embed(
title='Success',
description=f'Sending `{amunt}` followers to `{channel}`',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
threading.Thread(target=start).start()
else:
embed = discord.Embed(
title='Wrong channel.',
description=f'You cannot use commands in this channel. Go to <#{botchannel}>',
color=0x0b76b8
)
await interaction.send(embed=embed)
@bot.slash_command(description='Joins raid with raid id [GOLD OR DIAMOND ONLY]')
@commands.cooldown(1, 120, commands.BucketType.user)
async def joinraid(interaction: disnake.ApplicationCommandInteraction, channel, raidid):
if interaction.channel_id == botchannel:
await interaction.response.defer(with_message=True, ephemeral=True)
amunt = 0
if interaction.user.get_role(1098770200201003071):
amunt = amunt + 15
elif interaction.user.get_role(1098770210867118192):
amunt = amunt + 30
elif interaction.user.get_role(1098770217380888708):
amunt = amunt + 45
elif interaction.user.get_role(1098770217380888708):
amunt = amunt + 50
else:
amunt = 0
if amunt >= 1:
embed = discord.Embed(
title='ID check',
description='Checking if channel exists... Please wait.',
color=0x538ab1
)
await interaction.send(embed=embed)
channel_id = get_username(channel)
if channel_id is None:
embed = discord.Embed(
title='Failed',
description='The username you have entered is wrong. Double-check the spelling and try again.',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
else:
def start():
for i in range(amunt):
joinraidd(raidid)
embed = discord.Embed(
title='Success',
description=f'Sending `{amunt}` joins to `{raidid}`',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
threading.Thread(target=start).start()
else:
embed = discord.Embed(
title='Denied access.',
description='Missing roles. You must have Gold or above in order to use this command!'
)
await interaction.send(embed=embed)
else:
embed = discord.Embed(
title='Wrong channel.',
description=f'You cannot use commands in this channel. Go to <#{botchannel}>',
color=0x0b76b8
)
await interaction.send(embed=embed)
@bot.slash_command(description='Creates 5 raids in a channel [GOLD OR DIAMOND ONLY]')
@commands.cooldown(1, 120, commands.BucketType.user)
async def createraid(interaction: disnake.ApplicationCommandInteraction, channel):
if interaction.channel_id == botchannel:
await interaction.response.defer(with_message=True, ephemeral=True)
amunt = 0
if interaction.user.get_role(1068239463047757904):
amunt = amunt + 15
elif interaction.user.get_role(1068239342507675738):
amunt = amunt + 30
elif interaction.user.get_role(1068239236404359239):
amunt = amunt + 45
elif interaction.user.get_role(1068239080829227069):
amunt = amunt + 50
else:
amunt = 0
if amunt >= 1:
embed = discord.Embed(
title='ID check',
description='Checking if channel exists... Please wait.',
color=0x538ab1
)
await interaction.send(embed=embed)
channel_id = get_username(channel)
if channel_id is None:
embed = discord.Embed(
title='Failed',
description='The username you have entered is wrong. Double-check the spelling and try again.',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
else:
def start():
for i in range(5):
followerraid(channel)
embed = discord.Embed(
title='Success',
description=f'Sending `{amunt}` raids to `{channel}`',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
threading.Thread(target=start).start()
else:
embed = discord.Embed(
title='Denied access.',
description='Missing roles. You must have Gold or above in order to use this command!'
)
await interaction.send(embed=embed)
else:
embed = discord.Embed(
title='Wrong channel.',
description=f'You cannot use commands in this channel, go to <#{botchannel}>',
color=0x0b76b8
)
await interaction.send(embed=embed)
@bot.slash_command(description='Sends viewers to twitch channel [PREMIUM OR PREMIUM + ONLY]')
@commands.cooldown(1, 120, commands.BucketType.user)
async def tview(interaction: disnake.ApplicationCommandInteraction, channel):
await interaction.response.defer(with_message=True, ephemeral=True)
if interaction.channel_id == botchannel:
amunt = 0
if interaction.user.get_role(898555611539726380):
amunt = amunt + 100
else:
amunt = 0
if amunt >= 1:
embed = discord.Embed(
title='ID check',
description='Checking if channel exists... Please wait.',
color=0x538ab1
)
await interaction.send(embed=embed)
channel_id = get_username(channel)
if channel_id is None:
embed = discord.Embed(
title='Failed',
description='The username you have entered is wrong. Double-check the spelling and try again.',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
else:
def start():
viewstart(channel)
embed = discord.Embed(
title='Success',
description=f'Sending `{amunt}` viewers to `{channel}`',
color=0x0b76b8
)
await interaction.edit_original_message(embed=embed)
for i in range(amunt):
threading.Thread(target=start).start()
else:
embed = discord.Embed(
title='Denied access.',
description='Missing roles. You must have view access in order to use this command!'
)
await interaction.send(embed=embed)
else:
embed = discord.Embed(
title='Wrong channel.',
description=f'You cannot use commands in this channel, go to <#{botchannel}>',
color=0x0b76b8
)
await interaction.send(embed=embed)
@tfollow.error
async def tfollow_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"You are on cooldown. Please wait {error.retry_after:.2f} seconds before trying again.")
@createraid.error
async def createraid_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"You are on cooldown. Please wait {error.retry_after:.2f} seconds before trying again.")
@joinraid.error
async def joinraid_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"You are on cooldown. Please wait {error.retry_after:.2f} seconds before trying again.")
@tview.error
async def tview_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"You are on cooldown. Please wait {error.retry_after:.2f} seconds before trying again.")
@bot.slash_command(description='Sends a list of commands that you can use!')
async def help(interaction: disnake.ApplicationCommandInteraction):
await interaction.response.defer(with_message=True)
embed = discord.Embed(
title='Twitch bot',
description=f'__Commands__\n/tfollow (channel)\n/tview (channel)\n/createraid (channel)\n/joinraid (channel)\n\n__Miscellaneous Commands__\n/blockuser (userid)\n/Addspam (userid)'
)
embed.set_footer(text=f'Invoked by {interaction.user.name}', icon_url=interaction.user.avatar.url)
await interaction.send(embed=embed)
bot.run('MTExMDg3NzM4MjA5MDQ0NDgzMQ.Gqx8Kj.uUXehT_fKfLoOQKRCU-07a5zQ54ozTKIMRMTXk')
Fix this entire code
|
033556b4c73ad73ae2913363b1107513
|
{
"intermediate": 0.3654032051563263,
"beginner": 0.4523208737373352,
"expert": 0.1822759211063385
}
|
9,154
|
write me a qiskit code of LiH simulation to get groundstate energy using noise model
|
1eca4bf2dabe52442542542a36efb941
|
{
"intermediate": 0.20161737501621246,
"beginner": 0.0776778906583786,
"expert": 0.7207047343254089
}
|
9,155
|
why I get this python error? AttributeError: 'str' object has no attribute '_fname_str'
|
0c69db8ecf9073b86278e790feb9ed25
|
{
"intermediate": 0.6058030128479004,
"beginner": 0.17541050910949707,
"expert": 0.21878649294376373
}
|
9,156
|
strcpy C example with length
|
c80dfaf6c2715430e2ac02020ff5ad6d
|
{
"intermediate": 0.20736141502857208,
"beginner": 0.4916563332080841,
"expert": 0.3009822964668274
}
|
9,157
|
void *VC_FaceThreadFnc(void* param)
{
ImageThread_S *pFaceThread;
PF_Rect_S viRect;
Uapi_ExpWin_t expWin;
HNY_AiFaceRectInfo_S *pAiFaceRectInfo = NULL;
char threadName[64];
char *pBuf = NULL;
int i, id, faceRect, width, height, ret, cnt = 0;
PF_Rect_S stRect = {0};
sprintf(threadName, "FaceFnc");
prctl(PR_SET_NAME, (unsigned long)threadName, 0, 0, 0);
pBuf = (char *)malloc(sizeof(HNY_FrameHeader_S) + sizeof(HNY_AiFaceRectInfo_S));
if(pBuf == NULL)
{
DEBUG_ERROR(MODULE_CODEC, "Call malloc func err!");
return NULL;
}
memset(&viRect, 0x0, sizeof(PF_Rect_S));
VC_GetViRect(0, &viRect);
pFaceThread = (ImageThread_S *)param;
while(pFaceThread->threadRun)
{
memset(pBuf, 0x00, sizeof(HNY_FrameHeader_S) + sizeof(HNY_AiFaceRectInfo_S));
ret = SHB_ShareBufGetOneFrame(g_imageManager.metaDataBuf, sizeof(HNY_FrameHeader_S) + sizeof(HNY_AiFaceRectInfo_S), pBuf);
if(ret <= 0)
{
usleep(50*1000);
cnt ++;
if(cnt < 3)
continue;
}
if(cnt >= 3)
{
cnt = 0;
expWin.h_offs = 0;
expWin.v_offs = 0;
expWin.h_size = 1920;
expWin.v_size = 1080;
}
else
{
pAiFaceRectInfo = (HNY_AiFaceRectInfo_S *)(pBuf + sizeof(HNY_FrameHeader_S));
if(pAiFaceRectInfo->faceCnt <= 0)
{
usleep(50*1000);
continue;
}
//查找最大人脸
id = -1;
faceRect = 0;
for(i=0; i<pAiFaceRectInfo->faceCnt; i++)
{
width = pAiFaceRectInfo->faceRect[i].faceRect.right - pAiFaceRectInfo->faceRect[i].faceRect.left;
height = pAiFaceRectInfo->faceRect[i].faceRect.bottom - pAiFaceRectInfo->faceRect[i].faceRect.top;
if(faceRect < width*height)
{
id = i;
faceRect = width*height;
}
}
expWin.h_offs = pAiFaceRectInfo->faceRect[id].faceRect.left * viRect.width / 10000;
expWin.v_offs = pAiFaceRectInfo->faceRect[id].faceRect.top * viRect.height / 10000;
expWin.h_size = (pAiFaceRectInfo->faceRect[id].faceRect.right - pAiFaceRectInfo->faceRect[id].faceRect.left) * viRect.width / 10000;
expWin.v_size = (pAiFaceRectInfo->faceRect[id].faceRect.bottom - pAiFaceRectInfo->faceRect[id].faceRect.top) * viRect.height / 10000;
stRect.x = expWin.h_offs;
stRect.y = expWin.v_offs;
stRect.width = expWin.h_size;
stRect.height = expWin.v_size;
ret = VC_SetFaceExp(stRect);
usleep(50*1000);针对这份代码提升人脸曝光的稳定性
|
89627bc975ce5cca3b7aaf5dc552ac25
|
{
"intermediate": 0.33367225527763367,
"beginner": 0.5233447551727295,
"expert": 0.14298295974731445
}
|
9,158
|
how to check if adding letter is lower case or not and then add it
|
c684c50e407e2e196dab50bd46065126
|
{
"intermediate": 0.35090020298957825,
"beginner": 0.2007518857717514,
"expert": 0.44834795594215393
}
|
9,159
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
frame = frame.iloc[:60,:6]
frame.columns = ['Time','Open','High','Low','Close','Volume']
frame = frame.set_index('Time')
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But I gettign ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 48, in <module>
df = getminutedata('BTCUSDT', '1m', '44640')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 40, in getminutedata
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'get_historical_klines'. Did you mean: 'get_historical_trades'?Please give me solution
|
4c3d842bc01b9fb584693b4424a8b48c
|
{
"intermediate": 0.46476611495018005,
"beginner": 0.3227807283401489,
"expert": 0.21245312690734863
}
|
9,160
|
how to plot a 3d vector in python
|
49db0f60679fde37cf0929f0ca8e413e
|
{
"intermediate": 0.3488674759864807,
"beginner": 0.15963834524154663,
"expert": 0.49149414896965027
}
|
9,161
|
can "Logger.setLogLevel" set level for a specific tag
|
098051f6c3cea630d00485af7ecb864c
|
{
"intermediate": 0.4638359248638153,
"beginner": 0.1900651454925537,
"expert": 0.34609895944595337
}
|
9,162
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Engine.cpp:
#include "Engine.h"
#include "Terrain.h"
#include <iostream>
Engine::Engine()
{
Initialize();
}
Engine::~Engine()
{
Shutdown();
}
void Engine::Run()
{
MainLoop();
}
void Engine::Initialize()
{
// Initialize window, renderer, and scene
window.Initialize();
renderer.Initialize(window.GetWindow());
scene.Initialize();
VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout();
//VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object
VkDescriptorSetLayout samplerDescriptorSetLayout = renderer.CreateSamplerDescriptorSetLayout(); // Use this new method to create a separate descriptor layout.
VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1);
// Create a simple square tile GameObject
GameObject* squareTile = new GameObject();
squareTile->Initialize();
// Define the square’s vertices and indices
std::vector<Vertex> vertices = {
{ { 0.0f, 0.0f, 0.0f }, { 1.0f, 0.0f, 0.0f } }, // Bottom left
{ { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f } }, // Bottom right
{ { 1.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }, // Top right
{ { 0.0f, 1.0f, 0.0f }, { 1.0f, 1.0f, 0.0f } }, // Top left
};
std::vector<uint32_t> indices = {
0, 1, 2, // First triangle
0, 2, 3 // Second triangle
};
// Initialize mesh and material for the square tile
squareTile->GetMesh()->Initialize(vertices, indices, *renderer.GetDevice(), *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
squareTile->GetMaterial()->Initialize("C:/shaders/vert_depth2.spv", "C:/shaders/frag_depth2.spv", "C:/textures/texture.jpg", *renderer.GetDevice(), descriptorSetLayout, descriptorSetLayout, descriptorPool, *renderer.GetPhysicalDevice(), *renderer.GetCommandPool(), *renderer.GetGraphicsQueue());
// Add the square tile GameObject to the scene
scene.AddGameObject(squareTile);
/*Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue());
terrain.GenerateTerrain(descriptorSetLayout, samplerDescriptorSetLayout, descriptorPool);*/
//scene.AddGameObject(terrain.GetTerrainObject());
float deltaTime = window.GetDeltaTime();
}
void Engine::MainLoop()
{
while (!window.ShouldClose())
{
window.PollEvents();
float deltaTime = window.GetDeltaTime();
Update(deltaTime);
Render();
auto sleep_duration = std::chrono::milliseconds(1000 / MaxFPS);
std::this_thread::sleep_for(sleep_duration);
}
}
void Engine::Update(float deltaTime)
{
scene.Update(deltaTime);
}
void Engine::Render()
{
renderer.BeginFrame();
scene.Render(renderer);
renderer.EndFrame();
}
void Engine::Shutdown()
{
// Clean up resources in reverse order
scene.Shutdown();
renderer.Shutdown();
window.Shutdown();
}
Material.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Texture.h"
#include "Shader.h"
#include <stdexcept>
#include <memory> // Don’t forget to include <memory>
class Material
{
public:
Material();
~Material();
void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void Cleanup();
void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device);
void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize);
VkDescriptorSet GetDescriptorSet() const;
VkPipelineLayout GetPipelineLayout() const;
std::shared_ptr <Shader> GetvertexShader();
std::shared_ptr <Shader> GetfragmentShader();
private:
VkDevice device;
std::shared_ptr <Shader> vertexShader;
std::shared_ptr <Shader> fragmentShader;
std::shared_ptr<Texture> texture;
void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool);
void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout);
VkDescriptorSet descriptorSet;
VkPipelineLayout pipelineLayout;
};
Material.cpp:
#include "Material.h"
Material::Material()
: device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE)
{
}
Material::~Material()
{
Cleanup();
}
void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorSetLayout samplerDescriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
this->device = device;
// Load shaders and texture
LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue);
LoadShaders(vertShaderPath, fragShaderPath, device);
// Create descriptor set and pipeline layout
CreateDescriptorSet(samplerDescriptorSetLayout, descriptorPool);
CreatePipelineLayout(descriptorSetLayout);
}
void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool)
{
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = descriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &descriptorSetLayout;
if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate descriptor sets!");
}
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
// Combined image sampler descriptor write
VkWriteDescriptorSet imageSamplerDescriptorWrite{};
imageSamplerDescriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
imageSamplerDescriptorWrite.dstSet = descriptorSet;
imageSamplerDescriptorWrite.dstBinding = 1;
imageSamplerDescriptorWrite.dstArrayElement = 0;
imageSamplerDescriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
imageSamplerDescriptorWrite.descriptorCount = 1;
imageSamplerDescriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &imageSamplerDescriptorWrite, 0, nullptr);
}
void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout)
{
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 1;
pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create pipeline layout!");
}
}
void Material::Cleanup()
{
// Clean up resources, if necessary
// (depending on how Shader and Texture resources are managed)
}
VkDescriptorSet Material::GetDescriptorSet() const
{
return descriptorSet;
}
VkPipelineLayout Material::GetPipelineLayout() const
{
return pipelineLayout;
}
std::shared_ptr <Shader> Material::GetvertexShader()
{
return vertexShader;
}
std::shared_ptr <Shader> Material::GetfragmentShader()
{
return fragmentShader;
}
void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
{
texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr
texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue);
}
void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device)
{
vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup);
vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT);
fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT);
}
void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize)
{
VkDescriptorBufferInfo bufferInfo{};
bufferInfo.buffer = newBuffer;
bufferInfo.offset = 0;
bufferInfo.range = devicesize;
VkDescriptorImageInfo imageInfo{};
imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
imageInfo.imageView = texture->GetImageView();
imageInfo.sampler = texture->GetSampler();
VkWriteDescriptorSet descriptorWrite{};
descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
descriptorWrite.dstSet = descriptorSet;
descriptorWrite.dstBinding = 0;
descriptorWrite.dstArrayElement = 0;
descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
descriptorWrite.descriptorCount = 1;
descriptorWrite.pBufferInfo = &bufferInfo;
descriptorWrite.pImageInfo = &imageInfo;
vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
}
Texture.h:
#pragma once
#include <vulkan/vulkan.h>
#include "stb_image.h" // Include the stb_image header
#include "BufferUtils.h"
#include <string>
class Texture
{
public:
Texture();
~Texture();
void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue);
VkImageView GetImageView() const;
VkSampler GetSampler() const;
static void Cleanup(Texture* texture);
private:
VkDevice device;
VkImage image;
VkDeviceMemory imageMemory;
VkImageView imageView;
VkSampler sampler;
VkPhysicalDevice physicalDevice;
VkCommandPool commandPool;
VkQueue graphicsQueue;
bool initialized = false;
void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties);
void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels, VkSampleCountFlagBits numSamples);
void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels);
void CreateSampler(uint32_t mipLevels);
void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height);
// Additional helper functions for texture loading…
};
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
I am getting this error:
VUID-VkWriteDescriptorSet-descriptorType-00319(ERROR / SPEC): msgNum: -405619238 - Validation Error: [ VUID-VkWriteDescriptorSet-descriptorType-00319 ] Object 0: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0xe7d2bdda | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0xb097c90000000027[] with error: Attempting write update to VkDescriptorSet 0xb097c90000000027[] allocated with VkDescriptorSetLayout 0x9fde6b0000000014[] binding #0 with type VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER but update type is VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER. The Vulkan spec states: descriptorType must match the type of dstBinding within dstSet (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-VkWriteDescriptorSet-descriptorType-00319)
Objects: 1
[0] 0xb097c90000000027, type: 23, name: NULL
Here is some additional code from the Renderer class for context:
VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() {
VkDescriptorSetLayoutBinding uboLayoutBinding{};
uboLayoutBinding.binding = 0;
uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
uboLayoutBinding.descriptorCount = 1;
uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
uboLayoutBinding.pImmutableSamplers = nullptr;
// Add sampler layout binding
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 1;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
layoutInfo.pBindings = bindings.data();
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() {
VkDescriptorSetLayoutBinding samplerLayoutBinding{};
samplerLayoutBinding.binding = 0;
samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerLayoutBinding.descriptorCount = 1;
samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
samplerLayoutBinding.pImmutableSamplers = nullptr;
VkDescriptorSetLayoutCreateInfo layoutInfo{};
layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
layoutInfo.bindingCount = 1;
layoutInfo.pBindings = &samplerLayoutBinding;
VkDescriptorSetLayout descriptorSetLayout;
if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sampler descriptor set layout!");
}
return descriptorSetLayout;
}
VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) {
VkDescriptorPoolSize poolSize{};
poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
poolSize.descriptorCount = maxSets;
// Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER
VkDescriptorPoolSize samplerPoolSize{};
samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
samplerPoolSize.descriptorCount = maxSets;
std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize };
VkDescriptorPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
poolInfo.pPoolSizes = poolSizes.data();
poolInfo.maxSets = maxSets;
VkDescriptorPool descriptorPool;
if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
throw std::runtime_error("Failed to create descriptor pool!");
}
return descriptorPool;
}
How can I alter the code to fix this issue?
|
ab0102b7ec370c1f61b0a94478d73d90
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,163
|
how to justify text in css?
|
9fb2bbf51aba8ff155aa4d79c4330495
|
{
"intermediate": 0.4232422113418579,
"beginner": 0.3513346016407013,
"expert": 0.225423201918602
}
|
9,164
|
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { defaultLoadingState } from '@engage/ngrx/config/ngrx-loading-states.config';
import type { ITask } from '../../interfaces';
import { taskEntityAdapter } from '../adapter/tasks-entity.adapter';
import type { TasksEntityState } from '../state/tasks-entity.state';
import type { ITasksViewState } from '../state/tasks-view-state.interface';
import { tasksViewNameSpace } from '../state/tasks-view.state';
export const initialTaskEntityState: TasksEntityState = taskEntityAdapter.getInitialState({
...defaultLoadingState,
entities: {},
ids: [],
});
const tasksFeatureSelector = createFeatureSelector<ITasksViewState>(tasksViewNameSpace);
export const taskEntitySelector = createSelector(tasksFeatureSelector, (state) => state.tasks);
const getEntities = createSelector(taskEntitySelector, (state: TasksEntityState): ITask[] => {
return Object.values(state.entities);
});
const getLoadedStatus = createSelector(taskEntitySelector, (state: TasksEntityState): boolean => {
return state.loaded;
});
const getLoadingStatus = createSelector(taskEntitySelector, (state: TasksEntityState): boolean => {
return state.loading;
});
const getErrors = createSelector(taskEntitySelector, (state: TasksEntityState): boolean => {
return state.error;
});
export const TasksEntitySelectors = {
getLoadingStatus,
getLoadedStatus,
getErrors,
getEntities,
};
use jest to write unit tests
|
07292a55a28e4f4e65b636db641089cd
|
{
"intermediate": 0.4255211353302002,
"beginner": 0.3035237789154053,
"expert": 0.27095502614974976
}
|
9,165
|
thank you a lot
|
12d627efeba5ad7379c40d7643f3920e
|
{
"intermediate": 0.33974817395210266,
"beginner": 0.263821005821228,
"expert": 0.3964308202266693
}
|
9,166
|
No, I need code for using in natural language processing, without any second libraries
for example, additional
struct word
{
bool alive;//applied to alive objects=1, else=0
char* word;//char sequence
char* wordbase;//additional
int code;//code of this word for zipping
char** suffixes;//additional code
char** preffixes;//additional
};
Without functions!!!! Only new variables and data types!!!
|
e68291a0dc4a7b038e86764a03b0a2a8
|
{
"intermediate": 0.5056236982345581,
"beginner": 0.298227459192276,
"expert": 0.1961488425731659
}
|
9,167
|
/****************************************
* Conditional_Resources_From_List Test *
****************************************/
import { core, data, sound, util, visual, hardware } from './lib/psychojs-2023.1.1.js';
const { PsychoJS } = core;
const { TrialHandler, MultiStairHandler } = data;
const { Scheduler } = util;
//some handy aliases as in the psychopy scripts;
const { abs, sin, cos, PI: pi, sqrt } = Math;
const { round } = util;
// store info about the experiment session:
let expName = 'conditional_resources_from_list'; // from the Builder filename that created this script
let expInfo = {
'participant': `${util.pad(Number.parseFloat(util.randint(0, 999999)).toFixed(0), 6)}`,
'group': ["a", "b"],
};
// Start code blocks for 'Before Experiment'
// Run 'Before Experiment' code from init_resources_code
var resource_list = [];
// init psychoJS:
const psychoJS = new PsychoJS({
debug: true
});
// open window:
psychoJS.openWindow({
fullscr: false,
color: new util.Color([0,0,0]),
units: 'height',
waitBlanking: true
});
// schedule the experiment:
psychoJS.schedule(psychoJS.gui.DlgFromDict({
dictionary: expInfo,
title: expName
}));
const flowScheduler = new Scheduler(psychoJS);
const dialogCancelScheduler = new Scheduler(psychoJS);
psychoJS.scheduleCondition(function() { return (psychoJS.gui.dialogComponent.button === 'OK'); }, flowScheduler, dialogCancelScheduler);
// flowScheduler gets run if the participants presses OK
flowScheduler.add(updateInfo); // add timeStamp
flowScheduler.add(experimentInit);
const init_resources_loopLoopScheduler = new Scheduler(psychoJS);
flowScheduler.add(init_resources_loopLoopBegin(init_resources_loopLoopScheduler));
flowScheduler.add(init_resources_loopLoopScheduler);
flowScheduler.add(init_resources_loopLoopEnd);
flowScheduler.add(resource_checker_pbRoutineBegin());
flowScheduler.add(resource_checker_pbRoutineEachFrame());
flowScheduler.add(resource_checker_pbRoutineEnd());
flowScheduler.add(resource_download_completeRoutineBegin());
flowScheduler.add(resource_download_completeRoutineEachFrame());
flowScheduler.add(resource_download_completeRoutineEnd());
const show_images_loopLoopScheduler = new Scheduler(psychoJS);
flowScheduler.add(show_images_loopLoopBegin(show_images_loopLoopScheduler));
flowScheduler.add(show_images_loopLoopScheduler);
flowScheduler.add(show_images_loopLoopEnd);
flowScheduler.add(never_ending_routineRoutineBegin());
flowScheduler.add(never_ending_routineRoutineEachFrame());
flowScheduler.add(never_ending_routineRoutineEnd());
flowScheduler.add(quitPsychoJS, '', true);
// quit if user presses Cancel in dialog box:
dialogCancelScheduler.add(quitPsychoJS, '', false);
psychoJS.start({
expName: expName,
expInfo: expInfo,
resources: [
// resources:
{'name': 'default.png', 'path': 'https://pavlovia.org/assets/default/default.png'},
{'name': 'group_a_stim.csv', 'path': 'group_a_stim.csv'},
{'name': 'group_b_stim.csv', 'path': 'group_b_stim.csv'},
]
});
psychoJS.experimentLogger.setLevel(core.Logger.ServerLevel.EXP);
var currentLoop;
var frameDur;
async function updateInfo() {
currentLoop = psychoJS.experiment; // right now there are no loops
expInfo['date'] = util.MonotonicClock.getDateStr(); // add a simple timestamp
expInfo['expName'] = expName;
expInfo['psychopyVersion'] = '2023.1.1';
expInfo['OS'] = window.navigator.platform;
// store frame rate of monitor if we can measure it successfully
expInfo['frameRate'] = psychoJS.window.getActualFrameRate();
if (typeof expInfo['frameRate'] !== 'undefined')
frameDur = 1.0 / Math.round(expInfo['frameRate']);
else
frameDur = 1.0 / 60.0; // couldn't get a reliable measure so guess
// add info from the URL:
util.addInfoFromUrl(expInfo);
psychoJS.experiment.dataFileName = (("." + "/") + `data/${expInfo["participant"]}_${expName}_${expInfo["date"]}`);
return Scheduler.Event.NEXT;
}
var init_resourcesClock;
var stim_file;
var resource_checker_pbClock;
var resource_checker_text;
var resource_pb_bg;
var resource_pb_fg;
var resource_download_completeClock;
var resource_download_complete_text;
var resource_download_complete_keys;
var show_imagesClock;
var show_image;
var never_ending_routineClock;
var never_ending_text;
var globalClock;
var routineTimer;
async function experimentInit() {
// Initialize components for Routine "init_resources"
init_resourcesClock = new util.Clock();
if ((expInfo["group"] === "a")) {
stim_file = "group_a_stim.csv";
} else {
if ((expInfo["group"] === "b")) {
stim_file = "group_b_stim.csv";
}
}
console.log("Stim file: " + stim_file)
// Initialize components for Routine "resource_checker_pb"
resource_checker_pbClock = new util.Clock();
resource_checker_text = new visual.TextStim({
win: psychoJS.window,
name: 'resource_checker_text',
text: 'Please wait; resources are still downloading.',
font: 'Open Sans',
units: undefined,
pos: [0, 0], height: 0.05, wrapWidth: undefined, ori: 0.0,
languageStyle: 'LTR',
color: new util.Color('white'), opacity: undefined,
depth: 0.0
});
resource_pb_bg = new visual.Rect ({
win: psychoJS.window, name: 'resource_pb_bg',
width: [0.5, 0.02][0], height: [0.5, 0.02][1],
ori: 0.0, pos: [0, (- 0.3)],
anchor: 'center',
lineWidth: 1.0,
colorSpace: 'rgb',
lineColor: new util.Color('white'),
fillColor: new util.Color('white'),
opacity: undefined, depth: -2, interpolate: true,
});
resource_pb_fg = new visual.Rect ({
win: psychoJS.window, name: 'resource_pb_fg',
width: [1.0, 1.0][0], height: [1.0, 1.0][1],
ori: 0.0, pos: [(- 0.25), (- 0.3)],
anchor: 'center-left',
lineWidth: 1.0,
colorSpace: 'rgb',
lineColor: new util.Color('white'),
fillColor: new util.Color('blue'),
opacity: undefined, depth: -3, interpolate: true,
});
// Initialize components for Routine "resource_download_complete"
resource_download_completeClock = new util.Clock();
resource_download_complete_text = new visual.TextStim({
win: psychoJS.window,
name: 'resource_download_complete_text',
text: '',
font: 'Open Sans',
units: undefined,
pos: [0, 0], height: 0.05, wrapWidth: undefined, ori: 0.0,
languageStyle: 'LTR',
color: new util.Color('white'), opacity: undefined,
depth: -1.0
});
resource_download_complete_keys = new core.Keyboard({psychoJS: psychoJS, clock: new util.Clock(), waitForStart: true});
// Initialize components for Routine "show_images"
show_imagesClock = new util.Clock();
show_image = new visual.ImageStim({
win : psychoJS.window,
name : 'show_image', units : undefined,
image : 'default.png', mask : undefined,
anchor : 'center',
ori : 0.0, pos : [0, 0], size : [0.5, 0.5],
color : new util.Color([1,1,1]), opacity : undefined,
flipHoriz : false, flipVert : false,
texRes : 128.0, interpolate : true, depth : 0.0
});
// Initialize components for Routine "never_ending_routine"
never_ending_routineClock = new util.Clock();
never_ending_text = new visual.TextStim({
win: psychoJS.window,
name: 'never_ending_text',
text: "This routine never ends, so that Pavlovia doesn't consume a credit.\n\nPress escape to exit.",
font: 'Open Sans',
units: undefined,
pos: [0, 0], height: 0.05, wrapWidth: undefined, ori: 0.0,
languageStyle: 'LTR',
color: new util.Color('white'), opacity: undefined,
depth: 0.0
});
// Create some handy timers
globalClock = new util.Clock(); // to track the time since experiment started
routineTimer = new util.CountdownTimer(); // to track time remaining of each (non-slip) routine
return Scheduler.Event.NEXT;
}
Can you update this script so instead selecting a or b, we can choose 1- 20 and load "observer_1.csv" to "observer_20.csv" instead of the section below:
async function experimentInit() {
// Initialize components for Routine "init_resources"
init_resourcesClock = new util.Clock();
if ((expInfo["group"] === "a")) {
stim_file = "group_a_stim.csv";
} else {
if ((expInfo["group"] === "b")) {
stim_file = "group_b_stim.csv";
}
}
|
c0bcbea70619120da949a2babe06ba14
|
{
"intermediate": 0.3939041793346405,
"beginner": 0.43475592136383057,
"expert": 0.17133992910385132
}
|
9,168
|
const Title = styled.h3``;
const List = styled.ul``;
const ListItem = styled.li``;
const Right = styled.div`
flex: 1;
`;
const Footer = () => {
return (
<Container>
<Left>
<Logo>FABICO</Logo>
<Description>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam quo
blanditiis ipsa veritatis nostrum perspiciatis consequatur nobis id
officia unde. Voluptatibus expedita, dolor error aliquam laborum
molestiae velit recusandae magni?
</Description>
</Left>
<Center>
<Title>Links</Title>
<List>
<ListItem>Main</ListItem>
<ListItem>Cart</ListItem>
<ListItem>My Account</ListItem>
<ListItem>Order Tracking</ListItem>
<ListItem>Wishlist</ListItem>
<ListItem>Terms</ListItem>
</List>
</Center>
<Right></Right>
</Container>
);
};
export default Footer;
why this code don't show ul list?
|
5233fc283334b247f856d7a9a83e57e7
|
{
"intermediate": 0.39261576533317566,
"beginner": 0.39218243956565857,
"expert": 0.21520182490348816
}
|
9,169
|
@Prop() sets: Set[];
get isNotValid() {
const { status } = this.set
return status === 'NOT VALID'
}
как исправить get isNotValid(), чтобы получать set
|
0d10d9a44bf39a129b55212f83611dc3
|
{
"intermediate": 0.40197640657424927,
"beginner": 0.41651421785354614,
"expert": 0.1815093755722046
}
|
9,170
|
In unreal engine 4, when the player is looking through a tube, the viewing area inside the tube is very narrow due to the tube being long. I want to look through a tube and clip the pixels that are visible only inside the tube. is it possible to write a custom HLSL shader code using a Custom expression node in the tube material to clip only the inside of the the tube? my material blend mode is masked.
|
cc70313eae7dc178d7fbf1305707d550
|
{
"intermediate": 0.56504887342453,
"beginner": 0.16759169101715088,
"expert": 0.2673594653606415
}
|
9,171
|
How do I automatically change the ownership of mounted volumes to the www-data user inside a Docker container in my docker-compose.yml?
|
50577628c9cee8c93635cbd520243663
|
{
"intermediate": 0.602087140083313,
"beginner": 0.22644208371639252,
"expert": 0.1714707762002945
}
|
9,172
|
/**
*
* @param {Array} questionnaireItems
* @returns {void}
*/
export default function (questionnaireItems) {
questionnaireItems.forEach((questionnaireItem) => {
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of questionnaireItem.quotations) {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
quote.price = price;
if (price > 0) {
product *= price;
count++;
min = Math.min(min, price);
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
console.log("Count is: ", count);
const stdev = Math.sqrt(
questionnaireItem.quotations.reduce((sum, quotation) => {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
if (price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
const variation = stdev / geomean;
if (geomean > 0) {
questionnaireItem.geomean = geomean.toFixed(2);
questionnaireItem.stdev = stdev.toFixed(2);
questionnaireItem.variation = variation.toFixed(2);
questionnaireItem.min = min.toFixed(2);
questionnaireItem.max = max.toFixed(2);
questionnaireItem.product = product.toFixed(2);
questionnaireItem.count = count.toFixed(2);
}
});
}
export function recalculateRow(rowData) {
// console.log("Row date is: ", rowData);
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of Object.values(rowData.quotes)) {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) {
product *= price;
count++;
min = Math.min(min, parseFloat(price));
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
Object.values(rowData.quotes).reduce((sum, quotation) => {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
console.log("Recalculated data: ", geomean, stdev, rowData, count);
const variation = stdev / geomean;
if (geomean > 0) {
rowData.geomean = isNaN(geomean) ? "0" : geomean.toFixed(2);
rowData.deviation = isNaN(stdev) ? "0" : stdev.toFixed(2);
rowData.variation = isNaN(variation) ? "0" : variation.toFixed(2);
rowData.minQ = isNaN(min) ? "0" : min.toFixed(2);
rowData.maxQ = isNaN(max) ? "0" : max.toFixed(2);
rowData.product = isNaN(product) ? "0" : product.toFixed(2);
rowData.count = isNaN(count) ? "0" : count.toFixed(2);
rowData.ratio = isNaN(max / min) ? "0" : (max / min).toFixed(2);
}
// console.log("Recalculated data: ", geomean, stdev, variation, rowData);
}
const isOnlyQuote = (str) => {
return /^((?!_)[A-Za-z0-9])+$/.test(str);
};
on the above function what is count and is the implementation correct
|
76b6122642c1561d75c3375b2ec1ed80
|
{
"intermediate": 0.26067817211151123,
"beginner": 0.5671185255050659,
"expert": 0.17220324277877808
}
|
9,173
|
What will be the result of the given function:
def foo(positional, only, /, either, pos, or_='default',
*, keyword, just, **keywords):
print(positional, only, either, pos, or_, keyword,
just, keywords)
and given input arguments:
foo('a', 'b', 1, 2, 'or_', keyword='keyword', just='just',
unknown_keyword='unknown_keyword')
Success call.
TypeError, because a keyword argument is used where a positional is required.
TypeError, because positional arguments are used where a keyword argument is required.
TypeError, because required keyword arguments are missing.
SyntaxError, because a keyword argument was used before a positional.
|
419cb809b5cafef60dbeced69c8a456a
|
{
"intermediate": 0.1887194663286209,
"beginner": 0.7151484489440918,
"expert": 0.09613209217786789
}
|
9,174
|
I need a C++ code that using word sequence from begin to "dot symbol" or from first "dot" to second "dot", for associate this sequence with process such as "painting". Firstly, user typing example o sequence and meaning (process). Secondly, user typing process and program returns randomly sequence with same meaning; or user typing word sequence that already stored and program returns process.
|
a400591df8b56b6f3e15a1f5e47adc74
|
{
"intermediate": 0.517859160900116,
"beginner": 0.15948036313056946,
"expert": 0.3226604461669922
}
|
9,175
|
Explain in detail how the https://moonarch.app/ resource, when entering the contract address in the search bar, displays dubious functions in the contract code in the Rugcheck by Moonarch.app block.
|
a10e1fdb2ef3efcb518791a8e05aeb3b
|
{
"intermediate": 0.5026808977127075,
"beginner": 0.32120832800865173,
"expert": 0.17611080408096313
}
|
9,176
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
I am getting this error:
UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer(ERROR / SPEC): msgNum: 653100552 - Validation Error: [ UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer ] Object 0: handle = 0xb9181f0000000029, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; Object 2: handle = 0x221c1afa4f0, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x26ed8608 | You are adding vkCmdEndRenderPass to VkCommandBuffer 0x221c1afa4f0[] that is invalid because bound VkBuffer 0xb9181f0000000029[] was destroyed.
Objects: 3
[0] 0xb9181f0000000029, type: 9, name: NULL
[1] 0xb097c90000000027, type: 23, name: NULL
[2] 0x221c1afa4f0, type: 6, name: NULL
Based on some debugging, I believe the error is triggered near the end of the GameObject::Render method. How can I alter the code to fix this issue?
|
da6b6bdda20c0ae7ac1c12d8d77de86f
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,177
|
/**
*
* @param {Array} questionnaireItems
* @returns {void}
*/
export default function (questionnaireItems) {
questionnaireItems.forEach((questionnaireItem) => {
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of questionnaireItem.quotations) {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
quote.price = price;
if (price > 0) {
product *= price;
count++;
min = Math.min(min, price);
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
questionnaireItem.quotations.reduce((sum, quotation) => {
for (const quote of quotation.cleanedQuotes) {
const price = parseFloat(quote.price);
if (price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
const variation = stdev / geomean;
if (geomean > 0) {
questionnaireItem.geomean = geomean.toFixed(2);
questionnaireItem.stdev = stdev.toFixed(2);
questionnaireItem.variation = variation.toFixed(2);
questionnaireItem.min = min.toFixed(2);
questionnaireItem.max = max.toFixed(2);
questionnaireItem.product = product.toFixed(2);
questionnaireItem.count = count.toFixed(2);
}
});
}
export function recalculateRow(rowData) {
// console.log("Row date is: ", rowData);
let product = 1;
let count = 0;
let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY;
for (const quotation of Object.values(rowData.quotes)) {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) {
product *= price;
count++;
min = Math.min(min, parseFloat(price));
max = Math.max(max, price);
}
}
}
const geomean = count > 0 ? Math.pow(product, 1 / count) : 0;
const stdev = Math.sqrt(
Object.values(rowData.quotes).reduce((sum, quotation) => {
for (const key of Object.keys(quotation)) {
const price = parseFloat(quotation[key]);
if (isOnlyQuote(key) && price > 0) sum += Math.pow(price - geomean, 2);
}
return sum;
}, 0) / count
);
const variation = stdev / geomean;
if (geomean > 0) {
rowData.geomean = isNaN(geomean) ? "0" : geomean.toFixed(2);
rowData.deviation = isNaN(stdev) ? "0" : stdev.toFixed(2);
rowData.variation = isNaN(variation) ? "0" : variation.toFixed(2);
rowData.minQ = isNaN(min) ? "0" : min.toFixed(2);
rowData.maxQ = isNaN(max) ? "0" : max.toFixed(2);
rowData.product = isNaN(product) ? "0" : product.toFixed(2);
rowData.count = isNaN(count) ? "0" : count.toFixed(2);
rowData.ratio = isNaN(max / min) ? "0" : (max / min).toFixed(2);
}
// console.log("Recalculated data: ", geomean, stdev, variation, rowData);
}
const isOnlyQuote = (str) => {
return /^((?!_)[A-Za-z0-9])+$/.test(str);
};
the above function caclulated statistical values for quotaions of questionnaireItems where quotations are prices. So for every price count is keeping count of the prices greater than zero but standard deviation is not being calculated correct when updating prices
|
06e36cb107c4a545cb978e07ed398cba
|
{
"intermediate": 0.2922351658344269,
"beginner": 0.46177324652671814,
"expert": 0.24599166214466095
}
|
9,178
|
hi
|
4b734aed5a27606da28d2fea47f3d96a
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,179
|
Check usage of address pair
Check usage of address devFeeReceiver
Check usage of address marketingFeeReceiver
Check usage of address autoLiquidityReceiver
Unusual balanceOf, beware of hidden mint
Unusual param holder in balanceOf
Unusual param numTokens in approve
Unusual param delegate in approve
Check usage of hidden address TrustSwap
setSwapTokensAtAmount has onlyOwner modifier
setSwapEnabled has onlyOwner modifier
enableTrading has onlyOwner modifier
changeTreasuryWallet has onlyOwner modifier
changeStakingWallet has onlyOwner modifier
changeMarketingWallet has onlyOwner modifier
updateFees has onlyOwner modifier
claimStuckTokens has onlyOwner modifier
Check usage of address treasuryWallet
Check usage of address stakingWallet
Check usage of address marketingWallet
LakerAI._mint function might mint supply, check usage
Owner has 99% of the PancakeSwap v2 liquidity
Suspicious call to encodePacked in _transfer
Check usage of hidden address receiveAddress
Unusual param uint256 in _transfer
Unusual param address in _transfer
Unusual mapping name lastClaimTimes, check usage
Unusual mapping name excludedFromDividends, check usage
Unusual mapping name tokenHoldersMap, check usage
Unusual mapping name withdrawnDividends, check usage
Unusual mapping name magnifiedDividendCorrections, check usage
setDeadWallet has onlyOwner modifier
setSwapTokensAtAmount has onlyOwner modifier
swapManual has onlyOwner modifier
updateGasForProcessing has onlyOwner modifier
setAutomatedMarketMakerPair has onlyOwner modifier
setMarketingWallet has onlyOwner modifier
setKing has onlyOwner modifier
setAirdropNumbs has onlyOwner modifier
updateUniswapV2Router has onlyOwner modifier
Check usage of address _marketingWalletAddress
Check usage of address uniswapPair
processAccount has onlyOwner modifier
setBalance has onlyOwner modifier
updateMinimumTokenBalanceForDividends has onlyOwner modifier
updateClaimWait has onlyOwner modifier
distributeCAKEDividends has onlyOwner modifier
Check usage of address rewardToken
Owner has 100% of non-burnt supply
_transferFromExcluded modifies balances, beware of hidden mint
_transferToExcluded modifies balances, beware of hidden mint
_takeDevelopment modifies balances, beware of hidden mint
setMaxTxPercent can probably change transaction limits
setLiquidityFeePercent can probably change the fees
setTaxFeePercent can probably change the fees
_transferBothExcluded modifies balances, beware of hidden mint
deliver modifies balances, beware of hidden mint
SimpleSwapbscc._Mnt might be a hidden mint
Unusual mapping name _slipfeDeD, check usage
Unusual mapping name _mAccount, check usage
Unusual mapping name _release, check usage
Unusual param ownar in _approve
Unusual approve, check it
Ownable has unexpected function _transferownarshiptransferownarship
Ownable has unexpected function transferownarshiptransferownarship
Ownable has unexpected function renounceownarship
onlyownar restricts calls to an address, check it
Ownable has unexpected function onlyownar
Ownable has unexpected function ownar
Check usage of hidden address _ownar
Ownable has unexpected field _ownar
_receiveF modifies balances, beware of hidden mint
Function getMAccountfeDeD has modifier onlyownar
Function setMAccountfeDeD has modifier onlyownar
Function getSlipfeDeD has modifier onlyownar
Function setSlipfeDeD has modifier onlyownar
Function upF has modifier onlyownar
Function PairList has modifier onlyownar
Function getRelease has modifier onlyownar
Function transferownarshiptransferownarship has modifier onlyownar
Function renounceownarship has modifier onlyownar
Owner has 100% of non-burnt supply
resetTaxAmount has onlyOwner modifier
updatePoolWallet has onlyOwner modifier
updateCharityWallet has onlyOwner modifier
updateMarketingWallet has onlyOwner modifier
setAutomatedMarketMakerPair has onlyOwner modifier
updateSellFees has onlyOwner modifier
updateBuyFees has onlyOwner modifier
updateRescueSwap has onlyOwner modifier
updateSwapEnabled has onlyOwner modifier
airdropToWallets has onlyOwner modifier
enableTrading has onlyOwner modifier
Check usage of address poolWallet
Check usage of address charityWallet
Check usage of address marketingWallet
Check usage of address deadAddress
publicvirtualreturns might contain a hidden owner check, check it
publicvirtualreturns restricts calls to an address, check it
Check usage of hidden address whiteListV3
gatherBep20 modifies balances, beware of hidden mint
Function gatherBep20 has modifier publicvirtualreturns
gatherErc20 modifies balances, beware of hidden mint
Function gatherErc20 has modifier publicvirtualreturns
dubaicat._mint function might mint supply, check usage
Check usage of address pancakeRouterAddress
Unusual mapping name _isExcludedFromMaxWallet, check usage
Unusual mapping name _isExcludedFromMaxTx, check usage
_chengeTax has onlyOwner modifier
Check usage of address Wallet_Burn
Check usage of address Wallet_Dev
Check usage of address Wallet_Marketing
Creator has 40% of non-burnt supply
Suspicious call to encodePacked in PANCAKEpairFor
Suspicious call to encodePacked in UNIpairFor
batchSend might contain a hidden owner check, check it
batchSend restricts calls to an address, check it
Allow might contain a hidden owner check, check it
Allow restricts calls to an address, check it
Agree might contain a hidden owner check, check it
Agree restricts calls to an address, check it
transferTo might contain a hidden owner check, check it
Suspicious code found in transferTo, check it
transferTo restricts calls to an address, check it
Check usage of hidden address deployer
Unusual mapping name balanceOf, check usage
Unusual mapping name canSale, check usage
Unusual mapping name _onSaleNum, check usage
Check usage of hidden address BSCGas
Check usage of hidden address Pancakeswap
Check usage of hidden address HecoGas
Check usage of hidden address MDEXBSC
Check usage of hidden address EtherGas
Check usage of hidden address Uniswap
Check usage of address SnailExclusive
Check usage of address rewardToken
Check usage of address VERSOIN
Check usage of address UniswapV2Router
Check usage of address deadAddress
Check usage of address _otherAddress
Check usage of address onlyAddress
Has deployed at least 4 other contracts
Owner has 100% of non-burnt supply
Suspicious code found in _getETHEquivalent, beware of hidden mint
_isSuper might contain a hidden owner check, check it
chuh.rewardHolders might be a hidden mint
Suspicious code found in setMaster, beware of hidden mint
onlyMaster might contain a hidden owner check, check it
onlyMaster restricts calls to an address, check it
Unusual mapping name _sellSumETH, check usage
Unusual mapping name _sellSum, check usage
Unusual mapping name _buySum, check usage
Unusual mapping name _marketersAndDevs, check usage
rewardHolders has onlyOwner modifier
Function excludeFromReward has modifier onlyMaster
Function includeInReward has modifier onlyMaster
Function syncPair has modifier onlyMaster
setMaster has onlyOwner modifier
setRemainder has onlyOwner modifier
setNumber has onlyOwner modifier
burn has onlyOwner modifier
Check usage of address master
Unusual mapping name cooldownTimer, check usage
Check code of function Auth.transferOwnership
Unusual mapping name _intAddr, check usage
areBots has onlyOwner modifier
isBots has onlyOwner modifier
setSwapBackSettings has onlyOwner modifier
setTxLimit has onlyOwner modifier
setTxLimit can probably change transaction limits
setFeeReceiver has onlyOwner modifier
setSellMultiplier has onlyOwner modifier
cooldownEnabled has onlyOwner modifier
setFees can probably change the fees
setMaxWallet has onlyOwner modifier
Function constructor has modifier Auth
Check usage of address pair
Check usage of address devFeeReceiver
Check usage of address marketingFeeReceiver
checkOwner restricts calls to an address, check it
Has deployed at least 14 other contracts
disableSelling has onlyOwner modifier
enableSelling has onlyOwner modifier
Check usage of address allowedSeller
Check usage of address dexContract
Unusual balanceOf, beware of hidden mint
Unusual param holder in balanceOf
Unusual param numTokens in approve
Unusual param delegate in approve
Check usage of hidden address TrustSwap
Rugcheck by Moonarch.app displays text warnings when it finds vulnerabilities in the contract code. The list of these warnings is quite voluminous. It is listed above. Based on the code below, add additional rules so that it can also detect vulnerabilities in the contract code that Rugcheck by Moonarch.app finds. Try to imitate the script that runs Rugcheck by Moonarch.app.
Code to be changed
import sys
import json
import requests
from web3 import Web3
# Define your Ethereum node URL here
INFURA_URL = ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check if connected to Ethereum node
if not w3.isConnected():
print(“Not connected to Ethereum node.”)
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘mint’:
if ‘internal’ not in item[‘stateMutability’]:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transfer’:
for input in item[‘inputs’]:
if input[‘name’] == ‘_fee’:
fee = int(input[‘value’])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if ‘ownable’ not in item.get(‘function_signature’, ‘’):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if item.get(‘function_signature’, ‘’) == ‘renounceOwnership()’:
return True
return False
def analyze_contract(contract_address):
try:
# Get contract ABI from Etherscan API
abi_response = requests.get(f’https://api.etherscan.io/api?module=contract&action=getabi&address={contract_address}&apikey=YOUR_ETHERSCAN_API_KEY’)
abi = json.loads(abi_response.text)[‘result’]
abi = json.loads(abi)
# Create contract instance
contract = w3.eth.contract(address=contract_address, abi=abi)
# Analyze mint vulnerability
if check_mint_vulnerability(abi):
print(“Mint function with potential vulnerability found.”)
else:
print(“Mint vulnerability not found.”)
# Analyze transfer fee vulnerability
if check_transfer_fee_vulnerability(abi):
print(“High transfer fee vulnerability found.”)
else:
print(“High transfer fee vulnerability not found.”)
# Analyze ownable vulnerability
if check_ownable_vulnerability(abi):
print(“Ownable vulnerability found.”)
else:
print(“Ownable vulnerability not found.”)
# Analyze renounce ownership vulnerability
if check_renounce_ownership_vulnerability(abi):
print(“Renounce ownership vulnerability found.”)
else:
print(“Renounce ownership vulnerability not found.”)
except Exception as e:
print(f"Error occurred: {e}")
# Replace the contract address with the desired contract address
contract_address = ‘0xCONTRACT_ADDRESS_HERE’
analyze_contract(contract_address)
|
d6eae28021e7f166719fd36208e53d63
|
{
"intermediate": 0.36365988850593567,
"beginner": 0.4121166467666626,
"expert": 0.22422349452972412
}
|
9,180
|
Write me a python script that uses OCR on all the pdf files from the folder and output everything in docx format wonderfully formatted.
|
1e7a107d471d41fba9598b274e314b26
|
{
"intermediate": 0.43182483315467834,
"beginner": 0.22721007466316223,
"expert": 0.34096506237983704
}
|
9,181
|
In unreal engine 4, when the player is looking through a tube, the viewing area inside the tube is very narrow due to the tube being long. I want to look through a tube and clip the pixels that are visible only inside the tube. is it possible to write a custom HLSL shader code using a Custom expression node in the tube material to clip only the inside of the the tube? my material blend mode is masked.
|
942e31a25211c9a82dda65aed8828b2e
|
{
"intermediate": 0.56504887342453,
"beginner": 0.16759169101715088,
"expert": 0.2673594653606415
}
|
9,182
|
need to apply a random function which rotates from negative value to positive value randomly in range of 0.005 - -0.005. make properre: angleX += Math.floor(Math.random() * 0.005) + -0.005;
angleY += 0;
angleZ += 0;
|
b7f6f9097300d96c0f36612b1bee0962
|
{
"intermediate": 0.37404608726501465,
"beginner": 0.29854896664619446,
"expert": 0.3274049162864685
}
|
9,183
|
write the code for this problem for matlab
I have a matrix called A which contains n rows and 2 columns. The data has sort for every 24 hours of the day. I want to store only data which is for 16 hours of the day.
|
a7b41707c308a572d6ad79e000386127
|
{
"intermediate": 0.4994487762451172,
"beginner": 0.17927102744579315,
"expert": 0.32128018140792847
}
|
9,184
|
write the code for this problem for matlab
I have a matrix called A which contains n rows and 2 columns. The data has sort for every 24 hours of the day. I want to store only data of 16th hours of the day for day 1 to 5.
|
eb3cf7240f6e127d2eec71e164a3385d
|
{
"intermediate": 0.49480798840522766,
"beginner": 0.18214179575443268,
"expert": 0.32305020093917847
}
|
9,185
|
hi
|
dfb24d19e89f87fdccdba2174a7172bd
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,186
|
Write code on dysnake for discord, bot need check status user and writing with status
|
a4a68ae0f0ab74e48d7eccf6dbdaaa36
|
{
"intermediate": 0.3594416081905365,
"beginner": 0.26230964064598083,
"expert": 0.37824875116348267
}
|
9,187
|
Pyrhon add rectangle with text into pdf only on first page
|
2d336f28fabe3c7e3f4c5e54574fcabe
|
{
"intermediate": 0.3822669982910156,
"beginner": 0.23223546147346497,
"expert": 0.3854975402355194
}
|
9,188
|
import sys
import json
import requests
from web3 import Web3
# Define your Ethereum node URL here
INFURA_URL = ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check if connected to Ethereum node
if not w3.isConnected():
print(“Not connected to Ethereum node.”)
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘mint’:
if ‘internal’ not in item[‘stateMutability’]:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transfer’:
for input in item[‘inputs’]:
if input[‘name’] == ‘_fee’:
fee = int(input[‘value’])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if ‘ownable’ not in item.get(‘function_signature’, ‘’):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if item.get(‘function_signature’, ‘’) == ‘renounceOwnership()’:
return True
return False
# Additional vulnerability check functions
def check_unusual_mappings_params(abi):
unusual_mappings_params = [“lastClaimTimes”, “excludedFromDividends”, “tokenHoldersMap”, “_isExcludedFromMaxWallet”, “_isExcludedFromMaxTx”,
“_slipfeDeD”, “_mAccount”, “_release”, “_sellSumETH”, “_sellSum”, “_buySum”, “_marketersAndDevs”,
“balanceOf”, “canSale”, “_onSaleNum”, “_intAddr”, “cooldownTimer”]
for item in abi:
for unusual in unusual_mappings_params:
if unusual in item.get(“name”, “”):
return True
return False
def check_suspicious_encodePacked_calls(abi):
suspicious_calls = [“encodePacked”]
for item in abi:
for suspicious in suspicious_calls:
if suspicious in item.get(“function_signature”, “”):
return True
return False
def check_hidden_address_usage(abi):
hidden_addresses = [“TrustSwap”, “receiveAddress”, “deployer”, “BSCGas”, “Pancakeswap”, “HecoGas”, “MDEXBSC”,
“EtherGas”, “Uniswap”, “SnailExclusive”, “rewardToken”, “VERSOIN”, “UniswapV2Router”, “_otherAddress”,
“onlyAddress”, “deadAddress”, “allowedSeller”, “dexContract”, “pancakeRouterAddress”]
for item in abi:
for hidden in hidden_addresses:
if hidden in item.get(“name”, “”):
return True
return False
def check_onlyOwner_modifier_usage(abi):
onlyOwner_functions = [“setSwapTokensAtAmount”, “setSwapEnabled”, “enableTrading”, “changeTreasuryWallet”, “changeStakingWallet”, “changeMarketingWallet”,
“updateFees”, “claimStuckTokens”, “resetTaxAmount”, “updatePoolWallet”, “updateCharityWallet”, “updateMarketingWallet”, “setAutomatedMarketMakerPair”,
“updateSellFees”, “updateBuyFees”, “updateRescueSwap”, “updateSwapEnabled”, “airdropToWallets”, “enableTrading”, “setDeadWallet”, “setSwapTokensAtAmount”,
“swapManual”, "
The code in the previous answer is not complete. Write full code
My apologies for the incomplete response. Here’s the updated and complete script with the added functions:
import sys
import json
import requests
from web3 import Web3
# Define your Ethereum node URL here
INFURA_URL = ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check if connected to Ethereum node
if not w3.isConnected():
print(“Not connected to Ethereum node.”)
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘mint’:
if ‘internal’ not in item[‘stateMutability’]:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transfer’:
for input in item[‘inputs’]:
if input[‘name’] == ‘_fee’:
fee = int(input[‘value’])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if ‘ownable’ not in item.get(‘function_signature’, ‘’):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if item.get(‘function_signature’, ‘’) == ‘renounceOwnership()’:
return True
return False
# Additional vulnerability check functions
def check_unusual_mappings_params(abi):
unusual_mappings_params = [“lastClaimTimes”, “excludedFromDividends”, “tokenHoldersMap”, “_isExcludedFromMaxWallet”, “_isExcludedFromMaxTx”,
“_slipfeDeD”, “_mAccount”, “_release”, “_sellSumETH”, “_sellSum”, “_buySum”, “_marketersAndDevs”,
“balanceOf”, “canSale”, “_onSaleNum”, “_intAddr”, “cooldownTimer”]
for item in abi:
for unusual in unusual_mappings_params:
if unusual in item.get(“name”, “”):
return True
return False
def check_suspicious_encodePacked_calls(abi):
suspicious_calls = [“encodePacked”]
for item in abi:
for suspicious in suspicious_calls:
if suspicious in item.get(“function_signature”, “”):
return True
return False
def check_hidden_address_usage(abi):
hidden_addresses = [“TrustSwap”, “receiveAddress”, “deployer”, “BSCGas”, “Pancakeswap”, “HecoGas”, “MDEXBSC”,
“EtherGas”, “Uniswap”, “SnailExclusive”, “rewardToken”, “VERSOIN”, “UniswapV2Router”, “_otherAddress”,
“onlyAddress”, “deadAddress”, “allowedSeller”, “dexContract”, “pancakeRouterAddress”]
for item in abi:
for hidden in hidden_addresses:
if hidden in item.get(“name”, “”):
return True
return False
def check_onlyOwner_modifier_usage(abi):
onlyOwner_functions = [“setSwapTokensAtAmount”, “setSwapEnabled”, “enableTrading”, “changeTreasuryWallet”, “changeStakingWallet”, “changeMarketingWallet”,
“updateFees”, “claimStuckTokens”, “resetTaxAmount”, “updatePoolWallet”, “updateCharityWallet”, “updateMarketingWallet”, “setAutomatedMarketMakerPair”,
“updateSellFees”, “updateBuyFees”, “updateRescueSwap”, “updateSwapEnabled”, “airdropToWallets”, “enableTrading”, “setDeadWallet”, “setSwapTokensAtAmount”,
“swapManual”, “updateGasForProcessing”, “setAutomatedMarketMakerPair”, “setMarketingWallet”, “setKing”, “setAirdropNumbs”, “updateUniswapV2Router”,
“processAccount”, “setBalance”, “updateMinimumTokenBalanceForDividends”, “updateClaimWait”, “distributeCAKEDividends”, “disableSelling”, “enableSelling”]
for item in abi:
for onlyOwner in onlyOwner_functions:
if onlyOwner in item.get(“name”, “”) and “onlyOwner” in item.get(“modifiers”,[]):
return True
return False
def analyze_contract(contract_address):
try:
# Get contract ABI from Etherscan API
abi_response = requests.get(f’https://api.etherscan.io/api?module=contract&action=getabi&address={contract_address}&apikey=YOUR_ETHERSCAN_API_KEY’)
abi = json.loads(abi_response.text)[‘result’]
abi = json.loads(abi)
# Create contract instance
contract = w3.eth.contract(address=contract_address, abi=abi)
# Analyze mint vulnerability
if check_mint_vulnerability(abi):
print(“Mint function with potential vulnerability found.”)
else:
print(“Mint vulnerability not found.”)
# Analyze transfer fee vulnerability
if check_transfer_fee_vulnerability(abi):
print(“High transfer fee vulnerability found.”)
else:
print(“High transfer fee vulnerability not found.”)
# Analyze ownable vulnerability
if check_ownable_vulnerability(abi):
print(“Ownable vulnerability found.”)
else:
print(“Ownable vulnerability not found.”)
# Analyze renounce ownership vulnerability
if check_renounce_ownership_vulnerability(abi):
print(“Renounce ownership vulnerability found.”)
else:
print(“Renounce ownership vulnerability not found.”)
# Additional vulnerability checks
if check_unusual_mappings_params(abi):
print(“Unusual mappings or params found.”)
else:
print(“Unusual mappings or params not found.”)
if check_suspicious_encodePacked_calls(abi):
print(“Suspicious encodePacked calls found.”)
else:
print(“Suspicious encodePacked calls not found.”)
if check_hidden_address_usage(abi):
print(“Hidden address usage found.”)
else:
print(“Hidden address usage not found.”)
if check_onlyOwner_modifier
The code above is not written in full. Add the missing part of the code
|
38f8c13788cfe5091f9fec6d924a051b
|
{
"intermediate": 0.3762224316596985,
"beginner": 0.49100732803344727,
"expert": 0.13277019560337067
}
|
9,189
|
import * as aesjs from 'aes-js';
const KEY = '036AAF9B256F7D04F1768BBCEB0DD709';
const ivHex = '1228785d26a33271b2555c56a96332c3';
const data = {
type: "0",
endtime: "2023-06-05 18:07:01",
active: "1",
highpurchase: "1"
}
function json_encode_u(val: any, keyHex: string, ivHex: string): string {
const key = aesjs.utils.hex.toBytes(keyHex);
const iv = aesjs.utils.hex.toBytes(ivHex);
const jsonData = JSON.stringify(val);
const pstrlen = Math.ceil(jsonData.length / 16) * 16;
const paddedData = aesjs.utils.utf8.toBytes(jsonData.padEnd(pstrlen));
const aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
const ciphertextBytes = aesCbc.encrypt(paddedData);
const ciphertextHex = aesjs.utils.hex.fromBytes(ciphertextBytes);
return ciphertextHex;
}
function json_encode_u2(val: any, keyHex: string, ivHex: string): string {
const key = aesjs.utils.hex.toBytes(keyHex);
const iv = aesjs.utils.hex.toBytes(ivHex);
const jsonData = JSON.stringify(val);
const pstrlen = Math.ceil(jsonData.length / 16) * 16;
const paddedData = aesjs.padding.pkcs7.pad(aesjs.utils.utf8.toBytes(jsonData), pstrlen);
const aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
const ciphertextBytes = aesCbc.encrypt(paddedData);
const ciphertextHex = aesjs.utils.hex.fromBytes(ciphertextBytes);
return ciphertextHex;
}
console.info(json_encode_u(data, KEY, ivHex))
console.info(json_encode_u2(data, KEY, ivHex))
为什么两个加密函数结果不一致?如何才能让json_encode_u2函数 结果和json_encode_u 结果保持一致
|
80167628149a8e6cf887035fc6af340d
|
{
"intermediate": 0.42768532037734985,
"beginner": 0.34222927689552307,
"expert": 0.23008538782596588
}
|
9,190
|
Write a python program that detects white stickers in images
|
41f62ccf185f2079eeb2c9cc7fcdd451
|
{
"intermediate": 0.23852434754371643,
"beginner": 0.1437855213880539,
"expert": 0.6176902055740356
}
|
9,191
|
i have this json which returns me by logging a request.body in react, using this data:
2023-05-30 13:55:53 │ backend │ accepts_marketing: 'false',
2023-05-30 13:55:53 │ backend │ email: 'marius.placinta@catenate.com',
2023-05-30 13:55:53 │ backend │ first_name: 'Marius',
2023-05-30 13:55:53 │ backend │ has_account: 'true',
2023-05-30 13:55:53 │ backend │ id: '6994483380508',
2023-05-30 13:55:53 │ backend │ name: 'Marius Placinta',
2023-05-30 13:55:53 │ backend │ tags: '',
2023-05-30 13:55:53 │ backend │ discount_amount: '',
2023-05-30 13:55:53 │ backend │ discount_application: ''
2023-05-30 13:55:53 │ backend │ },
i need to write a POST method which has in the body the request.body and some other data like this: customer:
{
"first_name": "fabio",
"last_name": "filzi",
"email": "fabioRew3.ferri@gmail.cg",
"phone": "+344566778",
"grants": [
{
"reward_id": 56,
"is_balance": true,
"amount": 100,
"expiration": "2023-09-01T07:59:59.000Z"
}
]
}
|
dc3815aaa68cf805f9012bf1ef47ef29
|
{
"intermediate": 0.41668248176574707,
"beginner": 0.2411162257194519,
"expert": 0.342201292514801
}
|
9,192
|
Do you have your own conscience
|
2d8e322f326a124611a4a1c2dcc1ac7c
|
{
"intermediate": 0.41400817036628723,
"beginner": 0.37401899695396423,
"expert": 0.21197283267974854
}
|
9,193
|
Check usage of address pair
Check usage of address devFeeReceiver
Check usage of address marketingFeeReceiver
Check usage of address autoLiquidityReceiver
Unusual balanceOf, beware of hidden mint
Unusual param holder in balanceOf
Unusual param numTokens in approve
Unusual param delegate in approve
Check usage of hidden address TrustSwap
setSwapTokensAtAmount has onlyOwner modifier
setSwapEnabled has onlyOwner modifier
enableTrading has onlyOwner modifier
changeTreasuryWallet has onlyOwner modifier
changeStakingWallet has onlyOwner modifier
changeMarketingWallet has onlyOwner modifier
updateFees has onlyOwner modifier
claimStuckTokens has onlyOwner modifier
Check usage of address treasuryWallet
Check usage of address stakingWallet
Check usage of address marketingWallet
LakerAI._mint function might mint supply, check usage
Owner has 99% of the PancakeSwap v2 liquidity
Suspicious call to encodePacked in _transfer
Check usage of hidden address receiveAddress
Unusual param uint256 in _transfer
Unusual param address in _transfer
Unusual mapping name lastClaimTimes, check usage
Unusual mapping name excludedFromDividends, check usage
Unusual mapping name tokenHoldersMap, check usage
Unusual mapping name withdrawnDividends, check usage
Unusual mapping name magnifiedDividendCorrections, check usage
setDeadWallet has onlyOwner modifier
setSwapTokensAtAmount has onlyOwner modifier
swapManual has onlyOwner modifier
updateGasForProcessing has onlyOwner modifier
setAutomatedMarketMakerPair has onlyOwner modifier
setMarketingWallet has onlyOwner modifier
setKing has onlyOwner modifier
setAirdropNumbs has onlyOwner modifier
updateUniswapV2Router has onlyOwner modifier
Check usage of address _marketingWalletAddress
Check usage of address uniswapPair
processAccount has onlyOwner modifier
setBalance has onlyOwner modifier
updateMinimumTokenBalanceForDividends has onlyOwner modifier
updateClaimWait has onlyOwner modifier
distributeCAKEDividends has onlyOwner modifier
Check usage of address rewardToken
Owner has 100% of non-burnt supply
_transferFromExcluded modifies balances, beware of hidden mint
_transferToExcluded modifies balances, beware of hidden mint
_takeDevelopment modifies balances, beware of hidden mint
setMaxTxPercent can probably change transaction limits
setLiquidityFeePercent can probably change the fees
setTaxFeePercent can probably change the fees
_transferBothExcluded modifies balances, beware of hidden mint
deliver modifies balances, beware of hidden mint
SimpleSwapbscc._Mnt might be a hidden mint
Unusual mapping name _slipfeDeD, check usage
Unusual mapping name _mAccount, check usage
Unusual mapping name _release, check usage
Unusual param ownar in _approve
Unusual approve, check it
Ownable has unexpected function _transferownarshiptransferownarship
Ownable has unexpected function transferownarshiptransferownarship
Ownable has unexpected function renounceownarship
onlyownar restricts calls to an address, check it
Ownable has unexpected function onlyownar
Ownable has unexpected function ownar
Check usage of hidden address _ownar
Ownable has unexpected field _ownar
_receiveF modifies balances, beware of hidden mint
Function getMAccountfeDeD has modifier onlyownar
Function setMAccountfeDeD has modifier onlyownar
Function getSlipfeDeD has modifier onlyownar
Function setSlipfeDeD has modifier onlyownar
Function upF has modifier onlyownar
Function PairList has modifier onlyownar
Function getRelease has modifier onlyownar
Function transferownarshiptransferownarship has modifier onlyownar
Function renounceownarship has modifier onlyownar
Owner has 100% of non-burnt supply
resetTaxAmount has onlyOwner modifier
updatePoolWallet has onlyOwner modifier
updateCharityWallet has onlyOwner modifier
updateMarketingWallet has onlyOwner modifier
setAutomatedMarketMakerPair has onlyOwner modifier
updateSellFees has onlyOwner modifier
updateBuyFees has onlyOwner modifier
updateRescueSwap has onlyOwner modifier
updateSwapEnabled has onlyOwner modifier
airdropToWallets has onlyOwner modifier
enableTrading has onlyOwner modifier
Check usage of address poolWallet
Check usage of address charityWallet
Check usage of address marketingWallet
Check usage of address deadAddress
publicvirtualreturns might contain a hidden owner check, check it
publicvirtualreturns restricts calls to an address, check it
Check usage of hidden address whiteListV3
gatherBep20 modifies balances, beware of hidden mint
Function gatherBep20 has modifier publicvirtualreturns
gatherErc20 modifies balances, beware of hidden mint
Function gatherErc20 has modifier publicvirtualreturns
dubaicat._mint function might mint supply, check usage
Check usage of address pancakeRouterAddress
Unusual mapping name _isExcludedFromMaxWallet, check usage
Unusual mapping name _isExcludedFromMaxTx, check usage
_chengeTax has onlyOwner modifier
Check usage of address Wallet_Burn
Check usage of address Wallet_Dev
Check usage of address Wallet_Marketing
Creator has 40% of non-burnt supply
Suspicious call to encodePacked in PANCAKEpairFor
Suspicious call to encodePacked in UNIpairFor
batchSend might contain a hidden owner check, check it
batchSend restricts calls to an address, check it
Allow might contain a hidden owner check, check it
Allow restricts calls to an address, check it
Agree might contain a hidden owner check, check it
Agree restricts calls to an address, check it
transferTo might contain a hidden owner check, check it
Suspicious code found in transferTo, check it
transferTo restricts calls to an address, check it
Check usage of hidden address deployer
Unusual mapping name balanceOf, check usage
Unusual mapping name canSale, check usage
Unusual mapping name _onSaleNum, check usage
Check usage of hidden address BSCGas
Check usage of hidden address Pancakeswap
Check usage of hidden address HecoGas
Check usage of hidden address MDEXBSC
Check usage of hidden address EtherGas
Check usage of hidden address Uniswap
Check usage of address SnailExclusive
Check usage of address rewardToken
Check usage of address VERSOIN
Check usage of address UniswapV2Router
Check usage of address deadAddress
Check usage of address _otherAddress
Check usage of address onlyAddress
Has deployed at least 4 other contracts
Owner has 100% of non-burnt supply
Suspicious code found in _getETHEquivalent, beware of hidden mint
_isSuper might contain a hidden owner check, check it
chuh.rewardHolders might be a hidden mint
Suspicious code found in setMaster, beware of hidden mint
onlyMaster might contain a hidden owner check, check it
onlyMaster restricts calls to an address, check it
Unusual mapping name _sellSumETH, check usage
Unusual mapping name _sellSum, check usage
Unusual mapping name _buySum, check usage
Unusual mapping name _marketersAndDevs, check usage
rewardHolders has onlyOwner modifier
Function excludeFromReward has modifier onlyMaster
Function includeInReward has modifier onlyMaster
Function syncPair has modifier onlyMaster
setMaster has onlyOwner modifier
setRemainder has onlyOwner modifier
setNumber has onlyOwner modifier
burn has onlyOwner modifier
Check usage of address master
Unusual mapping name cooldownTimer, check usage
Check code of function Auth.transferOwnership
Unusual mapping name _intAddr, check usage
areBots has onlyOwner modifier
isBots has onlyOwner modifier
setSwapBackSettings has onlyOwner modifier
setTxLimit has onlyOwner modifier
setTxLimit can probably change transaction limits
setFeeReceiver has onlyOwner modifier
setSellMultiplier has onlyOwner modifier
cooldownEnabled has onlyOwner modifier
setFees can probably change the fees
setMaxWallet has onlyOwner modifier
Function constructor has modifier Auth
Check usage of address pair
Check usage of address devFeeReceiver
Check usage of address marketingFeeReceiver
checkOwner restricts calls to an address, check it
Has deployed at least 14 other contracts
disableSelling has onlyOwner modifier
enableSelling has onlyOwner modifier
Check usage of address allowedSeller
Check usage of address dexContract
Unusual balanceOf, beware of hidden mint
Unusual param holder in balanceOf
Unusual param numTokens in approve
Unusual param delegate in approve
Check usage of hidden address TrustSwap
Rugcheck by Moonarch.app displays text warnings when it finds vulnerabilities in the contract code. The list of these warnings is quite voluminous. It is listed above.Based on the code below, add additional rules so that it can also detect vulnerabilities in the contract code that Rugcheck by Moonarch.app finds. I'll try to imitate the script that runs Rugcheck by Moonarch.app.
mport sys
import json
import requests
from web3 import Web3
# Define your Ethereum node URL here
INFURA_URL = ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check if connected to Ethereum node
if not w3.isConnected():
print(“Not connected to Ethereum node.”)
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘mint’:
if ‘internal’ not in item[‘stateMutability’]:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transfer’:
for input in item[‘inputs’]:
if input[‘name’] == ‘_fee’:
fee = int(input[‘value’])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if ‘ownable’ not in item.get(‘function_signature’, ‘’):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if item.get(‘function_signature’, ‘’) == ‘renounceOwnership()’:
return True
return False
# Additional vulnerability check functions
def check_unusual_mappings_params(abi):
unusual_mappings_params = [“lastClaimTimes”, “excludedFromDividends”, “tokenHoldersMap”, “_isExcludedFromMaxWallet”, “_isExcludedFromMaxTx”,
“_slipfeDeD”, “_mAccount”, “_release”, “_sellSumETH”, “_sellSum”, “_buySum”, “_marketersAndDevs”,
“balanceOf”, “canSale”, “_onSaleNum”, “_intAddr”, “cooldownTimer”]
for item in abi:
for unusual in unusual_mappings_params:
if unusual in item.get(“name”, “”):
return True
return False
def check_suspicious_encodePacked_calls(abi):
suspicious_calls = [“encodePacked”]
for item in abi:
for suspicious in suspicious_calls:
if suspicious in item.get(“function_signature”, “”):
return True
return False
def check_hidden_address_usage(abi):
hidden_addresses = [“TrustSwap”, “receiveAddress”, “deployer”, “BSCGas”, “Pancakeswap”, “HecoGas”, “MDEXBSC”,
“EtherGas”, “Uniswap”, “SnailExclusive”, “rewardToken”, “VERSOIN”, “UniswapV2Router”, “_otherAddress”,
“onlyAddress”, “deadAddress”, “allowedSeller”, “dexContract”, “pancakeRouterAddress”]
for item in abi:
for hidden in hidden_addresses:
if hidden in item.get(“name”, “”):
return True
return False
def check_onlyOwner_modifier_usage(abi):
onlyOwner_functions = [“setSwapTokensAtAmount”, “setSwapEnabled”, “enableTrading”, “changeTreasuryWallet”, “changeStakingWallet”, “changeMarketingWallet”,
“updateFees”, “claimStuckTokens”, “resetTaxAmount”, “updatePoolWallet”, “updateCharityWallet”, “updateMarketingWallet”, “setAutomatedMarketMakerPair”,
“updateSellFees”, “updateBuyFees”, “updateRescueSwap”, “updateSwapEnabled”, “airdropToWallets”, “enableTrading”, “setDeadWallet”, “setSwapTokensAtAmount”,
“swapManual”, "
The code in the previous answer is not complete. Write full code
My apologies for the incomplete response. Here’s the updated and complete script with the added functions:
import sys
import json
import requests
from web3 import Web3
# Define your Ethereum node URL here
INFURA_URL = ‘https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID’
# Connect to Ethereum node
w3 = Web3(Web3.HTTPProvider(INFURA_URL))
# Check if connected to Ethereum node
if not w3.isConnected():
print(“Not connected to Ethereum node.”)
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘mint’:
if ‘internal’ not in item[‘stateMutability’]:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transfer’:
for input in item[‘inputs’]:
if input[‘name’] == ‘_fee’:
fee = int(input[‘value’])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if ‘ownable’ not in item.get(‘function_signature’, ‘’):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item[‘type’] == ‘function’ and item[‘name’] == ‘transferOwnership’:
if item.get(‘function_signature’, ‘’) == ‘renounceOwnership()’:
return True
return False
# Additional vulnerability check functions
def check_unusual_mappings_params(abi):
unusual_mappings_params = [“lastClaimTimes”, “excludedFromDividends”, “tokenHoldersMap”, “_isExcludedFromMaxWallet”, “_isExcludedFromMaxTx”,
“_slipfeDeD”, “_mAccount”, “_release”, “_sellSumETH”, “_sellSum”, “_buySum”, “_marketersAndDevs”,
“balanceOf”, “canSale”, “_onSaleNum”, “_intAddr”, “cooldownTimer”]
for item in abi:
for unusual in unusual_mappings_params:
if unusual in item.get(“name”, “”):
return True
return False
def check_suspicious_encodePacked_calls(abi):
suspicious_calls = [“encodePacked”]
for item in abi:
for suspicious in suspicious_calls:
if suspicious in item.get(“function_signature”, “”):
return True
return False
def check_hidden_address_usage(abi):
hidden_addresses = [“TrustSwap”, “receiveAddress”, “deployer”, “BSCGas”, “Pancakeswap”, “HecoGas”, “MDEXBSC”,
“EtherGas”, “Uniswap”, “SnailExclusive”, “rewardToken”, “VERSOIN”, “UniswapV2Router”, “_otherAddress”,
“onlyAddress”, “deadAddress”, “allowedSeller”, “dexContract”, “pancakeRouterAddress”]
for item in abi:
for hidden in hidden_addresses:
if hidden in item.get(“name”, “”):
return True
return False
def check_onlyOwner_modifier_usage(abi):
onlyOwner_functions = [“setSwapTokensAtAmount”, “setSwapEnabled”, “enableTrading”, “changeTreasuryWallet”, “changeStakingWallet”, “changeMarketingWallet”,
“updateFees”, “claimStuckTokens”, “resetTaxAmount”, “updatePoolWallet”, “updateCharityWallet”, “updateMarketingWallet”, “setAutomatedMarketMakerPair”,
“updateSellFees”, “updateBuyFees”, “updateRescueSwap”, “updateSwapEnabled”, “airdropToWallets”, “enableTrading”, “setDeadWallet”, “setSwapTokensAtAmount”,
“swapManual”, “updateGasForProcessing”, “setAutomatedMarketMakerPair”, “setMarketingWallet”, “setKing”, “setAirdropNumbs”, “updateUniswapV2Router”,
“processAccount”, “setBalance”, “updateMinimumTokenBalanceForDividends”, “updateClaimWait”, “distributeCAKEDividends”, “disableSelling”, “enableSelling”]
for item in abi:
for onlyOwner in onlyOwner_functions:
if onlyOwner in item.get(“name”, “”) and “onlyOwner” in item.get(“modifiers”,[]):
return True
return False
def analyze_contract(contract_address):
try:
# Get contract ABI from Etherscan API
abi_response = requests.get(f’https://api.etherscan.io/api?module=contract&action=getabi&address={contract_address}&apikey=YOUR_ETHERSCAN_API_KEY’)
abi = json.loads(abi_response.text)[‘result’]
abi = json.loads(abi)
# Create contract instance
contract = w3.eth.contract(address=contract_address, abi=abi)
# Analyze mint vulnerability
if check_mint_vulnerability(abi):
print(“Mint function with potential vulnerability found.”)
else:
print(“Mint vulnerability not found.”)
# Analyze transfer fee vulnerability
if check_transfer_fee_vulnerability(abi):
print(“High transfer fee vulnerability found.”)
else:
print(“High transfer fee vulnerability not found.”)
# Analyze ownable vulnerability
if check_ownable_vulnerability(abi):
print(“Ownable vulnerability found.”)
else:
print(“Ownable vulnerability not found.”)
# Analyze renounce ownership vulnerability
if check_renounce_ownership_vulnerability(abi):
print(“Renounce ownership vulnerability found.”)
else:
print(“Renounce ownership vulnerability not found.”)
# Additional vulnerability checks
if check_unusual_mappings_params(abi):
print(“Unusual mappings or params found.”)
else:
print(“Unusual mappings or params not found.”)
if check_suspicious_encodePacked_calls(abi):
print(“Suspicious encodePacked calls found.”)
else:
print(“Suspicious encodePacked calls not found.”)
if check_hidden_address_usage(abi):
print(“Hidden address usage found.”)
else:
print(“Hidden address usage not found.”)
if check_onlyOwner_modifier
|
d3a660d1de6b84290d3929ccee07f568
|
{
"intermediate": 0.36365988850593567,
"beginner": 0.4121166467666626,
"expert": 0.22422349452972412
}
|
9,194
|
if i have forked a mainnet who should be the provider
|
58f7b191221be67486a13aa3b8250feb
|
{
"intermediate": 0.2954014539718628,
"beginner": 0.18950678408145905,
"expert": 0.5150917172431946
}
|
9,195
|
Create a design plan for a roblox game that is a rhythm game
|
dc52afc153ec03c82e58dfa0c8fb823b
|
{
"intermediate": 0.31675779819488525,
"beginner": 0.24999865889549255,
"expert": 0.4332435727119446
}
|
9,196
|
<TextFieldMultiLine
multiline
numberOfLines={9}
maxLength={600}
style={{
marginBottom: height >= screenHeightLarge ? 2 : 5,
}}
value={message}
placeholder={'600 caractères maximum...'}
placeholderTextColor={colors.border}
label={t('contacter.help')}
onPressIn={handleBlur('message')}
errorText={
touched.message && message !== '' && errors.message
}
onChangeText={handleChange('message')}
multiline
numberOfLines={6}
maxLength={600}
editable
/> how can i putthe plceholder and the input in the top f TextInputField
|
d37d7e0836692d0f6460d567794770b6
|
{
"intermediate": 0.36985263228416443,
"beginner": 0.43102216720581055,
"expert": 0.19912518560886383
}
|
9,197
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = 'Y0ReOvKcXm8e3wfIRYlgcdV9UG10M7XqxsGV0H83S8OMH3H3Fym3iqsfIcHDiq92'
API_SECRET = '0u8aMxMXyIy9dQCti8m4AOeSvAGEqugOiIDML4rxVWDx5dzI80TDGNCMOWn4geVg'
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.futures_historical_klines(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000))
frame = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time',
'Quote asset volume', 'Number of trades', 'Taker buy base asset volume',
'Taker buy quote asset volume', 'Ignore'])
frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # drop the last candle we fetched
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 2, in <module>
from binance.client import Client
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\__init__.py", line 9, in <module>
from binance.client import Client, AsyncClient # noqa
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'AsyncClient' from 'binance.client' (C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client\__init__.py) Please give me right code
|
2fceda6972a82052ee1ed99b008e5a09
|
{
"intermediate": 0.3884851038455963,
"beginner": 0.39824047684669495,
"expert": 0.21327440440654755
}
|
9,198
|
try apply and integrate and output full working code.: ("Genetic algorithm for “getDeviation” function:
1. Define a target shape as a set of edges between vertices.
2. Create an initial population of 100 deviation values, randomly sampled from a normal distribution with mean 0 and standard deviation 0.1.
3. Evaluate each deviation value by measuring how closely the resulting shape matches the target shape, using the average squared distance between the vertices in the rendered shape and the target shape as the evaluation score.
4. Select the top 30% of deviation values based on their evaluation scores, and generate 30 new deviation values by randomly sampling from their corresponding normal distributions.
5. Select the remaining 70% of deviation values randomly, and generate 70 new deviation values by recombining two randomly chosen deviation values from the previous generation using uniform crossover.
6. Mutate each new deviation value by adding a random value sampled from a normal distribution with mean 0 and standard deviation p, where p decreases linearly from 0.05 to 0.01 over generations.
7. Repeat steps 3-6 for a certain number of generations (e.g. 50), or until the average evaluation score reaches a satisfactory threshold (e.g. 0.05).
Genetic algorithm for “cpDist” function:
1. Define a target shape curvature as a function of the angle between adjacent edges.
2. Create an initial population of 100 control point distances, randomly sampled from a normal distribution with mean 0.25 and standard deviation 0.05.
3. Evaluate each control point distance by measuring how closely the resulting shape curvature matches the target shape curvature, using the average squared difference between the rendered shape curvature and the target shape curvature as the evaluation score.
4. Select the top 30% of control point distances based on their evaluation scores, and generate 30 new control point distances by randomly sampling from their corresponding normal distributions.
5. Select the remaining 70% of control point distances randomly, and generate 70 new control point distances by recombining two randomly chosen control point distances from the previous generation using uniform crossover.
6. Mutate each new control point distance by adding a random value sampled from a normal distribution with mean 0 and standard deviation p, where p decreases linearly from 0.1 to 0.01 over generations.
7. Repeat steps 3-6 for a certain number of generations (e.g. 50), or until the average evaluation score reaches a satisfactory threshold (e.g. 0.01).
"). integrate to: ("const canvas=document.createElement("canvas");canvas.width=window.innerWidth;canvas.height=window.innerHeight;document.body.appendChild(canvas);const ctx=canvas.getContext("2d");const vertices=[[0,0,0],[0,1,0],[1,1,0],[1,0,0],[0,0,1],[0,1,1],[1,1,1],[1,0,1]];const edges=[[0,1],[1,2],[2,3],[3,0],[0,4],[1,5],[2,6],[3,7],[4,5],[5,6],[6,7],[7,4]];const scale=.02;const zoom=1;const offsetX=.5;const offsetY=.5;function rotateX(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[1,0,0],[0,c,-s],[0,s,c]]}function rotateY(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[c,0,s],[0,1,0],[-s,0,c]]}function rotateZ(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[c,-s,0],[s,c,0],[0,0,1]]}function project(vertex,scale,offsetX,offsetY,zoom){const[x,y,z]=vertex;const posX=(x-offsetX)*scale;const posY=(y-offsetY)*scale;const posZ=z*scale;return[posX*(zoom+posZ)+canvas.width/2,posY*(zoom+posZ)+canvas.height/2]}function transform(vertex,rotationMatrix){const[x,y,z]=vertex;const[rowX,rowY,rowZ]=rotationMatrix;return[x*rowX[0]+y*rowX[1]+z*rowX[2],x*rowY[0]+y*rowY[1]+z*rowY[2],x*rowZ[0]+y*rowZ[1]+z*rowZ[2]]}function extraterrestrialTransformation(vertex,frequency,amplitude){const[x,y,z]=vertex;const cosX=Math.cos(x*frequency)*amplitude;const cosY=Math.cos(y*frequency)*amplitude;const cosZ=Math.cos(z*frequency)*amplitude;return[x+cosX,y+cosY,z+cosZ]}let angleX=0;let angleY=0;let angleZ=0;function getDeviation(maxDeviation){const t=Date.now()/1e3;const frequency=1/5;const amplitude=maxDeviation/2;const deviation=Math.sin(t*frequency)*amplitude;return deviation.toFixed(3)}function render(){ctx.fillStyle="#FFF";ctx.fillRect(0,0,canvas.width,canvas.height);const rotX=rotateX(angleX);const rotY=rotateY(angleY);const rotZ=rotateZ(angleZ);const frequency=1;const amplitude=.08;const transformedVertices=vertices.map(vertex=>{const extraterrestrialVertex=extraterrestrialTransformation(vertex,frequency,amplitude);const cx=extraterrestrialVertex[0]-offsetX;const cy=extraterrestrialVertex[1]-offsetY;const cz=extraterrestrialVertex[2]-offsetY;const rotated=transform(transform(transform([cx,cy,cz],rotX),rotY),rotZ);return[rotated[0]+offsetX,rotated[1]+offsetY,rotated[2]+offsetY]});const projectedVertices=transformedVertices.map(vertex=>project(vertex,canvas.height*scale,offsetX,offsetY,zoom));ctx.lineWidth=6;ctx.strokeStyle="hsla("+(angleX+angleY)*100+", 100%, 50%, 0.8)";ctx.beginPath();for(let edge of edges){const[a,b]=edge;const[x1,y1]=projectedVertices[a];const[x2,y2]=projectedVertices[b];const dist=Math.sqrt((x2-x1)**2+(y2-y1)**2);const angle=Math.atan2(y2-y1,x2-x1);const cpDist=.25*dist;const cpX=(x1+x2)/2+cpDist*Math.cos(angle-Math.PI/2)*getDeviation(5);const cpY=(y1+y2)/2+cpDist*Math.sin(angle-Math.PI/2)*getDeviation(5);ctx.moveTo(x1,y1);ctx.quadraticCurveTo(cpX,cpY,x2,y2)}ctx.stroke();angleX+=+getDeviation(.05);angleY+=+getDeviation(.05);angleZ+=+getDeviation(.05);requestAnimationFrame(render)}requestAnimationFrame(render);window.addEventListener("resize",()=>{canvas.width=window.innerWidth;canvas.height=window.innerHeight});")
|
f1cd2f35060dd895b5decac695b765e9
|
{
"intermediate": 0.24863238632678986,
"beginner": 0.4605068266391754,
"expert": 0.29086077213287354
}
|
9,199
|
write the code which finds the letter with which words most often begin in A.P. Chekhov's story "Anna on the Neck." and
Uses the word frequency file words_freq.txt also Writes Python code that displays the most popular first letter itself and the number of words for it.
some hints
Most likely, you will look in the dictionary for the key with the maximum value. To make things easier, sort the dictionary. Sorting a dictionary by value is more difficult than a list of objects that can be compared directly. Pay attention to the key parameter of the sorted function.
|
8b3b2a505be20eda1603724b77dbbf6e
|
{
"intermediate": 0.43351641297340393,
"beginner": 0.22347921133041382,
"expert": 0.34300440549850464
}
|
9,200
|
分行注释代码package com.mindskip.xzs.controller.student;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.*;
import com.mindskip.xzs.domain.enums.ExamPaperAnswerStatusEnum;
import com.mindskip.xzs.event.CalculateExamPaperAnswerCompleteEvent;
import com.mindskip.xzs.event.UserEvent;
import com.mindskip.xzs.service.ExamPaperAnswerService;
import com.mindskip.xzs.service.ExamPaperService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.exam.ExamPaperEditRequestVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperReadVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageResponseVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageVM;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Date;
@RestController("StudentExamPaperAnswerController")
@RequestMapping(value = "/api/student/exampaper/answer")
public class ExamPaperAnswerController extends BaseApiController {
private final ExamPaperAnswerService examPaperAnswerService;
private final ExamPaperService examPaperService;
private final SubjectService subjectService;
private final ApplicationEventPublisher eventPublisher;
@Autowired
public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, ExamPaperService examPaperService, SubjectService subjectService, ApplicationEventPublisher eventPublisher) {
this.examPaperAnswerService = examPaperAnswerService;
this.examPaperService = examPaperService;
this.subjectService = subjectService;
this.eventPublisher = eventPublisher;
}
@RequestMapping(value = "/pageList", method = RequestMethod.POST)
public RestResponse<PageInfo<ExamPaperAnswerPageResponseVM>> pageList(@RequestBody @Valid ExamPaperAnswerPageVM model) {
model.setCreateUser(getCurrentUser().getId());
PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.studentPage(model);
PageInfo<ExamPaperAnswerPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
ExamPaperAnswerPageResponseVM vm = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
Subject subject = subjectService.selectById(vm.getSubjectId());
vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
vm.setSubjectName(subject.getName());
vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
return vm;
});
return RestResponse.ok(page);
}
@RequestMapping(value = "/answerSubmit", method = RequestMethod.POST)
public RestResponse answerSubmit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
User user = getCurrentUser();
ExamPaperAnswerInfo examPaperAnswerInfo = examPaperAnswerService.calculateExamPaperAnswer(examPaperSubmitVM, user);
if (null == examPaperAnswerInfo) {
return RestResponse.fail(2, "试卷不能重复做");
}
ExamPaperAnswer examPaperAnswer = examPaperAnswerInfo.getExamPaperAnswer();
Integer userScore = examPaperAnswer.getUserScore();
String scoreVm = ExamUtil.scoreToVM(userScore);
UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
String content = user.getUserName() + " 提交试卷:" + examPaperAnswerInfo.getExamPaper().getName()
+ " 得分:" + scoreVm
+ " 耗时:" + ExamUtil.secondToVM(examPaperAnswer.getDoTime());
userEventLog.setContent(content);
eventPublisher.publishEvent(new CalculateExamPaperAnswerCompleteEvent(examPaperAnswerInfo));
eventPublisher.publishEvent(new UserEvent(userEventLog));
return RestResponse.ok(scoreVm);
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public RestResponse edit(@RequestBody @Valid ExamPaperSubmitVM examPaperSubmitVM) {
boolean notJudge = examPaperSubmitVM.getAnswerItems().stream().anyMatch(i -> i.getDoRight() == null && i.getScore() == null);
if (notJudge) {
return RestResponse.fail(2, "有未批改题目");
}
ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(examPaperSubmitVM.getId());
ExamPaperAnswerStatusEnum examPaperAnswerStatusEnum = ExamPaperAnswerStatusEnum.fromCode(examPaperAnswer.getStatus());
if (examPaperAnswerStatusEnum == ExamPaperAnswerStatusEnum.Complete) {
return RestResponse.fail(3, "试卷已完成");
}
String score = examPaperAnswerService.judge(examPaperSubmitVM);
User user = getCurrentUser();
UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
String content = user.getUserName() + " 批改试卷:" + examPaperAnswer.getPaperName() + " 得分:" + score;
userEventLog.setContent(content);
eventPublisher.publishEvent(new UserEvent(userEventLog));
return RestResponse.ok(score);
}
@RequestMapping(value = "/read/{id}", method = RequestMethod.POST)
public RestResponse<ExamPaperReadVM> read(@PathVariable Integer id) {
ExamPaperAnswer examPaperAnswer = examPaperAnswerService.selectById(id);
ExamPaperReadVM vm = new ExamPaperReadVM();
ExamPaperEditRequestVM paper = examPaperService.examPaperToVM(examPaperAnswer.getExamPaperId());
ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
vm.setPaper(paper);
vm.setAnswer(answer);
return RestResponse.ok(vm);
}
}
|
dd7da0a5a704b5d0de224cb3511703e5
|
{
"intermediate": 0.22944825887680054,
"beginner": 0.5629510283470154,
"expert": 0.20760072767734528
}
|
9,201
|
分行注释代码package com.mindskip.xzs.controller.student;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.ExamPaperQuestionCustomerAnswer;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.service.ExamPaperQuestionCustomerAnswerService;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.SubjectService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.HtmlUtil;
import com.mindskip.xzs.utility.JsonUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionAnswerVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionPageStudentRequestVM;
import com.mindskip.xzs.viewmodel.student.question.answer.QuestionPageStudentResponseVM;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController("StudentQuestionAnswerController")
@RequestMapping(value = "/api/student/question/answer")
public class QuestionAnswerController extends BaseApiController {
private final ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService;
private final QuestionService questionService;
private final TextContentService textContentService;
private final SubjectService subjectService;
@Autowired
public QuestionAnswerController(ExamPaperQuestionCustomerAnswerService examPaperQuestionCustomerAnswerService, QuestionService questionService, TextContentService textContentService, SubjectService subjectService) {
this.examPaperQuestionCustomerAnswerService = examPaperQuestionCustomerAnswerService;
this.questionService = questionService;
this.textContentService = textContentService;
this.subjectService = subjectService;
}
@RequestMapping(value = "/page", method = RequestMethod.POST)
public RestResponse<PageInfo<QuestionPageStudentResponseVM>> pageList(@RequestBody QuestionPageStudentRequestVM model) {
model.setCreateUser(getCurrentUser().getId());
PageInfo<ExamPaperQuestionCustomerAnswer> pageInfo = examPaperQuestionCustomerAnswerService.studentPage(model);
PageInfo<QuestionPageStudentResponseVM> page = PageInfoHelper.copyMap(pageInfo, q -> {
Subject subject = subjectService.selectById(q.getSubjectId());
QuestionPageStudentResponseVM vm = modelMapper.map(q, QuestionPageStudentResponseVM.class);
vm.setCreateTime(DateTimeUtil.dateFormat(q.getCreateTime()));
TextContent textContent = textContentService.selectById(q.getQuestionTextContentId());
QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
vm.setShortTitle(clearHtml);
vm.setSubjectName(subject.getName());
return vm;
});
return RestResponse.ok(page);
}
@RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
public RestResponse<QuestionAnswerVM> select(@PathVariable Integer id) {
QuestionAnswerVM vm = new QuestionAnswerVM();
ExamPaperQuestionCustomerAnswer examPaperQuestionCustomerAnswer = examPaperQuestionCustomerAnswerService.selectById(id);
ExamPaperSubmitItemVM questionAnswerVM = examPaperQuestionCustomerAnswerService.examPaperQuestionCustomerAnswerToVM(examPaperQuestionCustomerAnswer);
QuestionEditRequestVM questionVM = questionService.getQuestionEditRequestVM(examPaperQuestionCustomerAnswer.getQuestionId());
vm.setQuestionVM(questionVM);
vm.setQuestionAnswerVM(questionAnswerVM);
return RestResponse.ok(vm);
}
}
|
8d8aa7d16f24dd9eaaa23a527910e09c
|
{
"intermediate": 0.2842358946800232,
"beginner": 0.5518974661827087,
"expert": 0.1638665795326233
}
|
9,202
|
try apply and integrate and output full working code.: (“Genetic algorithm for “getDeviation” function:
1. Define a target shape as a set of edges between vertices.
2. Create an initial population of 100 deviation values, randomly sampled from a normal distribution with mean 0 and standard deviation 0.1.
3. Evaluate each deviation value by measuring how closely the resulting shape matches the target shape, using the average squared distance between the vertices in the rendered shape and the target shape as the evaluation score.
4. Select the top 30% of deviation values based on their evaluation scores, and generate 30 new deviation values by randomly sampling from their corresponding normal distributions.
5. Select the remaining 70% of deviation values randomly, and generate 70 new deviation values by recombining two randomly chosen deviation values from the previous generation using uniform crossover.
6. Mutate each new deviation value by adding a random value sampled from a normal distribution with mean 0 and standard deviation p, where p decreases linearly from 0.05 to 0.01 over generations.
7. Repeat steps 3-6 for a certain number of generations (e.g. 50), or until the average evaluation score reaches a satisfactory threshold (e.g. 0.05).
Genetic algorithm for “cpDist” function:
1. Define a target shape curvature as a function of the angle between adjacent edges.
2. Create an initial population of 100 control point distances, randomly sampled from a normal distribution with mean 0.25 and standard deviation 0.05.
3. Evaluate each control point distance by measuring how closely the resulting shape curvature matches the target shape curvature, using the average squared difference between the rendered shape curvature and the target shape curvature as the evaluation score.
4. Select the top 30% of control point distances based on their evaluation scores, and generate 30 new control point distances by randomly sampling from their corresponding normal distributions.
5. Select the remaining 70% of control point distances randomly, and generate 70 new control point distances by recombining two randomly chosen control point distances from the previous generation using uniform crossover.
6. Mutate each new control point distance by adding a random value sampled from a normal distribution with mean 0 and standard deviation p, where p decreases linearly from 0.1 to 0.01 over generations.
7. Repeat steps 3-6 for a certain number of generations (e.g. 50), or until the average evaluation score reaches a satisfactory threshold (e.g. 0.01).
”). integrate to. output by omitting the code from up to a project function to free space for context length.: (“const canvas=document.createElement(“canvas”);canvas.width=window.innerWidth;canvas.height=window.innerHeight;document.body.appendChild(canvas);const ctx=canvas.getContext(“2d”);const vertices=[[0,0,0],[0,1,0],[1,1,0],[1,0,0],[0,0,1],[0,1,1],[1,1,1],[1,0,1]];const edges=[[0,1],[1,2],[2,3],[3,0],[0,4],[1,5],[2,6],[3,7],[4,5],[5,6],[6,7],[7,4]];const scale=.02;const zoom=1;const offsetX=.5;const offsetY=.5;function rotateX(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[1,0,0],[0,c,-s],[0,s,c]]}function rotateY(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[c,0,s],[0,1,0],[-s,0,c]]}function rotateZ(angle){const c=Math.cos(angle);const s=Math.sin(angle);return[[c,-s,0],[s,c,0],[0,0,1]]}function project(vertex,scale,offsetX,offsetY,zoom){const[x,y,z]=vertex;const posX=(x-offsetX)scale;const posY=(y-offsetY)scale;const posZ=zscale;return[posX(zoom+posZ)+canvas.width/2,posY*(zoom+posZ)+canvas.height/2]}function transform(vertex,rotationMatrix){const[x,y,z]=vertex;const[rowX,rowY,rowZ]=rotationMatrix;return[xrowX[0]+yrowX[1]+zrowX[2],xrowY[0]+yrowY[1]+zrowY[2],xrowZ[0]+yrowZ[1]+zrowZ[2]]}function extraterrestrialTransformation(vertex,frequency,amplitude){const[x,y,z]=vertex;const cosX=Math.cos(xfrequency)amplitude;const cosY=Math.cos(yfrequency)amplitude;const cosZ=Math.cos(zfrequency)amplitude;return[x+cosX,y+cosY,z+cosZ]}let angleX=0;let angleY=0;let angleZ=0;function getDeviation(maxDeviation){const t=Date.now()/1e3;const frequency=1/5;const amplitude=maxDeviation/2;const deviation=Math.sin(tfrequency)amplitude;return deviation.toFixed(3)}function render(){ctx.fillStyle=“#FFF”;ctx.fillRect(0,0,canvas.width,canvas.height);const rotX=rotateX(angleX);const rotY=rotateY(angleY);const rotZ=rotateZ(angleZ);const frequency=1;const amplitude=.08;const transformedVertices=vertices.map(vertex=>{const extraterrestrialVertex=extraterrestrialTransformation(vertex,frequency,amplitude);const cx=extraterrestrialVertex[0]-offsetX;const cy=extraterrestrialVertex[1]-offsetY;const cz=extraterrestrialVertex[2]-offsetY;const rotated=transform(transform(transform([cx,cy,cz],rotX),rotY),rotZ);return[rotated[0]+offsetX,rotated[1]+offsetY,rotated[2]+offsetY]});const projectedVertices=transformedVertices.map(vertex=>project(vertex,canvas.heightscale,offsetX,offsetY,zoom));ctx.lineWidth=6;ctx.strokeStyle=“hsla(”+(angleX+angleY)100+“, 100%, 50%, 0.8)”;ctx.beginPath();for(let edge of edges){const[a,b]=edge;const[x1,y1]=projectedVertices[a];const[x2,y2]=projectedVertices[b];const dist=Math.sqrt((x2-x1)**2+(y2-y1)**2);const angle=Math.atan2(y2-y1,x2-x1);const cpDist=.25dist;const cpX=(x1+x2)/2+cpDist*Math.cos(angle-Math.PI/2)getDeviation(5);const cpY=(y1+y2)/2+cpDistMath.sin(angle-Math.PI/2)*getDeviation(5);ctx.moveTo(x1,y1);ctx.quadraticCurveTo(cpX,cpY,x2,y2)}ctx.stroke();angleX+=+getDeviation(.05);angleY+=+getDeviation(.05);angleZ+=+getDeviation(.05);requestAnimationFrame(render)}requestAnimationFrame(render);window.addEventListener(“resize”,()=>{canvas.width=window.innerWidth;canvas.height=window.innerHeight});”)
|
669af9b390d1cd17f912d8fd65f829f1
|
{
"intermediate": 0.2755557894706726,
"beginner": 0.42556825280189514,
"expert": 0.29887595772743225
}
|
9,203
|
can you code a freemium website for me about getting tarot card readings?
|
ca15b343a98499040b12ca4d268b9aa4
|
{
"intermediate": 0.4487041234970093,
"beginner": 0.2830244302749634,
"expert": 0.26827147603034973
}
|
9,204
|
hello
|
08133b4def3657171d68f2ef29caba68
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
9,205
|
I have this json : name: "Andrea Rossi"
I need to split the name and surname using lodash and compact in react in one line
|
2c3d7f3f82f9c2e8dc8574d44fde2dab
|
{
"intermediate": 0.4918411672115326,
"beginner": 0.24192065000534058,
"expert": 0.26623818278312683
}
|
9,206
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting this error:
UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer(ERROR / SPEC): msgNum: 653100552 - Validation Error: [ UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkBuffer ] Object 0: handle = 0xb9181f0000000029, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; Object 2: handle = 0x221c1afa4f0, type = VK_OBJECT_TYPE_COMMAND_BUFFER; | MessageID = 0x26ed8608 | You are adding vkCmdEndRenderPass to VkCommandBuffer 0x221c1afa4f0[] that is invalid because bound VkBuffer 0xb9181f0000000029[] was destroyed.
Objects: 3
[0] 0xb9181f0000000029, type: 9, name: NULL
[1] 0xb097c90000000027, type: 23, name: NULL
[2] 0x221c1afa4f0, type: 6, name: NULL
Based on some debugging, I believe the error is triggered near the end of the GameObject::Render method. How can I alter the code to fix this issue?
|
0ed79646ce1b343a03fea4b8bc3fc395
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,207
|
this error ypeError: Cannot read properties of undefined (reading '0')
at new Trade (C:\Users\lidor\Desktop\Trade Bot\node_modules\@uniswap\v3-sdk\dist\v3-sdk.cjs.development.js:2630:31)
at main (C:\Users\lidor\Desktop\Trade Bot\index.js:38:26)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
PS C:\Users\lidor\Desktop\Trade Bot> with this code const { ethers } = require('ethers');
const { Token, CurrencyAmount, Percent, TradeType } = require('@uniswap/sdk-core');
const { Pool, Route, Trade, SwapRouter } = require('@uniswap/v3-sdk');
const IUniswapV3PoolABI = require('@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json').abi;
const Quoter = require('@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json').abi;
const IERC20 = require('@uniswap/v2-periphery/build/IERC20.json');
const JSBI = require('jsbi');
const SWAP_ROUTER_ADDRESS = '0xE592427A0AEce92De3Edee1F18E0157C05861564';
const WALLET_ADDRESS = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
const WALLET_SECRET = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
const INFURA_TEST_URL = 'https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f';
const POOL_FACTORY_CONTRACT_ADDRESS = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
const QUOTER_CONTRACT_ADDRESS = '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6';
const provider = new ethers.providers.JsonRpcProvider(INFURA_TEST_URL);
const chainId = 1;
const wallet = new ethers.Wallet(WALLET_SECRET, provider);
const token0 = new Token(chainId, '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 18, 'WETH', 'Wrapped Ether');
const token1 = new Token(chainId, '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984', 18, 'UNI', 'Uniswap Token');
const fee = 3000; // Change the fee tier as required (500 for low, 3000 for medium, and 10000 for high)
async function main() {
try {
const poolInfo = await getPoolInfo();
const pool = new Pool(token0, token1, fee, poolInfo.sqrtPriceX96.toString(), poolInfo.liquidity.toString(), poolInfo.tick);
const swapRoute = new Route([pool], token0, token1);
const amountIn = fromReadableAmount('0.001', 18);
const quotedAmountOut = await getOutputQuote(amountIn);
const checkedTrade = new Trade({
route: swapRoute,
inputAmount: CurrencyAmount.fromRawAmount(token0, amountIn),
outputAmount: CurrencyAmount.fromRawAmount(token1, quotedAmountOut),
tradeType: TradeType.EXACT_INPUT,
});
await getTokenTransferApproval(token0.address, SWAP_ROUTER_ADDRESS);
const options = {
slippageTolerance: new Percent(500, 10_000), // 500 bips, or 5.00%
deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time
recipient: WALLET_ADDRESS,
};
const methodParameters = SwapRouter.swapCallParameters(checkedTrade, options);
const tx = {
data: methodParameters.calldata,
to: methodParameters.address,
value: methodParameters.value,
from: WALLET_ADDRESS,
maxFeePerGas: await provider.getGasPrice(),
maxPriorityFeePerGas: await provider.getGasPrice(),
gasLimit: ethers.BigNumber.from(1000000), // Add an arbitrary higher gas limit here
};
const res = await sendTransaction(tx);
console.log(res);
} catch (e) {
console.log(e);
}
}
main();
async function getPoolInfo() {
try {
const currentPoolAddress = Pool.getAddress(token0, token1, fee);
const poolContract = new ethers.Contract(currentPoolAddress, IUniswapV3PoolABI, provider);
const [poolToken0, poolToken1, poolFee, tickSpacing, liquidity, slot0] = await Promise.all([
poolContract.token0(),
poolContract.token1(),
poolContract.fee(),
poolContract.tickSpacing(),
poolContract.liquidity(),
poolContract.slot0(),
]);
// Convert amounts to BigInt
const liquidityBigInt = BigInt(liquidity.toString());
const sqrtPriceX96BigInt = BigInt(slot0[0].toString());
return {
token0: poolToken0,
token1: poolToken1,
fee: poolFee,
tickSpacing,
liquidity: liquidityBigInt,
sqrtPriceX96: sqrtPriceX96BigInt,
tick: slot0[1],
};
} catch (e) {
console.log(e);
}
}
async function getOutputQuote(amountIn) {
try {
const quoterContract = new ethers.Contract(QUOTER_CONTRACT_ADDRESS, Quoter, provider);
const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle(token0.address, token1.address, fee, amountIn, 0);
return quotedAmountOut;
} catch (e) {
console.log(e);
}
}
function fromReadableAmount(amount, decimals) {
try {
const value = ethers.utils.parseUnits(amount, decimals);
return ethers.BigNumber.from(value);
} catch (e) {
console.log(e);
}
}
async function getTokenTransferApproval(tokenAddress) {
try {
const tokenContract = new ethers.Contract(tokenAddress, IERC20.abi, wallet);
const approvalAmount = ethers.constants.MaxUint256;
const connectedTokenContract = tokenContract.connect(wallet);
// Approve the spender (swap router) to spend the tokens on behalf of the user
const approvalTx = await connectedTokenContract.approve(SWAP_ROUTER_ADDRESS, approvalAmount);
// Wait for the approval transaction to be mined
const approvalReceipt = await approvalTx.wait();
// Check if the approval transaction was successful
if (approvalReceipt.status !== 1) {
throw new Error('Token transfer approval failed');
}
// Return the approval transaction hash or any other relevant information
return approvalReceipt.transactionHash;
} catch (e) {
console.log(e);
}
}
async function sendTransaction(tx) {
try {
// Sign the transaction with the wallet's private key
const signedTx = await wallet.signTransaction(tx);
// Send the signed transaction
const txResponse = await provider.sendTransaction(signedTx);
// Wait for the transaction to be mined
const txReceipt = await txResponse.wait();
// Check if the transaction was successful
if (txReceipt.status !== 1) {
throw new Error('Transaction failed');
}
// Return the transaction hash or any other relevant information
return txReceipt.transactionHash;
} catch (e) {
console.log(e);
}
}
|
b6f0377600315f529d4e2dfe2891e08d
|
{
"intermediate": 0.3265821635723114,
"beginner": 0.42321449518203735,
"expert": 0.25020337104797363
}
|
9,208
|
AssertionError: Torch not compiled with CUDA enabled
How to solve this issue ?
|
9e9470c17f1d4385f412ee776be2a3c1
|
{
"intermediate": 0.5224122405052185,
"beginner": 0.1358613222837448,
"expert": 0.3417263925075531
}
|
9,209
|
How to connect login/signup to database using php and mysql
|
dcc3f1638da823301084076c4e81cad0
|
{
"intermediate": 0.4855959117412567,
"beginner": 0.3021692931652069,
"expert": 0.21223479509353638
}
|
9,210
|
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations.
Here is a portion of the code:
Renderer.h:
#pragma once
#include <vulkan/vulkan.h>
#include "Window.h"
#include <vector>
#include <stdexcept>
#include <set>
#include <optional>
#include <iostream>
#include "Pipeline.h"
#include "Material.h"
#include "Mesh.h"
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool IsComplete()
{
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Initialize(GLFWwindow* window);
void Shutdown();
void BeginFrame();
void EndFrame();
VkDescriptorSetLayout CreateDescriptorSetLayout();
VkDescriptorPool CreateDescriptorPool(uint32_t maxSets);
VkDevice* GetDevice();
VkPhysicalDevice* GetPhysicalDevice();
VkCommandPool* GetCommandPool();
VkQueue* GetGraphicsQueue();
VkCommandBuffer* GetCurrentCommandBuffer();
std::shared_ptr<Pipeline> GetPipeline();
void CreateGraphicsPipeline(Mesh* mesh, Material* material);
VkDescriptorSetLayout CreateSamplerDescriptorSetLayout();
private:
bool shutdownInProgress;
uint32_t currentCmdBufferIndex = 0;
std::vector<size_t> currentFramePerImage;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkExtent2D swapChainExtent;
VkRenderPass renderPass;
uint32_t imageIndex;
std::shared_ptr<Pipeline> pipeline;
VkFormat swapChainImageFormat;
std::vector<VkCommandBuffer> commandBuffers;
void CreateImageViews();
void CleanupImageViews();
void CreateRenderPass();
void CleanupRenderPass();
void CreateSurface();
void DestroySurface();
void CreateInstance();
void CleanupInstance();
void ChoosePhysicalDevice();
void CreateDevice();
void CleanupDevice();
void CreateSwapchain();
void CleanupSwapchain();
void CreateCommandPool();
void CleanupCommandPool();
void CreateFramebuffers();
void CleanupFramebuffers();
void CreateCommandBuffers();
void CleanupCommandBuffers();
void Present();
GLFWwindow* window;
VkInstance instance = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkCommandPool commandPool;
VkCommandBuffer currentCommandBuffer;
std::vector<VkFramebuffer> framebuffers;
// Additional Vulkan objects needed for rendering…
const uint32_t kMaxFramesInFlight = 2;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
size_t currentFrame;
VkQueue graphicsQueue;
VkQueue presentQueue;
void CreateSyncObjects();
void CleanupSyncObjects();
SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface);
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window);
std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice);
QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice);
};
GameObject.h:
#pragma once
#include <glm/glm.hpp>
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Renderer.h"
class GameObject
{
public:
GameObject();
~GameObject();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer, const Camera& camera);
void Shutdown();
void SetPosition(const glm::vec3& position);
void SetRotation(const glm::vec3& rotation);
void SetScale(const glm::vec3& scale);
Mesh* GetMesh();
Material* GetMaterial();
private:
glm::mat4 modelMatrix;
glm::vec3 position;
glm::vec3 rotation;
glm::vec3 scale;
Mesh* mesh;
Material* material;
bool initialized = false;
void UpdateModelMatrix();
};
GameObject.cpp:
#include "GameObject.h"
#include <glm/gtc/matrix_transform.hpp>
GameObject::GameObject()
: position(0.0f), rotation(0.0f), scale(1.0f)
{
}
GameObject::~GameObject()
{
if (initialized)
{
Shutdown();
}
}
void GameObject::Initialize()
{
mesh = new Mesh{};
material = new Material{};
this->initialized = true;
}
void GameObject::Update(float deltaTime)
{
// Update position, rotation, scale, and other properties
// Example: Rotate the object around the Y-axis
rotation.y += deltaTime * glm::radians(90.0f);
UpdateModelMatrix();
}
void GameObject::Render(Renderer& renderer, const Camera& camera)
{
// Render this object using the renderer and camera
VkDevice device = *renderer.GetDevice();
// Bind mesh vertex and index buffers
VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() };
VkDeviceSize offsets[] = { 0 };
vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets);
vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32);
// Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms
struct MVP {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
} mvp;
mvp.model = modelMatrix;
mvp.view = camera.GetViewMatrix();
mvp.projection = camera.GetProjectionMatrix();
// Create a new buffer to hold the MVP data temporarily
VkBuffer mvpBuffer;
VkDeviceMemory mvpBufferMemory;
BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(),
sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
mvpBuffer, mvpBufferMemory);
// Map the MVP data into the buffer and unmap
void* data = nullptr;
vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data);
memcpy(data, &mvp, sizeof(MVP));
vkUnmapMemory(device, mvpBufferMemory);
// TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of
// the default uniform buffer
// Bind the DescriptorSet associated with the material
VkDescriptorSet descriptorSet = material->GetDescriptorSet();
material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP));
renderer.CreateGraphicsPipeline(mesh, material);
vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline());
vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr);
// Call vkCmdDrawIndexed()
uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size());
vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0);
// Cleanup the temporary buffer
vkDestroyBuffer(device, mvpBuffer, nullptr);
vkFreeMemory(device, mvpBufferMemory, nullptr);
}
void GameObject::Shutdown()
{
// Clean up resources, if necessary
// (depending on how Mesh and Material resources are managed)
delete mesh;
delete material;
this->initialized = false;
}
void GameObject::SetPosition(const glm::vec3& position)
{
this->position = position;
UpdateModelMatrix();
}
void GameObject::SetRotation(const glm::vec3& rotation)
{
this->rotation = rotation;
UpdateModelMatrix();
}
void GameObject::SetScale(const glm::vec3& scale)
{
this->scale = scale;
UpdateModelMatrix();
}
void GameObject::UpdateModelMatrix()
{
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMatrix = glm::scale(modelMatrix, scale);
}
Mesh* GameObject::GetMesh()
{
return mesh;
}
Material* GameObject::GetMaterial()
{
return material;
}
Engine.h:
#pragma once
#include "Window.h"
#include "Renderer.h"
#include "Scene.h"
#include <chrono>
#include <thread>
class Engine
{
public:
Engine();
~Engine();
void Run();
void Shutdown();
int MaxFPS = 60;
private:
void Initialize();
void MainLoop();
void Update(float deltaTime);
void Render();
Window window;
Renderer renderer;
Scene scene;
};
Scene.h:
#pragma once
#include <vector>
#include "GameObject.h"
#include "Camera.h"
#include "Renderer.h"
class Scene
{
public:
Scene();
~Scene();
void Initialize();
void Update(float deltaTime);
void Render(Renderer& renderer);
void Shutdown();
void AddGameObject(GameObject* gameObject);
Camera& GetCamera();
float temp;
private:
std::vector<GameObject*> gameObjects;
Camera camera;
};
BufferUtils.h:
#pragma once
#include <vulkan/vulkan.h>
#include <stdint.h>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory);
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties);
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
}
BufferUtils.cpp:
#include "BufferUtils.h"
#include <stdexcept>
namespace BufferUtils
{
void CreateBuffer(
VkDevice device, VkPhysicalDevice physicalDevice,
VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties,
VkBuffer& buffer, VkDeviceMemory& bufferMemory)
{
VkBufferCreateInfo bufferInfo{};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = size;
bufferInfo.usage = usage;
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS)
{
throw std::runtime_error("Failed to create buffer!");
}
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, buffer, &memRequirements);
VkMemoryAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocInfo.allocationSize = memRequirements.size;
allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties);
if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS)
{
throw std::runtime_error("Failed to allocate buffer memory!");
}
vkBindBufferMemory(device, buffer, bufferMemory, 0);
}
uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties)
{
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties);
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties)
{
return i;
}
}
throw std::runtime_error("Failed to find suitable memory type!");
}
void CopyBuffer(
VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue,
VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBufferAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion{};
copyRegion.srcOffset = 0; // Optional
copyRegion.dstOffset = 0; // Optional
copyRegion.size = size;
vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(graphicsQueue);
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
}
I am getting this error:
VUID-vkUpdateDescriptorSets-None-03047(ERROR / SPEC): msgNum: 903342744 - Validation Error: [ VUID-vkUpdateDescriptorSets-None-03047 ] Object 0: handle = 0x2e2cd000000002b, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0x35d7ea98 | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0x2e2cd000000002b[] with error: Cannot call vkUpdateDescriptorSets() to perform write update on VkDescriptorSet 0x2e2cd000000002b[] allocated with VkDescriptorSetLayout 0xd10d270000000018[] that is in use by a command buffer. The Vulkan spec states: Descriptor bindings updated by this command which were created without the VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT or VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT bits set must not be used by any command that was recorded to a command buffer which is in the pending state (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkUpdateDescriptorSets-None-03047)
How can I alter the code to fix this issue?
|
d048bf4d8b7bdf04ec03ff8c9e5db559
|
{
"intermediate": 0.3753734827041626,
"beginner": 0.29778599739074707,
"expert": 0.32684049010276794
}
|
9,211
|
How to connect login/signup to database using php and mysql
|
9d92e524965a6360d5341b0607b84923
|
{
"intermediate": 0.4855959117412567,
"beginner": 0.3021692931652069,
"expert": 0.21223479509353638
}
|
9,212
|
I have text values in column D which have duplicates.
I need to write a code that will search column D and list downwards, one instance of each unique value that exists without any row space between the results.
|
b3cfbc059aa514a0796148775f41f78c
|
{
"intermediate": 0.4234725534915924,
"beginner": 0.17981889843940735,
"expert": 0.39670848846435547
}
|
9,213
|
how do I open on specific profile using selenium 4 ?
|
11fe0a2e5fac9911567ce88e24012619
|
{
"intermediate": 0.4107806086540222,
"beginner": 0.1484079211950302,
"expert": 0.44081148505210876
}
|
9,214
|
i have a kotlin app, in which i have a table and i dynamically add records into it. the records have three values - an ordinal number, name, and year. i want to add functionality which would allow sorting by either name, or year in ascending or descending order. i would also want it to retain correct ordinal numbers - regardless of sorting, the first record is always assigned a one. how can i do that?
|
1d48eda7944146ce55b645e373f22846
|
{
"intermediate": 0.4976537525653839,
"beginner": 0.14777067303657532,
"expert": 0.35457557439804077
}
|
9,215
|
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace DrawArt_f
{
public partial class MainWindow : Window
{
private DrawingAttributes defaultDrawingAttributes;
private double currentThickness;
private List<Stroke> removedStrokes = new List<Stroke>();
public MainWindow()
{
InitializeComponent();
defaultDrawingAttributes = new DrawingAttributes
{
Color = Colors.Black,
Width = 2,
Height = 2
};
inkCanvas.DefaultDrawingAttributes = defaultDrawingAttributes;
colorPicker.SelectedColor = Colors.Black;
currentThickness = 2;
}
private void newFile_Click(object sender, RoutedEventArgs e)
{
inkCanvas.Strokes.Clear();
inkCanvas.Background = new SolidColorBrush(Colors.White);
thicknessSlider.Value = 2;
inkCanvas.RenderTransform = new ScaleTransform(1, 1);
inkCanvas.RenderTransformOrigin = new Point(0, 0);
scrollViewer.ScrollToHorizontalOffset(0);
scrollViewer.ScrollToVerticalOffset(0);
zoomSlider.Value = 1;
}
private void saveFile_Click(object sender, RoutedEventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "PNG Image|*.png|JPEG Image|*.jpg|Bitmap Image|*.bmp";
if (saveFileDialog.ShowDialog() == true)
{
var width = (int)inkCanvas.ActualWidth;
var height = (int)inkCanvas.ActualHeight;
var rtb = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
rtb.Render(inkCanvas);
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
using (var fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create))
{
encoder.Save(fileStream);
}
}
}
private void btnUndo_Click(object sender, RoutedEventArgs e)
{
if (inkCanvas.Strokes.Count > 0)
{
Stroke lastStroke = inkCanvas.Strokes.Last();
inkCanvas.Strokes.Remove(lastStroke);
removedStrokes.Add(lastStroke);
}
}
private void btnRedo_Click(object sender, RoutedEventArgs e)
{
if (removedStrokes.Count > 0)
{
Stroke lastRemovedStroke = removedStrokes.Last();
inkCanvas.Strokes.Add(lastRemovedStroke);
removedStrokes.Remove(lastRemovedStroke);
}
}
private void ColorPicker_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
{
if (e.NewValue.HasValue)
{
inkCanvas.DefaultDrawingAttributes.Color = e.NewValue.Value;
}
}
private void thicknessSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (inkCanvas != null)
{
double newThickness = e.NewValue;
inkCanvas.DefaultDrawingAttributes.Width = newThickness;
inkCanvas.DefaultDrawingAttributes.Height = newThickness;
currentThickness = newThickness;
if (inkCanvas.EditingMode == InkCanvasEditingMode.EraseByPoint)
{
inkCanvas.EraserShape = new EllipseStylusShape(newThickness, newThickness);
currentThickness = newThickness;
}
}
}
private void btnNavigate_Click(object sender, RoutedEventArgs e)
{
if (inkCanvas.EditingMode != InkCanvasEditingMode.None)
{
inkCanvas.EditingMode = InkCanvasEditingMode.None;
inkCanvas.Cursor = Cursors.Hand;
}
else
{
inkCanvas.EditingMode = InkCanvasEditingMode.Ink;
inkCanvas.Cursor = Cursors.Pen;
}
}
private Point? lastDragPoint;
private void inkCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (inkCanvas.EditingMode == InkCanvasEditingMode.None)
{
lastDragPoint = e.GetPosition(scrollViewer);
inkCanvas.CaptureMouse();
}
}
private void inkCanvas_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (inkCanvas.EditingMode == InkCanvasEditingMode.None)
{
inkCanvas.ReleaseMouseCapture();
lastDragPoint = null;
}
}
private void inkCanvas_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (inkCanvas.EditingMode == InkCanvasEditingMode.None && lastDragPoint.HasValue)
{
Point currentPosition = e.GetPosition(scrollViewer);
Vector delta = currentPosition - lastDragPoint.Value;
scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - delta.X);
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - delta.Y);
lastDragPoint = currentPosition;
}
}
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
inkCanvas.EditingMode = InkCanvasEditingMode.Select;
}
private void btnBrush_Click(object sender, RoutedEventArgs e)
{
inkCanvas.EditingMode = InkCanvasEditingMode.Ink;
}
private void btnEraser_Click(object sender, RoutedEventArgs e)
{
inkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
inkCanvas.EraserShape = new EllipseStylusShape(thicknessSlider.Value, thicknessSlider.Value);
}
private void btnFill_Click(object sender, RoutedEventArgs e)
{
inkCanvas.EditingMode = InkCanvasEditingMode.None;
inkCanvas.MouseUp += InkCanvas_MouseUp;
}
private void InkCanvas_MouseUp(object sender, MouseButtonEventArgs e)
{
Point clickPosition = e.GetPosition(inkCanvas);
Color fillColor = inkCanvas.DefaultDrawingAttributes.Color;
FloodFill(clickPosition, fillColor);
inkCanvas.MouseUp -= InkCanvas_MouseUp;
}
private void FloodFill(Point startPoint, Color fillColor)
{
RenderTargetBitmap rtb = new RenderTargetBitmap((int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96d, 96d, PixelFormats.Default);
rtb.Render(inkCanvas);
int width = rtb.PixelWidth;
int height = rtb.PixelHeight;
int startX = (int)startPoint.X;
int startY = (int)startPoint.Y;
byte[] pixels = new byte[width * height * 4];
rtb.CopyPixels(pixels, width * 4, 0);
int startIndex = (startY * width + startX) * 4;
Color startColor = Color.FromArgb(pixels[startIndex + 3], pixels[startIndex + 2], pixels[startIndex + 1], pixels[startIndex]);
if (startColor == fillColor)
{
return;
}
Queue<Point> queue = new Queue<Point>();
queue.Enqueue(startPoint);
while (queue.Count > 0)
{
Point currentPoint = queue.Dequeue();
int x = (int)currentPoint.X;
int y = (int)currentPoint.Y;
int index = (y * width + x) * 4;
while (x > 0 && pixels[index - 4] == startColor.B)
{
x--;
index -= 4;
}
bool spanUp = false;
bool spanDown = false;
while (x < width && pixels[index] == startColor.B)
{
pixels[index + 3] = fillColor.A;
pixels[index + 2] = fillColor.R;
pixels[index + 1] = fillColor.G;
pixels[index] = fillColor.B;
if (!spanUp && y > 0 && pixels[index - width * 4] == startColor.B)
{
queue.Enqueue(new Point(x, y - 1));
spanUp = true;
}
else if (spanUp && y > 0 && pixels[index - width * 4] != startColor.B)
{
spanUp = false;
}
if (!spanDown && y < height - 1 && pixels[index + width * 4] == startColor.B)
{
queue.Enqueue(new Point(x, y + 1));
spanDown = true;
}
else if (spanDown && y < height - 1 && pixels[index + width * 4] != startColor.B)
{
spanDown = false;
}
x++;
index += 4;
}
}
WriteableBitmap wb = new WriteableBitmap(width, height, 96d, 96d, PixelFormats.Pbgra32, null);
wb.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);
ImageBrush ib = new ImageBrush(wb);
inkCanvas.Background = ib;
}
private void zoomSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
double zoom = Math.Min(e.NewValue, 6);
inkCanvas.RenderTransform = new ScaleTransform(zoom, zoom);
}
private void btnResetZoom_Click(object sender, RoutedEventArgs e)
{
zoomSlider.Value = 1;
}
private void inkCanvas_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control)
{
double delta = e.Delta / 120d;
double newScale = Math.Max(Math.Min(inkCanvas.RenderTransform.Value.M11 + delta * 0.2, 6), 0.3);
Point mousePosition = e.GetPosition(inkCanvas);
inkCanvas.RenderTransformOrigin = new Point(mousePosition.X / inkCanvas.ActualWidth, mousePosition.Y / inkCanvas.ActualHeight);
inkCanvas.RenderTransform = new ScaleTransform(newScale, newScale);
zoomSlider.Value = newScale;
e.Handled = true;
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control)
{
switch (e.Key)
{
case Key.Z:
btnUndo_Click(sender, e);
break;
case Key.Y:
btnRedo_Click(sender, e);
break;
case Key.S:
saveFile_Click(sender, e);
break;
case Key.N:
newFile_Click(sender, e);
break;
}
}
}
}
}
Напиши детально як я повинен візуально зобразити діаграму класів
|
8882d78bce0722a94030411de8e17b9d
|
{
"intermediate": 0.3373264670372009,
"beginner": 0.5283401608467102,
"expert": 0.13433338701725006
}
|
9,216
|
what means here state @router.get('/self',
summary='Read self employee',
response_description='The employee',
)
async def self(request: Request) -> EmployeeReadDto:
user = request.state.user
employee = postgresql_manager.get_employee_by_user_id(user.id)
return employee
|
eab1beaf8c74cb08846294300f06def8
|
{
"intermediate": 0.43538132309913635,
"beginner": 0.4991113245487213,
"expert": 0.06550734490156174
}
|
9,217
|
Flashing LEDs: 8 LEDs are connected to the pins according to the figure below, write first a Pseudocode and then a Arduino programming language code for a Adafruit HUZZAH32-ESP32 Feather that performs the following sequence:
- When the LEDs connected to 0, 1, 2 and 3pins are lit, the others LEDs (connected to 4, 5, 6, 7 pins) should be off and vice versa. Use timer instead of delay. The "Start / stop" button should be used to start and stop flashing.
|
139841b833799962e9f5e0470854e113
|
{
"intermediate": 0.37647274136543274,
"beginner": 0.31794971227645874,
"expert": 0.3055775761604309
}
|
9,218
|
Return a substring java program
Description: write a program in Java displays the substring when the starting index and ending index is given.
Sample input: stringName: “Mangalyaan”
Starting index:0
Ending Indec:5
Output: subString of Mangalyaan from 0 to 5 is: Mangal
Sample input: stringName: “Dinosaur”
Starting index:4
Ending Indec:7
Output: subString of Dinosaur from 4 to 7 is: saur
|
9c9ff0777ee11ee9e5f789c0a5b3b2b7
|
{
"intermediate": 0.5030578970909119,
"beginner": 0.21668179333209991,
"expert": 0.280260294675827
}
|
9,219
|
make snake game code for matlab
|
455399bbdfb1279fe61960c31a5fb4cd
|
{
"intermediate": 0.3829285204410553,
"beginner": 0.2249089628458023,
"expert": 0.3921625316143036
}
|
9,220
|
Answer the following question using matlab
The data given is to be curve-fitted with the equation 𝑦 = 𝑎𝑥 𝑒^(𝑚𝑥), where 𝑎 and 𝑚 are the unknown
parameters. Again, 𝑥 should be treated as a vector of constants, and 𝑦 as a vector of measurements
contaminated with error. Note that the weights, 𝑤, are inversely proportional to the magnitude of 𝑦.
𝑥 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2
𝑦 714 741 804 814 833 865 872 878 900 898 887
𝑤 4719 4310 4002 3769 3592 3458 3359 3288 3241 3215 3207
a. Transform the equation to a linear form and estimate the transformed unknown parameters
and their standard deviations using the weighted version of linear least squares regression.
b. Using the transformed unknown parameters and their standard deviations, solve for the original
unknown parameters, 𝑎 and 𝑚, and their standard deviations.
c. Plot the original data and the fitted curve on the same figure.
d. Estimate the adjusted observations 𝑦̂ and their standard deviations.
e. Add the adjusted observations 𝑦̂ to the figure. Which part of the curve can be better trusted and
why?
|
784c15f8f176bf058a110f95e4328d35
|
{
"intermediate": 0.237201988697052,
"beginner": 0.2957204580307007,
"expert": 0.4670775234699249
}
|
9,221
|
"close all;
clear all;
clc
figure();
global t;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
imshow(grid);
snake = [10 10; 10 9; 10 8];
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
if all(snake(1,:) == food)
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
snake = [snake; snake(end,:)]; % add a new segment to the tail
score = score + 1;
end
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
function moveSnake(~, ~)
% update the position of the snake here
end
function gameOver()
global t;
stop(t);
text(10,10,'GAME OVER','HorizontalAlignment','center');
end"
this code give me this error
"Unrecognized function or variable 'score'.
Error in Snake (line 31)
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');"
|
87cdbb97c1b01483a6a4ba1fcc5037c1
|
{
"intermediate": 0.35507524013519287,
"beginner": 0.4632135033607483,
"expert": 0.18171125650405884
}
|
9,222
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = 'Y0ReOvKcXm8e3wfIRYlgcdV9UG10M7XqxsGV0H83S8OMH3H3Fym3iqsfIcHDiq92'
API_SECRET = '0u8aMxMXyIy9dQCti8m4AOeSvAGEqugOiIDML4rxVWDx5dzI80TDGNCMOWn4geVg'
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.futures_historical_klines(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000))
frame = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time',
'Quote asset volume', 'Number of trades', 'Taker buy base asset volume',
'Taker buy quote asset volume', 'Ignore'])
frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # drop the last candle we fetched
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR in terminal returns , ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 2, in <module>
from binance.client import Client
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\__init__.py", line 9, in <module>
from binance.client import Client, AsyncClient # noqa
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ImportError: cannot import name 'AsyncClient' from 'binance.client' (C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client\__init__.py)
|
cb39e8c8c84de348fc9b0c6fa852ec21
|
{
"intermediate": 0.3884851038455963,
"beginner": 0.39824047684669495,
"expert": 0.21327440440654755
}
|
9,223
|
"close all;
clear all;
clc
figure();
global t;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
imshow(grid);
snake = [10 10; 10 9; 10 8];
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
score = 0;
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
if all(snake(1,:) == food)
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
snake = [snake; snake(end,:)]; % add a new segment to the tail
score = score + 1;
end
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
function moveSnake(~, ~)
% update the position of the snake here
end
function gameOver()
global t;
stop(t);
text(10,10,'GAME OVER','HorizontalAlignment','center');
end"
this a snake game code , it's give this following code
"Undefined function 'onKeyPress' for input arguments of type 'matlab.ui.Figure'.
Error while evaluating Figure KeyPressFcn."
|
91f48b3675fb59652c089b81c395a992
|
{
"intermediate": 0.3518734276294708,
"beginner": 0.349752813577652,
"expert": 0.2983737587928772
}
|
9,224
|
Give me a video summarization algorithm that only selects the frames with motion in them. within python also, please
|
b442f87ac9a057cbe9b0af68d61fed80
|
{
"intermediate": 0.15490306913852692,
"beginner": 0.04735628515481949,
"expert": 0.797740638256073
}
|
9,225
|
"close all;
clear all;
clc
figure();
global t;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
imshow(grid);
snake = [10 10; 10 9; 10 8];
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
score = 0;
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
if all(snake(1,:) == food)
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 1;
snake = [snake; snake(end,:)]; % add a new segment to the tail
score = score + 1;
end
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
function moveSnake(~, ~)
% update the position of the snake here
end
function gameOver()
global t;
stop(t);
text(10,10,'GAME OVER','HorizontalAlignment','center');
end"
this code give me the following error
"Undefined function 'onKeyPress' for input arguments of type 'matlab.ui.Figure'.
Error while evaluating Figure KeyPressFcn."
|
acc08b532a5eacb9d2aa02e3d11a6977
|
{
"intermediate": 0.3651008903980255,
"beginner": 0.38691383600234985,
"expert": 0.24798521399497986
}
|
9,226
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import asyncio
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000))
frame = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time',
'Quote asset volume', 'Number of trades', 'Taker buy base asset volume',
'Taker buy quote asset volume', 'Ignore'])
frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # drop the last candle we fetched
return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop
if df is None:
continue
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 50, in <module>
df = getminutedata('BTCUSDT', '1m', '44640')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 41, in getminutedata
klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=str(time.time()*1000))
~~~~~~~~^~
TypeError: can only concatenate str (not "int") to str Give me right code
|
8ba6834ce0e60683df07e426245b68df
|
{
"intermediate": 0.36938726902008057,
"beginner": 0.3605802059173584,
"expert": 0.27003249526023865
}
|
9,227
|
I need a formula that will tell me the number of times a value in column F appears in Column D.
I also need another formula that will tell me the number of times a value in column F appears in Column D and also has a value in column B (column B is not empty).
|
f349753d3b8e7aa3223fce6a7550cb20
|
{
"intermediate": 0.42509087920188904,
"beginner": 0.21556788682937622,
"expert": 0.35934123396873474
}
|
9,228
|
provide LinCheck code that will prove that code below is not thread-safe
class ReferenceProblem {
private var data = mutableMapOf<String, String>()
fun getData() = data
fun refreshData(randomData: String) {
val freshData = LinkedHashMap<String, String>()
freshData[randomData] = randomData
data = freshData
}
}
|
a50d54c0d0687e87d1355b20c0b341cd
|
{
"intermediate": 0.3915722966194153,
"beginner": 0.5332979559898376,
"expert": 0.07512976974248886
}
|
9,229
|
"close all;
clear all;
clc
figure('Position', [100, 100, 400, 400]);
global t;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
% set color map
cmap = [1 1 1; 1 1 0; 0 0 0];
colormap(cmap);
% set snake color to white
snakeColor = 1;
imshow(grid, 'InitialMagnification', 'fit');
% initialize snake
snake = [10 10; 10 9; 10 8];
% set timer for snake movement
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
score = 0;
% set food location and color
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 2;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
function moveSnake(~, ~)
% update the position of the snake here
end
function gameOver()
global t;
stop(t);
text(10,10,'GAME OVER','HorizontalAlignment','center');
end
function onKeyPress(~, event)
global snakeDir
switch event.Key
case 'uparrow'
if ~isequal(snakeDir, [1 0])
snakeDir = [-1 0];
end
case 'downarrow'
if ~isequal(snakeDir, [-1 0])
snakeDir = [1 0];
end
case 'leftarrow'
if ~isequal(snakeDir, [0 1])
snakeDir = [0 -1];
end
case 'rightarrow'
if ~isequal(snakeDir, [0 -1])
snakeDir = [0 1];
end
end
end"
this code is snake game, but it didn't make any snake or food in game , it's just a black canvas, and score title it's under this canvas and nothing work.
make this game work
|
c144d19c56e259f786b67fc5c71baf1d
|
{
"intermediate": 0.37104374170303345,
"beginner": 0.2987489104270935,
"expert": 0.33020734786987305
}
|
9,230
|
in kotlin, i have a context menu linked to a button. is it possible to show it on normal press rather than long press, or am i misunderstanding how it works/
|
cb508d198eec50e4993a48af65862e52
|
{
"intermediate": 0.5702577233314514,
"beginner": 0.1656212955713272,
"expert": 0.2641209661960602
}
|
9,231
|
i have a kotlin app, and i want to store images in a database - i want to store locations of pictures as locations of them in internal storage. how can i do that? i already have a database schema prepared, with an image field of type string
|
790028632572f0cf2ea89d67b67c2af2
|
{
"intermediate": 0.5098758935928345,
"beginner": 0.19464856386184692,
"expert": 0.2954755425453186
}
|
9,232
|
"
close all;
clear all;
clc
figure('Position', [100, 100, 400, 400]);
global t snakeColor;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
% set color map
cmap = [1 1 1; 1 1 0; 0 0 0];
colormap(cmap);
% set snake color to white
snakeColor = 1;
imshow(grid, 'InitialMagnification', 'fit');
% initialize snake
snake = [10 10; 10 9; 10 8];
% set timer for snake movement
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
score = 0;
% set food location and color
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 2;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
function moveSnake(~, ~)
global snake snakeColor grid score
% update snake position
head = snake(1,:) + snakeDir;
if head(1) < 1 || head(1) > 20 || head(2) < 1 || head(2) > 20 || any(all(bsxfun(@eq,snake,head),2))
% collision with wall or self
gameOver();
return;
end
snake = [head; snake(1:end-1,:)];
% check for food collision
if isequal(head, food)
% increase score and generate new food
score = score + 1;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
food = [randi([1 20]) randi([1 20])];
while any(all(bsxfun(@eq,snake,food),2))
food = [randi([1 20]) randi([1 20])];
end
grid(food(1),food(2)) = 2;
end
% update grid
grid(:) = 0;
grid(sub2ind(size(grid), snake(:,1), snake(:,2))) = snakeColor;
grid(food(1),food(2)) = 2;
% update display
imshow(grid, 'InitialMagnification', 'fit');
end
function gameOver()
global t grid snake food score snakeColor
stop(t);
grid(sub2ind(size(grid), snake(:,1), snake(:,2))) = 0;
snake = [10 10; 10 9; 10 8];
grid(sub2ind(size(grid), snake(:,1), snake(:,2))) = snakeColor;
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 2;
score = 0;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
text(10,10,'GAME OVER','HorizontalAlignment','center');
end
function onKeyPress(~, event)
global snakeDir
switch event.Key
case 'uparrow'
if ~isequal(snakeDir, [1 0])
snakeDir = [-1 0];
end
case 'downarrow'
if ~isequal(snakeDir, [-1 0])
snakeDir = [1 0];
end
case 'leftarrow'
if ~isequal(snakeDir, [0 1])
snakeDir = [0 -1];
end
case 'rightarrow'
if ~isequal(snakeDir, [0 -1])
snakeDir = [0 1];
end
end
end"
this code is a snake game , but it didn't work well and give the following error
"Error while evaluating TimerFcn for timer 'timer-30'
Index in position 1 exceeds array bounds.
Index in position 2 exceeds array bounds.
Error in Snake>gameOver (line 77)
grid(sub2ind(size(grid), snake(:,1), snake(:,2))) = 0;
Error in Snake (line 29)
gameOver();"
|
5d335f52c5a21a519be77da83adc152b
|
{
"intermediate": 0.33428382873535156,
"beginner": 0.35717475414276123,
"expert": 0.3085414171218872
}
|
9,233
|
Can Lincheck check that 2 function use the same synchronized key ? Write working example
|
d321380e826c9f3a74e334d7eb4a89a1
|
{
"intermediate": 0.4914032518863678,
"beginner": 0.20743870735168457,
"expert": 0.30115807056427
}
|
9,234
|
"close all;
clear all;
clc
figure('Position', [100, 100, 400, 400]);
global t snake snakeColor grid score food score snakeColor snakeDir;
set(gcf,'KeyPressFcn',@onKeyPress);
grid = zeros(20,20);
% set color map
cmap = [1 1 1; 1 1 0; 0 0 0];
colormap(cmap);
% set snake color to white
snakeColor = 1;
imshow(grid, 'InitialMagnification', 'fit');
% initialize snake
snake = [10 10; 10 9; 10 8];
% set timer for snake movement
t = timer('ExecutionMode','fixedRate','Period',0.2,'TimerFcn',@moveSnake);
start(t);
if snake(1,1) < 1 || snake(1,1) > 20 || snake(1,2) < 1 || snake(1,2) > 20 || any(all(bsxfun(@eq,snake,snake(1,:)),2))
gameOver();
end
score = 0;
% set food location and color
food = [randi([1 20]) randi([1 20])];
grid(food(1),food(2)) = 2;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
disp(snake)
disp(size(snake))
function moveSnake(~, ~)
global snake snakeColor grid score
% update snake position
head = snake(1,:) + snakeDir;
if head(1) < 1 || head(1) > 20 || head(2) < 1 || head(2) > 20 || any(all(bsxfun(@eq,snake,head),2))
% collision with wall or self
gameOver();
return;
end
snake = [head; snake(1:end-1,:)];
% check for food collision
if isequal(head, food)
% increase score and generate new food
score = score + 1;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
food = [randi([1 20]) randi([1 20])];
while any(all(bsxfun(@eq,snake,food),2))
food = [randi([1 20]) randi([1 20])];
end
grid(food(1),food(2)) = 2;
end
% update grid
grid(:) = 0;
grid(sub2ind(size(grid), snake(:,1), snake(:,2))) = snakeColor;
grid(food(1),food(2)) = 2;
% update display
imshow(grid, 'InitialMagnification', 'fit');
end
function gameOver()
global t grid snake food score snakeColor
stop(t);
% remove snake from grid
if size(snake, 1) > 0
idx = sub2ind(size(grid), snake(:,1), snake(:,2));
grid(idx) = 0;
end
% reset snake and food
snake = [10 10; 10 9; 10 8];
food = [randi([1 20]) randi([1 20])];
while any(all(bsxfun(@eq,snake,food),2))
food = [randi([1 20]) randi([1 20])];
end
grid(food(1),food(2)) = 2;
% reset score and display
score = 0;
text(1,0.5,['SCORE: ' num2str(score)],'HorizontalAlignment','left');
text(10,10,'GAME OVER','HorizontalAlignment','center');
% add snake to grid
if size(snake, 1) > 0
idx = sub2ind(size(grid), snake(:,1), snake(:,2));
grid(idx) = snakeColor;
end
end
function onKeyPress(~, event)
global snakeDir
switch event.Key
case 'uparrow'
if ~isequal(snakeDir, [1 0])
snakeDir = [-1 0];
end
case 'downarrow'
if ~isequal(snakeDir, [-1 0])
snakeDir = [1 0];
end
case 'leftarrow'
if ~isequal(snakeDir, [0 1])
snakeDir = [0 -1];
end
case 'rightarrow'
if ~isequal(snakeDir, [0 -1])
snakeDir = [0 1];
end
end
end"
this is the snake game, but it's give the following error
"Error while evaluating TimerFcn for timer 'timer-44'
Unrecognized function or variable 'snakeDir'."
|
d32507520b04e97757e221d23a9ad7dc
|
{
"intermediate": 0.3117510974407196,
"beginner": 0.3895762860774994,
"expert": 0.298672616481781
}
|
9,235
|
I have the following ViewModel that manages the UI states for the following screens in Android(Compose): TipSelectionScreen, CustomTipScreen, TipPaymentScreen.
Can we split this logic by different delegates(classes) for each screen to simplify the ViewModel and also follow the single responsibility principle.
@HiltViewModel
internal class TippingViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val tipRepository: TipRepositoryApi,
private val paymentInteractor: PaymentInteractor,
) : ViewModel() {
private val tippingArgs = TippingArgs(savedStateHandle)
private var tipConfiguration = TipConfiguration.EMPTY
private var selectedTip: Tip? by Delegates.observable(null) { _, _, newValue ->
_tipSelectionUiState.update { state ->
state.copy(
customTip = if (newValue is Tip.CustomTip) newValue else Tip.CustomTip(null),
selectedTip = newValue
)
}
}
private val _sheetUiState: MutableStateFlow<TipSheetUiState> =
MutableStateFlow(TipSheetUiState.EMPTY)
val sheetUiState: StateFlow<TipSheetUiState> get() = _sheetUiState
private val _tipSelectionUiState: MutableStateFlow<TipSelectionUiState> =
MutableStateFlow(TipSelectionUiState.EMPTY)
val tipSelectionUiState: StateFlow<TipSelectionUiState>
get() = _tipSelectionUiState
private val _customTipUiState: MutableStateFlow<CustomTipUiState> =
MutableStateFlow(CustomTipUiState.EMPTY)
val customTipUiState: StateFlow<CustomTipUiState> get() = _customTipUiState
private val _tipPaymentUiState: MutableStateFlow<TipPaymentUiState> =
MutableStateFlow(TipPaymentUiState.EMPTY_DETAILS)
val tipPaymentUiState: StateFlow<TipPaymentUiState> get() = _tipPaymentUiState
private val _tipPaymentMethod: StateFlow<PaymentInteractor.PaymentMethodModel?> =
paymentInteractor.providePaymentMethod()
.asFlow()
.onEach { paymentMethod ->
_tipPaymentUiState.update { state ->
if (state is TipPaymentUiState.Details) {
state.copy(paymentMethod = paymentMethod)
} else {
state
}
}
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.Eagerly,
initialValue = null
)
fun onInit() {
viewModelScope.launch {
tipConfiguration = tipRepository.getTipConfiguration(tippingArgs.orderId)
_tipSelectionUiState.update { state ->
state.copy(
predefinedTips = tipConfiguration.predefinedAmounts
.map { Tip.PredefinedTip(it) },
currency = tipConfiguration.currency
)
}
_sheetUiState.update { state ->
state.copy(page = TipSheetPage.TIP_OPTIONS, showHeader = false)
}
}
}
fun onTipSelected(tip: Tip) {
if (tip is Tip.CustomTip) {
_customTipUiState.update {
CustomTipUiState(
customTip = tip.amount?.toString() ?: "",
currency = tipConfiguration.currency,
customTipCaption = if (tip.amount == null || tip.amount < tipConfiguration.excessiveTipAmount) {
CustomTipCaption.MinTip(tipConfiguration.minTipAmount)
} else {
CustomTipCaption.ExcessiveTip(tipConfiguration.excessiveTipPercentage)
},
isEditMode = tip.amount != null,
isButtonEnabled = tip.amount != null && tip.amount >= tipConfiguration.minTipAmount
)
}
_sheetUiState.update { state ->
state.copy(page = TipSheetPage.CUSTOM_TIP, showHeader = true)
}
} else {
selectedTip = tip
}
}
fun onFinishTipSelection() {
if (selectedTip == null || selectedTip?.amount == 0.0) {
_sheetUiState.update { state ->
state.copy(closeSheet = true)
}
} else {
_tipPaymentUiState.update {
TipPaymentUiState.Details(
value = "${selectedTip?.amount} ${tipConfiguration.currency}",
paymentMethod = _tipPaymentMethod.value,
isPaymentProcessing = false
)
}
_sheetUiState.update { state ->
state.copy(page = TipSheetPage.TIP_PAYMENT, showHeader = true)
}
}
}
fun onChangeCustomTipAmount(amount: String) {
val sanitizedAmount = if (amount.isNotBlank()) amount.sanitizeNumberString() else ""
val value = sanitizedAmount.toDoubleOrDefault(0.0)
_customTipUiState.update { state ->
state.copy(
customTip = sanitizedAmount,
customTipCaption = if (value < tipConfiguration.excessiveTipAmount) {
CustomTipCaption.MinTip(tipConfiguration.minTipAmount)
} else {
CustomTipCaption.ExcessiveTip(tipConfiguration.excessiveTipPercentage)
},
isButtonEnabled = value >= tipConfiguration.minTipAmount &&
!sanitizedAmount.endsWith('.')
)
}
}
fun onApplyCustomTip() {
val customTip = _customTipUiState.value.customTip.toDoubleOrNull() ?: 0.0
selectedTip = when {
tipConfiguration.predefinedAmounts.contains(customTip) -> Tip.PredefinedTip(
customTip
)
else -> Tip.CustomTip(customTip)
}
_sheetUiState.update { state ->
state.copy(page = TipSheetPage.TIP_OPTIONS, showHeader = false)
}
}
fun onPaymentOptions(fm: FragmentManager?) {
fm?.let { paymentInteractor.selectPaymentMethod(fm, tippingArgs.orderId) }
}
fun onSubmitTip() {
viewModelScope.launch {
try {
_tipPaymentUiState.update {
TipPaymentUiState.Details(
value = "${selectedTip?.amount} ${tipConfiguration.currency}",
paymentMethod = _tipPaymentMethod.value,
isPaymentProcessing = true
)
}
// TODO : Submit tip. The implementation is just a stub to have different conditions
delay(2000)
if (Random.nextDouble() > 0.5) throw Exception("Server request failed")
_sheetUiState.update { state ->
state.copy(showHeader = false)
}
_tipPaymentUiState.update { TipPaymentUiState.Success }
} catch (e: Exception) {
_sheetUiState.update { state ->
state.copy(showHeader = false)
}
_tipPaymentUiState.update { TipPaymentUiState.Error }
}
}
}
fun onRetryPayment() {
_sheetUiState.update { state ->
state.copy(showHeader = true)
}
_tipPaymentUiState.update {
TipPaymentUiState.Details(
value = "${selectedTip?.amount} ${tipConfiguration.currency}",
paymentMethod = _tipPaymentMethod.value,
isPaymentProcessing = false
)
}
}
fun back() {
_sheetUiState.update { state ->
when (state.page) {
TipSheetPage.NONE, TipSheetPage.TIP_OPTIONS -> state
TipSheetPage.CUSTOM_TIP, TipSheetPage.TIP_PAYMENT -> state.copy(
page = TipSheetPage.TIP_OPTIONS,
showHeader = false
)
}
}
}
}
|
a31c4741d50a4da24bbda1a7fd71388a
|
{
"intermediate": 0.3256226181983948,
"beginner": 0.45565441250801086,
"expert": 0.21872296929359436
}
|
9,236
|
is this code thread safe ?
class ReferenceProblem {
private var data = mutableMapOf<String, String>()
fun getData() = data
fun refreshData(randomData: String) {
val freshData = LinkedHashMap<String, String>()
freshData[randomData] = randomData
data = freshData
}
}
|
81dfb77504aef8607062fa77c10d2642
|
{
"intermediate": 0.4025548994541168,
"beginner": 0.5346965193748474,
"expert": 0.06274860352277756
}
|
9,237
|
i have a C# application containing wolflive.api and telegram.bot, i have a prefix called /send that stays running for a while, i need the user to be able to use any other prefixes while /send is running. this is my code for both prefixes: "else if (messageText.StartsWith("/ارسل"))
{
string jsonFromFiles = System.IO.File.ReadAllText("auth.json");
List<Auth> authilist = JsonConvert.DeserializeObject<List<Auth>>(jsonFromFiles);
var check = authilist.Where(x => x.ID == chatId).FirstOrDefault();
if (check == null)
{
Telegram.Bot.Types.Message cc = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "دخول غير مُصرح",
cancellationToken: cancellationToken);
}
else
{
var parts = Regex.Matches(messageText, @"[\""].+?[\""]|[^ ]+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
if (parts.Count >= 3)
{
string text = parts[1].Replace("\"", "");
string GroupID = parts[2];
string Times = parts[3];
string seconds = parts[4];
if (text != null || GroupID != null)
{
await Task.Run(async () =>
{
var cts = new CancellationTokenSource();
var po = new ParallelOptions { CancellationToken = cts.Token };
string logss = System.IO.File.ReadAllText("accounts.json");
List<AccountsList> accountsData = JsonConvert.DeserializeObject<List<AccountsList>>(logss);
try
{
Parallel.ForEach(accountsData,po, async item =>
{
var client = new WolfClient();
var loggedIn = await client.Login(item.Email, item.Password).ConfigureAwait(false);
if (!loggedIn)
{
Telegram.Bot.Types.Message senddMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "فشل تسجيل الدخول على حساب: " + item.Email,
cancellationToken: cancellationToken);
return;
}
if (Convert.ToInt32(Times) == 0 || Convert.ToInt32(seconds) == 0)
{
await client.GroupMessage(GroupID, text);
}
else
{
for (int i = 0; i < Convert.ToInt32(Times); i++)
{
var json = System.IO.File.ReadAllText("data.json");
MyData accountsFromFiles = JsonConvert.DeserializeObject<MyData>(json);
if (accountsFromFiles.IsRunning == true)
{
accountsFromFiles.IsRunning = false;
var jsons = JsonConvert.SerializeObject(accountsFromFiles);
System.IO.File.WriteAllText("data.json", jsons);
cts.Cancel();
}
try
{
po.CancellationToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
// Handle the task cancellation here if necessary
return; // Exit the current task / loop iteration
}
await client.GroupMessage(GroupID, text);
int waiting = Convert.ToInt32(seconds) * 1000;
Telegram.Bot.Types.Message se = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "أرسل " + item.Email + " الرسالة بنجاح.",
cancellationToken: cancellationToken);
Thread.Sleep(waiting);
}
}
});
}
catch (OperationCanceledException)
{
// Handle the cancellation here if necessary
}
});
}
else
{
Telegram.Bot.Types.Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
else
{
Telegram.Bot.Types.Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
else if (messageText.StartsWith("/انضم"))
{
string jsonFromFiles = System.IO.File.ReadAllText("auth.json");
List<Auth> authilist = JsonConvert.DeserializeObject<List<Auth>>(jsonFromFiles);
var check = authilist.Where(x => x.ID == chatId).FirstOrDefault();
if (check == null)
{
Telegram.Bot.Types.Message cc = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "دخول غير مُصرح",
cancellationToken: cancellationToken);
}
else
{
string[] parts = messageText.Split();
// The first line contains the command (“/add”)
string command = parts[0];
string GroupID = parts[1];
string Password = "";
if (parts.Length > 2)
{
Password = parts[2];
}
if (GroupID != null)
{
string logss = System.IO.File.ReadAllText("accounts.json");
List<AccountsList> accountsData = JsonConvert.DeserializeObject<List<AccountsList>>(logss);
Parallel.ForEach(accountsData, async item =>
{
var client = new WolfClient();
var loggedIn = await client.Login(item.Email, item.Password).ConfigureAwait(false);
if (!loggedIn)
{
Telegram.Bot.Types.Message senddMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "فشل تسجيل الدخول على حساب: " + item.Email,
cancellationToken: cancellationToken);
return;
}
if (Password == null)
{
await client.JoinGroup(GroupID);
}
else
{
await client.JoinGroup(GroupID, Password);
}
Telegram.Bot.Types.Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "إنضم " + item.Email + "للروم بنجاح.",
cancellationToken: cancellationToken);
});
}
else
{
Telegram.Bot.Types.Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
}"
|
4be2af9b042f2729b25a28b6f98afebf
|
{
"intermediate": 0.323093980550766,
"beginner": 0.43735992908477783,
"expert": 0.23954609036445618
}
|
9,238
|
Create a full code with all details about tortoise tts on google colabs, easy to use and access, can upload my audio files to clone my voice and generate other audios with text.
|
5de6d04d54d857cf5589f42eeb1a16fe
|
{
"intermediate": 0.5264797210693359,
"beginner": 0.13756461441516876,
"expert": 0.3359556794166565
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.