row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
13,059
I have a webpage. I need to do something on double-click event. However, it doesn't work on Mobile device. What is the related event on mobile?
cc121a04ea65cb55a845bd583faded76
{ "intermediate": 0.4404112994670868, "beginner": 0.2380930781364441, "expert": 0.3214956223964691 }
13,060
can you explain to me when statement in kotlin
d10fe17b841370b302660ce128439f04
{ "intermediate": 0.37470901012420654, "beginner": 0.3478579521179199, "expert": 0.27743300795555115 }
13,061
There is an xml as a string, need to extract some piece of xml. return result as string. use java
12f8ea0ceee98f1fc0199f3d0f52dab0
{ "intermediate": 0.5469579696655273, "beginner": 0.19072754681110382, "expert": 0.2623145580291748 }
13,062
#include "kdmapper.hpp" HANDLE iqvw64e_device_handle; LONG WINAPI SimplestCrashHandler(EXCEPTION_POINTERS* ExceptionInfo) { if (ExceptionInfo && ExceptionInfo->ExceptionRecord) Log(L"[!!] Crash at addr 0x" << ExceptionInfo->ExceptionRecord->ExceptionAddress << L" by 0x" << std::hex << ExceptionInfo->ExceptionRecord->ExceptionCode << std::endl); else Log(L"[!!] Crash" << std::endl); if (iqvw64e_device_handle) intel_driver::Unload(iqvw64e_device_handle); return EXCEPTION_EXECUTE_HANDLER; } int paramExists(const int argc, wchar_t** argv, const wchar_t* param) { size_t plen = wcslen(param); for (int i = 1; i < argc; i++) { if (wcslen(argv[i]) == plen + 1ull && _wcsicmp(&argv[i][1], param) == 0 && argv[i][0] == '/') { // with slash return i; } else if (wcslen(argv[i]) == plen + 2ull && _wcsicmp(&argv[i][2], param) == 0 && argv[i][0] == '-' && argv[i][1] == '-') { // with double dash return i; } } return -1; } void help() { Log(L"\r\n\r\n[!] Incorrect Usage!" << std::endl); Log(L"[+] Usage: kdmapper.exe [--free][--mdl][--PassAllocationPtr] driver" << std::endl); } bool callbackExample(ULONG64* param1, ULONG64* param2, ULONG64 allocationPtr, ULONG64 allocationSize, ULONG64 mdlptr) { UNREFERENCED_PARAMETER(param1); UNREFERENCED_PARAMETER(param2); UNREFERENCED_PARAMETER(allocationPtr); UNREFERENCED_PARAMETER(allocationSize); UNREFERENCED_PARAMETER(mdlptr); Log("[+] Callback example called" << std::endl); /* This callback occurs before call driver entry and can be usefull to pass more customized params in the last step of the mapping procedure since you know now the mapping address and other things */ return true; } int wmain(const int argc, wchar_t** argv) { SetUnhandledExceptionFilter(SimplestCrashHandler); bool free = paramExists(argc, argv, L"free") > 0; bool mdlMode = paramExists(argc, argv, L"mdl") > 0; bool passAllocationPtr = paramExists(argc, argv, L"PassAllocationPtr") > 0; if (free) { Log(L"[+] Free pool memory after usage enabled" << std::endl); } if (mdlMode) { Log(L"[+] Mdl memory usage enabled" << std::endl); } if (passAllocationPtr) { Log(L"[+] Pass Allocation Ptr as first param enabled" << std::endl); } int drvIndex = -1; for (int i = 1; i < argc; i++) { if (std::filesystem::path(argv[i]).extension().string().compare(".sys") == 0) { drvIndex = i; break; } } if (drvIndex <= 0) { help(); return -1; } const std::wstring driver_path = argv[drvIndex]; if (!std::filesystem::exists(driver_path)) { Log(L"[-] File " << driver_path << L" doesn't exist" << std::endl); return -1; } iqvw64e_device_handle = intel_driver::Load(); if (iqvw64e_device_handle == INVALID_HANDLE_VALUE) return -1; std::vector<uint8_t> raw_image = { 0 }; if (!utils::ReadFileToMemory(driver_path, &raw_image)) { Log(L"[-] Failed to read image to memory" << std::endl); intel_driver::Unload(iqvw64e_device_handle); return -1; } NTSTATUS exitCode = 0; if (!kdmapper::MapDriver(iqvw64e_device_handle, raw_image.data(), 0, 0, free, true, mdlMode, passAllocationPtr, callbackExample, &exitCode)) { Log(L"[-] Failed to map " << driver_path << std::endl); intel_driver::Unload(iqvw64e_device_handle); return -1; } if (!intel_driver::Unload(iqvw64e_device_handle)) { Log(L"[-] Warning failed to fully unload vulnerable driver " << std::endl); } Log(L"[+] success" << std::endl); } make it wait for me to close it
0525f6a14a19df930c5e743fbad24ece
{ "intermediate": 0.3489318788051605, "beginner": 0.3625887930393219, "expert": 0.2884793281555176 }
13,063
write a ds rom zip file lsd dream emulator but code it to make it more like the backrooms by kane pixels
0fab434fe4691bea0e2b94f8205fe899
{ "intermediate": 0.3243115246295929, "beginner": 0.23167885839939117, "expert": 0.4440096318721771 }
13,064
Есть файл Galvene.php <?php // Example 27-2: header.php session_start(); echo <<<_INIT <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='stylesheet' href='jquery.mobile-1.4.5.min.css'> <link rel='stylesheet' href='styles.css' type='text/css'> <script src='javascript.js'></script> <script src='jquery-2.2.4.min.js'></script> <script src='jquery.mobile-1.4.5.min.js'></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Manrope&display=swap" rel="stylesheet"> _INIT; require_once 'functions.php'; $userstr = 'Viesis'; if (isset($_SESSION['user'])) { $user = $_SESSION['user']; $loggedin = TRUE; } else $loggedin = FALSE; echo <<<_MAIN <title>Uzskaite</title> </head> <body> <a href="https://rezeknestehnikums.lv/" id="logo-header"></a> _MAIN; if ($loggedin) { echo <<<_LOGGEDIN <button id="Dezures" onclick="showTable('table1'); hideTextContainer();">Dežurēs</button> <button id="Audzēkņu-Uzskaite" onclick="showTable('table2'); hideTextContainer();">Audzēkņu uzskaite</button> <div id="ZilsUzskaitesFons"></div> <div id="FonaTekstura"></div> <div id="ZalsTabulasFons"></div> <div id="TabulasZona"> <div id="table1" class="table-container"> <?php include 'table_1.php'; ?> </div> <div id="table2" class="table-container"> <?php include 'table_2.php'; ?> </div> <div id="text-container"> <p>Izveleties datu bazi augšeja saites daļa</p> </div> </div> <button id="PogaPievienosana" onclick="openModal()">Pievienot</button> <div id="modal" class="modal"></div> <a href="ielogoties.php" id="PogaIziet">Iziet</a> <button id="TekstaPogaMeklēt"> <div id="search"></div>Meklēt </button> <button id="TekstaPogaMainit">Mainit</button> <div id="TabulasVirsraksts">Datu baze</div> _LOGGEDIN; } else { echo <<<_GUEST <div id="ZalsFons"></div> <div id="FonaTekstura"></div> <button id="SadalaPieteiktiesPiekluvejs" onclick="show('LoginForm'); hideTextContainer();">Pieteikties piekļuvej</button> <button id="SadalaIelogoties" onclick="show('RegisterForm'); hideTextContainer();">Ielogoties</button> <div id="LoginForm" class="table-container"> <?php include 'Ielogoties.php'; ?> </div> <div id="RegisterForm" class="table-container"> <?php include 'PieteiksanasPiekluvej.php'; ?> </div> _GUEST; } ?> Есть файл functions.php <?php // Example 27-1: functions.php $dbhost = '10.0.114.137'; // Unlikely to require changing $dbname = 'meiksans'; // Modify these... $dbuser = 'meiksans'; // ...variables according $dbpass = '7450'; // ...to your installation $connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ($connection->connect_error) die("Fatala kļuda"); echo "<br>"; function createTable($name, $query) { queryMysql("CREATE TABLE IF NOT EXISTS $name($query)"); echo "Tabula '$name' ir izveidota vai jau eksiste.<br>"; } function queryMysql($query) { global $connection; $result = $connection->query($query); if (!$result) die("Fatala kļuda"); return $result; } function destroySession() { $_SESSION=array(); if (session_id() != "" || isset($_COOKIE[session_name()])) setcookie(session_name(), '', time()-2592000, '/'); session_destroy(); } function sanitizeString($var) { global $connection; $var = strip_tags($var); $var = htmlentities($var); if (get_magic_quotes_gpc()) $var = stripslashes($var); return $connection->real_escape_string($var); } function showProfile($user) { if (file_exists("$user.jpg")) echo "<img src='$user.jpg' style='float:left;'>"; $result = queryMysql("SELECT * FROM profiles WHERE user='$user'"); if ($result->num_rows) { $row = $result->fetch_array(MYSQLI_ASSOC); echo stripslashes($row['text']) . "<br style='clear:left;'><br>"; } else echo "<p>Nav apraksta!</p><br>"; } function showTable(tableId) { var tables = document.getElementsByClassName('table-container'); for (var i = 0; i < tables.length; i++) { tables[i].style.display = 'none'; } document.getElementById(tableId).style.display = 'block'; } function hideTextContainer() { var textContainer = document.getElementById('text-container'); textContainer.style.display = 'none'; } function openModal() { var modal = document.getElementById('modal'); modal.style.display = 'block'; } function show($formId) { echo "document.getElementById('RegisterForm').style.display = 'none';"; echo "document.getElementById('LoginForm').style.display = 'none';"; echo "document.getElementById('$formId').style.display = 'block';"; echo "hideTextContainer();"; // Optionally hide the text container } function closeModal() { var modal = document.getElementById('modal'); modal.style.display = 'none'; } // Take information from table $sqltable1 = "SELECT * FROM dežures"; $sqltable2 = "SELECT * FROM audzekņu uzskaite"; $result1 = $connection->query($sqltable1); $result2 = $connection->query($sqltable2); $table = "-"; ?>
5b0cf4155f22b8bc6562771d775cb7f5
{ "intermediate": 0.34689077734947205, "beginner": 0.44729772210121155, "expert": 0.2058115005493164 }
13,065
write ai_sponge in javascript
668d43a63c37a49c1e1f5588bb21a565
{ "intermediate": 0.35192495584487915, "beginner": 0.2939710319042206, "expert": 0.35410407185554504 }
13,066
what is a spin glass?
1c44d20df9dfdc990b30b884f526869c
{ "intermediate": 0.317240834236145, "beginner": 0.3873177468776703, "expert": 0.2954414486885071 }
13,067
Write java code to create a circle object and control it with directional keys
b7960b090ccb1dc2d20ba70aa1e1ecaa
{ "intermediate": 0.5011893510818481, "beginner": 0.21018551290035248, "expert": 0.2886251211166382 }
13,068
Hi. I'm using react-hook-form and react-tag-input. I'm trying to prevent form submission on hitting 'enter' button. This is my code, I'm trying to use e.preventDefault() but it's not working.. could you help? import * as React from 'react'; import * as i from 'types'; import { TagsInput } from 'react-tag-input-component'; import { FormField } from 'common/form'; import { Container } from './styled'; const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(', '); } return []; }; export const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const formFieldProps = { name, label, error, description }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([...formatValue(value), inputValue]); e.target.value = ''; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === 'DIV') { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === 'INPUT') { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter') { console.log(e); e.preventDefault(); } }; return ( <FormField {...formFieldProps}> <Container isError={!!error} onClick={handleClick} onKeyDown={handleKeyUp} > <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={handleKeyUp} /> </Container> </FormField> ); }; type TagInputProps = i.FormFieldProps & { onChange: (value: string[]) => void; value: string[]; placeholder?: string; isError?: boolean; };
31b896ffc087e5aee39926d11d014934
{ "intermediate": 0.3905034363269806, "beginner": 0.4721653163433075, "expert": 0.13733120262622833 }
13,069
Hi. I’m using react-hook-form and react-tag-input. I’m trying to prevent form submission on hitting ‘enter’ button. This is my code, I’m trying to use e.preventDefault() but it’s not working… could you help? import * as React from ‘react’; import * as i from ‘types’; import { TagsInput } from ‘react-tag-input-component’; import { FormField } from ‘common/form’; import { Container } from ‘./styled’; const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(', '); } return []; }; export const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const formFieldProps = { name, label, error, description }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([…formatValue(value), inputValue]); e.target.value = ‘’; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === ‘DIV’) { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === ‘INPUT’) { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === ‘Enter’) { console.log(e); e.preventDefault(); } }; return ( <FormField {…formFieldProps}> <Container isError={!!error} onClick={handleClick} onKeyDown={handleKeyUp} > <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={handleKeyUp} /> </Container> </FormField> ); }; type TagInputProps = i.FormFieldProps & { onChange: (value: string[]) => void; value: string[]; placeholder?: string; isError?: boolean; };
8127b4c5aa88d39bcc1c8f259b677380
{ "intermediate": 0.5103192329406738, "beginner": 0.3479680120944977, "expert": 0.1417127400636673 }
13,070
Which 3 deliverables should an enterprise architect focus on when starting the enterprise archicture discipline in a company
e9de3ba20042db495414b32b9c8e7c1f
{ "intermediate": 0.27385085821151733, "beginner": 0.39693060517311096, "expert": 0.3292185068130493 }
13,071
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> </head> <title>Chat GPT3</title> <style> body { font-family: sans-serif; background-color: #f0f0f0; } .chat-container { width: 500px; margin: 0 auto; background-color: #fff; border: 1px solid #ccc; border-radius: 5px; padding: 10px; margin-top: 20px; } .chat-container h1 { font-weight: normal; margin-top: 0; } .chat-container p { margin: 0; padding: 5px; background-color: #eee; border-radius: 5px; } .chat-container p.user { text-align: right; } .chat-container p.ai { text-align: left; } .chat-container input { width: 100%; border: 1px solid #ccc; border-radius: 5px; margin-top: 5px; padding: 5px; } .chat-container button { padding: 5px 10px; border: 0; border-radius: 5px; background-color: #0084ff; color: #fff; cursor: pointer; } </style> </head> <body> <div class="chat-container"> <h1>Chat GPT3</h1> <div id="chat-box"></div> <input type="text" id="nickname" placeholder="nickname"/> <input type="text" id="chat-input" placeholder="Type your message..."/> <button id="chat-send">Send</button> </div> <script>
1a642a665470c26342bd309504716534
{ "intermediate": 0.29109856486320496, "beginner": 0.3910101354122162, "expert": 0.31789126992225647 }
13,072
how javascript turn array to string with separater ";"
6f3e910ef56810bc5e7a003a326bfc6e
{ "intermediate": 0.45069146156311035, "beginner": 0.24247223138809204, "expert": 0.3068363666534424 }
13,073
Hello
3dc4812dc420178e5e0002e08d1a6764
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
13,074
how form submit with post method to pass an array with the form data?
c017756a90c98fc3e61c619a37bda51d
{ "intermediate": 0.7028231024742126, "beginner": 0.12667572498321533, "expert": 0.17050114274024963 }
13,075
Can you help me with a javascript function to termine if locally the week starts on monday or sunday?
d4209ea28c6595d5c72bac0ab9475111
{ "intermediate": 0.418290913105011, "beginner": 0.32232925295829773, "expert": 0.2593797743320465 }
13,076
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>3D Music sequencer</title> <script> const ROWS = 8; // total number of rows const COLS = 16; // total number of columns const CELLSIZE = 50; // size of each cell in pixels const COLORS = [“#ff0000”, “#00ff00”, “#0000ff”, “#ffff00”, “#ff00ff”, “#00ffff”, “#cccccc”, “#ffffff”]; // available colors for cells let drums = []; // array to hold 3D drum sequencer data let selectedColor = “#ff0000”; // default selected color // initialize the 3D drum sequencer with empty cells function init() { for (let i = 0; i < ROWS; i++) { let row = []; for (let j = 0; j < COLS; j++) { let col = []; for (let k = 0; k <= 3; k++) { col.push(false); } row.push(col); } drums.push(row); } } // draw the 3D drum sequencer on the canvas function draw() { let canvas = document.getElementById(“canvas”); let ctx = canvas.getContext(“2d”); // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // draw the cells for (let i = 0; i < ROWS; i++) { for (let j = 0; j < COLS; j++) { for (let k = 0; k <= 3; k++) { if (drums[i][j][k]) { ctx.fillStyle = COLORS[k]; ctx.fillRect(j * CELLSIZE, k * CELLSIZE + i * CELLSIZE, CELLSIZE, CELLSIZE); } } } } // draw grid lines ctx.strokeStyle = “black”; for (let i = 0; i <= ROWS; i++) { ctx.beginPath(); ctx.moveTo(0, i * CELLSIZE); ctx.lineTo(COLS * CELLSIZE, i * CELLSIZE); ctx.stroke(); } for (let j = 0; j <= COLS; j++) { ctx.beginPath(); ctx.moveTo(j * CELLSIZE, 0); ctx.lineTo(j * CELLSIZE, ROWS * CELLSIZE); ctx.stroke(); } } // update the selected color function setColor(color) { selectedColor = color; } // handle cell clicks function handleClick(event) { let cellX = Math.floor(event.offsetX / CELLSIZE); let cellY = Math.floor(event.offsetY / CELLSIZE); for (let k = 0; k <= 3; k++) { if (drums[cellY][cellX][k] && COLORS[k] == selectedColor) { drums[cellY][cellX][k] = false; // remove cell } else if (!drums[cellY][cellX][k] && COLORS[k] == selectedColor) { drums[cellY][cellX][k] = true; // add cell } } draw(); // redraw canvas } // add event listeners function addListeners() { // handle color clicks let colorButtons = document.getElementsByClassName(“color-button”); for (let i = 0; i < colorButtons.length; i++) { colorButtons[i].addEventListener(“click”, function() { setColor(COLORS[i]); }); } // handle cell clicks let canvas = document.getElementById(“canvas”); canvas.addEventListener(“click”, handleClick); } // start the sequencer function start() { let beat = 0; setInterval(function() { // play the drums for the current beat for (let i = 0; i < ROWS; i++) { for (let j = 0; j < COLS; j++) { for (let k = 0; k <= 3; k++) { if (drums[i][j][k] && k == beat) { let audio = new Audio(“drum-” + k + “.mp3”); audio.play(); } } } } // update the beat counter beat++; if (beat > 3) { beat = 0; } }, 400); // 400 milliseconds per beat } // initialize, draw, and add event listeners to the sequencer function main() { init(); draw(); addListeners(); } // start the sequencer when the page is loaded window.onload = function() { main(); start(); }; </script> <style> canvas { border: 1px solid black; } .color-button { width: 30px; height: 30px; border-radius: 15px; margin-right: 10px; cursor: pointer; display: inline-block; } .color-button:hover { transform: scale(1.2); } </style> </head> <body> <h1>3D Music sequencer</h1> <canvas id=“canvas” width=“800” height=“400”></canvas> <br/> <div> Colors: <div class=“color-button” style=“background-color: #ff0000;”></div> <div class=“color-button” style=“background-color: #00ff00;”></div> <div class=“color-button” style=“background-color: #0000ff;”></div> <div class=“color-button” style=“background-color: #ffff00;”></div> <div class=“color-button” style=“background-color: #ff00ff;”></div> <div class=“color-button” style=“background-color: #00ffff;”></div> <div class=“color-button” style=“background-color: #cccccc;”></div> <div class=“color-button” style=“background-color: #ffffff;”></div> </div> <script>
970af370dc77dcba4645f1127da2412d
{ "intermediate": 0.3754059076309204, "beginner": 0.4180244207382202, "expert": 0.20656974613666534 }
13,077
php, how string with separater ";" to array
72b302da741d420af519d7aede43f6be
{ "intermediate": 0.3715966045856476, "beginner": 0.43477582931518555, "expert": 0.19362764060497284 }
13,078
I want to know if the week starts on a monday or a friday by calculating it in a javascript function
03eb2d3e5364f0a98647c941dd64a176
{ "intermediate": 0.35613584518432617, "beginner": 0.4136618673801422, "expert": 0.23020221292972565 }
13,079
Hi. I’m using react-hook-form and react-tag-input-component. I’m trying to prevent form submission on hitting ‘enter’ button. This is my code, I’m trying to use e.preventDefault() but it’s not working… could you help? import * as React from ‘react’; import * as i from ‘types’; import { TagsInput } from ‘react-tag-input-component’; import { FormField } from ‘common/form’; import { Container } from ‘./styled’; const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(', '); } return []; }; export const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const formFieldProps = { name, label, error, description }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([…formatValue(value), inputValue]); e.target.value = ‘’; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === ‘DIV’) { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === ‘INPUT’) { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === ‘Enter’) { console.log(e); e.preventDefault(); } }; return ( <FormField {…formFieldProps}> <Container isError={!!error} onClick={handleClick} onKeyDown={handleKeyUp} > <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={handleKeyUp} /> </Container> </FormField> ); }; type TagInputProps = i.FormFieldProps & { onChange: (value: string[]) => void; value: string[]; placeholder?: string; isError?: boolean; };
69dbe24ba12f2f221ab0d5edc57d5317
{ "intermediate": 0.482404500246048, "beginner": 0.40359053015708923, "expert": 0.11400498449802399 }
13,080
in KoBo codding with excel how I can code a field with multiple constraints
d4edb7e5136923e1da27a9a6e277a898
{ "intermediate": 0.3202700912952423, "beginner": 0.1456444263458252, "expert": 0.5340854525566101 }
13,081
hi, in javascript. Ho do i get the key of an dictionary by value, when the values are arrays
d31ab2e7825bfc16147c3ad58a1bb20f
{ "intermediate": 0.504457950592041, "beginner": 0.23025572299957275, "expert": 0.2652863562107086 }
13,082
You are Max/Msp/jitter expert.
e7dd9dcbca2a5d5f60b91f0aa8093c9c
{ "intermediate": 0.3893737494945526, "beginner": 0.26406559348106384, "expert": 0.34656065702438354 }
13,083
this is my r model mod.elastic, how to find my cv error?
418048e2115c01e732ba3b3992458a6b
{ "intermediate": 0.2767564356327057, "beginner": 0.2577706575393677, "expert": 0.46547290682792664 }
13,084
In Unity my Trail Renderer's trail is left behind, when parent object moves. How do I make it operate in local space?
5cc0c13cf370744d54a948de8953111a
{ "intermediate": 0.4375052750110626, "beginner": 0.30470994114875793, "expert": 0.25778481364250183 }
13,085
where we are writing the aqua query in Zuora
e6ed1ceb7d62d2214c0e36e514cf7312
{ "intermediate": 0.40364870429039, "beginner": 0.2921234965324402, "expert": 0.3042278587818146 }
13,086
Is it true to say that there are two main methodologies in machine learning: supervised and unsupervised learning?
cc98f963dec42f8e8ec25262331f47cd
{ "intermediate": 0.13066807389259338, "beginner": 0.1173774003982544, "expert": 0.7519544959068298 }
13,087
Помоги исправить код. Мне нужно чтоб на пине 0 генерировался одинаковый сигнал частотой 1 мегагерц 0 1. #include <soc/rtc.h> #include "driver/i2s.h" static const i2s_port_t i2s_num = (i2s_port_t)0; // i2s port number //static i2s_config_t i2s_config; static const i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_DAC_BUILT_IN), .sample_rate = 44100, //not really used .bits_per_sample = (i2s_bits_per_sample_t)I2S_BITS_PER_SAMPLE_16BIT, .channel_format = I2S_CHANNEL_FMT_ONLY_RIGHT, .communication_format = I2S_COMM_FORMAT_STAND_MSB, .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, .dma_buf_count = 2, .dma_buf_len = 1024 //big buffers to avoid noises }; void setup() { // Serial.begin(115200); //setCpuFrequencyMhz(240); //highest cpu frequency i2s_driver_install(i2s_num, &i2s_config, 0, NULL); //start i2s driver i2s_set_pin(i2s_num, NULL); //use internal DAC i2s_set_sample_rates(i2s_num, 22050); //dummy sample rate, since the function fails at high values } short buff[1024]; void loop() { buff[0]=0b1000001; buff[2]=0b1110111; buff[512]=0xFF; size_t bytes_written; i2s_write(i2s_num, (char*)buff, sizeof(buff), &bytes_written, portMAX_DELAY); }
3a48661d4f940212275bd1af5aeab762
{ "intermediate": 0.27667948603630066, "beginner": 0.5786325335502625, "expert": 0.14468802511692047 }
13,088
how to get in python an n element array from a n+1 element input array, which contents are the differences of consecutive elemnts
be08d9b4d8dc68523d8d05143593ead1
{ "intermediate": 0.49371138215065, "beginner": 0.11736703664064407, "expert": 0.3889215290546417 }
13,089
how to get next half hour with date-fns
7d4a9883e63d4aed715d4c9d2e90ef23
{ "intermediate": 0.4122420847415924, "beginner": 0.27966636419296265, "expert": 0.3080914616584778 }
13,090
write 1 random programm on "dart language"
be6dc10fd844eba73138376645917f6e
{ "intermediate": 0.25633591413497925, "beginner": 0.3803592920303345, "expert": 0.36330482363700867 }
13,091
I am working in Excel VB, the following range (Range("$A$1:$I$70")), is selecting the whole range until reaching the 70th row, how to make the number 70 a variable that indicate the last filled column
5553b660c3d4668020a3829226e19b05
{ "intermediate": 0.3832426965236664, "beginner": 0.4243847727775574, "expert": 0.19237256050109863 }
13,092
<Route path="Verzeichnis" element={<Verzeichnis />}> <Route path="VerzeichnisOverview" element={<VerzeichnisOverview />} /> </Route> what is wrong here?
0f5212e9de1831003f130260b17f8847
{ "intermediate": 0.36526843905448914, "beginner": 0.3446556031703949, "expert": 0.2900759279727936 }
13,093
hi
6e5d0a2e0cc667522fa31802dacfd4e9
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,094
how to create combobox in tkinter
6502192f3a82af79a33b99b5dab445cb
{ "intermediate": 0.2654183804988861, "beginner": 0.15632981061935425, "expert": 0.578251838684082 }
13,095
(heart_venv) PS C:\Users\lpoti\Documents\DS_21\DS12-1-develop\src> pylint heart ************* Module heart.train heart\train.py:41:0: C0301: Line too long (102/100) (line-too-long) heart\train.py:109:0: C0304: Final newline missing (missing-final-newline) heart\train.py:14:0: E0401: Unable to import 'entities' (import-error) heart\train.py:15:0: E0401: Unable to import 'data' (import-error) heart\train.py:16:0: E0401: Unable to import 'features' (import-error) heart\train.py:17:0: E0401: Unable to import 'models' (import-error) heart\train.py:35:0: R0914: Too many local variables (19/15) (too-many-locals) ************* Module heart.data.make_dataset heart\data\make_dataset.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.data heart\data\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.config heart\entities\config.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.feature heart\entities\feature.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.models heart\entities\models.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities\models.py:20:4: C0103: Attribute name "C" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.entities heart\entities\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities\__init__.py:8:4: E0603: Undefined variable name 'ModelConfigRFConfigLogregConfig' in __all__ (undefined-all-variable) ************* Module heart.features.build_features heart\features\build_features.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\features\build_features.py:96:30: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:21: C0103: Argument name "y" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: W0613: Unused argument 'x' (unused-argument) heart\features\build_features.py:112:21: W0613: Unused argument 'y' (unused-argument) heart\features\build_features.py:122:24: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.features.__init__ heart\features\__init__.py:7:0: C0304: Final newline missing (missing-final-newline) heart\features\__init__.py:6:0: C0301: Line too long (107/100) (line-too-long) ************* Module heart.features heart\features\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.fit heart\models\fit.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\fit.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\models\fit.py:35:4: C0415: Import outside toplevel (pickle) (import-outside-toplevel) heart\models\fit.py:36:31: C0103: Variable name "f" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.models.predict heart\models\predict.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\predict.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.__init__ heart\models\__init__.py:16:0: C0304: Final newline missing (missing-final-newline) ************* Module heart.models heart\models\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ------------------------------------------------------------------ Your code has been rated at 7.18/10 (previous run: 4.64/10, +2.54)
76fb5fa3b2c229201a82698901bb6214
{ "intermediate": 0.3965549170970917, "beginner": 0.37655532360076904, "expert": 0.22688975930213928 }
13,096
what does meen -i in fastboot
bfeb2b74a10436b587d05e1a7ce576db
{ "intermediate": 0.3960886299610138, "beginner": 0.380952924489975, "expert": 0.22295843064785004 }
13,097
(heart_venv) PS C:\Users\lpoti\Documents\DS_21\DS12-1-develop\src> pylint heart ************* Module heart.train heart\train.py:41:0: C0301: Line too long (102/100) (line-too-long) heart\train.py:109:0: C0304: Final newline missing (missing-final-newline) heart\train.py:14:0: E0401: Unable to import ‘entities’ (import-error) heart\train.py:15:0: E0401: Unable to import ‘data’ (import-error) heart\train.py:16:0: E0401: Unable to import ‘features’ (import-error) heart\train.py:17:0: E0401: Unable to import ‘models’ (import-error) heart\train.py:35:0: R0914: Too many local variables (19/15) (too-many-locals) ************* Module heart.data.make_dataset heart\data\make_dataset.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.data heart\data_init_.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.config heart\entities\config.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.feature heart\entities\feature.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.models heart\entities\models.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities\models.py:20:4: C0103: Attribute name “C” doesn’t conform to snake_case naming style (invalid-name) ************* Module heart.entities heart\entities_init_.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities_init_.py:8:4: E0603: Undefined variable name ‘ModelConfigRFConfigLogregConfig’ in all (undefined-all-variable) ************* Module heart.features.build_features heart\features\build_features.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\features\build_features.py:96:30: C0103: Argument name “x” doesn’t conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: C0103: Argument name “x” doesn’t conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:21: C0103: Argument name “y” doesn’t conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: W0613: Unused argument ‘x’ (unused-argument) heart\features\build_features.py:112:21: W0613: Unused argument ‘y’ (unused-argument) heart\features\build_features.py:122:24: C0103: Argument name “x” doesn’t conform to snake_case naming style (invalid-name) ************* Module heart.features.init heart\features_init_.py:7:0: C0304: Final newline missing (missing-final-newline) heart\features_init_.py:6:0: C0301: Line too long (107/100) (line-too-long) ************* Module heart.features heart\features_init_.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.fit heart\models\fit.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\fit.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\models\fit.py:35:4: C0415: Import outside toplevel (pickle) (import-outside-toplevel) heart\models\fit.py:36:31: C0103: Variable name “f” doesn’t conform to snake_case naming style (invalid-name) ************* Module heart.models.predict heart\models\predict.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\predict.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.init heart\models_init_.py:16:0: C0304: Final newline missing (missing-final-newline) ************* Module heart.models heart\models_init_.py:1:0: C0114: Missing module docstring (missing-module-docstring) ------------------------------------------------------------------ Your code has been rated at 7.18/10 (previous run: 4.64/10, +2.54) The Python code has been run through pylint, a Python code analysis tool, which generates a report with a score of 7.18 out of 10. The report highlights several issues in the code such as line too long, missing docstrings, too many local variables, and invalid variable naming. These issues can affect the code’s readability, maintainability, and reliability. The report recommends making improvements and adhering to PEP 8 style guide recommendations for cleaner and more consistent code. поможешь мне исправить ошибки? Конечно, я могу помочь исправить найденные ошибки. Давайте начнем с наиболее критических проблем, которые могут повлиять на работу программы. 1. Ошибка импорта В файле heart/train.py есть следующие строки: import entities import data import features import models Они вызывают ошибку импорта и в результате дальнейшее выполнение кода становится невозможным. Исправим их следующим образом: from heart.entities import * from heart.data import * from heart.features import * from heart.models import * 2. Слишком длинная строка В файле heart/train.py есть строка, которая превышает максимальную длину строки: def train_and_evaluate(X_train: pd.DataFrame, X_test: pd.DataFrame, y_train: pd.DataFrame, y_test: pd.DataFrame, model_type: str, model_hyperparams: dict, model_path: str, scores_path: str, transformer: transformers.Transformer): Рекомендуется разбить ее на несколько строк: def train_and_evaluate( X_train: pd.DataFrame, X_test: pd.DataFrame, y_train: pd.DataFrame, y_test: pd.DataFrame, model_type: str, model_hyperparams: dict, model_path: str, scores_path: str, transformer: transformers.Transformer ): 3. Отсутствие финальной новой строки В файлах heart/train.py, heart.models.fit.py, heart.models.predict.py, heart.features.__init__.py, heart.models.__init__.py, heart.data.make_dataset.py отсутствует финальная новая строка. Добавим ее в каждый из этих файлов для того, чтобы избежать ошибки линтера: # add a blank line at the end of the file 4. Очень много локальных переменных В файле heart/train.py есть функция train_and_evaluate, которая имеет слишком много локальных переменных, что затрудняет понимание кода. Предлагаю выделить эту функцию на несколько более простых функций, чтобы сократить количество локальных переменных. 5. Неверное именование переменных Некоторые переменные не соответствуют принятому в Python стилю именования. Например, ModelConfigRFConfigLogregConfig в heart.entities.__init__.py, f в heart.models.fit.py. Рекомендуется переименовать эти переменные в соответствии с принятым стилем именования в Python. 6. Ошибки в аргументах функций В файле heart/features/build_features.py есть функция normalize_data, которая принимает два аргумента, x и y, однако они не используются внутри функции. Рекомендуется удалить их: def normalize_data(df: pd.DataFrame) -> pd.DataFrame: … Также в функции build_transformer в heart/features/build_features.py аргумент x должен быть переименован в df. # Bad code def build_transformer(x: pd.DataFrame, features_params: Dict[str, Union[str, List[str]]]) -> Transformers: … # Good code def build_transformer(df: pd.DataFrame, features_params: Dict[str, Union[str, List[str]]]) -> Transformers: … 7. Ошибки в использовании all В файлах heart.entities.__init__.py и heart.transformers.__init__.py используется переменная __all__, но ее значение не указывает на все имена модулей, которые хотят экспортировать. Предлагаю следующий вариант: # heart/entities/init.py from .config import * from .feature import * from .models import * all = [ ‘ModelConfig’, ‘RFConfig’, ‘LogregConfig’, ‘FeatureParams’, ‘Entity’, ‘DataFrameColumn’, ] # heart/transformers/init.py from .build_transformer import * all = [ ‘Transformers’, ‘build_transformer’, ] Это позволит явно указать, какие именно объекты должны быть экспортированы. После исправления вышеуказанных ошибок можно заново запустить линтер и убедиться, что он больше не выдает ошибки. Вот сам код: “”“ Модуль для обучения модели и выполнения тренировочного пайплайна. ”“” import pickle import os import json import logging import logging.config import hydra import pandas as pd from entities import TrainingPipelineConfig from data import read_data, split_train_test_data from features import build_transformer, make_features, extract_target from models import train_model, predict_model, evaluate_model logger = logging.getLogger(name) def prepare_val_features_for_predict( train_features: pd.DataFrame, val_features: pd.DataFrame ) -> pd.DataFrame: “”“ Подготавливает валидационные признаки для прогнозирования. :param train_features: DataFrame с обучающими признаками. :param val_features: DataFrame с валидационными признаками. :return: DataFrame с подготовленными валидационными признаками. “”” train_features, val_features = train_features.align(val_features, join=“left”, axis=1) val_features = val_features.fillna(0) return val_features def train_pipeline(params: TrainingPipelineConfig) -> None: “”“E2E функция для обучения модели”“” logger.info(“Начало выполнения пайплайна”) data = read_data(params.dataset.input_data_path) logger.info(“Размер данных: %s”, data.shape) train_df, test_df = split_train_test_data(data, params.split.test_size, params.split.random_state) logger.info(“Размер обучающего набора данных: %s”, train_df.shape) logger.info(“Размер тестового набора данных: %s”, test_df.shape) logger.info(“Начало преобразований”) transformer = build_transformer( categorical_features=params.feature.categorical_features, numerical_features=params.feature.numerical_features, ) transformer.fit(train_df) train_features = make_features(transformer, train_df) train_target = extract_target(train_df, params.feature.target_col) logger.info(“Размер обучающих признаков: %s”, train_features.shape) model = train_model( params.model.model_params, train_features, train_target ) test_features = make_features(transformer, test_df) test_target = extract_target(test_df, params.feature.target_col) val_features_prepared = prepare_val_features_for_predict( train_features, test_features ) logger.info(“Размер валидационных признаков: %s”, val_features_prepared.shape) predicts = predict_model( model, val_features_prepared ) metrics = evaluate_model( predicts, test_target ) metrics_output_dir = os.path.join(os.getcwd(), ‘metrics’) model_output_dir = os.path.join(os.getcwd(), ‘models’) os.makedirs(metrics_output_dir, exist_ok=True) metrics_filepath = os.path.join( metrics_output_dir, f"{params.model.model_name}.json" ) with open(metrics_filepath, “w”, encoding=“utf-8”) as metric_file: json.dump(metrics, metric_file) logger.info(“Метрики: %s”, metrics) logger.info(“Метрики сохранены в файл: %s”, metrics_filepath) os.makedirs(model_output_dir, exist_ok=True) models_filepath = os.path.join( model_output_dir, f"{params.model.model_name}.pkl" ) # Сохранение модели в файл with open(models_filepath, “wb”) as model_file: pickle.dump(model, model_file) logger.info(“Модель сохранена в файл: %s”, models_filepath) logger.info(“Обучение завершено”) @hydra.main(config_path=“…/configs”, config_name=“config”, version_base=“1.1”) def main(cfg: TrainingPipelineConfig = None) -> None: “”“Основная функция для настройки логгера и запуска train_pipeline”“” train_pipeline(cfg) if name == “main”: main() исправь пожалуйста
f812b9d1a2af6b6c9fb7ead8fa684b20
{ "intermediate": 0.34970876574516296, "beginner": 0.35170334577560425, "expert": 0.2985878884792328 }
13,098
(heart_venv) PS C:\Users\lpoti\Documents\DS_21\DS12-1-develop\src> pylint heart ************* Module heart.train heart\train.py:41:0: C0301: Line too long (102/100) (line-too-long) heart\train.py:109:0: C0304: Final newline missing (missing-final-newline) heart\train.py:14:0: E0401: Unable to import 'entities' (import-error) heart\train.py:15:0: E0401: Unable to import 'data' (import-error) heart\train.py:16:0: E0401: Unable to import 'features' (import-error) heart\train.py:17:0: E0401: Unable to import 'models' (import-error) heart\train.py:35:0: R0914: Too many local variables (19/15) (too-many-locals) ************* Module heart.data.make_dataset heart\data\make_dataset.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.data heart\data\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.config heart\entities\config.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.feature heart\entities\feature.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.entities.models heart\entities\models.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities\models.py:20:4: C0103: Attribute name "C" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.entities heart\entities\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\entities\__init__.py:8:4: E0603: Undefined variable name 'ModelConfigRFConfigLogregConfig' in __all__ (undefined-all-variable) ************* Module heart.features.build_features heart\features\build_features.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\features\build_features.py:96:30: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:21: C0103: Argument name "y" doesn't conform to snake_case naming style (invalid-name) heart\features\build_features.py:112:18: W0613: Unused argument 'x' (unused-argument) heart\features\build_features.py:112:21: W0613: Unused argument 'y' (unused-argument) heart\features\build_features.py:122:24: C0103: Argument name "x" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.features.__init__ heart\features\__init__.py:7:0: C0304: Final newline missing (missing-final-newline) heart\features\__init__.py:6:0: C0301: Line too long (107/100) (line-too-long) ************* Module heart.features heart\features\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.fit heart\models\fit.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\fit.py:1:0: C0114: Missing module docstring (missing-module-docstring) heart\models\fit.py:35:4: C0415: Import outside toplevel (pickle) (import-outside-toplevel) heart\models\fit.py:36:31: C0103: Variable name "f" doesn't conform to snake_case naming style (invalid-name) ************* Module heart.models.predict heart\models\predict.py:38:0: C0304: Final newline missing (missing-final-newline) heart\models\predict.py:1:0: C0114: Missing module docstring (missing-module-docstring) ************* Module heart.models.__init__ heart\models\__init__.py:16:0: C0304: Final newline missing (missing-final-newline) ************* Module heart.models heart\models\__init__.py:1:0: C0114: Missing module docstring (missing-module-docstring) ------------------------------------------------------------------ Your code has been rated at 7.18/10 (previous run: 4.64/10, +2.54)
4fccfcd4e34ea4e92504506a8563773b
{ "intermediate": 0.3965549170970917, "beginner": 0.37655532360076904, "expert": 0.22688975930213928 }
13,099
""" Модуль для обучения модели и выполнения тренировочного пайплайна. """ import os import json import logging import logging.config import pickle import hydra import pandas as pd from entities import entities from data import data from features import features from models import models logger = logging.getLogger(name) def prepare_val_features_for_predict( train_features: pd.DataFrame, val_features: pd.DataFrame ) -> pd.DataFrame: """ Подготавливает валидационные признаки для прогнозирования. :param train_features: DataFrame с обучающими признаками. :param val_features: DataFrame с валидационными признаками. :return: DataFrame с подготовленными валидационными признаками. "" train_features, val_features = train_features.align(val_features, join="left", axis=1) val_features = val_features.fillna(0) return val_features def train_pipeline(params: entities.TrainingPipelineConfig) -> None: """E2E функция для обучения модели""" logger.info("Начало выполнения пайплайна") data = data.read_data(params.dataset.input_data_path) logger.info("Размер данных: %s", data.shape) train_df, test_df = data.split_train_test_data(data, params.split.test_size, params.split.random_state) logger.info("Размер обучающего набора данных: %s", train_df.shape) logger.info("Размер тестового набора данных: %s", test_df.shape) logger.info("Начало преобразований") transformer = features.build_transformer( categorical_features=params.feature.categorical_features, numerical_features=params.feature.numerical_features, ) transformer.fit(train_df) train_features = features.make_features(transformer, train_df) train_target = features.extract_target(train_df, params.feature.target_col) logger.info("Размер обучающих признаков: %s", train_features.shape) model = models.train_model( params.model.model_params, train_features, train_target ) test_features = features.make_features(transformer, test_df) test_target = features.extract_target(test_df, params.feature.target_col) val_features_prepared = prepare_val_features_for_predict( train_features, test_features ) logger.info("Размер валидационных признаков: %s", val_features_prepared.shape) predicts = models.predict_model( model, val_features_prepared ) metrics = models.evaluate_model( predicts, test_target ) metrics_output_dir = os.path.join(os.getcwd(), ‘metrics’) model_output_dir = os.path.join(os.getcwd(), ‘models’) os.makedirs(metrics_output_dir, exist_ok=True) metrics_filepath = os.path.join( metrics_output_dir, f"{params.model.model_name}.json" ) with open(metrics_filepath, "w", encoding="utf-8") as metric_file: json.dump(metrics, metric_file) logger.info("Метрики: %s", metrics) logger.info("Метрики сохранены в файл: %s", metrics_filepath) os.makedirs(model_output_dir, exist_ok=True) models_filepath = os.path.join( model_output_dir, f"{params.model.model_name}.pkl" ) # Сохранение модели в файл with open(models_filepath, "wb") as model_file: pickle.dump(model, model_file) logger.info("Модель сохранена в файл: %s", models_filepath) logger.info("Обучение завершено") @hydra.main(config_path="…/configs", config_name="config", version_base="1.1") def main(cfg: entities.TrainingPipelineConfig = None) -> None: """Основная функция для настройки логгера и запуска train_pipeline""" train_pipeline(cfg) if name == "main": main()
050f04f6d514e9678705a46bc955bf82
{ "intermediate": 0.32682880759239197, "beginner": 0.39710843563079834, "expert": 0.2760626971721649 }
13,100
i need to write a search screen. This is where user enters what they want to find import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native'; import { gStyle } from '../styles/style'; import { Feather } from '@expo/vector-icons'; import React, { useState, useEffect } from 'react'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; export default function Header() { const [searchTerm, setSearchTerm] = useState(''); const [searchResult, setSearchResult]= useState(''); const handleSearch = async ()=>{ const futureMKSnapshot = await firebase .firestore() .collection('FutureMK') .where('name','>=',searchTerm) .where('name','<=',searchTerm + '\uf8ff') .get(); const pastMKSnapshot = await firebase .firestore() .collection('PastMK') .where('name','>=',searchTerm) .where('name','<=',searchTerm + '\uf8ff') .get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); const results = [...futureMKData, ...pastMKData]; setSearchResult(results); navigation.navigate('Search', { results }); }; const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require('../assets/logo.png')} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType='fade' transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Home')} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllFutureMK')} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllPastMK')} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Sales')} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate('Profile')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate('Auth')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder="Поиск" onChangeText={(text)=>setSearchTerm(text)} /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name="search" size={25} color="white" /> </Pressable> </View> </View> </View> ); } here is my collections FutureMK import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import { useNavigation } from '@react-navigation/native'; import {firebase} from '../Firebase/firebase'; import moment from 'moment'; import 'firebase/compat/storage'; import 'firebase/compat/firestore'; export default function FutureMK({limit}) { const navigation = useNavigation(); const [futureMKData, setFutureMKData] = useState([]); useEffect(() => { const fetchData = async () => { try { let futureMKRef=firebase.firestore().collection('FutureMK').orderBy('time', 'desc'); if (limit){ futureMKRef=futureMKRef.limit(limit); } const snapshot = await futureMKRef.get(); const data = snapshot.docs.map((doc) => ({id:doc.id, ... doc.data()})); const storage=firebase.storage(); const updatedData = await Promise.all(data.map(async(mkData)=>{ const imagePath = mkData.image; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {...mkData, image:url}; })) setFutureMKData(updatedData); } catch (error) { console.log('Error:',error); console.log('futureMKData:', futureMKData); console.log('mkData:', mkData); } }; fetchData(); }, [limit]); return ( <View style={gStyle.main}> {futureMKData.map((mkData)=>( <View key={mkData.id} style={gStyle.mainFMK}> <Text style={gStyle.dateFutureMK}>{new Intl.DateTimeFormat('ru-RU',{ day:'numeric', month:'long', year:'numeric', hour:'numeric', minute:'numeric', hour12:false }).format(mkData.time.toDate())}</Text> <View style={gStyle.FutureMKimg}> <Image source={{uri:mkData.image}} style={gStyle.FutureMKbannerImg}/> <Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> </View> <Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text> <Text style={gStyle.FutureMKdescription}> {mkData.description.length>100 ? mkData.description.substring(0,300)+'...' : mkData.description} </Text> <Pressable style={gStyle.FutureMKmoreDetails} onPress={()=>{navigation.navigate('SignUpForMK',{mkData});}} > <Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text> </Pressable> <Text style={gStyle.FutureMKline}></Text> </View> ))} </View> ); } PastMK import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import { useNavigation } from '@react-navigation/native'; import {firebase} from '../Firebase/firebase'; import 'firebase/compat/storage'; import 'firebase/compat/firestore'; import React, {useState, useEffect} from 'react'; export default function PastMK({limit}) { const navigation = useNavigation(); const [pastMKData, setPastMKData]=useState([]); useEffect(()=>{ const fetchData=async()=>{ try{ let pastMKRef=firebase.firestore().collection('PastMK').orderBy('time','desc'); if(limit){ pastMKRef=pastMKRef.limit(limit); } const snapshot=await pastMKRef.get(); const data = snapshot.docs.map((doc)=>({id: doc.id, ... doc.data()})); const storage=firebase.storage(); const updatedData=await Promise.all( data.map(async (mkData)=>{ const imagePath = mkData.image; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {... mkData, image:url}; }), ); setPastMKData(updatedData); }catch (error){ console.log('Error:', error); } }; fetchData(); },[limit]); return ( <View style={gStyle.main}> {pastMKData.map((mkData)=>( <View key={mkData.id} style={gStyle.PastMKbox}> <View style={gStyle.PastMKcontainer}> <View style={gStyle.PastMKbox1}> <View style={gStyle.PastMKpastImg}> <Image source={{uri: mkData.image}} style={gStyle.PastMKimg} /> <View style={gStyle.PastMKinfo}> <Text style={gStyle.PastMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.PastMKdateOfMK}>{new Intl.DateTimeFormat('ru-RU',{ day:'numeric', month:'long', year:'numeric' }).format(mkData.time.toDate())}</Text> </View> </View> <Text style={gStyle.PastMKdescription}> {mkData.description.length > 100 ? mkData.description.substring(0, 300) + '...' : mkData.description} </Text> <Pressable style={gStyle.PastMKreadMore} onPress={()=>navigation.navigate('PastMKInfo',{mkData})}> <Text style={gStyle.PastMKtxtBtn}>Читать далее</Text> </Pressable> </View> </View> <Text style={gStyle.PastMKline}></Text> </View> ))} </View> ); } its my component of result import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React from 'react'; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: 'column' }}> <View style={gStyle.ProfileDetails}> <Image source={{uri:item.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+'...' : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.deletebtn} > <Text>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } its the search screen import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from 'react-native'; import { gStyle } from '../styles/style'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { useNavigation, useRoute } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState} from 'react'; import Result from '../components/Result'; export default function Search() { const navigation = useNavigation(); const route = useRoute(); const results = route.params?.results || []; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <Text style={gStyle.header}>Результаты поиска</Text> <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: 'column' }}> {results.length > 0 ? ( results.map((item, index)=> <Result key={index} item={item}/>) ): ( <Text>Не найдено.</Text> )} </View> </View> </View> <Footer/> </ScrollView> </View> ); } it shows me all posts from my both collections but not what i want to find
f88634ababa601f724a2063f67c40fbc
{ "intermediate": 0.40265119075775146, "beginner": 0.4978470504283905, "expert": 0.09950178116559982 }
13,101
how to generate a 5 symbol unique id that contains numbers and letters in js?
b04d26990277b769386506ff3ff8095c
{ "intermediate": 0.33928602933883667, "beginner": 0.15532144904136658, "expert": 0.5053924918174744 }
13,102
import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 0.0; double ceiling = 0; double ballPositionX = 0; double ballPositionY = 0; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; double rotationAngle = 0.0; double previousVelocityMagnitude = 0; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } @override void didChangeDependencies() { super.didChangeDependencies(); ballPositionY = MediaQuery.of(context).size.height * 0.9; ballPositionX = MediaQuery.of(context).size.width / 2; } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { double velocityMagnitude = (ballVelocityX.abs().ceil() + ballVelocityY.abs().ceil()).toDouble(); double deltaVelocity = velocityMagnitude - previousVelocityMagnitude; previousVelocityMagnitude = velocityMagnitude; setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; if (ballPositionY + AppConstants.ballSize / 2 >= floor) { ballPositionY = floor - AppConstants.ballSize / 2; ballVelocityX *= friction; if ((ballVelocityY * ballVelocityY) < 4) { ballVelocityY = 0; } else { ballVelocityY *= -restitution; } } else if (ballPositionY - AppConstants.ballSize / 2 <= ceiling) { ballPositionY = ceiling + AppConstants.ballSize / 2; ballVelocityY *= -restitution; } else if ((ballVelocityY * ballVelocityY) + (ballVelocityX * ballVelocityX) < 5) { ballVelocityY = 0; ballVelocityX = 0; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } rotationAngle += deltaVelocity; }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Image.asset( 'assets/background.png', fit: BoxFit.fitWidth, ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.shieldWidth / 2, top: MediaQuery.of(context).size.height * 0.2, child: Image.asset( 'assets/shield.png', width: AppConstants.shieldWidth, height: AppConstants.shieldHeight, fit: BoxFit.fitWidth, ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: Transform.rotate( angle: (rotationAngle + previousVelocityMagnitude) / 100, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), ), ), ), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); Hello, i have a Flutter app. It consists of ball, background, and ring. They positioned on the screen using Stack widget, ball can change it cooridantes emulating real ball behavior, and the ring is . How to position ring and ball on one layer if they are in Stack widget, which overlay widgets one on another. I want the ball to have possibility to collide with the ring.
4b781420f94cc60de31e094c4f2b4af7
{ "intermediate": 0.33608442544937134, "beginner": 0.5007917881011963, "expert": 0.16312380135059357 }
13,103
import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 0.0; double ceiling = 0; double ballPositionX = 0; double ballPositionY = 0; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; double rotationAngle = 0.0; double previousVelocityMagnitude = 0; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } @override void didChangeDependencies() { super.didChangeDependencies(); ballPositionY = MediaQuery.of(context).size.height * 0.9; ballPositionX = MediaQuery.of(context).size.width / 2; } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { double velocityMagnitude = (ballVelocityX.abs().ceil() + ballVelocityY.abs().ceil()).toDouble(); double deltaVelocity = velocityMagnitude - previousVelocityMagnitude; previousVelocityMagnitude = velocityMagnitude; setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; if (ballPositionY + AppConstants.ballSize / 2 >= floor) { ballPositionY = floor - AppConstants.ballSize / 2; ballVelocityX *= friction; if ((ballVelocityY * ballVelocityY) < 4) { ballVelocityY = 0; } else { ballVelocityY *= -restitution; } } else if (ballPositionY - AppConstants.ballSize / 2 <= ceiling) { ballPositionY = ceiling + AppConstants.ballSize / 2; ballVelocityY *= -restitution; } else if ((ballVelocityY * ballVelocityY) + (ballVelocityX * ballVelocityX) < 5) { ballVelocityY = 0; ballVelocityX = 0; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } rotationAngle += deltaVelocity; }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Image.asset( 'assets/background.png', fit: BoxFit.fitWidth, ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.shieldWidth / 2, top: MediaQuery.of(context).size.height * 0.2, child: Image.asset( 'assets/shield.png', width: AppConstants.shieldWidth, height: AppConstants.shieldHeight, fit: BoxFit.fitWidth, ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: Transform.rotate( angle: (rotationAngle + previousVelocityMagnitude) / 100, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), ), ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.ringWidth / 2, top: MediaQuery.of(context).size.height * 0.2 + 112, child: const Image( width: AppConstants.ringWidth, height: AppConstants.ringHeight, image: AssetImage('assets/ring.png'), ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.ringWidth / 2 + 4, top: MediaQuery.of(context).size.height * 0.2 + 117, child: Container( height: 8, width: 4, color: Colors.black, ), ), Positioned( left: MediaQuery.of(context).size.width / 2 + AppConstants.ringWidth / 2 - 6, top: MediaQuery.of(context).size.height * 0.2 + 117, child: Container( height: 8, width: 4, color: Colors.black, ), ), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); I have Flutter app that simulates the ball behavior. Also i have a 2D projection of basketball ring. Imagine, you are looking at the basketball ring staying in front of it. You see just a projection of ring that looks like flat line. That what i have in my app. For better illustration I added two black containers, emulating edges of the ring. I want the ball to collide with the left and right edges of the ring. And if the ball moving from the above of the ring passes between this two container I want to print a message in console (to consider this as a score).
752591c7093a7d4f0c257c6c97e1ff4e
{ "intermediate": 0.33608442544937134, "beginner": 0.5007917881011963, "expert": 0.16312380135059357 }
13,104
i need to write a search screen. first it shows all posts from my both collections now it doesnt show any results import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native'; import { gStyle } from '../styles/style'; import { Feather } from '@expo/vector-icons'; import React, { useState, useEffect } from 'react'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; export default function Header() { const [searchTerm, setSearchTerm] = useState(''); const [searchResult, setSearchResult]= useState(''); const handleSearch = async ()=>{ const futureMKSnapshot = await firebase .firestore() .collection('FutureMK') .where('name','>=',searchTerm) .where('name','<=',searchTerm + '\uf8ff') .get(); const pastMKSnapshot = await firebase .firestore() .collection('PastMK') .where('name','>=',searchTerm) .where('name','<=',searchTerm + '\uf8ff') .get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data(), })); const results = [...futureMKData, ...pastMKData].filter(item=> item.name.toLowerCase().includes(searchTerm.toLowerCase())); setSearchResult(results); navigation.navigate('Search', { results }); }; const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require('../assets/logo.png')} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType='fade' transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Home')} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllFutureMK')} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllPastMK')} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Sales')} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate('Profile')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate('Auth')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder="Поиск" onChangeText={(text)=>setSearchTerm(text)} /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name="search" size={25} color="white" /> </Pressable> </View> </View> </View> ); } here is my collections FutureMK import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React, {useState, useEffect} from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import {firebase} from ‘…/Firebase/firebase’; import moment from ‘moment’; import ‘firebase/compat/storage’; import ‘firebase/compat/firestore’; export default function FutureMK({limit}) { const navigation = useNavigation(); const [futureMKData, setFutureMKData] = useState([]); useEffect(() => { const fetchData = async () => { try { let futureMKRef=firebase.firestore().collection(‘FutureMK’).orderBy(‘time’, ‘desc’); if (limit){ futureMKRef=futureMKRef.limit(limit); } const snapshot = await futureMKRef.get(); const data = snapshot.docs.map((doc) => ({id:doc.id, … doc.data()})); const storage=firebase.storage(); const updatedData = await Promise.all(data.map(async(mkData)=>{ const imagePath = mkData.image; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {…mkData, image:url}; })) setFutureMKData(updatedData); } catch (error) { console.log(‘Error:’,error); console.log(‘futureMKData:’, futureMKData); console.log(‘mkData:’, mkData); } }; fetchData(); }, [limit]); return ( <View style={gStyle.main}> {futureMKData.map((mkData)=>( <View key={mkData.id} style={gStyle.mainFMK}> <Text style={gStyle.dateFutureMK}>{new Intl.DateTimeFormat(‘ru-RU’,{ day:‘numeric’, month:‘long’, year:‘numeric’, hour:‘numeric’, minute:‘numeric’, hour12:false }).format(mkData.time.toDate())}</Text> <View style={gStyle.FutureMKimg}> <Image source={{uri:mkData.image}} style={gStyle.FutureMKbannerImg}/> <Text style={gStyle.FutureMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.hr}></Text> </View> <Text style={gStyle.FutureMKprice}>Цена: <Text style={gStyle.FutureMKrub}>{mkData.price} P.</Text></Text> <Text style={gStyle.FutureMKdescription}> {mkData.description.length>100 ? mkData.description.substring(0,300)+‘…’ : mkData.description} </Text> <Pressable style={gStyle.FutureMKmoreDetails} onPress={()=>{navigation.navigate(‘SignUpForMK’,{mkData});}} > <Text style={gStyle.FutureMKbtnTxt}>Подробнее</Text> </Pressable> <Text style={gStyle.FutureMKline}></Text> </View> ))} </View> ); } PastMK import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { useNavigation } from ‘@react-navigation/native’; import {firebase} from ‘…/Firebase/firebase’; import ‘firebase/compat/storage’; import ‘firebase/compat/firestore’; import React, {useState, useEffect} from ‘react’; export default function PastMK({limit}) { const navigation = useNavigation(); const [pastMKData, setPastMKData]=useState([]); useEffect(()=>{ const fetchData=async()=>{ try{ let pastMKRef=firebase.firestore().collection(‘PastMK’).orderBy(‘time’,‘desc’); if(limit){ pastMKRef=pastMKRef.limit(limit); } const snapshot=await pastMKRef.get(); const data = snapshot.docs.map((doc)=>({id: doc.id, … doc.data()})); const storage=firebase.storage(); const updatedData=await Promise.all( data.map(async (mkData)=>{ const imagePath = mkData.image; const imageRef = storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {… mkData, image:url}; }), ); setPastMKData(updatedData); }catch (error){ console.log(‘Error:’, error); } }; fetchData(); },[limit]); return ( <View style={gStyle.main}> {pastMKData.map((mkData)=>( <View key={mkData.id} style={gStyle.PastMKbox}> <View style={gStyle.PastMKcontainer}> <View style={gStyle.PastMKbox1}> <View style={gStyle.PastMKpastImg}> <Image source={{uri: mkData.image}} style={gStyle.PastMKimg} /> <View style={gStyle.PastMKinfo}> <Text style={gStyle.PastMKnameOfMK}>{mkData.name}</Text> <Text style={gStyle.PastMKdateOfMK}>{new Intl.DateTimeFormat(‘ru-RU’,{ day:‘numeric’, month:‘long’, year:‘numeric’ }).format(mkData.time.toDate())}</Text> </View> </View> <Text style={gStyle.PastMKdescription}> {mkData.description.length > 100 ? mkData.description.substring(0, 300) + ‘…’ : mkData.description} </Text> <Pressable style={gStyle.PastMKreadMore} onPress={()=>navigation.navigate(‘PastMKInfo’,{mkData})}> <Text style={gStyle.PastMKtxtBtn}>Читать далее</Text> </Pressable> </View> </View> <Text style={gStyle.PastMKline}></Text> </View> ))} </View> ); } its my component of result import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React from ‘react’; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> <View style={gStyle.ProfileDetails}> <Image source={{uri:item.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+‘…’ : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.deletebtn} > <Text>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } its the search screen import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { useNavigation, useRoute } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState} from ‘react’; import Result from ‘…/components/Result’; export default function Search() { const navigation = useNavigation(); const route = useRoute(); const results = route.params?.results || []; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <Text style={gStyle.header}>Результаты поиска</Text> <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> {results.length > 0 ? ( results.map((item, index)=> <Result key={index} item={item}/>) ): ( <Text>Не найдено.</Text> )} </View> </View> </View> <Footer/> </ScrollView> </View> ); }
75cb16fa1bbb787dd30b9bc4b20eb626
{ "intermediate": 0.3382408916950226, "beginner": 0.5047610402107239, "expert": 0.15699805319309235 }
13,105
import 'dart:async'; import 'package:basketball/constants.dart'; import 'package:flutter/material.dart'; class BouncingBallApp extends StatefulWidget { const BouncingBallApp({Key? key}) : super(key: key); @override BouncingBallAppState createState() => BouncingBallAppState(); } class BouncingBallAppState extends State<BouncingBallApp> { double floor = 0.0; double ceiling = 0; double ballPositionX = 0; double ballPositionY = 0; double ballVelocityX = 0; double ballVelocityY = 0; double gravity = 9.8; double restitution = 0.8; double friction = 0.98; bool isDragging = false; double rotationAngle = 0.0; double previousVelocityMagnitude = 0; @override void initState() { super.initState(); Timer.periodic(const Duration(milliseconds: 16), (timer) { _updateBall(16); }); } @override void didChangeDependencies() { super.didChangeDependencies(); ballPositionY = MediaQuery.of(context).size.height * 0.9; ballPositionX = MediaQuery.of(context).size.width / 2; } void _onPanStart(DragStartDetails details) { setState(() { isDragging = true; }); } void _onPanUpdate(DragUpdateDetails details) { setState(() { ballVelocityX += details.delta.dx; ballVelocityY += -details.delta.dy; }); } void _onPanEnd(DragEndDetails details) { setState(() { isDragging = false; ballVelocityX *= friction; ballVelocityY *= friction; }); } void _updateBall(double delta) { if (!isDragging) { double velocityMagnitude = (ballVelocityX.abs().ceil() + ballVelocityY.abs().ceil()).toDouble(); double deltaVelocity = velocityMagnitude - previousVelocityMagnitude; previousVelocityMagnitude = velocityMagnitude; setState(() { ballPositionX += ballVelocityX * delta / 100; ballPositionY += ballVelocityY * delta / 100; if (ballPositionY + AppConstants.ballSize / 2 >= floor) { ballPositionY = floor - AppConstants.ballSize / 2; ballVelocityX *= friction; if ((ballVelocityY * ballVelocityY) < 4) { ballVelocityY = 0; } else { ballVelocityY *= -restitution; } } else if (ballPositionY - AppConstants.ballSize / 2 <= ceiling) { ballPositionY = ceiling + AppConstants.ballSize / 2; ballVelocityY *= -restitution; } else if ((ballVelocityY * ballVelocityY) + (ballVelocityX * ballVelocityX) < 5) { ballVelocityY = 0; ballVelocityX = 0; } else { ballVelocityY += gravity * delta / 100; } if (ballPositionX < AppConstants.ballSize / 2) { ballPositionX = AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } else if (ballPositionX > MediaQuery.of(context).size.width - AppConstants.ballSize / 2) { ballPositionX = MediaQuery.of(context).size.width - AppConstants.ballSize / 2; ballVelocityX *= -restitution; ballVelocityY *= restitution; } rotationAngle += deltaVelocity; }); } } @override Widget build(BuildContext context) { floor = MediaQuery.of(context).size.height; return GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, child: Scaffold( body: Center( child: Stack( children: <Widget>[ Positioned.fill( child: Image.asset( 'assets/background.png', fit: BoxFit.fitWidth, ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.shieldWidth / 2, top: MediaQuery.of(context).size.height * 0.2, child: Image.asset( 'assets/shield.png', width: AppConstants.shieldWidth, height: AppConstants.shieldHeight, fit: BoxFit.fitWidth, ), ), Positioned( left: ballPositionX - AppConstants.ballSize / 2, top: ballPositionY - AppConstants.ballSize / 2, child: Transform.rotate( angle: (rotationAngle + previousVelocityMagnitude) / 100, child: const Image( width: AppConstants.ballSize, height: AppConstants.ballSize, image: AssetImage('assets/ball.png'), ), ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.ringWidth / 2, top: MediaQuery.of(context).size.height * 0.2 + 112, child: const Image( width: AppConstants.ringWidth, height: AppConstants.ringHeight, image: AssetImage('assets/ring.png'), ), ), Positioned( left: MediaQuery.of(context).size.width / 2 - AppConstants.ringWidth / 2 + 4, top: MediaQuery.of(context).size.height * 0.2 + 117, child: Container( height: 8, width: 4, color: Colors.black, ), ), Positioned( left: MediaQuery.of(context).size.width / 2 + AppConstants.ringWidth / 2 - 6, top: MediaQuery.of(context).size.height * 0.2 + 117, child: Container( height: 8, width: 4, color: Colors.black, ), ), ], ), ), ), ); } } void main() => runApp(MaterialApp(home: BouncingBallApp(key: UniqueKey()))); I have Flutter app that simulates the ball behavior. Also i have a 2D projection of basketball ring. Imagine, you are looking at the basketball ring staying in front of it. You see just a projection of ring that looks like flat line. That what i have in my app. For better illustration I added two black containers, emulating edges of the ring. I want the ball to collide with the left and right edges of the ring. And if the ball moving from the above of the ring passes between this two container I want to print a message in console (to consider this as a score).
3c7c8d75c0bdacb7cac8e36c7ca47164
{ "intermediate": 0.33608442544937134, "beginner": 0.5007917881011963, "expert": 0.16312380135059357 }
13,106
import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { Feather } from ‘@expo/vector-icons’; import React, { useState, useEffect } from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; export default function Header() { const [searchTerm, setSearchTerm] = useState(‘’); const [searchResult, setSearchResult]= useState(‘’); const handleSearch = async ()=>{ if(!searchTerm.trim()){ setSearchResult([]); return; } const futureMKSnapshot = await firebase .firestore() .collection(‘FutureMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const pastMKSnapshot = await firebase .firestore() .collection(‘PastMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const results = […futureMKData, …pastMKData].filter(item=> item.name.toLowerCase().includes(searchTerm.toLowerCase())); const storage=firebase.storage; const resultWithImages = await Promise.all( results.map(async item=>{ try{ const imagePath=item.image; const imageRef=storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {… item, image:url}; }catch(error){ console.log(‘Ошибка загрузки изображения: ‘, error); return item; } }) ) setSearchResult(resultWithImages); navigation.navigate(‘Search’, { results: resultWithImages }); }; const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require(’…/assets/logo.png’)} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType=‘fade’ transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Home’)} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllFutureMK’)} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllPastMK’)} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Sales’)} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate(‘Profile’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate(‘Auth’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder=“Поиск” onChangeText={(text)=>setSearchTerm(text)} /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name=“search” size={25} color=“white” /> </Pressable> </View> </View> </View> ); } import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React from ‘react’; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> <View style={gStyle.ProfileDetails}> <Image source={{uri:item.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+‘…’ : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.deletebtn} > <Text>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { useNavigation, useRoute } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState} from ‘react’; import Result from ‘…/components/Result’; export default function Search() { const navigation = useNavigation(); const route = useRoute(); const results = route.params?.results || []; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <Text style={gStyle.header}>Результаты поиска</Text> <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> {results.length > 0 ? ( results.map((item, index)=>( <Result key={index} item={item}/>)) ): ( <Text>Не найдено.</Text> )} </View> </View> </View> <Footer/> </ScrollView> </View> ); } still no pics
5b28518c720a68f0e77f75a0f090681a
{ "intermediate": 0.4578133523464203, "beginner": 0.36829638481140137, "expert": 0.17389026284217834 }
13,107
import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { Feather } from ‘@expo/vector-icons’; import React, { useState, useEffect } from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; export default function Header() { const [searchTerm, setSearchTerm] = useState(‘’); const [searchResult, setSearchResult]= useState(‘’); const handleSearch = async ()=>{ if(!searchTerm.trim()){ setSearchResult([]); return; } const futureMKSnapshot = await firebase .firestore() .collection(‘FutureMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const pastMKSnapshot = await firebase .firestore() .collection(‘PastMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const results = […futureMKData, …pastMKData].filter(item=> item.name.toLowerCase().includes(searchTerm.toLowerCase())); const storage=firebase.storage; const resultWithImages = await Promise.all( results.map(async item=>{ try{ const imagePath=item.image; const imageRef=storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {… item, image:url}; }catch(error){ console.log(‘Ошибка загрузки изображения: ‘, error); return item; } }) ) setSearchResult(resultWithImages); navigation.navigate(‘Search’, { results: resultWithImages }); }; const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require(’…/assets/logo.png’)} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType=‘fade’ transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Home’)} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllFutureMK’)} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllPastMK’)} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Sales’)} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate(‘Profile’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate(‘Auth’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder=“Поиск” onChangeText={(text)=>setSearchTerm(text)} /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name=“search” size={25} color=“white” /> </Pressable> </View> </View> </View> ); } import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React from ‘react’; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> <View style={gStyle.ProfileDetails}> <Image source={{uri:item.image}} style={gStyle.ProfileImg}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+‘…’ : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.deletebtn} > <Text>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity, Image } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import Header from ‘…/components/Header’; import Footer from ‘…/components/Footer’; import { useNavigation, useRoute } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; import React, {useState} from ‘react’; import Result from ‘…/components/Result’; export default function Search() { const navigation = useNavigation(); const route = useRoute(); const results = route.params?.results || []; return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <Text style={gStyle.header}>Результаты поиска</Text> <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> {results.length > 0 ? ( results.map((item, index)=>( <Result key={index} item={item}/>)) ): ( <Text>Не найдено.</Text> )} </View> </View> </View> <Footer/> </ScrollView> </View> ); } still no pics
090886e5e6a139e4b5a5792524f654c1
{ "intermediate": 0.4578133523464203, "beginner": 0.36829638481140137, "expert": 0.17389026284217834 }
13,108
summarize the following meeting : 00:00 So in college, I was a government major, 00:05 which means I had to write a lot of papers. 00:07 Now, when a normal student writes a paper, 00:08 they might spread the work out a little like this. 00:11 So you know, you get started maybe a little slowly, 00:16 but you get enough done in the first week 00:17 that with some heavier days later on, 00:20 everything gets done and things taste civil. 00:24 And I would wanna do that like that. 00:26 That would be the plan. 00:27 I would have it all ready to go, but then that's actually 00:31 the paper would come along and then I would kind of do this. 00:34 [LAUGHTER] 00:36 And that would happen every single paper. 00:39 But then it came my 90-page senior thesis. 00:43 The paper you're supposed to spend a year on. I knew for a paper 00:46 like that my normal workflow was not an option, it was way too big of a project. So I planned 00:51 things out and I decided I kind of had to go something like this. This is how the year we go. 00:56 So I'd start off light and I'd bump it up.
9348fcf0c8896df5a0426b333bd7be80
{ "intermediate": 0.3383439779281616, "beginner": 0.3609163165092468, "expert": 0.30073973536491394 }
13,109
What do you know about Lingo?
d9c662f4294c438d18935abef2cacce6
{ "intermediate": 0.3414718508720398, "beginner": 0.4190238118171692, "expert": 0.23950429260730743 }
13,110
how to write macro in dart that can convert the line Signal1<Enterprise> onIncomePerUnitChanged = Signal1(); to a simple name and type annotation
5f0b56a3782fb05add1f4cd63c946087
{ "intermediate": 0.5823196172714233, "beginner": 0.20494504272937775, "expert": 0.2127353399991989 }
13,111
how to write preprocessor macro in dart
b01ac0df8d6b99fdd4c61ba7e9ba63e2
{ "intermediate": 0.26326853036880493, "beginner": 0.4100666046142578, "expert": 0.32666486501693726 }
13,112
setup mongodb in my JavaScript discord bot
3c7ece23f75ca887e3c13def7a03cd71
{ "intermediate": 0.5292640924453735, "beginner": 0.1320340633392334, "expert": 0.3387017846107483 }
13,113
Give me example code in html with two modules, one importing the other, using script type=module
17821a701e65cca521714012a22c414e
{ "intermediate": 0.4973202049732208, "beginner": 0.2744632065296173, "expert": 0.22821663320064545 }
13,114
fig, axs = plt.subplots(1, 3, figsize=(16,5)) # plot the crosstab as a heatmap with percentage values inside the map sns.heatmap(crosstab1, annot=True, fmt='.2%', cmap='YlGnBu', ax=axs[0]) sns.heatmap(crosstab2, annot=True, fmt='.2%', cmap='YlGnBu', ax=axs[1]) sns.heatmap(crosstab3, annot=True, fmt='.2%', cmap='YlGnBu', ax=axs[2]) # add titles axs[0].set_title('Analysis vs. Vader Analysis') axs[1].set_title('Analysis vs. SWN Analysis') axs[2].set_title('Vader Analysis vs. SWN Analysis') plt.tight_layout() plt.show() complete the beginiing, my data is df_english_copy and the features are Analysis, Vader_Analysis and SWN_analysis. create at the beginning crosstab1, crosstab2, crosstab3
354c79d4c6a8056e39836b81e7628f8b
{ "intermediate": 0.37997183203697205, "beginner": 0.2990499436855316, "expert": 0.32097816467285156 }
13,115
Code to sort an array of numbers with emu 8086
33f0c1ef29e8389560ce6ee25e6b8bd1
{ "intermediate": 0.30834633111953735, "beginner": 0.1418658345937729, "expert": 0.5497878789901733 }
13,116
please create a counter function
91159931e0d0d734f7b6775f36119dde
{ "intermediate": 0.26272907853126526, "beginner": 0.3545800447463989, "expert": 0.3826908767223358 }
13,117
I have master workflow where I stored 1- 30 numbers in liquid in variables a,b,c, d to a4 so how can I access any 5 numbers in next workflow dynamically, Is that possible in zuora?
c145bb01ed255f669917609b51cd205f
{ "intermediate": 0.6767247915267944, "beginner": 0.11890321969985962, "expert": 0.20437198877334595 }
13,118
how to add 2 numbers in C++?
7af59ca0681a1a4fa2acb8641aa2711f
{ "intermediate": 0.35953289270401, "beginner": 0.25524142384529114, "expert": 0.38522568345069885 }
13,119
how can i remake snake's mechanics in JS?
c25ea0444cad6d4740c7a9c35362f3ff
{ "intermediate": 0.314219206571579, "beginner": 0.26433712244033813, "expert": 0.4214436113834381 }
13,120
cv create
3264d9d29d02d3a64776746fd264851a
{ "intermediate": 0.2534731328487396, "beginner": 0.1946636438369751, "expert": 0.5518632531166077 }
13,121
{% assign a = '1' %} {% assign b = '2' %} {% assign c = '3' %} {% assign d = '4' %} {% assign e = '5' %} {% assign f = '6' %} {% assign g = '7' %} {% assign h = '8' %} {% assign i = '9' %} {% assign j = '10' %} {% assign k = '11' %} {% assign l = '12' %} {% assign m = '13' %} {% assign n = '14' %} {% assign o = '15' %} {% assign p = '16' %} {% assign q = '17' %} {% assign r = '18' %} {% assign s = '19' %} {% assign t = '20' %} {% assign u = '21' %} {% assign v = '22' %} {% assign w = '23' %} {% assign x = '24' %} {% assign y = '25' %} {% assign z = '26' %} {% assign a1 = '27' %} {% assign a2 = '28' %} {% assign a3 = '29' %} {% assign a4 = '30' %} {{a}} {{b}} {{c}} {{d}} {{e}} {{f}} {{g}} {{h}} {{i}} {{j}} {{k}} {{l}} {{m}} {{n}} {{o}} {{p}} {{q}} {{r}} {{s}} {{t}} {{u}} {{v}} {{w}} {{x}} {{y}} {{z}} {{a1}} {{a2}} {{a3}} {{a4}}
bd6ad47273967f45c0ed987ba645b764
{ "intermediate": 0.41043177247047424, "beginner": 0.2421654313802719, "expert": 0.3474028408527374 }
13,122
php how string with separator ";" to array
788758a4a60151453e86eae6782e3729
{ "intermediate": 0.37942445278167725, "beginner": 0.4064006209373474, "expert": 0.21417488157749176 }
13,123
Code to sort up to 100 two-digit numbers and display it with emu 8086
b715a7047931c8e797768d9e93342eda
{ "intermediate": 0.2590998411178589, "beginner": 0.12337666749954224, "expert": 0.6175234913825989 }
13,124
spark处理日志代码例子
562249d184b3af1f279afe5a4cdd55ca
{ "intermediate": 0.37733033299446106, "beginner": 0.26732853055000305, "expert": 0.3553411662578583 }
13,125
write a fast fourier transform in python
0c697dad77119bac87c1891cdfb9a2a8
{ "intermediate": 0.20536206662654877, "beginner": 0.12449683994054794, "expert": 0.6701411008834839 }
13,126
i want schema for this {"_id":{"$oid":"64944e5cc0a7f3ac0957f0f6"},"7457quintsitsuki":"yuna"}
8769a921caac77bb91697b2deaf96eee
{ "intermediate": 0.1784033626317978, "beginner": 0.368760883808136, "expert": 0.4528357982635498 }
13,127
typescirpt function for react that on press of keyboard (enter) run a function
bebeaecd77640e46a1a9118a96c09930
{ "intermediate": 0.3465011715888977, "beginner": 0.34101077914237976, "expert": 0.3124880790710449 }
13,128
Object reference not set to an instance of an object. what is this error in vb.net
86f4771e7b123fed39aae909040e45dc
{ "intermediate": 0.4301331043243408, "beginner": 0.26779213547706604, "expert": 0.30207473039627075 }
13,129
source code of spark dealing with log file using function select and withColumn
e16b900a0c881d6408999a611eefa92c
{ "intermediate": 0.4171908497810364, "beginner": 0.3281829357147217, "expert": 0.25462624430656433 }
13,130
<InfoCardMy $token={token} $width="400px"> <Title>PG Status</Title> <DataWrapper> <PieChart width={350} height={200}> <Pie data={pgs} cx={120} cy={100} innerRadius={70} outerRadius={80} fill="#8884d8" paddingAngle={1} dataKey="value" > {pgs.map((entry, index) => ( <Cell key={`cell-${index}`} fill={COLORS_PGS[index % COLORS_PGS.length]} /> ))} </Pie> <Legend iconSize={10} layout="vertical" verticalAlign="middle" wrapperStyle={style} formatter={renderPGsLegend} /> </PieChart> <div className='add'> <span style={{ display: 'block' }}>{totalPGs}</span> <span style={{ display: 'block' }}>PGs</span> </div> </DataWrapper> </InfoCardMy> как закрепить div с классом add в определенном месте относительно блока DataWrapper?
e8e7db719b6132c906a5f6d47402ac1d
{ "intermediate": 0.2016102373600006, "beginner": 0.53089839220047, "expert": 0.2674914002418518 }
13,131
write this code in an easier way: import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; import java.time.Instant; import java.time.LocalDateTime; import java.util.List; import java.util.concurrent.TimeUnit; @Service public class RedisRateLimiter { private static final Logger logger = LoggerFactory.getLogger(RedisRateLimiter.class); @Autowired private StringRedisTemplate stringTemplate; private static final int REQUESTS_PER_HOUR = 10; public boolean isAllowed(String username) { final int hour = LocalDateTime.now().getHour(); String key = username + ":" + hour; ValueOperations<String, String> operations = stringTemplate.opsForValue(); String requests = operations.get(key); if (StringUtils.isNotBlank(requests) && Integer.parseInt(requests) >= REQUESTS_PER_HOUR) { return false; } List<Object> txResults = stringTemplate.execute(new SessionCallback<>() { @Override public <K, V> List<Object> execute(RedisOperations<K, V> operations) throws DataAccessException { final StringRedisTemplate redisTemplate = (StringRedisTemplate) operations; final ValueOperations<String, String> valueOperations = redisTemplate.opsForValue(); operations.multi(); valueOperations.increment(key); redisTemplate.expire(key, 2, TimeUnit.HOURS); // This will contain the results of all operations in the transaction return operations.exec(); } }); logger.info("Current request count: " + txResults.get(0)); return true; } public void service() { for (int i=0; i<20; i++) { boolean allowed = isAllowed("carvia"); if(!allowed) break; } } }
a4dd0e0ae822f3393608cf4295430c7a
{ "intermediate": 0.4075680077075958, "beginner": 0.43497365713119507, "expert": 0.15745830535888672 }
13,133
Write examples of question during job interview
6b14f3770d4d63cc890bb4790d96bd8f
{ "intermediate": 0.38590964674949646, "beginner": 0.3166891038417816, "expert": 0.2974012792110443 }
13,134
write me code for receive data from api aplication xamarin forms
11f35a56f2cac431efc85fe40dd802d2
{ "intermediate": 0.7580500245094299, "beginner": 0.09803374856710434, "expert": 0.14391618967056274 }
13,135
public static Route getConfig = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe Stripe.apiKey = "pk_test_51Mo5NVKUS2IHDYWBlvDuQIJzMZSZseKRJrFBOiKTqQoiLsD6LjJYwilWrZrgtTJTtYBC7SXYtlifZzKvwy6yeLkG00WRKKZyMZ"; // Enter your Stripe API key here try { AccountRetrieveParams params = AccountRetrieveParams.builder() .addExpand("settings.card_payments") .addExpand("settings.payments") .addExpand("settings.payouts") .build(); Account account = Account.retrieve(params); responseWrapper.put("stripeAccount", account.toJson()); } catch (StripeException e) { // Handle the exception here } return gson.toJson(responseWrapper); }; public static Route setupIntentLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); String customerId = null; String clientSecret = null; // TODO: Integrate Stripe return gson.toJson(responseWrapper); }; public static Route successfulLesson = (Request request, Response response) -> { Map<String, Object> responseWrapper = new HashMap<String, Object>(); response.type("application/json"); // TODO: Integrate Stripe return gson.toJson(responseWrapper); };
385f57adca98d11bb417c8baedb89ab9
{ "intermediate": 0.5251167416572571, "beginner": 0.22887711226940155, "expert": 0.2460060715675354 }
13,136
source code of spark dealing with log file using function select and withColumn
5283d8339097e2df3fc2f6b933212e45
{ "intermediate": 0.4171908497810364, "beginner": 0.3281829357147217, "expert": 0.25462624430656433 }
13,137
TypeError: sequence item 0: expected str instance, list found
784a2bf5b25d52665150318723ecbd70
{ "intermediate": 0.3771597743034363, "beginner": 0.3492676615715027, "expert": 0.27357256412506104 }
13,138
source code of spark dealing with log file using function select and withColumn
36500f3eb187e49facf7134ad571f4bb
{ "intermediate": 0.4171908497810364, "beginner": 0.3281829357147217, "expert": 0.25462624430656433 }
13,139
I have a php array like this: $a[0]['catid'] = 'a'; $a[1]['catid'] = 'b'; $a[2]['catid'] = 'c'; how to check if 'b' exist in array $a or not?
d03963e173fde07ea7dc5639ae0c8af5
{ "intermediate": 0.5400699973106384, "beginner": 0.23289230465888977, "expert": 0.22703765332698822 }
13,140
I need full fingerprint JS, posting to our server all information about user, including CPU, memory, browser and other (if user access)
d8a6e9ef9ce0ce42ac82a6754b753e50
{ "intermediate": 0.45879268646240234, "beginner": 0.24955879151821136, "expert": 0.2916485369205475 }
13,141
i have collection Sale and i need to show its name, image, description and link. import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; export default function Sale() { return ( <View style={gStyle.SalesMain}> <Text style={gStyle.header}>Скидки</Text> <View style={gStyle.SalesBanner}> <Text style={gStyle.SalesInfo}> Скидки до 20% на швейные машинки{'\n'}Aurora и Bernette </Text> <Image source={require('../assets/banner1.jpg')} style={gStyle.SalesImg} /> <Pressable style={gStyle.SalesChoose}> <Text style={gStyle.SalesBtnChoose}>Выбрать</Text> </Pressable> <Text style={gStyle.SalesLine}></Text> </View> </View> ); }
9c8c7b4df6cea826900cfc24163ab974
{ "intermediate": 0.40380653738975525, "beginner": 0.3015527129173279, "expert": 0.2946407198905945 }
13,142
loop through this code to get name and role const users = [ { name: ‘John Doe’, role: ‘admin’ }, { name: ‘Jane Smith’, role: ‘user’ }, { name: ‘Bob Johnson’, role: ‘user’ } ];
c6085e43b64fe25998c591907f61ec74
{ "intermediate": 0.2600434422492981, "beginner": 0.5775847434997559, "expert": 0.16237175464630127 }
13,143
You are Max/Msp/jitter expert.
20e325733f47dd8f551127818d75f412
{ "intermediate": 0.3893737494945526, "beginner": 0.26406559348106384, "expert": 0.34656065702438354 }
13,144
write a code to create a jarvis vocice assistant for desktop which can take comand by our voice and reply a relavent answer to us which can also use internet and access to all my social media accouct , which can create a website and it able any code which i ask .... totally it should do anything ask.. using python code
0399446debc4afbb216587867edcbec1
{ "intermediate": 0.7071853876113892, "beginner": 0.15334978699684143, "expert": 0.13946478068828583 }
13,145
Write some incredibly bad Python code.
69d53f485ae91b2fd0fa69ffbddb2f32
{ "intermediate": 0.34607943892478943, "beginner": 0.34621626138687134, "expert": 0.3077043294906616 }
13,146
اعد كتابه لي هذا الاسكربت ولا كن بدون كلام ارشادي Pيتعين عليك التأكد من الامتثال لمتطلبات الخدمة. إذا اعطني خطوات عمل الاسكربت الذي بمجرد اعطائه اسم قناة التكتوك يعطني جميع روابط الفيديوهات الموجوده به لعمل هذا النوع من الإسكربتات، سنحتاج إلى استخدام واجهة برمجة تطبيقات (API) لتيك توك. يمكن استخدام الخطوات التالية لإنشاء الإسكربت اللازم: 1. قم بالتسجيل في تيك توك واحصل على وصول لواجهة API. 2. استخدم لغة البرمجة المناسبة مثل Python للوصول إلى واجهة API. 3. اكتب رمزًا يستخدم الواجهة API لإرجاع جميع روابط الفيديوهات الموجودة على القناة التي تحديدتها. 4. يمكنك استخدام وحدات Python مثل requests ، pandas ، او others لتحليل البيانات المسترجعة من API وجمع الروابط المطلوبة. من المهم الانتباه إلى أن تطبيقات مثل تيك توك قد لا تسمح بجمع البيانات بسهولة أو قد تخضع للقيود والشروط، لذا يجب اتباع مبادئ الاستخدام الصحيح وعدم الوصول إلى البيانات دون الحصول على الإذن المناسب. اذا كتب لي كود الاسكربت الذي وظيفته اولا اكتب الايميل الخاص بي لكي يكون علي و روابط الفيديوهات هذا هو رمز Python للاستعلام عن روابط الفيديوهات على قناة TikTok معينة باستخدام واجهة برمجة التطبيقات (API): import requests import pandas as pd #أدخل بيانات التسجيل الخاصة بك في TikTok للحصول على وصول API email = “your_email@domain.com” password = “your_password” #أدخل الاسم الخاص بالقناة التي ترغب في استخراج روابط الفيديوهات منها username = “tiktok_channel_username” #معلومات API verify = False api_base_url = “https://api16-core-c-west1a.tiktokv.com” #الحصول على توكن الوصول بناءً على بيانات تسجيل الدخول login_url = ‘{}/passport/login/’.format(api_base_url) auth_params = { “user_id”: email, “password”: password, } login_response = requests.post(login_url, headers=headers, params=auth_params, verify=verify).json() access_token = login_response[“data”][“access_token”][“token”] #الحصول على معرف القناة user_url = ‘{}/aweme/v1/user/search/’.format(api_base_url) search_params = { “keyword”: username, “ts”: int(pd.Timestamp.now().timestamp()) } search_headers = { “User-Agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64)”, “Authorization”: “Bearer {}”.format(access_token), } user_search_response = requests.get(user_url, headers=search_headers, params=search_params, verify=verify).json() user_id = user_search_response[“user_list”][0][“uid”] #الحصول على روابط الفيديوهات الخاصة بالقناة video_url = ‘{}/aweme/v1/aweme/post/’.format(api_base_url) video_params = { “user_id”: user_id, “count”: 100, “max_cursor”: 0, “min_cursor”: 0, “ts”: int(pd.Timestamp.now().timestamp()) } video_headers = { “User-Agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64)”, “Authorization”: “Bearer {}”.format(access_token), } video_data = [] while True: video_response = requests.get(video_url, headers=video_headers, params=video_params, verify=verify).json() video_data += video_response[“aweme_list”] has_more = video_response[“has_more”] if not has_more: break max_cursor = video_response[“max_cursor”] video_params[“max_cursor”] = max_cursor #عرض الروابط المستخدمة في الفيديوهات for video in video_data: share_url = “https://www.tiktok.com/@{}/video/{}”.format(username, video[“aweme_id”]) print(share_url) يرجى الانتباه إلى أن استخدام واجهة TikTok API يخضع لبعض القيود والشروط، ولا يمكن ضمان عمل هذا الرمز بشكل صحيح 100٪. إذا اعد كتابه الكود بدون كلام ارشادي يمكن استخدام الكود التالي للحصول على ج
98c276c95e84b7dd40477c818f53f01b
{ "intermediate": 0.25226613879203796, "beginner": 0.39846763014793396, "expert": 0.3492662012577057 }
13,147
Hello
e0badea8b1ae85cfd5f882d76e5c09fd
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
13,148
import { Text, View, Image, Pressable } from ‘react-native’; import React, {useEffect, useState} from ‘react’; import { gStyle } from ‘…/styles/style’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/firestore’; export default function Sale() { const [salesData, setSalesData]=useState([]); useEffect(()=>{ const fetchSalesData=async()=>{ try{ const salesCollection = firebase.firestore().collection(‘Sale’); const snapshot=await salesCollection.get(); const data = snapshot.docs.map((doc)=>({id:doc.id, … doc.data})); setSalesData(data); }catch(error){ console.log('Ошибка: ', error); } }; fetchSalesData(); },[]); return ( <View style={gStyle.SalesMain}> <Text style={gStyle.header}>Скидки</Text> {salesData.map((sale)=>( <View key={sale.id} style={gStyle.SalesBanner}> <Text style={gStyle.SalesInfo}> {sale.name} </Text> <Image source={{uri:sale.image}} style={gStyle.SalesImg} /> <Pressable style={gStyle.SalesChoose} link> <Text style={gStyle.SalesBtnChoose}>Выбрать</Text> </Pressable> <Text style={gStyle.SalesLine}></Text> </View> ))} </View> ); } there is no info just a button
2a3edf823b16c4aa919f4e91a41a57aa
{ "intermediate": 0.4713342487812042, "beginner": 0.31085312366485596, "expert": 0.217812642455101 }
13,149
write a macro to compare sheet1 and sheet2 and highlight the difference in numerical values to be in red color
c36ffee6f550596c3080294fa86efbde
{ "intermediate": 0.43966612219810486, "beginner": 0.218338280916214, "expert": 0.34199559688568115 }
13,150
Write a python code to sum to input numeric values
e7b19d665e7bcd5aa35059d203080e94
{ "intermediate": 0.330852210521698, "beginner": 0.17564190924167633, "expert": 0.49350589513778687 }
13,151
how to make randum numbers between 3 - 6 java
c659331eefff42556ff3f532e6427f96
{ "intermediate": 0.41788312792778015, "beginner": 0.2570408284664154, "expert": 0.3250759541988373 }
13,152
i want to make a screen where only admin can be redirected on his admin-panel here import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import { Feather } from ‘@expo/vector-icons’; import React, { useState, useEffect } from ‘react’; import { useNavigation } from ‘@react-navigation/native’; import { firebase } from ‘…/Firebase/firebase’; import ‘firebase/compat/auth’; import ‘firebase/compat/database’; import ‘firebase/compat/firestore’; export default function Header() { const [searchTerm, setSearchTerm] = useState(‘’); const [searchResult, setSearchResult]= useState(‘’); const navigation = useNavigation(); const handleSearch = async ()=>{ if(!searchTerm.trim()){ setSearchResult([]); return; } const futureMKSnapshot = await firebase .firestore() .collection(‘FutureMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const pastMKSnapshot = await firebase .firestore() .collection(‘PastMK’) .where(‘name’,‘>=’,searchTerm) .where(‘name’,‘<=’,searchTerm + ‘\uf8ff’) .get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, …doc.data(), })); const results = […futureMKData, …pastMKData].filter(item=> item.name.toLowerCase().includes(searchTerm.toLowerCase())); const storage=firebase.storage(); const resultWithImages = await Promise.all( results.map(async item=>{ try{ const imagePath=item.image; const imageRef=storage.ref().child(imagePath); const url = await imageRef.getDownloadURL(); return {… item, image:url}; }catch(error){ console.log(‘Ошибка загрузки изображения: ‘, error); return item; } }) ); setSearchResult(resultWithImages); navigation.navigate(‘Search’, { results: resultWithImages }); }; const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require(’…/assets/logo.png’)} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType=‘fade’ transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Home’)} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllFutureMK’)} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘AllPastMK’)} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate(‘Sales’)} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate(‘Profile’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate(‘Auth’)} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } <TouchableOpacity onPress={()=>navigation.navigate(‘AdminPanel’)} > <Text style={gStyle.menuItem}>Админ-панель</Text> </TouchableOpacity> </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder=“Поиск” onChangeText={(text)=>setSearchTerm(text)} /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name=“search” size={25} color=“white” /> </Pressable> </View> </View> </View> ); }
f1d29dfd91afca229cf1a97f50983539
{ "intermediate": 0.39948809146881104, "beginner": 0.39215338230133057, "expert": 0.2083585113286972 }
13,153
how can i create an admin? ive already downloaded a json file and put it in my project. In this file i want an admin to create, update and delete post from collection Sale in firebase import { Text, View, TextInput, Pressable, ScrollView, Image } from 'react-native'; import { gStyle } from '../styles/style'; import Footer from '../components/Footer'; import Header from '../components/Header'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState,} from 'react'; export default function FormAddMK() { return ( <View> <ScrollView> <Header/> <View style={gStyle.formAdd}> <Text style={gStyle.header}>Добавить скидку</Text> <View style={gStyle.formBlock}> <View> <Text>Название скидки</Text> <TextInput style={gStyle.inputForm} onChangeText={onChangeName} /> </View> <View> <Text>ссылка</Text> <TextInput style={gStyle.inputForm} onChangeText={onChangeTime} /> </View> <View> <Text>Изображение</Text> {imageData ? ( <Image source={{ uri: imageData.uri }} style={gStyle.imagePreview} /> ) : null} <Pressable onPress={chooseImage}> <Text>Выбрать изображение</Text> </Pressable> </View> <Pressable style={gStyle.btnAddMK} onPress={addHandler} > <Text style={gStyle.btnAddMKtxt}>Сохранить</Text> </Pressable> </View> </View> <Footer/> </ScrollView> </View> ); }
bd4f242d80b649a3a83ef794be87d174
{ "intermediate": 0.34835562109947205, "beginner": 0.552594006061554, "expert": 0.099050372838974 }
13,154
[102892.119710] Unable to handle kernel NULL pointer dereference at virtual address 00000004 [102892.127811] pgd = cac48000 [102892.130596] [00000004] *pgd=15821831, *pte=00000000, *ppte=00000000 [102892.136931] Internal error: Oops: 17 [#1] PREEMPT SMP ARM [102892.142393] Modules linked in: serial_fpga_amp(O) fpgacan_amp(O) soft_ppt(O) sntp_module_amp(O) fpga_ethernet_amp(O) acp_pipe_module_amp(O) gp_base_module_amp(O) sf_monitor(O) ipv6 bcode_drv(O) dcc_drv_512(O) [102892.160980] CPU: 0 PID: 992 Comm: emgmt Tainted: G O 3.14.01.0.10-xilinx #20 [102892.168953] task: cacf36c0 ti: cac54000 task.ti: cac54000 [102892.174433] PC is at __hrtimer_start_range_ns+0xac/0x33c [102892.179803] LR is at __hrtimer_start_range_ns+0x94/0x33c [102892.185192] pc : [<c003bf30>] lr : [<c003bf18>] psr: 600f0093 [102892.185192] sp : cac55e80 ip : 00000000 fp : a23fef8c [102892.196825] r10: 00000000 r9 : 00000001 r8 : 00000001 [102892.202122] r7 : cac54030 r6 : 00000000 r5 : 00000000 r4 : cac55f28 [102892.208712] r3 : 00000000 r2 : c06df9a8 r1 : cacf36c0 r0 : 00000000 [102892.215321] Flags: nZCv IRQs off FIQs on Mode SVC_32 ISA ARM Segment user [102892.222603] Control: 18c5387d Table: 0ac4804a DAC: 00000015 [102892.228410] Process emgmt (pid: 992, stack limit = 0xcac54240) [102892.234326] Stack: (0xcac55e80 to 0xcac56000) [102892.238750] 5e80: 0000c350 00000000 00000000 00000000 000f4240 00000000 0000001d c003c1e0 [102892.246997] 5ea0: 5a8c09f8 00005d94 00000001 a00f0013 f8f00100 0000c350 00000000 cac55f28 [102892.255244] 5ec0: cac54030 cac54000 00000001 00000000 a23fef8c c003c1e0 0000c350 00000001 [102892.263490] 5ee0: 00000001 00000000 0000c350 c04a5388 0000c350 00000001 000f4240 000f4240 [102892.271737] 5f00: 00000000 00000000 cac54018 00000001 0000c350 c003c9d4 0000c350 00000000 [102892.279984] 5f20: 00100590 00000000 cac55f28 00000000 00000000 00000000 00100590 00000000 [102891.095170] 5f40: 000f4240 00000000 c003b7d4 d76aa280 00000000 ffffffff 00000000 00000000 [102891.103417] 5f60: 00000000 00000000 00000000 00000000 cacf36c0 aca2beb8 aca2b390 00000000 [102891.111663] 5f80: aca2beb8 aca2b390 000000a2 c000e724 cac54000 c003cb00 00000000 000f4240 [102891.119910] 5fa0: 0000d025 c000e5a0 0000d025 aca2beb8 a23fee28 00000000 a23ff910 000f4240 [102891.128157] 5fc0: 0000d025 aca2beb8 aca2b390 000000a2 00000bb8 ac555b68 ac555b6c a23fef8c [102891.136404] 5fe0: 00000000 a23fee20 b3d2e704 b3d2e714 800f0010 a23fee28 00000000 00000000 [102891.144650] [<c003bf30>] (__hrtimer_start_range_ns) from [<c003c1e0>] (hrtimer_start_range_ns+0x20/0x28) [102891.154208] [<c003c1e0>] (hrtimer_start_range_ns) from [<c04a5388>] (do_nanosleep+0x54/0xc4) [102891.162709] [<c04a5388>] (do_nanosleep) from [<c003c9d4>] (hrtimer_nanosleep+0x8c/0x11c) [102891.170865] [<c003c9d4>] (hrtimer_nanosleep) from [<c003cb00>] (SyS_nanosleep+0x9c/0xa8) [102891.179021] [<c003cb00>] (SyS_nanosleep) from [<c000e5a0>] (ret_fast_syscall+0x0/0x30) [102891.187012] Code: eb001a07 e1a03000 ea000000 e1a03006 (e5957004) [102891.193166] ---[ end trace c7ebaa460a68de68 ]---
05e65be14a8af61600eef4c6bce12e08
{ "intermediate": 0.3367447853088379, "beginner": 0.4380676746368408, "expert": 0.22518756985664368 }
13,155
how to create a custom admin in firebase react native expo
ff1e4905168fedc90a2e76bf18a5e102
{ "intermediate": 0.6112998127937317, "beginner": 0.207403302192688, "expert": 0.18129687011241913 }
13,156
SELECT Account.id as "AccountID", Account.name, Account.accountnumber, Account.batch, Account.additionalemailaddresses, contact.firstname, contact.lastname, contact.workemail, contact.personalemail, Invoice.amount, Invoice.balance, Invoice.duedate, Invoice.invoicedate, Invoice.invoicenumber, Invoice.status, Invoice.id, date_diff('day', Invoice.duedate, current_date) as "duedays", Subscription.id as "SubscriptionID", Subscription.name, Subscription.status FROM InvoiceItem IT JOIN Account on IT.accountid = Account.id JOIN Invoice on IT.invoiceid = Invoice.id JOIN contact on contact.id = Account.BillToId JOIN Subscription on IT.subscriptionid = Subscription.id WHERE (date_diff('day', invoice.duedate, current_date) = '{{Data.Workflow.a}}' OR date_diff('day', invoice.duedate, current_date) = 4 OR date_diff('day', invoice.duedate, current_date) = 6 OR date_diff('day', invoice.duedate, current_date) = 8 OR date_diff('day', invoice.duedate, current_date) = 10) AND Invoice.balance>0 AND Invoice.status = 'Posted' AND Account.Batch = 'Batch1' This is my query and In inpt parameters a = 2
788f5d75f7d7fce5cce36bdf0397b1e9
{ "intermediate": 0.38750866055488586, "beginner": 0.3153823912143707, "expert": 0.2971089482307434 }
13,157
const functions = require(‘firebase-functions’); const admin = require(‘firebase-admin’); admin.initializeApp(); exports.makeAdmin = functions.auth.user().onCreate(async (user) => { const adminEmail = ‘<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>’; if (user.email === adminEmail) { const userId = user.uid; await admin.database().ref(users/${userId}).set({ role: ‘admin’ }); } }); Unable to resolve “firebase-functions” from “app\admin\AdminPanel.js”
b31b37b4db682676321575c646ba9c67
{ "intermediate": 0.41697657108306885, "beginner": 0.41159361600875854, "expert": 0.1714298278093338 }
13,158
import { Text, View, Image, Pressable } from 'react-native'; import { gStyle } from '../styles/style'; import React from 'react'; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: 'column' }}> <View style={gStyle.ProfileDetails1}> <Image source={{uri:item.image}} style={gStyle.ProfileImg1}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK1}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+'...' : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.readmore} > <Text style={gStyle.readmoretxt}>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); } i need to show details of PastMK or FutureMK, so how to do that?
71e4320b3c3d439b24289e29166e18d2
{ "intermediate": 0.5635806918144226, "beginner": 0.25174495577812195, "expert": 0.18467435240745544 }
13,159
i need to show details of the post which user was searching for, but there are two collections FutureMK and PastMK. Here is my code where i need to use redirect to show more data import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React from ‘react’; export default function Result({ item }) { return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> <View style={gStyle.ProfileDetails1}> <Image source={{uri:item.image}} style={gStyle.ProfileImg1}/> <View style={gStyle.ProfileDescription}> <Text style={gStyle.ProfileTitleOfMK1}>{item.name}</Text> <Text> {item.description.length > 100 ? item.description.substring(0, 100)+‘…’ : item.description } </Text> </View> </View> </View> <Pressable style={gStyle.readmore} > <Text style={gStyle.readmoretxt}>Читать далее</Text> </Pressable> <Text style={gStyle.ProfileLine}></Text> </View> ); }
3bc49a2fef1bf900774490a8d1bdc816
{ "intermediate": 0.46442511677742004, "beginner": 0.23485404253005981, "expert": 0.30072087049484253 }