row_id int64 0 48.4k | init_message stringlengths 1 342k | conversation_hash stringlengths 32 32 | scores dict |
|---|---|---|---|
20,195 | По какой то причине у меня обновление новости завязано в корутине замены случайной новости. class NewsViewModel : ViewModel() {
private val newsList = mutableListOf(
News("Новость 1", "Lorem ipsum", 0, false),
News("Новость 2", "Lorem ipsum", 0, false),
News("Новость 3", "Lorem ipsum", 0, false),
News("Новость 4", "Lorem ipsum", 0, false),
News("Новость 5", "Lorem ipsum", 0, false),
News("Новость 6", "Lorem ipsum", 0,false),
News("Новость 7", "Lorem ipsum", 0,false),
News("Новость 8", "Lorem ipsum", 0,false),
News("Новость 9", "Lorem ipsum", 0,false),
News("Новость 10", "Lorem ipsum", 0,false),
)
private val _newsState = MutableStateFlow(getRandomNewsSubset())
val newsState: StateFlow<List> = _newsState
init {
startUpdatingNews()
}
kotlin
Copy code
fun onLikeClick(news: News) {
val index = newsList.indexOf(news)
if (index != -1 && !newsList[index].likedByUser) {
newsList[index].likes++
newsList[index].likedByUser = true // Устанавливаем флаг, что пользователь поставил лайк
}
}
private fun startUpdatingNews() {
GlobalScope.launch {
while (true) {
delay(5000)
replaceRandomNews()
}
}
}
private fun replaceRandomNews() {
val visibleNews = _newsState.value
val remainingNews = newsList.filterNot { it in visibleNews }
if (remainingNews.isNotEmpty()) {
val randomVisibleIndex = Random.nextInt(visibleNews.size)
val randomRemainingIndex = Random.nextInt(remainingNews.size)
val updatedVisibleList = visibleNews.toMutableList()
updatedVisibleList[randomVisibleIndex] = remainingNews[randomRemainingIndex]
_newsState.value = updatedVisibleList
}
}
private fun getRandomNewsSubset(): List<News> {
return newsList.shuffled().take(4) // Выбираем случайные 4 новости из списка
}
}
Как это исправить? | 08cc38b260e7cb3511449bed7fe7d08c | {
"intermediate": 0.36244454979896545,
"beginner": 0.3803613781929016,
"expert": 0.25719407200813293
} |
20,196 | значение количество лайков обновляется только спустя 5 секунд: package com.example.myapplication22
import android.os.Debug
import android.util.Log
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.launch
import kotlin.random.Random
class NewsViewModel : ViewModel() {
private val newsList = mutableListOf(
News("Новость 1", "Lorem ipsum", 0, false),
News("Новость 2", "Lorem ipsum", 0, false),
News("Новость 3", "Lorem ipsum", 0, false),
News("Новость 4", "Lorem ipsum", 0, false),
News("Новость 5", "Lorem ipsum", 0, false),
News("Новость 6", "Lorem ipsum", 0,false),
News("Новость 7", "Lorem ipsum", 0,false),
News("Новость 8", "Lorem ipsum", 0,false),
News("Новость 9", "Lorem ipsum", 0,false),
News("Новость 10", "Lorem ipsum", 0,false),
)
private val _newsState = MutableStateFlow(getRandomNewsSubset())
val newsState: StateFlow<List<News>> = _newsState
init {
startUpdatingNews()
}
fun onLikeClick(news: News) {
val index = newsList.indexOf(news)
if (index != -1 && !newsList[index].likedByUser) {
newsList[index].likes++
newsList[index].likedByUser = true // Устанавливаем флаг, что пользователь поставил лайк
val news_ = _newsState.value.toMutableList()
news_[news_.indexOf(news)] = newsList[newsList.indexOf(news)]
_newsState.value = news_
}
}
private fun startUpdatingNews() {
GlobalScope.launch {
while (true) {
delay(5000)
replaceRandomNews()
}
}
}
private fun replaceRandomNews() {
val visibleNews = _newsState.value
val remainingNews = newsList.filterNot { it in visibleNews }
if (remainingNews.isNotEmpty()) {
val randomVisibleIndex = Random.nextInt(visibleNews.size)
val randomRemainingIndex = Random.nextInt(remainingNews.size)
val updatedVisibleList = visibleNews.toMutableList()
updatedVisibleList[randomVisibleIndex] = remainingNews[randomRemainingIndex]
_newsState.value = updatedVisibleList
}
}
private fun getRandomNewsSubset(): List<News> {
return newsList.shuffled().take(4) // Выбираем случайные 4 новости из списка
}
} | 655cdc96aa11878a9840612348778f64 | {
"intermediate": 0.3323233127593994,
"beginner": 0.5192098021507263,
"expert": 0.14846684038639069
} |
20,197 | В этом коде поставленный лайк обновляется каждые 5 секунд. Как сделать так чтобы лайк обновлялся мгновенно и при этом не нужно было бы менять случайную новость? class NewsViewModel : ViewModel() {
private val newsList = mutableListOf(
News("Новость 1", "Lorem ipsum", 0, false),
News("Новость 2", "Lorem ipsum", 0, false),
News("Новость 3", "Lorem ipsum", 0, false),
News("Новость 4", "Lorem ipsum", 0, false),
News("Новость 5", "Lorem ipsum", 0, false),
News("Новость 6", "Lorem ipsum", 0,false),
News("Новость 7", "Lorem ipsum", 0,false),
News("Новость 8", "Lorem ipsum", 0,false),
News("Новость 9", "Lorem ipsum", 0,false),
News("Новость 10", "Lorem ipsum", 0,false),
)
private val _newsState = MutableStateFlow(getRandomNewsSubset())
val newsState: StateFlow<List<News>> = _newsState
init {
startUpdatingNews()
}
fun onLikeClick(news: News) {
val index = newsList.indexOf(news)
if (index != -1 && !newsList[index].likedByUser) {
newsList[index].likes++
newsList[index].likedByUser = true // Устанавливаем флаг, что пользователь поставил лайк
val news_ = _newsState.value.toMutableList()
news_[news_.indexOf(news)] = newsList[newsList.indexOf(news)]
_newsState.value = news_
}
}
private fun startUpdatingNews() {
GlobalScope.launch {
while (true) {
delay(5000)
replaceRandomNews()
}
}
}
private fun replaceRandomNews() {
val visibleNews = _newsState.value
val remainingNews = newsList.filterNot { it in visibleNews }
if (remainingNews.isNotEmpty()) {
val randomVisibleIndex = Random.nextInt(visibleNews.size)
val randomRemainingIndex = Random.nextInt(remainingNews.size)
val updatedVisibleList = visibleNews.toMutableList()
updatedVisibleList[randomVisibleIndex] = remainingNews[randomRemainingIndex]
_newsState.value = updatedVisibleList
}
}
private fun getRandomNewsSubset(): List<News> {
return newsList.shuffled().take(4) // Выбираем случайные 4 новости из списка
}
} | 907d21ad8d61ddee7b71ff27f613f718 | {
"intermediate": 0.36181342601776123,
"beginner": 0.47527778148651123,
"expert": 0.16290883719921112
} |
20,198 | Power BI: Need to create a new custom column whose value is pointing to another table colimn value | 61f07e9ddbe98bf7c8e6e260677f092d | {
"intermediate": 0.367351770401001,
"beginner": 0.21811312437057495,
"expert": 0.4145350754261017
} |
20,199 | Power BI: Have two input excel files Previous and Current. Would like to track their loaded timestamp each time a new file is loaded. If not new file the Timestamp shall be same as old | 692a729e00ea1a01b3aa87d1f3683823 | {
"intermediate": 0.36323073506355286,
"beginner": 0.2155715823173523,
"expert": 0.4211976230144501
} |
20,200 | Power BI: Simple requirement, have two input files as Tables "Previous" and "Current". Need to track their first time load timestamp. This column will updated only once a new file source is changed for each "Previous" and "Current", else the value should be same always | 3886ad29e81cfb1a1522392176212fc1 | {
"intermediate": 0.301076203584671,
"beginner": 0.2908689081668854,
"expert": 0.408054918050766
} |
20,201 | Please a code for GameMaker studio 2 that creates a page with three tap | 14ac08f3fd3b25937f30443676e486d8 | {
"intermediate": 0.49382197856903076,
"beginner": 0.26832494139671326,
"expert": 0.23785300552845
} |
20,202 | Power BI: Have two input files "Previous" and "Current", need to track their timestamp for last load of a new updated file. I am using DateTime.LocalNow() formula for new custom column "Loaded Timestamp" each table, how ever this is not serving the purpose as each time i open the Power BI they get loaded with current time. What we need is this column be updated only if there is change in source file | 199c3317e03f95de484afd58831f8e22 | {
"intermediate": 0.5447313785552979,
"beginner": 0.2306160032749176,
"expert": 0.22465258836746216
} |
20,203 | Почему здесь при нажатии на кнопку лайка лайк не обновляется мгновенно, но через 5 секунд при обновлении новостей лайк появляется? Как это исправить чтобы лайк появлялся мгновенно? class NewsViewModel : ViewModel() {
private val newsList = mutableListOf(
News("Новость 1", "Lorem ipsum", 0, false),
News("Новость 2", "Lorem ipsum", 0, false),
News("Новость 3", "Lorem ipsum", 0, false),
News("Новость 4", "Lorem ipsum", 0, false),
News("Новость 5", "Lorem ipsum", 0, false),
News("Новость 6", "Lorem ipsum", 0,false),
News("Новость 7", "Lorem ipsum", 0,false),
News("Новость 8", "Lorem ipsum", 0,false),
News("Новость 9", "Lorem ipsum", 0,false),
News("Новость 10", "Lorem ipsum", 0,false),
)
private val _newsState = MutableStateFlow(getRandomNewsSubset())
val newsState: StateFlow<List> = _newsState
init {
startUpdatingNews()
}
kotlin
Copy code
fun onLikeClick(news: News) {
val index = newsList.indexOf(news)
if (index != -1 && !newsList[index].likedByUser) {
newsList[index].likes++
newsList[index].likedByUser = true // Устанавливаем флаг, что пользователь поставил лайк
replaceCurrentNews(_newsState.value.indexOf(news),newsList.indexOf(news) )
}
}
private fun startUpdatingNews() {
GlobalScope.launch {
while (true) {
delay(5000)
replaceRandomNews()
}
}
}
private fun replaceRandomNews() {
val visibleNews = _newsState.value
val remainingNews = newsList.filterNot { it in visibleNews }
if (remainingNews.isNotEmpty()) {
val randomVisibleIndex = Random.nextInt(visibleNews.size)
val randomRemainingIndex = Random.nextInt(remainingNews.size)
replaceCurrentNews(randomVisibleIndex, newsList.indexOf(remainingNews[randomRemainingIndex]))
}
}
private fun replaceCurrentNews(visibleIndex: Int, newsListIndex: Int) {
val updatedVisibleList = _newsState.value.toMutableList()
updatedVisibleList[visibleIndex] = newsList[newsListIndex]
_newsState.value = updatedVisibleList.toList()
}
private fun getRandomNewsSubset(): List<News> {
return newsList.shuffled().take(4) // Выбираем случайные 4 новости из списка
}
} | f8cf500c7f0f12fe24e6007aebcefb30 | {
"intermediate": 0.29893219470977783,
"beginner": 0.541380763053894,
"expert": 0.15968702733516693
} |
20,204 | add value in p tag depend on condition in angular | 24225de137b4fffb76ad2014b1f4c0c4 | {
"intermediate": 0.362435907125473,
"beginner": 0.37927719950675964,
"expert": 0.25828686356544495
} |
20,205 | I want to make this code parametrized
Dim Financialscmd As New OleDbCommand("insert into Financials (FinIID, FinDate, FinState, FinPerson, FinDetails,FinBill,FinInstallment,FinAssets,FinNotes,FinUser) Values ()", con)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Financialscmd.ExecuteNonQuery() | 33cf6f6b180c1a9fb9e82076e495bada | {
"intermediate": 0.3932272493839264,
"beginner": 0.41118499636650085,
"expert": 0.19558773934841156
} |
20,206 | please tell me the formula of the force scheme in D2G9 model of CLBGK | 62575779488c0decc2c68e06a2bb54dd | {
"intermediate": 0.25032687187194824,
"beginner": 0.13667453825473785,
"expert": 0.6129986047744751
} |
20,207 | i have text with many lines i just want to display the first line css | 1968b1e24d4d13b24e9b3a829db5872c | {
"intermediate": 0.38160035014152527,
"beginner": 0.33394166827201843,
"expert": 0.2844579517841339
} |
20,208 | Give a definition and an javascript illustration/sample code for each topic:
1. Math.random()
2. Getting user input from the command-line
3. Loops
4. Casting primitives from a large size to a smaller size
5. Converting string to an int | f9cd87b046b9f96aac8f5eb01a943176 | {
"intermediate": 0.20141054689884186,
"beginner": 0.6120642423629761,
"expert": 0.18652518093585968
} |
20,209 | Give a definition and a javascript illustration/sample code for each topic:
1. Math.random()
2. Getting user input from the command-line
3. Loops
4. Casting primitives from a large size to a smaller size
5. Converting string to an int | 58449a2c1a743c2bd98b9f9b6dcb41a2 | {
"intermediate": 0.19055156409740448,
"beginner": 0.6371642351150513,
"expert": 0.17228415608406067
} |
20,210 | Give a definition and a javascript illustration/sample code for each topic:
1. Math.random()
2. Getting user input from the command-line
3. Loops
4. Casting primitives from a large size to a smaller size
5. Converting string to an int | e8d22accea66da0c349ab82392342462 | {
"intermediate": 0.19055156409740448,
"beginner": 0.6371642351150513,
"expert": 0.17228415608406067
} |
20,211 | write code for GameMaker studio 2 that encode a text with salt to ready to send to server | 4b1ec4a0dd2682e7ef00d9ece5545eab | {
"intermediate": 0.39765089750289917,
"beginner": 0.20585289597511292,
"expert": 0.3964962363243103
} |
20,212 | hi ill send u one script on two parts | adcb51400ab2af0cdb95407d684a31d7 | {
"intermediate": 0.36363089084625244,
"beginner": 0.24430078268051147,
"expert": 0.3920682668685913
} |
20,213 | RuntimeError: Running cythonize failed! | c71db380598b4b3bdaeda0d432366c5e | {
"intermediate": 0.3910682797431946,
"beginner": 0.20062202215194702,
"expert": 0.408309668302536
} |
20,214 | also, there’s a problem with this exponential slowdown. because it endlessly slowdowns, until it reaches a year in timeout, which is idiotic. maybe if request is passed then reset slowdown exponent? how? implement?: async function query(data, modelToken) {
const url = modelUrl;
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: data
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
// Handle HTTP 429 errors by throwing an error with the response object
if (response.status === 429) {
const error = new Error('Backend error');
error.response = response;
throw error;
}
const result = await response.blob();
return result;
}
let modelToken = modelTokens[currentTokenIndex];
let tokenSwitched = false;
let lastTokenSwitchTime = null;
let retryDelay = 2000;
let currentRetries = 0;
async function executeQuery(data, modelToken, currentTokenIndex) {
try {
// Send the request with the current model token
const result = await query(data, modelToken);
// Reset the retry delay and current retries count
retryDelay = retryDelay;
currentRetries = 0;
// Check if the result contains an image or an error
if (result.type === 'image/jpeg') {
return result;
} else {
throw new Error('Backend error');
}
} catch (error) {
// Check if the error is an HTTP 429 error
if (error.message === 'Backend error' && error.response && error.response.status === 429) {
console.log('Received HTTP 429 error');
// Check if the token has already been switched for this particular error
if (!tokenSwitched) {
console.log('Switching to another model token');
currentRetries = 0;
lastTokenSwitchTime = Date.now();
tokenSwitched = true;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
// Check if the timeout duration for token switching has passed
const currentTime = Date.now();
const timeDiff = currentTime - lastTokenSwitchTime;
const minutesPassed = Math.floor(timeDiff / (1000 * 60));
// Check if the timeout duration has been exceeded
if (minutesPassed >= 1) {
console.log('Switching to another model token after timeout');
currentRetries = 0;
lastTokenSwitchTime = currentTime;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
console.log('Still within timeout duration, delaying request');
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
// Retry the query with the new model token
return await executeQuery(data, modelToken, currentTokenIndex);
} else {
console.log('Received HTTP error. Slowing down request rate.');
await new Promise(resolve => setTimeout(resolve, retryDelay));
retryDelay = retryDelay * 2;
// Retry the query with the same model token
return await executeQuery(data, modelToken, currentTokenIndex);
}
}
} | f3cf9da4163f6e2864cbfc1f8819b740 | {
"intermediate": 0.3162096440792084,
"beginner": 0.5003733038902283,
"expert": 0.18341712653636932
} |
20,215 | Создай скрипт для блендера который создаст детализированную тыкву | 67e12c988d543e36d9b4724dc088b673 | {
"intermediate": 0.3080107867717743,
"beginner": 0.23255804181098938,
"expert": 0.4594312012195587
} |
20,216 | Tell me shortly please if I bought BCH at $200 and sold it at $215 how many percent difference between my entry price and exit price | a87ff7e8a9e2fe48aac998fe20163c5c | {
"intermediate": 0.43485742807388306,
"beginner": 0.2703401446342468,
"expert": 0.29480239748954773
} |
20,217 | the fix need here that on http code 429 it should only switch token and handle appropriate logic algorithm for specifically http code 429, but on all other codes it should simply slowdown request rate, understand? also, there’s a problem with this exponential slowdown. because it endlessly slowdowns, until it reaches a year in timeout, which is idiotic. maybe if request is passed then reset slowdown exponent, but how do you let algorithm to understand that request passed? how? implement?: async function query(data, modelToken) {
const url = modelUrl;
const response = await fetch(url, {
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + modelToken
},
method: 'POST',
body: data
});
const headers = response.headers;
const estimatedTimeString = headers.get('estimated_time');
estimatedTime = parseFloat(estimatedTimeString) * 1000;
// Handle HTTP 429 errors by throwing an error with the response object
if (response.status === 429) {
const error = new Error('Backend error');
error.response = response;
throw error;
}
const result = await response.blob();
return result;
}
let modelToken = modelTokens[currentTokenIndex];
let tokenSwitched = false;
let lastTokenSwitchTime = null;
let retryDelay = 2000;
let currentRetries = 0;
async function executeQuery(data, modelToken, currentTokenIndex) {
try {
// Send the request with the current model token
const result = await query(data, modelToken);
// Reset the retry delay and current retries count
retryDelay = retryDelay;
currentRetries = 0;
// Check if the result contains an image or an error
if (result.type === 'image/jpeg') {
return result;
} else {
throw new Error('Backend error');
}
} catch (error) {
// Check if the error is an HTTP 429 error
if (error.message === 'Backend error' && error.response && error.response.status === 429) {
console.log('Received HTTP 429 error');
// Check if the token has already been switched for this particular error
if (!tokenSwitched) {
console.log('Switching to another model token');
currentRetries = 0;
lastTokenSwitchTime = Date.now();
tokenSwitched = true;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
// Check if the timeout duration for token switching has passed
const currentTime = Date.now();
const timeDiff = currentTime - lastTokenSwitchTime;
const minutesPassed = Math.floor(timeDiff / (1000 * 60));
// Check if the timeout duration has been exceeded
if (minutesPassed >= 1) {
console.log('Switching to another model token after timeout');
currentRetries = 0;
lastTokenSwitchTime = currentTime;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
console.log('Still within timeout duration, delaying request');
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
// Retry the query with the new model token
return await executeQuery(data, modelToken, currentTokenIndex);
} else {
console.log('Received HTTP error. Slowing down request rate.');
await new Promise(resolve => setTimeout(resolve, retryDelay));
retryDelay = retryDelay * 2;
// Retry the query with the same model token
return await executeQuery(data, modelToken, currentTokenIndex);
}
}
} | e20bf285e7cd0d185f6cbdb6ae8a933f | {
"intermediate": 0.31562724709510803,
"beginner": 0.447620153427124,
"expert": 0.23675261437892914
} |
20,218 | Как исправить эту ошибку : Python: Traceback (most recent call last):
File "\Text.001", line 24, in <module>
TypeError: edge_split() argument 2 must be BMVert, not BMEdge
в этом коде : import bpy
import bmesh
from mathutils import Vector, Matrix
# Создаем объем тыквы
bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=Vector((0,0,0)), segments=32, ring_count=16, enter_editmode=False)
# Изменяем соотношение эллипсоида, чтобы он выглядел как тыква
ob = bpy.context.object
ob.scale *= Vector((1.2, 0.8, 1.2))
# Добавляем глубокие резы в тыкве
bm = bmesh.new()
bm.from_mesh(ob.data)
# Выбираем верхнюю половину тыквы
top_half_verts = [v for v in bm.verts if v.co.z > 0]
# Создаем пустые списки для хранения вершин и ребер резов
cut_verts = []
cut_edges = []
# Создаем резы в верхней половине тыквы
for v in top_half_verts:
if v.co.x**2 + v.co.y**2 > 0.7**2:
cut_verts.append(v)
_, e = bmesh.utils.edge_split(v.link_edges[0], v.link_edges[1], v)
cut_edges.append(e)
# Создаем объект с резами
cut_bm = bmesh.new()
cut_bm.from_mesh(ob.data)
cut_bm_verts = cut_bm.verts
cut_bm_verts.ensure_lookup_table()
cut_bm_edges = cut_bm.edges
cut_bm_edges.ensure_lookup_table()
cut_bm_verts_in_cut = [cut_bm_verts[i] for i in range(len(cut_bm_verts)) if cut_bm_verts[i] in cut_verts]
for v in cut_bm_verts_in_cut:
cut_bm_verts.remove(v)
for e in cut_bm_edges[:]:
if e not in cut_edges:
cut_bm_edges.remove(e)
cut_bm.to_mesh(ob.data)
cut_ob = bpy.context.object
# Создаем стебель тыквы
bpy.ops.mesh.primitive_cylinder_add(radius=0.2, depth=0.8, enter_editmode=False, location=Vector((0,0,1.4)))
stem_ob = bpy.context.object
# Объединяем тыкву и стебель в один объект
bpy.ops.object.select_all(action='DESELECT')
ob.select_set(True)
cut_ob.select_set(True)
stem_ob.select_set(True)
bpy.context.view_layer.objects.active = ob
bpy.ops.object.join()
# Добавляем рельеф на поверхности тыквы
bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_random(percent=20)
bpy.ops.mesh.extrude_region_shrink_fatten(MESH_OT_extrude_region={"use_normal_flip":False, "mirror":False}, TRANSFORM_OT_shrink_fatten={"value":-0.1, "use_even_offset":False, "mirror":False, "use_proportional_edit":False, "proportional_edit_falloff":'SMOOTH', "proportional_size":1, "use_proportional_connected":False, "use_proportional_projected":False, "snap":False, "snap_target":'CLOSEST', "snap_point":(0, 0, 0), "snap_align":False, "snap_normal":(0, 0, 0), "release_confirm":True})
bpy.ops.object.editmode_toggle()
# Назначаем материалы для тыквы и стебля
ob.active_material = bpy.data.materials.new(name="Pumpkin")
ob.active_material.diffuse_color = (1,0.5,0) # оранжевый цвет
stem_ob.active_material = bpy.data.materials.new(name="Stem")
stem_ob.active_material.diffuse_color = (0.2,0.6,0) # зеленый цвет | 7bd1d5a1a2f28849af51f5a9ed6a6e6b | {
"intermediate": 0.35492610931396484,
"beginner": 0.4669993221759796,
"expert": 0.17807455360889435
} |
20,219 | on http code 429 it should only switch token and handle appropriate logic algorithm for specifically http code 429, but on all other codes it should simply slowdown request rate, understand? there’s a problem with this exponential slowdown. because it endlessly slowdowns, until it reaches a year in timeout, which is idiotic. maybe if request is passed then reset slowdown exponent, but how do you let algorithm to understand that request passed and need to reset delay exponent to initial 2000 miliseconds for all other subsequent future errors, except 429, which has its own logic and algorithm? need this retry delay algrithm formula more interesingly awesome and within in range of random eponent that resets itself on successful passage. as from 10 seconds to 25 seconds, something in that range for in within attempts. no, need to make it awesomely-awesome, don’t faggot. the min delay should not be lower than 2 seconds. now implement supercrazyawesome overall algorithm. any other non faggot ideas you may suggest to overallity? "1. Implement an exponential backoff strategy: Instead of using a random exponential factor, you can implement an exponential backoff strategy. Start with a smaller initial delay (e.g., 2 seconds) and exponentially increase the delay with each subsequent retry. This approach provides a more controlled and predictable delay pattern.
", "3. Implement jitter in the retry delay: Jitter adds randomness to the retry delay, which helps distribute requests more evenly and avoids congestion peaks. You can add a random value within a certain range to the calculated delay to introduce jitter."
now do random in range exponential backoff strategical jitter delay of absolute awesomeness! implement?: async function query(data, modelToken) {
const url = modelUrl;
const response = await fetch(url, {
headers: {
“Content-Type”: “application/json”,
Authorization: "Bearer " + modelToken
},
method: ‘POST’,
body: data
});
const headers = response.headers;
const estimatedTimeString = headers.get(‘estimated_time’);
estimatedTime = parseFloat(estimatedTimeString) * 1000;
// Handle HTTP 429 errors by throwing an error with the response object
if (response.status === 429) {
const error = new Error(‘Backend error’);
error.response = response;
throw error;
}
const result = await response.blob();
return result;
}
let modelToken = modelTokens[currentTokenIndex];
let tokenSwitched = false;
let lastTokenSwitchTime = null;
let retryDelay = 2000;
let currentRetries = 0;
async function executeQuery(data, modelToken, currentTokenIndex) {
try {
// Send the request with the current model token
const result = await query(data, modelToken);
// Reset the retry delay and current retries count
retryDelay = retryDelay;
currentRetries = 0;
// Check if the result contains an image or an error
if (result.type === ‘image/jpeg’) {
return result;
} else {
throw new Error(‘Backend error’);
}
} catch (error) {
// Check if the error is an HTTP 429 error
if (error.message === ‘Backend error’ && error.response && error.response.status === 429) {
console.log(‘Received HTTP 429 error’);
// Check if the token has already been switched for this particular error
if (!tokenSwitched) {
console.log(‘Switching to another model token’);
currentRetries = 0;
lastTokenSwitchTime = Date.now();
tokenSwitched = true;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
// Check if the timeout duration for token switching has passed
const currentTime = Date.now();
const timeDiff = currentTime - lastTokenSwitchTime;
const minutesPassed = Math.floor(timeDiff / (1000 * 60));
// Check if the timeout duration has been exceeded
if (minutesPassed >= 1) {
console.log(‘Switching to another model token after timeout’);
currentRetries = 0;
lastTokenSwitchTime = currentTime;
// Increment the current token index and get the next model token
currentTokenIndex = (currentTokenIndex + 1) % modelTokens.length;
modelToken = modelTokens[currentTokenIndex];
} else {
console.log(‘Still within timeout duration, delaying request’);
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
// Retry the query with the new model token
return await executeQuery(data, modelToken, currentTokenIndex);
} else {
console.log(‘Received HTTP error. Slowing down request rate.’);
await new Promise(resolve => setTimeout(resolve, retryDelay));
retryDelay = retryDelay * 2;
// Retry the query with the same model token
return await executeQuery(data, modelToken, currentTokenIndex);
}
}
} | bb2edf390d7c95cd93d5cccc223b6a06 | {
"intermediate": 0.3995211124420166,
"beginner": 0.33349642157554626,
"expert": 0.2669825255870819
} |
20,220 | Will a new class B inherited from class A have all its methods in Kotlin? | 605a0ec3b712098aba2c8f0e128805d8 | {
"intermediate": 0.2747190594673157,
"beginner": 0.45917564630508423,
"expert": 0.2661052942276001
} |
20,221 | przekształć ten kod, na kod w go: /*++
Copyright (c) 2007 - 2017, Matthieu Suiche
Copyright (c) 2012 - 2014, MoonSols Limited
Copyright (c) Comae Technologies DMCC. All rights reserved.
Copyright (c) 2022, Magnet Forensics, Inc. All rights reserved.
Module Name:
Hibr2Bin.cpp
Abstract:
This module contains the internal structure definitions and APIs used by
the Hibr2Bin.
Author:
Matthieu Suiche (m) 1-April-2016
Revision History:
--*/
#include "precomp.h"
#ifndef COMAE_TOOLKIT_VERSION
#define COMAE_TOOLKIT_VERSION "3.0.0.undefined"
#endif
VOID
Help()
{
wprintf(L"Usage: Hibr2Bin [Options] /INPUT <FILENAME> /OUTPUT <FILENAME>\n\n");
wprintf(L"Description:\n"
L" Enables users to uncompress Windows hibernation file.\n\n");
wprintf(L"Options:\n"
L" /PLATFORM, /P Select platform (X64 or X86)\n"
L" /MAJOR, /V Select major version (e.g. 6 for NT 6.1\n"
L" /MINOR, /M Select minor version (e.g. 1 for NT 6.1)\n"
L" /OFFSET, /L Data offset in hexadecimal (optional)\n"
L" /INPUT, /I Input hiberfil.sys file.\n"
L" /OUTPUT, /O Output hiberfil.sys file.\n\n");
wprintf(L"Versions:\n"
L" /MAJOR 5 /MINOR 1 Windows XP\n"
L" /MAJOR 5 /MINOR 2 Windows XP x64, Windows 2003 R2\n"
L" /MAJOR 6 /MINOR 0 Windows Vista, Windows Server 2008\n"
L" /MAJOR 6 /MINOR 1 Windows 7, Windows Server 2008 R2\n"
L" /MAJOR 6 /MINOR 2 Windows 8, Windows Server 2012\n"
L" /MAJOR 6 /MINOR 3 Windows 8.1, Windows Server 2012 R2\n"
L" /MAJOR 10 /MINOR 0 Windows 10, Windows Server 2017\n\n");
wprintf(L"Examples:\n\n");
wprintf(L" Uncompress a Windows 7 (NT 6.1) x64 hibernation file:\n"
L" Hibr2Bin /PLATFORM X64 /MAJOR 6 /MINOR 1 /INPUT hiberfil.sys /OUTPUT uncompressed.bin\n\n"
L" Uncompress a Windows 10 (NT 10.0) x86 hibernation file:\n"
L" Hibr2Bin /PLATFORM X86 /MAJOR 10 /MINOR 0 /INPUT hiberfil.sys /OUTPUT uncompressed.bin\n");
}
BOOLEAN
Parse(
ULONG MaxArg,
LPWSTR *argv,
PPROGRAM_ARGUMENTS Arguments
)
{
ULONG Index = 1;
while (Index < MaxArg)
{
if ((argv[Index][0] == L'/') || (argv[Index][0] == L'-'))
{
if ((_wcsicmp(argv[Index], L"/PLATFORM") == 0) || (_wcsicmp(argv[Index], L"/P") == 0))
{
Index++;
Arguments->HasPlatform = TRUE;
if (_wcsicmp(argv[Index], L"X86") == 0) Arguments->Platform = PlatformX86;
else if (_wcsicmp(argv[Index], L"X64") == 0) Arguments->Platform = PlatformX64;
else
{
Arguments->HasPlatform = FALSE;
}
}
else if ((_wcsicmp(argv[Index], L"/MAJOR") == 0) || (_wcsicmp(argv[Index], L"/V") == 0))
{
Index++;
Arguments->MajorVersion = _wtoi(argv[Index]);
Arguments->HasMajorVersion = TRUE;
}
else if ((_wcsicmp(argv[Index], L"/MINOR") == 0) || (_wcsicmp(argv[Index], L"/M") == 0))
{
Index++;
Arguments->MinorVersion = _wtoi(argv[Index]);
Arguments->HasMinorVersion = TRUE;
}
else if ((_wcsicmp(argv[Index], L"/OFFSET") == 0) || (_wcsicmp(argv[Index], L"/L") == 0))
{
LPWSTR p;
Index++;
Arguments->DataOffset = wcstol(argv[Index], &p, 16);
Arguments->HasDataOffset = TRUE;
}
else if ((_wcsicmp(argv[Index], L"/INPUT") == 0) || (_wcsicmp(argv[Index], L"/I") == 0))
{
Index++;
Arguments->FileName = argv[Index];
}
else if ((_wcsicmp(argv[Index], L"/OUTPUT") == 0) || (_wcsicmp(argv[Index], L"/O") == 0))
{
Index++;
Arguments->OutFileName = argv[Index];
}
else if ((_wcsicmp(argv[Index], L"/?") == 0) || (_wcsicmp(argv[Index], L"/HELP") == 0))
{
return FALSE;
}
else
{
wprintf(L" Error: Invalid parameter.\n");
return FALSE;
}
}
Index++;
}
//
// Validate parameters.
//
if (!Arguments->HasPlatform) wprintf(L" Error: Please provide a platform type using /P.\n");
if (!Arguments->HasMajorVersion) wprintf(L" Error: Please provide a major version using /V parameter.\n");
if (!Arguments->HasMinorVersion) wprintf(L" Error: Please provide a minor version using /M parameter.\n");
if (!Arguments->HasMajorVersion || !Arguments->HasMinorVersion || !Arguments->HasPlatform) return FALSE;
// Known versions of Windows: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
if (Arguments->MajorVersion == 10)
{
//
// NT 10.0
//
if (Arguments->MinorVersion != 0)
{
wprintf(L" Error: Unsupported target version.");
return FALSE;
}
}
else if (Arguments->MajorVersion == 6)
{
//
// NT 6.3, NT 6.2, NT 6.1, NT 6.0
//
if ((Arguments->MinorVersion != 3) && (Arguments->MinorVersion != 2) &&
(Arguments->MinorVersion != 1) && (Arguments->MinorVersion != 0))
{
wprintf(L" Error: Unsupported target version.");
return FALSE;
}
}
else if (Arguments->MajorVersion == 5)
{
//
// NT 5.2 (X64), NT 5.1 (x86)
//
if (((Arguments->MinorVersion != 2) && (Arguments->Platform != PlatformX64)) ||
((Arguments->MinorVersion != 1) && (Arguments->Platform != PlatformX86)))
{
wprintf(L" Error: Unsupported target version.");
return FALSE;
}
}
return TRUE;
}
BOOLEAN
IsLicenseValid()
{
SYSTEMTIME SystemTime = { 0 };
GetLocalTime(&SystemTime);
#if 0
if (!((SystemTime.wYear == 2017) && (SystemTime.wMonth == 6)))
{
return FALSE;
}
#endif
return TRUE;
}
LPWSTR
GetPlatformType(
PlatformType Type
)
{
switch (Type)
{
case PlatformX86:
return L"X86";
case PlatformX64:
return L"X64";
}
return L"Unknown";
}
int
wmain(
ULONG argc,
LPWSTR *argv
)
{
PROGRAM_ARGUMENTS Arguments = { 0 };
wprintf(L"\n"
L" Hibr2Bin %S\n"
L" Copyright (C) 2007 - 2021, Matthieu Suiche <http://www.msuiche.net>\n"
L" Copyright (C) 2012 - 2014, MoonSols Limited <http://www.moonsols.com>\n"
L" Copyright (C) 2016 - 2021, Comae Technologies DMCC <http://www.comae.io>\n"
L" Copyright (c) 2022, Magnet Forensics, Inc. <https://www.magnetforensics.com/>\n\n",
COMAE_TOOLKIT_VERSION);
if ((argc < 2) || !Parse(argc, argv, &Arguments))
{
Help();
return FALSE;
}
if (!IsLicenseValid())
{
Red(L" Error: Beta program expired. Get the latest version on www.comae.io \n");
return FALSE;
}
wprintf(L" In File: %s\n", Arguments.FileName);
wprintf(L" Out File: %s\n", Arguments.OutFileName);
wprintf(L" Target Version: Microsoft Windows NT %d.%d (%s)\n", Arguments.MajorVersion, Arguments.MinorVersion, GetPlatformType(Arguments.Platform));
MemoryBlock *MemoryBlocks = NULL;
BOOLEAN Result = FALSE;
if (ProcessHiberfil(&Arguments, &MemoryBlocks))
{
Result = WriteMemoryBlocksToDisk(MemoryBlocks, &Arguments);
}
return Result;
} | 2741f36d03dfd408c20aa026c59d1f63 | {
"intermediate": 0.2747906744480133,
"beginner": 0.3736017644405365,
"expert": 0.3516075611114502
} |
20,222 | I used your code:
lookback = 10080
quantity = 0.05
active_signal = None
buy_entry_price = None
sell_entry_price = None
def calculate_percentage_difference(entry_price, exit_price):
percentage_difference = ((exit_price - entry_price) / entry_price) * 100
return percentage_difference
while True:
if df is not None:
signals = signal_generator(df)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}")
if 'buy' in signals and active_signal != 'buy':
try:
active_signal = 'buy'
buy_entry_price = mark_price # Record the buy entry price
print(f"Buy Entry Price: {buy_entry_price}")
# Execute buy orders here
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
print("Long order executed!")
if buy_entry_price is not None:
buy_exit_price = mark_price
difference_buy = calculate_percentage_difference(buy_entry_price, buy_exit_price)
profit_buy = difference_buy * 50
total_profit_buy = profit_buy + (0.04 * profit_buy)
print(f"Buy Profit: {total_profit_buy}")
else:
print("Buy Entry price is not defined.")
except binance.error.ClientError as e:
print(f"Error executing long order: {e}")
elif 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
# Execute sell orders here
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: {e}")
if sell_entry_price is not None and buy_entry_price is not None:
sell_exit_price = buy_entry_price
difference_sell = calculate_percentage_difference(sell_entry_price, sell_exit_price)
profit_sell = difference_sell * 50
total_profit_sell = profit_sell + (0.04 * profit_sell)
print(f"Sell Profit: {total_profit_sell}")
else:
print("Sell Entry price or Buy Entry price is not defined.")
time.sleep(1)
But it printing me only short position profit and loss , | 688d187f70aeaf5970d2522c627305cb | {
"intermediate": 0.37756815552711487,
"beginner": 0.4051089882850647,
"expert": 0.21732282638549805
} |
20,223 | popraw ten kod o błąd:
.\hyb.go:86:27: cannot use strconv.ParseInt(argv[index], 16, 64) (value of type int64) as int value in assignment
package main
import (
“fmt”
“os”
“strconv”
“strings”
)
type PlatformType int
const (
PlatformX86 PlatformType = iota
PlatformX64
)
type PROGRAM_ARGUMENTS struct {
HasPlatform bool
Platform PlatformType
HasMajorVersion bool
MajorVersion int
HasMinorVersion bool
MinorVersion int
HasDataOffset bool
DataOffset int
FileName string
OutFileName string
}
const COMAE_TOOLKIT_VERSION string = “3.0.0.undefined”
func Help() {
fmt.Printf(“Usage: Hibr2Bin [Options] /INPUT <FILENAME> /OUTPUT <FILENAME>\n\n”)
fmt.Printf(“Description:\n Enables users to uncompress Windows hibernation file.\n\n”)
fmt.Printf(“Options:\n /PLATFORM, /P Select platform (X64 or X86)\n”)
fmt.Printf(" /MAJOR, /V Select major version (e.g. 6 for NT 6.1\n")
fmt.Printf(" /MINOR, /M Select minor version (e.g. 1 for NT 6.1)\n")
fmt.Printf(" /OFFSET, /L Data offset in hexadecimal (optional)\n")
fmt.Printf(" /INPUT, /I Input hiberfil.sys file.\n")
fmt.Printf(" /OUTPUT, /O Output hiberfil.sys file.\n\n")
fmt.Printf(“Versions:\n”)
fmt.Printf(" /MAJOR 5 /MINOR 1 Windows XP\n")
fmt.Printf(" /MAJOR 5 /MINOR 2 Windows XP x64, Windows 2003 R2\n")
fmt.Printf(" /MAJOR 6 /MINOR 0 Windows Vista, Windows Server 2008\n")
fmt.Printf(" /MAJOR 6 /MINOR 1 Windows 7, Windows Server 2008 R2\n")
fmt.Printf(" /MAJOR 6 /MINOR 2 Windows 8, Windows Server 2012\n")
fmt.Printf(" /MAJOR 6 /MINOR 3 Windows 8.1, Windows Server 2012 R2\n")
fmt.Printf(" /MAJOR 10 /MINOR 0 Windows 10, Windows Server 2017\n\n")
fmt.Printf(“Examples:\n\n”)
fmt.Printf(" Uncompress a Windows 7 (NT 6.1) x64 hibernation file:\n")
fmt.Printf(" Hibr2Bin /PLATFORM X64 /MAJOR 6 /MINOR 1 /INPUT hiberfil.sys /OUTPUT uncompressed.bin\n\n")
fmt.Printf(" Uncompress a Windows 10 (NT 10.0) x86 hibernation file:\n")
fmt.Printf(" Hibr2Bin /PLATFORM X86 /MAJOR 10 /MINOR 0 /INPUT hiberfil.sys /OUTPUT uncompressed.bin\n")
}
func Parse(argv []string) (PROGRAM_ARGUMENTS, bool) {
arguments := PROGRAM_ARGUMENTS{}
maxArg := len(argv)
index := 1
for index < maxArg {
if strings.HasPrefix(argv[index], “/”) || strings.HasPrefix(argv[index], “-”) {
option := strings.ToUpper(argv[index])
switch option {
case “/PLATFORM”, “/P”:
index++
arguments.HasPlatform = true
switch strings.ToUpper(argv[index]) {
case “X86”:
arguments.Platform = PlatformX86
case “X64”:
arguments.Platform = PlatformX64
default:
arguments.HasPlatform = false
}
case “/MAJOR”, “/V”:
index++
arguments.MajorVersion, _ = strconv.Atoi(argv[index])
arguments.HasMajorVersion = true
case “/MINOR”, “/M”:
index++
arguments.MinorVersion, _ = strconv.Atoi(argv[index])
arguments.HasMinorVersion = true
case “/OFFSET”, “/L”:
index++
arguments.DataOffset, _ = strconv.ParseInt(argv[index], 16, 64)
arguments.HasDataOffset = true
case “/INPUT”, “/I”:
index++
arguments.FileName = argv[index]
case “/OUTPUT”, “/O”:
index++
arguments.OutFileName = argv[index]
case “/?”, “/HELP”:
return arguments, false
default:
fmt.Printf(“Error: Invalid parameter.\n”)
return arguments, false
}
}
index++
}
// Validate parameters.
if !arguments.HasPlatform {
fmt.Printf(“Error: Please provide a platform type using /P.\n”)
}
if !arguments.HasMajorVersion {
fmt.Printf(“Error: Please provide a major version using /V parameter.\n”)
}
if !arguments.HasMinorVersion {
fmt.Printf(“Error: Please provide a minor version using /M parameter.\n”)
}
if !arguments.HasMajorVersion || !arguments.HasMinorVersion || !arguments.HasPlatform {
return arguments, false
}
// Known versions of Windows: http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
if arguments.MajorVersion == 10 {
// NT 10.0
if arguments.MinorVersion != 0 {
fmt.Printf(“Error: Unsupported target version.”)
return arguments, false
}
} else if arguments.MajorVersion == 6 {
// NT 6.3, NT 6.2, NT 6.1, NT 6.0
if arguments.MinorVersion != 3 && arguments.MinorVersion != 2 &&
arguments.MinorVersion != 1 && arguments.MinorVersion != 0 {
fmt.Printf(“Error: Unsupported target version.”)
return arguments, false
}
} else if arguments.MajorVersion == 5 {
// NT 5.2 (X64), NT 5.1 (x86)
if (arguments.MinorVersion != 2 && arguments.Platform != PlatformX64) ||
(arguments.MinorVersion != 1 && arguments.Platform != PlatformX86) {
fmt.Printf(“Error: Unsupported target version.”)
return arguments, false
}
}
return arguments, true
}
func IsLicenseValid() bool {
// Placeholder for GetLocalTime and SYSTEMTIME
// GetLocalTime(&SystemTime)
// if !((SystemTime.wYear == 2017) && (SystemTime.wMonth == 6)) {
// return false
// }
return true
}
func GetPlatformType(Type PlatformType) string {
switch Type {
case PlatformX86:
return “X86”
case PlatformX64:
return “X64”
}
return “Unknown”
}
func processHiberfil(arguments *PROGRAM_ARGUMENTS) ([]string, bool) {
// Placeholder for processHiberfil function
return []string{}, true
}
func writeMemoryBlocksToDisk(memoryBlocks []string, arguments *PROGRAM_ARGUMENTS) bool {
// Placeholder for writeMemoryBlocksToDisk function
return true
}
func main() {
fmt.Printf(“\n Hibr2Bin %s\n”, COMAE_TOOLKIT_VERSION)
fmt.Printf(" Copyright © 2007 - 2021, Matthieu Suiche <http://www.msuiche.net>\n")
fmt.Printf(" Copyright © 2012 - 2014, MoonSols Limited <http://www.moonsols.com>\n")
fmt.Printf(" Copyright © 2016 - 2021, Comae Technologies DMCC <http://www.comae.io>\n")
fmt.Printf(" Copyright © 2022, Magnet Forensics, Inc. <https://www.magnetforensics.com/>\n\n")
args := os.Args
if len(args) < 2 {
Help()
return
}
arguments, parsed := Parse(args)
if !parsed {
Help()
return
}
if !IsLicenseValid() {
fmt.Printf(" Error: Beta program expired. Get the latest version on www.comae.io \n")
return
}
fmt.Printf(" In File: %s\n", arguments.FileName)
fmt.Printf(" Out File: %s\n", arguments.OutFileName)
fmt.Printf(" Target Version: Microsoft Windows NT %d.%d (%s)\n", arguments.MajorVersion, arguments.MinorVersion, GetPlatformType(arguments.Platform))
memoryBlocks, success := processHiberfil(&arguments)
if success {
success = writeMemoryBlocksToDisk(memoryBlocks, &arguments)
}
// Placeholder for return value
return
} | 077729cb4686bd85080615d7dd9d5ff3 | {
"intermediate": 0.3675272762775421,
"beginner": 0.44469234347343445,
"expert": 0.18778036534786224
} |
20,224 | I go better idea. here’s a randondom gaynerador: “const genRanNum = () => {
const randomValues = new Uint32Array(3);
crypto.getRandomValues(randomValues);
const bigEndian32 = (randomValues[0] * 0x100000000) + randomValues[1];
const key = bigEndian32.toString().padStart(10, ‘0’).substring(0, 10);
return key;
};”. so by setting a padstring to 4 and substring to 4, I can set all environment in my code to some in random 4 digits in milliseconds timings. need that number to be not less than 1000 milliseconds but highly random in all else range in 4 digits only. | 544404e491a27bd6d92ce745245d41a8 | {
"intermediate": 0.39440181851387024,
"beginner": 0.201908677816391,
"expert": 0.40368953347206116
} |
20,225 | implement now anti-superhacker custom entropy!!!!!!!!!!!!!!!!!!!!!!!: (((""" | 3a735ca781f67fac005b6f0461681ae8 | {
"intermediate": 0.21077385544776917,
"beginner": 0.204219251871109,
"expert": 0.5850068926811218
} |
20,226 | you now GPT implement now anti-superhacker custom entropy!!!!!!!!!!!!!!!!!!!!!!!: (((""" | 45b0a66795e32114c60262d4300cc040 | {
"intermediate": 0.22572778165340424,
"beginner": 0.15319672226905823,
"expert": 0.6210755109786987
} |
20,227 | this seems unstable as babylon tower. some crazy overheat out there, without any particular errors.: const calculateEntropy = (str) => {
let freqMap = {};
let entropy = 0;
// Calculate the frequency of each character in the string
for (let i = 0; i < str.length; i++) {
let char = str[i];
if (freqMap[char]) {
freqMap[char] += 1;
} else {
freqMap[char] = 1;
}
}
// Calculate the entropy using the frequency of each character
Object.keys(freqMap).forEach((char) => {
let prob = freqMap[char] / str.length;
entropy -= prob * Math.log2(prob);
});
return entropy;
};
const generateUniqueRandomNum = (() => {
const generatedNumbers = new Set();
const generateNum = () => {
const randomValues = new Uint32Array(1);
crypto.getRandomValues(randomValues);
const key = randomValues[0] % 9000 + 1000;
return key;
};
const entropyThreshold = Math.log2(9000); // Calculate entropy threshold
return () => {
let num = generateNum();
let entropyValue;
do {
num = generateNum();
entropyValue = calculateEntropy(num.toString());
} while (generatedNumbers.has(num) || entropyValue < entropyThreshold);
generatedNumbers.add(num);
// Reset state if a certain percentage of numbers have been generated
if (generatedNumbers.size > 0.9 * 9000) {
generatedNumbers.clear();
}
return num;
};
})(); | ef417b5ad3b12b220b6d456c2dc6a8a7 | {
"intermediate": 0.337228387594223,
"beginner": 0.45184028148651123,
"expert": 0.21093133091926575
} |
20,228 | uinty code, create a PHP mysqul conectore, create player register UI, Player name, password, E-mail, save it to mysqul, create player logind UI | 2332bd904be64acbf856dd34b825d769 | {
"intermediate": 0.5435703992843628,
"beginner": 0.16985942423343658,
"expert": 0.2865702211856842
} |
20,229 | x=[1, 2, 3, 4, 5, 6]
z=[x/2 for i in x]
print(z) | 8f76485fdf8f7fdb055c43c318326900 | {
"intermediate": 0.11042618751525879,
"beginner": 0.7951225638389587,
"expert": 0.09445125609636307
} |
20,230 | i'm working on an audio processor, and i'm trying to write a function that plays an audio at half speed:
For example, suppose I have an audio file with the following samples:
100, 90, 70, 20
I would output these samples:
100, 95, 90, 80, 70, 45, 20
Every other sample is simply the average of the two samples they are between.
this is my function so far:
void CAudioProcessDoc::OnProcessHalfspeed()
{
// Call to open the processing output
if (!ProcessBegin())
return;
short audio[2];
// keep track of time
double time = 0;
for (int i = 0; i < SampleFrames(); i++, time += 1.0 / SampleRate())
{
ProcessReadFrame(audio);
// output i, then average of (i and i++)
audio[0] = short(audio[0] * m_amplitude);
audio[1] = short(audio[1] * m_amplitude);
ProcessWriteFrame(audio);
// The progress control
if (!ProcessProgress(double(i) / SampleFrames()))
break;
}
// Call to close the generator output
ProcessEnd();
}
how am i supposed to get, for example, the first sample and the second, so i can average them and play that sound? | 61e1d53a0f9722c287c19f89e492bad6 | {
"intermediate": 0.48032087087631226,
"beginner": 0.2727225124835968,
"expert": 0.24695660173892975
} |
20,231 | i have to write some audio processing code that plays the audio backwards. this is what the general processing code looks like:
void CAudioProcessDoc::OnProcessBackwards()
{
// Call to open the processing output
if (!ProcessBegin())
return;
short audio[2];
// keep track of time
double time = 0;
for (int i = 0; i < SampleFrames(); i++, time += 1.0 / SampleRate())
{
ProcessReadFrame(audio);
ProcessWriteFrame(audio);
// The progress control
if (!ProcessProgress(double(i) / SampleFrames()))
break;
}
// Call to close the generator output
ProcessEnd();
}
i know i'll need to allocate some memory to hold the backwards audio, and then play *that*, but how would i go about doing it | 1611dbbb32a91610be2979fbba0dfb99 | {
"intermediate": 0.4856296479701996,
"beginner": 0.27016258239746094,
"expert": 0.24420779943466187
} |
20,232 | Summarize and explain what each one does. Make the entire summary about half the word length: Comparison operations compares some value or operand. Then based on some condition, they produce a Boolean. Let's say we assign a value of a to six. We can use the equality operator denoted with two equal signs to determine if two values are equal. In this case, if seven is equal to six. In this case, as six is not equal to seven, the result is false. If we performed an equality test for the value six, the two values would be equal. As a result, we would get a true. Consider the following equality comparison operator: If the value of the left operand, in this case, the variable i is greater than the value of the right operand, in this case five, the condition becomes true or else we get a false. Let's display some values for i on the left. Let's see the value is greater than five in green and the rest in red. If we set i equal to six, we see that six is larger than five and as a result, we get a true. We can also apply the same operations to floats. If we modify the operator as follows, if the left operand i is greater than or equal to the value of the right operand, in this case five, then the condition becomes true. In this case, we include the value of five in the number line and the color changes to green accordingly. If we set the value of i equal to five, the operand will produce a true. If we set the value of i to two, we would get a false because two is less than five. We can change the inequality if the value of the left operand, in this case, i is less than the value of the right operand, in this case, six. Then condition becomes true. Again, we can represent this with a colored number line. The areas where the inequality is true are marked in green and red where the inequality is false. If the value for i is set to two, the result is a true. As two is less than six. The inequality test uses an explanation mark preceding the equal sign. If two operands are not equal, then the condition becomes true. We can use a number line. When the condition is true, the corresponding numbers are marked in green and red for where the condition is false. If we set i equal to two, the operator is true as two is not equal to six. We compare strings as well. Comparing ACDC and Michael Jackson using the equality test, we get a false, as the strings are not the same. Using the inequality test, we get a true, as the strings are different. See the Lapps for more examples. Branching allows us to run different statements for a different input. It's helpful to think of an if statement as a locked room. If this statement is true, you can enter the room and your program can run some predefined task. If the statement is false, your program will skip the task. For example, consider the blue rectangle representing an ACDC concert. If the individual is 18 or older, they can enter the ACDC concert. If they are under the age of 18, they cannot enter the concert. Individual proceeds to the concert their age is 17, therefore, they are not granted access to the concert and they must move on. If the individual is 19, the condition is true. They can enter the concert then they can move on. This is the syntax of the if statement from our previous example. We have the if statement. We have the expression that can be true or false. The brackets are not necessary. We have a colon. Within an indent, we have the expression that is run if the condition is true. The statements after the if statement will run regardless if the condition is true or false. For the case where the age is 17, we set the value of the variable age to 17. We check the if statement, the statement is false. Therefore the program will not execute the statement to print, "you will enter". In this case, it will just print "move on". For the case where the age is 19, we set the value of the variable age to 19. We check the if statement. The statement is true. Therefore, the program will execute the statement to print "you will enter". Then it will just print "move on". The else statement will run a different block of code if the same condition is false. Let's use the ACDC concert analogy again. If the user is 17, they cannot go to the ACDC concert but they can go to the Meat Loaf concert represented by the purple square. If the individual is 19, the condition is true, they can enter the ACDC concert then they can move on as before. The syntax of the else statement is similar. We simply append the statement else. We then add the expression we would like to execute with an indent. For the case where the age is 17, we set the value of the variable age to 17. We check the if statement, the statement is false. Therefore, we progress to the else statement. We run the statement in the indent. This corresponds to the individual attending the Meat Loaf concert. The program will then continue running. For the case where the age is 19, we set the value of the variable age to 19. We check the if statement, the statement is true. Therefore, the program will execute the statement to print "you will enter". The program skips the expressions in the else statement and continues to run the rest of the expressions. The elif statement, short for else if, allows us to check additional conditions if the preceding condition is false. If the condition is true, the alternate expressions will be run. Consider the concert example, if the individual is 18, they will go to the Pink Floyd concert instead of attending the ACDC or Meat Loaf concerts. The person of 18 years of age enters the area as they are not over 19 years of age. They cannot see ACDC but as their 18 years, they attend Pink Floyd. After seeing Pink Floyd, they move on. The syntax of the elif statement is similar. We simply add the statement elif with the condition. We, then add the expression we would like to execute if the statement is true with an indent. Let's illustrate the code on the left. An 18 year old enters. They are not older than 18 years of age. Therefore, the condition is false. So the condition of the elif statement is checked. The condition is true. So then we would print "go see Pink Floyd". Then we would move on as before. If the variable age was 17, the statement "go see Meat Loaf" would print. Similarly, if the age was greater than 18, the statement "you can enter" would print. Check the Lapps for more examples. Now let's take a look at logic operators. Logic operations take Boolean values and produce different Boolean values. The first operation is the not operator. If the input is true, the result is a false. Similarly, if the input is false, the result is a true. Let A and B represent Boolean variables. The OR operator takes in the two values and produces a new Boolean value. We can use this table to represent the different values. The first column represents the possible values of A. The second column represents the possible values of B. The final column represents the result of applying the OR operation. We see the OR operator only produces a false if all the Boolean values are false. The following lines of code will print out: "This album was made in the 70s' or 90's", if the variable album year does not fall in the 80s. Let's see what happens when we set the album year to 1990. The colored number line is green when the condition is true and red when the condition is false. In this case, the condition is false. Examining the second condition, we see that 1990 is greater than 1989. So the condition is true. We can verify by examining the corresponding second number line. In the final number line, the green region indicates, where the area is true. This region corresponds to where at least one statement is true. We see that 1990 falls in the area. Therefore, we execute the statement. Let A and B represent Boolean variables. The AND operator takes in the two values and produces a new Boolean value. We can use this table to represent the different values. The first column represents the possible values of A. The second column represents the possible values of B. The final column represents the result of applying the AND operation. We see the OR operator only produces a true if all the Boolean values are true. The following lines of code will print out "This album was made in the 80's" if the variable album year is between 1980 and 1989. Let's see what happens when we set the album year to 1983. As before, we can use the colored number line to examine where the condition is true. In this case, 1983 is larger than 1980, so the condition is true. Examining the second condition, we see that 1990 is greater than 1983. So, this condition is also true. We can verify by examining the corresponding second number line. In the final number line, the green region indicates where the area is true. Similarly, this region corresponds to where both statements are true. We see that 1983 falls in the area. Therefore, we execute the statement. Branching allows us to run different statements for different inputs." | a9e58e81e6e21cac8cdd34d36601c0a6 | {
"intermediate": 0.4243650436401367,
"beginner": 0.42524799704551697,
"expert": 0.1503869593143463
} |
20,233 | Using x, write a short python program that uses: not, or, true, false, and | 0d9c2357160991e2153bfdbfa031f140 | {
"intermediate": 0.25179386138916016,
"beginner": 0.5431288480758667,
"expert": 0.20507729053497314
} |
20,234 | need movement left,right,top,bottom. here: 0% {
background-position: 300% 0%;
}
100% {
background-position:0% 300% ;
}
0% {
background-position: 300% 0%;
}
100% {
background-position:0% 300% ;
}
} | ffd757954a8b57d7e2afe175c6a738b3 | {
"intermediate": 0.38442349433898926,
"beginner": 0.3010995388031006,
"expert": 0.31447696685791016
} |
20,235 | summarize this to about half its word length. Then, include examples for each one: "Before we talk about loops, let's go over the range function. The range function outputs and ordered sequence as a list I. If the input is a positive integer, the output is a sequence. The sequence contains the same number of elements as the input but starts at zero. For example, if the input is three the output is the sequence zero, one, two. If the range function has two inputs where the first input is smaller than the second input, the output is a sequence that starts at the first input. Then the sequence iterates up to but not including the second number. For the input 10 and 15 we get the following sequence. See the labs for more capabilities of the range function. Please note, if you use Python three, the range function will not generate a list explicitly like in Python two. In this section, we will cover for loops. We will focus on lists, but many of the procedures can be used on tuples. Loops perform a task over and over. Consider the group of colored squares. Let's say we would like to replace each colored square with a white square. Let's give each square a number to make things a little easier and refer to all the group of squares as squares. If we wanted to tell someone to replace squares zero with a white square, we would say equals replace square zero with a white square or we can say four squares zero in squares square zero equals white square. Similarly, for the next square we can say for square one in squares, square one equals white square. For the next square we can say for square two in squares, square two equals white square. We repeat the process for each square. The only thing that changes is the index of the square we are referring to. If we're going to perform a similar task in Python we cannot use actual squares. So let's use a list to represent the boxes. Each element in the list is a string representing the color. We want to change the name of the color in each element to white. Each element in the list has the following index. This is a syntax to perform a loop in Python. Notice the indent, the range function generates a list. The code will simply repeat everything in the indent five times. If you were to change the value to six it would do it 6 times. However, the value of I is incremented by one each time. In this segment we change the I element of the list to the string white. The value of I is set to zero. Each iteration of the loop starts at the beginning of the indent. We then run everything in the indent. The first element in the list is set to white. We then go to the start of the indent, we progress down each line. When we reach the line to change the value of the list, we set the value of index one to white. The value of I increases by one. We repeat the process for index two. The process continues for the next index, until we've reached the final element. We can also iterate through a list or tuple directly in python, we do not even need to use indices. Here is the list squares. Each iteration of the list we pass one element of the list squares to the variable square. Lets display the value of the variable square on this section. For the first iteration, the value of square is red, we then start the second iteration. For the second iteration, the value of square is yellow. We then start the third iteration. For the final iteration, the value of square is green, a useful function for iterating data is enumerate. It can be used to obtain the index and the element in the list. Let's use the box analogy with the numbers representing the index of each square. This is the syntax to iterate through a list and provide the index of each element. We use the list squares and use the names of the colors to represent the colored squares. The argument of the function enumerate is the list. In this case squares the variable I is the index and the variable square is the corresponding element in the list. Let's use the left part of the screen to display the different values of the variable square and I for the various iterations of the loop. For the first iteration, the value of the variable is red corresponding to the zeroth index, and the value for I is zero for the second iteration. The value of the variable square is yellow, and the value of I corresponds to its index i.e. 1. We repeat the process for the last index. While loops are similar to for loops but instead of executing a statement a set number of times a while loop will only run if a condition is met. Let's say we would like to copy all the orange squares from the list squares to the list New squares. But we would like to stop if we encounter a non-orange square. We don't know the value of the squares beforehand. We would simply continue the process while the square is orange or see if the square equals orange. If not, we would stop. For the first example, we would check if the square was orange. It satisfies the conditions so we would copy the square. We repeat the process for the second square. The condition is met. So we copy the square. In the next iteration, we encounter a purple square. The condition is not met. So we stop the process. This is essentially what a while loop does. Let's use the figure on the left to represent the code. We will use a list with the names of the color to represent the different squares. We create an empty list of new squares. In reality the list is of indeterminate size. We start the index at zero the while statement will repeatedly execute the statements within the indent until the condition inside the bracket is false. We append the value of the first element of the list squares to the list new squares. We increase the value of I by one. We append the value of the second element of the list squares to the list new squares. We increment the value of I. Now the value in the array squares is purple; therefore, the condition for the while statement is false and we exit the loop." | be65d1928244a00b64ea41a478813c70 | {
"intermediate": 0.4452061951160431,
"beginner": 0.4076912999153137,
"expert": 0.14710254967212677
} |
20,236 | Элемент имеет такую структуру, как при нажатии на первый элемент делать так чтобы класс active переместился на следующий элемент.
<div class="wheel">
<div class="backbutton"></div>
<div class="wheelpart col-3 ">
<img src="1.jpg" img="wheelimg">
</div>
<div class="wheelpart active col-3">
<img src="2.jpg" img="wheelimg">
</div>
<div class="wheelpart active col-3">
<img src="3.jpg" img="wheelimg">
</div>
<div class="wheelpart col-3">
<img src="4.jpg" img="wheelimg">
</div>
<div class="nextbutton"></div>
</div> | 62b5deb0a1c648d2fed9a79b21819b2e | {
"intermediate": 0.3800221085548401,
"beginner": 0.3124336004257202,
"expert": 0.3075442910194397
} |
20,237 | Convert the python code in my next message to clojure. Say OK to confirm. | 3e6a8e67cbf3c7e53b2f933d530ed670 | {
"intermediate": 0.46139317750930786,
"beginner": 0.3134765625,
"expert": 0.22513028979301453
} |
20,238 | html:
<div class="wheel">
<div class="backbutton"></div>
<div class="wheelpart col-3 ">
<img src="1.jpg" img="wheelimg">
</div>
<div class="wheelpart active col-3">
<img src="2.jpg" img="wheelimg">
</div>
<div class="wheelpart col-3">
<img src="3.jpg" img="wheelimg">
</div>
<div class="wheelpart col-3">
<img src="4.jpg" img="wheelimg">
</div>
<div class="nextbutton"></div>
</div>
js :
var wheels=document.querySelectorAll("wheel");
wheels.forEach(function(a){
alert(a);
a.firstChild.addEventListener("click", function(a)
{
alert("click")
var b = a.querySelector(".wheelpart.active");
b.classList.remove("active");
if (b.nextElementSibling != a.lastChild){
b.nextElementSibling.classList.add("active");
}
else
{
a.childNodes[1].classList.add("active");
}
})
a.lastChild.addEventListener("click", function(a)
{
alert("click")
var b = a.querySelector(".wheelpart.active");
b.classList.remove("active");
if (b.previousElementSibling != a.firstChild){
b.previousElementSibling.classList.add("active");
}
else
{
a.lastChild.previousElementSibling.classList.add("active");
}
})
}
);
Почему не работает | 49dcd1dd82c58037d72427533a84d492 | {
"intermediate": 0.37444624304771423,
"beginner": 0.37961345911026,
"expert": 0.24594026803970337
} |
20,239 | Write a code to do link prediction in heterogeneous graph with torch_geometric | 1f8b3ca5097abc665d05553e644726c6 | {
"intermediate": 0.2789485454559326,
"beginner": 0.06067488715052605,
"expert": 0.6603765487670898
} |
20,240 | create procedure get_list_region(OUT p_json json)
language plpgsql
as
$$
begin
select json_agg(d)
from
(select distinct region_code as code,
region_name as name
from address
) d
into p_json;
end;
$$;
alter procedure get_list_region(out json) owner to postgres;
how to call it in python and get json data | 01ce20a53a75e9c8416f3dc606b6b91d | {
"intermediate": 0.5062687397003174,
"beginner": 0.2557908296585083,
"expert": 0.2379404604434967
} |
20,241 | nodejs how do i debug why is the memory usage so high | 689266f83a5aff289987bcc3c944655d | {
"intermediate": 0.8986470699310303,
"beginner": 0.05475901812314987,
"expert": 0.046593960374593735
} |
20,242 | create procedure get_list_region(OUT p_json json)
language plpgsql
as
$$
begin
select json_agg(d)
from
(select distinct region_code as code,
region_name as name
from address
) d
into p_json;
end;
$$;
alter procedure get_list_region(out json) owner to postgres;
call it with python
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'var' | a7825338f23df5dc2340fb68daf5af2b | {
"intermediate": 0.40593478083610535,
"beginner": 0.28681012988090515,
"expert": 0.3072550296783447
} |
20,243 | prevent referrer header CSRF | 68f36afe696b9570bb177d2286ac4e92 | {
"intermediate": 0.28194859623908997,
"beginner": 0.378298819065094,
"expert": 0.33975252509117126
} |
20,244 | debian, how to know if a user have sudo privileges; | ec498a512397980ae0f735c6f952e1c5 | {
"intermediate": 0.34402772784233093,
"beginner": 0.3258567750453949,
"expert": 0.3301154673099518
} |
20,245 | The following explanatory text doesn't include example code. Make example code that is concise and add comments to illustrate what is happening.:
"8.8. Ordered and sorted collections and map keys
Java lists and maps don’t map very naturally to foreign key relationships between tables, and so we tend to avoid using them to represent associations between our entity classes. But if you feel like you really need a collection with a fancier structure than Set, Hibernate does have options.
The first two options let us map the index of a List or key of a Map to a column:
Table 62. Annotations for mapping lists and maps
Annotation Purpose JPA-standard
@OrderColumn
Specifies the column used to maintain the order of a list
✔
@MapKeyColumn
Specifies the column used to persist the keys of a map
✔
For an unowned association, the column must also be mapped on the owning side, usually by an attribute of the target entity.
Now, let’s introduce a little distinction:
an ordered collection is one with an ordering maintained in the database, and
a sorted collection is one which is sorted in Java code.
These annotations allow us to specify how the elements of a collection should be ordered as they are read from the database:
Table 63. Annotations for ordered collections
Annotation Purpose JPA-standard
@OrderBy
Specifies a fragment of JPQL used to order the collection
✔
@SQLOrder
Specifies a fragment of SQL used to order the collection
✖
On the other hand, the following annotation specify how a collection should be sorted in memory, and are used for collections of type SortedSet or SortedMap:
Table 64. Annotations for sorted collections
Annotation Purpose JPA-standard
@SortNatural
Specifies that the elements of a collection are Comparable
✖
@SortComparator
Specifies a Comparator used to sort the collection
✖
Under the covers, Hibernate uses a TreeSet or TreeMap to maintain the collection in sorted order." | 032bd6a2408052f9c2c3733e86b9d8ad | {
"intermediate": 0.43738049268722534,
"beginner": 0.335514634847641,
"expert": 0.22710484266281128
} |
20,246 | I have a list<P> with fields x , a , b and a List<Q> with fields x, a
I want to put value of a for each x in list Q in list P ( somehow join and change value of a in P and turn it to value of a in Q )
how to do it in c# using linq | 03df617f980843ddb2c8b011a1ee5b62 | {
"intermediate": 0.5349981784820557,
"beginner": 0.23326438665390015,
"expert": 0.2317374050617218
} |
20,247 | AttributeError: module 'pandas' has no attribute 'dataframe' | a21a4d65b07aba848980780c83c341d6 | {
"intermediate": 0.5825730562210083,
"beginner": 0.11667777597904205,
"expert": 0.30074915289878845
} |
20,248 | It is required to develop in C++ language, without using third-party
libraries,
frameworks, and the standard template library the following program: A program for creating a two-dimensional dynamic array from
one-dimensional. The user should be able to set the size
one-dimensional array, the width of a two-dimensional one, delete old data and
create new ones. The array is filled with random data in the range,
specified by the user. It must be possible to withdraw
both arrays as a whole or an arbitrary element of each. Program
supports working with arrays with at least 1^8 elements. | 8ffe9bc2e1f3b68aa073465f4ceafd71 | {
"intermediate": 0.6733578443527222,
"beginner": 0.12223569303750992,
"expert": 0.2044065147638321
} |
20,249 | Hi I have error 400 when Im trying to send post method by such code like this import { useState } from "react";
//import "./companies.scss";
import { ICreateCompanyDto } from "../../types/global.typing";
import {} from "@mui/material";
import TextField from "@mui/material/TextField/TextField";
import FormControl from "@mui/material/FormControl/FormControl";
import InputLabel from "@mui/material/InputLabel/InputLabel";
import Select from "@mui/material/Select/Select";
import MenuItem from "@mui/material/MenuItem/MenuItem";
import Button from "@mui/material/Button/Button";
import { useNavigate } from "react-router-dom";
import httpModule from "../../helpers/http.module";
const AddCompany = () => {
const [company, setCompany] = useState<ICreateCompanyDto>({ name: "", size: "" });
const redirect = useNavigate();
const handleClickSaveBtn = () => {
if (company.name === "" || company.size === "") {
alert("Fill all fields");
return;
}
httpModule
.post("/GasConsumption/Create", company)
.then((responst) => redirect("/companies"))
.catch((error) => console.log(error));
};
const handleClickBackBtn = () => {
redirect("/companies");
};
return (
<div className="content">
<div className="add-company">
<h2>Add New Company</h2>
<TextField
autoComplete="off"
label="Company Name"
variant="outlined"
value={company.name}
onChange={(e) => setCompany({ ...company, name: e.target.value })}
/>
<FormControl fullWidth>
<InputLabel>Company Size</InputLabel>
<Select
value={company.size}
label="Company Size"
onChange={(e) => setCompany({ ...company, size: e.target.value })}
>
<MenuItem value="Small">Small</MenuItem>
<MenuItem value="Medium">Medium</MenuItem>
<MenuItem value="Large">Large</MenuItem>
</Select>
</FormControl>
<div className="btns">
<Button variant="outlined" color="primary" onClick={handleClickSaveBtn}>
Save
</Button>
<Button variant="outlined" color="secondary" onClick={handleClickBackBtn}>
Back
</Button>
</div>
</div>
</div>
);
};
export default AddCompany | d2126df194809b78de557a801fea9f4e | {
"intermediate": 0.4372574985027313,
"beginner": 0.43964576721191406,
"expert": 0.123096764087677
} |
20,250 | You are a python programmer. You have to create a program that reads the bookmarks file of Google Chrome and presents it as a treeview container that stores all the folders in it. Every time a folder is clicked on, it shows the elements contained in that folder as well as its properties. The code to create must contain the opening of the bookmarks file and the loading of its records into the treeview. In summary, it must work just as the Windows file explorer does. | 44608c2cf7d0d82385eb9aa2679bd2d5 | {
"intermediate": 0.569588840007782,
"beginner": 0.16456939280033112,
"expert": 0.2658417522907257
} |
20,251 | You are a python programmer. You have to create a program that reads the
bookmarks file of Google Chrome and presents it as a treeview container that
stores all the folders in it. Every time a folder is clicked on, it shows the
elements contained in that folder as well as its properties. The code to create
must contain the opening of the bookmarks file and the loading of its records
into the treeview. In summary, it must work just as the Windows file explorer
does. | ccfb56eb287cc4337c64692fbd5e1cb8 | {
"intermediate": 0.546112596988678,
"beginner": 0.17155614495277405,
"expert": 0.282331258058548
} |
20,252 | create procedure get_list_region(OUT p_cursor refcursor)
language plpgsql
as
$$
declare
begin
open p_cursor for select distinct region_code, region_name from address;
end;
$$;
alter procedure get_list_region(out refcursor) owner to postgres;
how to call and check it in postgres | 73dd121d8f7731fd97b61c0428910ab6 | {
"intermediate": 0.4049142301082611,
"beginner": 0.3935016691684723,
"expert": 0.2015841156244278
} |
20,253 | You are a python programmer. You have to create a program that reads the
bookmarks file of Google Chrome and presents it as a treeview container that
stores all the folders in it. Every time a folder is clicked on, it shows the
elements contained in that folder as well as its properties. The code to create
must contain the opening of the bookmarks file and the loading of its records
into the treeview. In summary, it must work just as the Windows file explorer
does. | 456593b0fb19e84f83d87f6de46eb410 | {
"intermediate": 0.546112596988678,
"beginner": 0.17155614495277405,
"expert": 0.282331258058548
} |
20,254 | write a BGMI No recoil config file code and ready to use | 4b017e02a825e6c2d3045468fa5d2067 | {
"intermediate": 0.39692434668540955,
"beginner": 0.2181326299905777,
"expert": 0.38494300842285156
} |
20,255 | I got some data in access dataabase I want to show it in a report I 'm using vb.net program and crystal report for reporting I don't know how to do that | 7c8d8c5d509e9b30819de98bcc4d8b24 | {
"intermediate": 0.4384555518627167,
"beginner": 0.16679830849170685,
"expert": 0.39474615454673767
} |
20,256 | C# SendMessage show window | 929ec5eea5ed9b647533d0edf52dfd37 | {
"intermediate": 0.3463152348995209,
"beginner": 0.3619209825992584,
"expert": 0.2917637526988983
} |
20,257 | Use this MatLab code, but for the if-condition that identifies when the ball hits the wall or goes past the wall, modify the calculation by adding a linear interpolation. To do this, first assume the same equation of motion that would occur if the floor was not present. Then calculate the velocity that the ball will have just before the collision at 𝑦 = 0 using linear interpolation of a velocity versus height. Model the motion of the ball that is outside the time interval when it collides with the wall using a time resolution of 𝑑𝑡 = 0.001 seconds. At the wall, it will generally be the case that the time the ball hits the floor will not be a perfect multiple of 𝑑𝑡, but rather an incomplete time interval that must be ≤ 𝑑𝑡. As such, make tArray() non-uniform. Once the collision between the ball and floor takes place, you should then track the flight of the ball upward initially, and follow it back down until the ball hits the floor again. At this point, you will have the same situation. Repeat this cycle for 20 seconds. Each time you work out the time that the ball hits the floor, you will need to modify the tArray to reflect starting at the floor with some initial velocity upward.
%% simulating a bouncing ball: example code
% This script simulates a ball dropped or thrown in a vertical direction
% under constant gravitational acceleration. The ball will hit the floor
% and it will bounce a multiple number of times based on the coefficient
% of restitution given by epsilon. We have just before/after a collision.
% epsilon = |just after velocity| divided by |just before velocity|
%
% INPUT
% yo = initial height of ball
% vyo = initial velocity of ball in the y-direction
% dt = time resolution
% tMax = total time of the process
% epsilon = coefficient of restitution
%
% PROCESS
% solve differential equation using Euler's method
% use crude approximation to determine when ball hits floor
%
% OUTPUT
% height versus time graph
% velocity versus time graph
clear all % never not do this
%% set initial condition
to = 0; % initial time on clock (seconds)
yo = 2.5; % meters (m)
vyo = 5; % velocity --> meters/second (m/s)
dt = 0.001; % time resolution --> seconds (s)
tMax = 20; % maximum time range --> (s)
epsilon = 0.7; % coefficient of restitution
%% set constants
ay = -9.8; % acceleration due to gravity m/s^2
%% solve differential equation using Euler's method
tArray = to:dt:(to+tMax); % time range as an array (s)
npts = length(tArray);
y = zeros(1,npts); % preallocate the y array (height) (m)
vy = zeros(1,npts); % preallocate the vy array (height) (m)
y(1) = yo;
vy(1) = vyo;
% ------------------------------- calculate position as a function of time
for i=1:npts-1
% ----------------------------------------------------------- detect floor
t = tArray(i);
vy(i+1) = vy(i) + ay*dt;
y(i+1) = y(i) + vy(i)*dt;
if( y(i+1) <= 0 ) % => hit the floor with dt time resolution
vy(i+1) = - vy(i)*epsilon;
y(i+1) = 0;
end
end
%% plot results
figure(1);
clf;
plot(tArray,y,'b','lineWidth',1.8);
xlabel('time (seconds)');
ylabel('height (meters)');
figure(2);
clf;
plot(tArray,vy,'b','lineWidth',1.8);
xlabel('time (seconds)');
ylabel('velocity (meters)'); | 7157f5e1bf38c4329f8ac353b7a1a779 | {
"intermediate": 0.5012779235839844,
"beginner": 0.3257156014442444,
"expert": 0.17300650477409363
} |
20,258 | import {TradeItem} from “…/…/…/store/orderClusterSlice”;
import {OrderFeedProps} from “./OrderFeed.props”;
import {GPU} from “gpu.js”;
const OrderFeed = ({workerRef, symbol, settings}: OrderFeedProps) => {
const cupParams = useSelector((state: AppState) => state.cupSlice);
const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio));
const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0});
const containerRef = useRef<HTMLDivElement|null>(null);
const canvasRef = useRef<HTMLCanvasElement|null>(null);
const theme = useTheme();
const draw = (trades: TradeItem[], camera: number) => {
if (null === canvasRef || !Array.isArray(trades)) return;
const context = canvasRef.current?.getContext(“webgl”);
if (context) {
const gpu = new GPU({canvas: canvasRef, context});
orderFeedDrawer.clear(context, canvasSize);
orderFeedDrawer.drawLine(
context,
canvasSize,
trades,
camera,
cupParams.aggregatedPriceStep,
cupParams.cellHeight,
cupParams.quantityDivider,
!settings.minQuantity ? 0 : parseFloat(settings.minQuantity),
dpiScale,
theme,
);
orderFeedDrawer.drawChain(
context,
canvasSize,
trades,
camera,
cupParams.aggregatedPriceStep,
cupParams.cellHeight,
cupParams.quantityDivider,
cupParams.priceDivider,
!settings.minQuantity ? 0 : parseFloat(settings.minQuantity),
dpiScale,
theme,
settings.volumeAsDollars,
);
}
};
useEffect(() => {
if (!workerRef.current) return;
draw(event.data.trades, event.data.camera)
}, [workerRef.current, canvasRef.current, canvasSize, symbol
]);
return <Box ref={containerRef} className={${styles.canvasWrapper} scroll-block}>
<canvas
ref={canvasRef}
className={styles.canvas}
width={canvasSize?.width}
height={canvasSize?.height}
/>
</Box>;
};
export default OrderFeed;
const orderFeedDrawer = {
clear: (ctx: WebGLRenderingContext, size: CanvasSize) => {
ctx.clearRect(0, 0, size.width, size.height);
},
drawLine: (
ctx: WebGLRenderingContext,
canvasSize: CanvasSize,
trades: TradeItem[],
camera: number,
aggregatedPriceStep: number,
cupCellHeight: number,
quantityDivider: number,
minQuantity: number,
dpiScale: number,
theme: Theme,
) => {
let startX = canvasSize.width - 10 * dpiScale;
const fullHeightRowsCount = parseInt((canvasSize.height / cupCellHeight).toFixed(0));
const startY = (fullHeightRowsCount % 2 ? fullHeightRowsCount - 1 : fullHeightRowsCount) / 2 * cupCellHeight;
const halfCupCellHeight = cupCellHeight / 2;
ctx.beginPath();
ctx.strokeStyle = orderFeedOptions(theme).line.color;
ctx.lineWidth = (dpiScale) => 2 * dpiScale;
trades.forEach(trade => {
const yModifier = (trade.price - (trade.price - (trade?.secondPrice || trade.price)) / 2 - camera) / aggregatedPriceStep * cupCellHeight + halfCupCellHeight;
const width = 1.75 * clamp((trade.quantity / quantityDivider < minQuantity ? 0 : trade.radius), 5, 50) * dpiScale;
ctx.lineTo(startX - width / 2, startY - yModifier);
startX = startX - width;
});
ctx.stroke();
},
полностью напиши функцию orderFeedDrawer на библиотеку gpu.js по WebGLRenderingContext, у нас функциональные компоненты | 9eaa42d30356300b90d1e64332e1180c | {
"intermediate": 0.32557475566864014,
"beginner": 0.45786622166633606,
"expert": 0.2165590226650238
} |
20,259 | left join in c# using linq | c1bea1ff3de312d8e9f21962cf7928fd | {
"intermediate": 0.35246533155441284,
"beginner": 0.3166641592979431,
"expert": 0.33087047934532166
} |
20,260 | write code in C# for game flappy bird | 9e9844d0381f9f5fe8d092ee93a43104 | {
"intermediate": 0.29603806138038635,
"beginner": 0.41312068700790405,
"expert": 0.2908412516117096
} |
20,261 | `top` command how to display cwd also | 9cbf744b0647c6ad2d33e21e389df017 | {
"intermediate": 0.4022555947303772,
"beginner": 0.24097782373428345,
"expert": 0.35676661133766174
} |
20,262 | C# postmessage minimize window | 40065a4318485fe7c2199c3db3e6c775 | {
"intermediate": 0.3597228527069092,
"beginner": 0.40194952487945557,
"expert": 0.23832762241363525
} |
20,263 | how to make this code faster, but without extra imports:
//********************'*******************
// Program: Dio.java
//
// Purpose: Make k = x3 + y3 + z3 work, with certain ranges
// Made by Michael Ortola
// Mr Friebe's Class
// Finished 9/5/23
//***************************************
import java.util.Scanner;
public class Dio_MAO {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// ET start - insert at start of algorithm of interest
long et = System.nanoTime();
System.out.print("Enter range for k: ");
int krange = scan.nextInt();
System.out.print("Enter span for x, y, z: ");
int span = scan.nextInt();
System.out.println("");
int solution = 0;
for (int k = 0; k <= krange; k++)
{
boolean solutionFound = false;
for (int x = -span; x <= span && !solutionFound; x++)
{
for (int y = -span; y <= span && !solutionFound; y++) //negative span to positive span, is the range xyz can be pickekd
{
int z = (int) Math.cbrt(k - x*x*x - y*y*y);
if (z*z*z == k - x*x*x - y*y*y)
{
System.out.println("k: " + k + ", x: " + x + ", y: " + y + ", z: " + z);
solutionFound = true;
// used for the the check later in the code to find not founds
solution++;
}
}
}
if (!solutionFound)
{
System.out.println("k: " + k + " Not found!");
}
}
// ET end - insert at end of algorithm of interest
et = System.nanoTime() - et;
System.out.println("\nSolution(s) found for " + solution + " values of k.");
System.out.printf("\nElapsed time: %.2E nsecs", (double) et);
}
} | df18de5d42fd098aa932c900f4ce22b1 | {
"intermediate": 0.37528765201568604,
"beginner": 0.310712993144989,
"expert": 0.31399938464164734
} |
20,264 | We know the exact equations of motion of the ball, except during the collision. However, by assuming the collisions take place instantaneously, we can solve the equations of motion up to the exact instant of time the ball touches the floor, and then, switch the velocity using the coefficient of restitution, and then, solve the exact analytical equations again until the next exact time the ball hits the floor. In this case, use non uniform 𝑑𝑡. Since you can calculate the time between bounces, always plot 40 points between the times the ball bounces. In this way, you will have an exact solution under the simplifying assumptions of the model. Make a code in MatLab by modifying the code below:
%% simulating a bouncing ball
% This script simulates a ball dropped or thrown in a vertical direction
% under constant gravitational acceleration. The ball will hit the floor
% and it will bounce a multiple number of times based on the coefficient
% of restitution given by epsilon. We have just before/after a collision.
% epsilon = |just after velocity| divided by |just before velocity|
%
% INPUT
% yo = initial height of ball
% vyo = initial velocity of ball in the y-direction
% dt = time resolution
% tMax = total time of the process
% epsilon = coefficient of restitution
%
% PROCESS
% solve differential equation using Euler’s method
% use crude approximation to determine when ball hits floor
%
% OUTPUT
% height versus time graph
% velocity versus time graph
clear all % never not do this
%% set initial condition
to = 0; % initial time on clock (seconds)
yo = 2.5; % meters (m)
vyo = 5; % velocity --> meters/second (m/s)
dt = 0.001; % time resolution --> seconds (s)
tMax = 20; % maximum time range --> (s)
epsilon = 0.7; % coefficient of restitution (unitless)
%% set constants
ay = -9.8; % acceleratin due to gravity m/s^2
%% solve differential equation using Euler’s method
%% Create interpolation data for velocity versus height
heights = [0, 2.5]; % heights at which velocity is known (m)
velocities = [0, vyo]; % velocities at corresponding heights (m/s)
v_interpolation = @(h) interp1(heights, velocities, h); % interpolation function
%% solve differential equation using Euler’s method
tArray = to; % time range as an array (s)
y = yo; % preallocate the y array (height) (m)
vy = vyo; % preallocate the vy array (height) (m)
% ------------------------------- calculate position as a function of time
while tArray(end) < (to+tMax)
% ----------------------------------------------------------- detect floor
t = tArray(end);
vy_next = vy(end) + ay*dt;
y_next = y(end) + vy(end)dt;
if (y_next <= 0) % => hit the floor with dt time resolution
% Linear interpolation for velocity just before collision at y = 0
vy_collision = v_interpolation(y_next);
% Update the velocity and height after collision
vy_next = - vy_collisionepsilon;
y_next = 0;
% Append the interpolated velocities and heights to the arrays
tArray = [tArray, t+dt/2, t+dt];
vy = [vy, vy_collision, vy_next];
y = [y, 0, 0];
else
% Append the next velocity and height to the arrays
tArray = [tArray, t+dt];
vy = [vy, vy_next];
y = [y, y_next];
end
end
%% plot results
figure(1);
clf;
plot(tArray,y,‘b’,‘lineWidth’,1.8);
xlabel(‘time (seconds)’);
ylabel(‘height (meters)’);
figure(2);
plot(tArray,vy,‘b’,‘lineWidth’,1.8);
xlabel(‘time (seconds)’);
ylabel(‘velocity (meters)’); | 5fedbce5b99d4fb4cf1c15b819f7dfd8 | {
"intermediate": 0.44254881143569946,
"beginner": 0.3889349699020386,
"expert": 0.16851617395877838
} |
20,265 | please make the code in google colab | 5f03cdc3929d9df930250bc9c8c44303 | {
"intermediate": 0.3269943594932556,
"beginner": 0.23097936809062958,
"expert": 0.442026287317276
} |
20,266 | train an ai w ith python on two types of images with diffrent sized images stored in two diffrent folders.
teach it to differenciate between them
make two programs one to train and annother to use the model. | d9dbb4ab9e0f18cfb20f19ec1d05a78c | {
"intermediate": 0.31581729650497437,
"beginner": 0.0894792377948761,
"expert": 0.5947034358978271
} |
20,267 | I used this code:
lookback = 10080
quantity = 0.05
active_signal = None
buy_entry_price = None
sell_entry_price = None
def calculate_percentage_difference(entry_price, exit_price):
percentage_difference = ((exit_price - entry_price) / entry_price) * 100
return percentage_difference
while True:
if df is not None:
signals = signal_generator(df)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}")
if 'buy' in signals and active_signal != 'buy':
try:
active_signal = 'buy'
buy_entry_price = mark_price # Record the Buy entry price
print(f"Buy Entry Price: {buy_entry_price}")
# Execute Buy orders here
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
print("Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
if buy_entry_price is not None and sell_entry_price is not None:
buy_exit_price = sell_entry_price
difference_buy = calculate_percentage_difference(buy_entry_price, buy_exit_price)
profit_buy = difference_buy * 50
total_profit_buy = profit_buy - (0.04 * profit_buy)
print(f"Buy Profit: {total_profit_buy} %, buy entry: {buy_entry_price}, sell entry {sell_entry_price}")
else:
print("Buy Entry price or Sell Entry price is not defined.")
elif 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
# Execute sell orders here
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
if sell_entry_price is not None and buy_entry_price is not None:
sell_exit_price = buy_entry_price
difference_sell = calculate_percentage_difference(sell_entry_price, sell_exit_price)
profit_sell = difference_sell * 50
total_profit_sell = profit_sell - (0.04 * profit_sell)
print(f"Sell Profit: {total_profit_sell} %, sell entry price {sell_entry_price} buy entry price {buy_entry_price}")
else:
print("Sell Entry price or Buy Entry price is not defined.")
time.sleep(1)
But it returning me wrong info, just look at Sell or buy profit and entry prices: The signal time is: 2023-09-18 19:30:20, Price 220.46 - Signals: ['sell']
Sell Entry Price: 220.46
Error executing short order:
Sell Profit: -3.0481720039919757 %, sell entry price 220.46 buy entry price 220.32
The signal time is: 2023-09-18 19:30:22, Price 220.42 - Signals: ['']
The signal time is: 2023-09-18 19:30:24, Price 220.46 - Signals: ['']
The signal time is: 2023-09-18 19:30:26, Price 220.47 - Signals: ['buy']
Buy Entry Price: 220.47
Error executing long order:
Buy Profit: -0.2177166961489379 %, buy entry: 220.47, sell entry 220.46 | 1c5ca248b4411886ef111a9851a32c1d | {
"intermediate": 0.38162529468536377,
"beginner": 0.42440295219421387,
"expert": 0.19397176802158356
} |
20,268 | Hello! Can you please generate code that takes in a first and last name and determines if they both start with the same letter written in htdp beginner student language? | fa8f1993658337ddfd7e6146129f4b41 | {
"intermediate": 0.4991542398929596,
"beginner": 0.23285037279129028,
"expert": 0.26799532771110535
} |
20,269 | I have the matrix with 2928 row and 5 column , write the code to remove the row that contains one column that is zero. | 5a10aaa2cd0ab3669d8903c14a2bb3a2 | {
"intermediate": 0.33090919256210327,
"beginner": 0.18126176297664642,
"expert": 0.4878290593624115
} |
20,270 | I am making an ai to detect not safe for work imagery and flag it and also add tags to what it thinks it is.
currently my dataset is just pictures, please make two python scripts to 1, train the model, and 2 to use the model and annotate test data | 2be40b1c9caa7b18fba49965e68a4290 | {
"intermediate": 0.5447657704353333,
"beginner": 0.046812426298856735,
"expert": 0.4084217846393585
} |
20,271 | in python make an image generative ai, for now I just want it to train the model on the spot with images found in a folder.
all the images are in diffrent sizes and I cant change them so you are gonna have to accomodate for that.
make it train the model if it doesnt already detect one in the file system and if it does use it on the test data folder | 7c0f097cb0489028b2a559d1945b4d6a | {
"intermediate": 0.31460288166999817,
"beginner": 0.16367289423942566,
"expert": 0.521724283695221
} |
20,272 | in python make an image generative ai, for now I just want it to train the model on the spot with images found in a folder.
all the images are in diffrent sizes and I cant change them so you are gonna have to accomodate for that.
make it train the model if it doesnt already detect one in the file system and if it does use it on the test data folder
also remember that in newer versions of tensorflow you import keras by tensorflow.python.keras not tensorflow.keras | 9c895049e5e91c716ff6cc6819dd8c3b | {
"intermediate": 0.439619243144989,
"beginner": 0.1482652723789215,
"expert": 0.4121154546737671
} |
20,273 | in python make an image generative ai, for now I just want it to train the model on the spot with images found in a folder.
all the images are in diffrent sizes and I cant change them so you are gonna have to accomodate for that.
make it train the model if it doesnt already detect one in the file system and if it does generate the x amm of images to a specified folder.
also remember that in newer versions of tensorflow you import keras by tensorflow.python.keras not tensorflow.keras | 142b40c36bcad472f795dbc353ca140c | {
"intermediate": 0.4342935085296631,
"beginner": 0.16664715111255646,
"expert": 0.39905935525894165
} |
20,274 | FROM python:3.12-slim
ADD requirements.txt .
RUN apt update
RUN pip install --upgrade pip --no-cache-dir
RUN pip install -r requirements.txt --no-cache-dir
ENV PORT 5000
CMD["mlflow", "ui", "-port", "5000"]
--------------------
8 | ENV PORT 5000
9 |
10 | >>> CMD["mlflow", "ui", "-port", "5000"]
--------------------
ERROR: failed to solve: dockerfile parse error on line 10: unknown instruction: CMD["mlflow", | afbe88793df1d68cc0fb4b2ade40b194 | {
"intermediate": 0.35321351885795593,
"beginner": 0.3654036223888397,
"expert": 0.28138279914855957
} |
20,275 | write c++ code to start local server and handle http requests to specific uri | 3dedc721b81721106a98f0828385953e | {
"intermediate": 0.3879469931125641,
"beginner": 0.1901836097240448,
"expert": 0.4218693673610687
} |
20,276 | how to use early stop validation in MLP in matlab? | fa2638e22242d687d82e3fc971a78768 | {
"intermediate": 0.20136497914791107,
"beginner": 0.054236967116594315,
"expert": 0.7443979978561401
} |
20,277 | python how to get n work days ago | ee6669de681d1984afc530976d60bf2d | {
"intermediate": 0.33974939584732056,
"beginner": 0.21764534711837769,
"expert": 0.44260528683662415
} |
20,278 | у меня есть вот такой код,как мне перейти сразу к определенному моменту в анимации?
код:
const modelWithCube = gltf.scene;
const animations = gltf.animations;
const mixer = new THREE.AnimationMixer(modelWithCube);
const startTime = 3;
const realTime = 5;
for (let i = 0; i < animations.length; i++) {
const clip = animations[i];
animations[i].playbackSpeed = 0.01;
mixer.clipAction(clip).play();
} | c02bc919cc01607eb19bdbafadf12aa7 | {
"intermediate": 0.4308280944824219,
"beginner": 0.2887521982192993,
"expert": 0.2804197072982788
} |
20,279 | C# allow only one instance of the app to be running on the machine | 8b9e275942b618b345eb5100eaabb539 | {
"intermediate": 0.42934736609458923,
"beginner": 0.21941153705120087,
"expert": 0.3512411415576935
} |
20,280 | im on arch linux I need a simple way to emulate android games specifically one that can play asure lane | d7d0b1e0c908e02a2f70152c698a3d44 | {
"intermediate": 0.4828861355781555,
"beginner": 0.26699885725975037,
"expert": 0.25011494755744934
} |
20,281 | Create a summary of this, including examples in python: "Functions take some input then produce some output or change. The function is just a piece of code you can reuse. You can implement your own function, but in many cases, you use other people’s functions. In this case, you just have to know how the function works and in some cases how to import the functions. Let the orange and yellow squares represent similar blocks of code. We can run the code using some input and get an output. If we define a function to do the task we just have to call the function. Let the small squares represent the lines of code used to call the function. We can replace these long lines of code by just calling the function a few times. Now we can just call the function; our code is much shorter. The code performs the same task. You can think of the process like this: when we call the function f1, we pass an input to the function. These values are passed to all those lines of code you wrote. This returns a value; you can use the value. For example, you can input this value to a new function f2. When we call this new function f2, the value is passed to another set of lines of code. The function returns a value. The process is repeated passing the values to the function you call. You can save these functions and reuse them, or use other people’s functions. Python has many built-in functions; you don't have to know how those functions work internally, but simply what task those functions perform. The function len takes in an input of type sequence, such as a string or list, or type collection, such as a dictionary or set, and returns the length of that sequence or collection. Consider the following list. The len function takes this list as an argument, and we assign the result to the variable L. The function determines there are 8 items in the list, then returns the length of the list, in this case, 8. The function sum takes in an iterable like a tuple or list and returns the total of all the elements. Consider the following list. We pass the list into the sum function and assign the result to the variable S. The function determines the total of all the elements, then returns it, in this case, the value is 70. There are two ways to sort a list. The first is using the function sorted. We can also use the list method sort. Methods are similar to functions. Let's use this as an example to illustrate the difference. The function sorted Returns a new sorted list or tuple. Consider the list album ratings. We can apply the function sorted to the list album ratings and get a new list sorted album rating. The result is a new sorted list. If we look at the list album ratings, nothing has changed. Generally, functions take an input, in this case, a list. They produce a new output, in this instance, a sorted list. If we use the method sort, the list album ratings will change and no new list will be created. Let's use this diagram to help illustrate the process. In this case, the rectangle represents the list album ratings. When we apply the method sort to the list, the list album rating changes. Unlike the previous case, we see that the list album rating has changed. In this case, no new list is created. Now that we have gone over how to use functions in Python, let’s see how to build our own functions. We will now get you started on building your own functions in python. This is an example of a function in python that returns its input value + 1. To define a function, we start with the keyword def. The name of the function should be descriptive of what it does. We have the function formal parameter "A" in parentheses. Followed by a colon. We have a code block with an indent, for this case, we add 1 to "A" and assign it to B. We return or output the value for b. After we define the function, we can call it. The function will add 1 to 5 and return a 6. We can call the function again; this time assign it to the variable "c" The value for 'c' is 11. Let's explore this further. Let's go over an example when you call a function. It should be noted that this is a simplified model of Python, and Python does not work like this under the hood. We call the function giving it an input, 5. It helps to think of the value of 5 as being passed to the function. Now the sequences of commands are run, the value of "A" is 5. "B" would be assigned a value of 6. We then return the value of b, in this case, as b was assigned a value of 6, the function returns a 6. If we call the function again, the process starts from scratch; we pass in an 8. The subsequent operations are performed. Everything that happened in the last call will happen again with a different value of "A" The function returns a value, in this case, 9. Again, this is just a helpful analogy. Let’s try and make this function more complex. It's customary to document the function on the first few lines; this tells anyone who uses the function what it does. This documentation is surrounded in triple quotes. You can use the help command on the function to display the documentation as follows. This will printout the function name and the documentation. We will not include the documentation in the rest of the examples. A function can have multiple parameters. The function mult multiplies two numbers; in other words, it finds their product. If we pass the integers 2 and 3, the result is a new integer. If we pass the integer 10 and the float 3.14, the result is a float 31.4. If we pass in the integer two and the string “Michael Jackson,” the string Michael Jackson is repeated two times. This is because the multiplication symbol can also mean repeat a sequence. If you accidentally multiply an integer and a String instead of two integers, you won’t get an error. Instead, you will get a String, and your program will progress, potentially failing later because you have a String where you expected an integer. This property will make coding simpler, but you must test your code more thoroughly. In many cases a function does not have a return statement. In these cases, Python will return the special “None” object. Practically speaking, if your function has no return statement, you can treat it as if the function returns nothing at all. The function MJ simply prints the name 'Michael Jackson’. We call the function. The function prints “Michael Jackson.” Let's define the function “No work” that performs no task. Python doesn’t allow a function to have an empty body, so we can use the keyword pass, which doesn’t do anything, but satisfies the requirement of a non-empty body. If we call the function and print it out, the function returns a None. In the background, if the return statement is not called, Python will automatically return a None. It is helpful to view the function No Work with the following return statement. Usually, functions perform more than one task. This function prints a statement then returns a value. Let's use this table to represent the different values as the function is called. We call the function with an input of 2. We find the value of b. The function prints the statement with the values of a and b. Finally, the function returns the value of b, in this case, 3. We can use loops in functions. This function prints out the values and indexes of a loop or tuple. We call the function with the list album ratings as an input. Let's display the list on the right with its corresponding index. Stuff is used as an input to the function enumerate. This operation will pass the index to i and the value in the list to “s”. The function would begin to iterate through the loop. The function will print the first index and the first value in the list. We continue iterating through the loop. The values of i and s are updated. The print statement is reached. Similarly, the next values of the list and index are printed. The process is repeated. The values of i and s are updated. We continue iterating until the final values in the list are printed out. Variadic parameters allow us to input a variable number of elements. Consider the following function; the function has an asterisk on the parameter names. When we call the function, three parameters are packed into the tuple names. We then iterate through the loop; the values are printed out accordingly. If we call the same function with only two parameters as inputs, the variable names only contain two elements. The result is only two values are printed out. The scope of a variable is the part of the program where that variable is accessible. Variables that are defined outside of any function are said to be within the global scope, meaning they can be accessed anywhere after they are defined. Here we have a function that adds the string DC to the parameter x. When we reach the part where the value of x is set to AC, this is within the global scope, meaning x is accessible anywhere after it is defined. A variable defined in the global scope is called a global variable. When we call the function, we enter a new scope or the scope of AddDC. We pass as an argument to the AddDC function, in this case, AC. Within the scope of the function, the value of x is set to ACDC. The function returns the value and is assigned to z. Within the global scope, the value z is set to ACDC After the value is returned, the scope of the function is deleted. Local variables only exist within the scope of a function. Consider the function thriller; the local variable Date is set to 1982. When we call the function, we create a new scope. Within that scope of the function, the value of the date is set to 1982. The value of date does not exist within the global scope. Variables inside the global scope can have the same name as variables in the local scope with no conflict. Consider the function thriller; the local variable Date is set to 1982. The global variable date is set to 2017. When we call the function, we create a new scope. Within that scope, the value of the date is set to 1982. If we call the function, it returns the value of Date in the local scope, in this case, 1982. (click6) When we print in the global scope, we use the global variable value. The global value of the variable is 2017. Therefore, the value is set to 2017. If a variable is not defined within a function, Python will check the global scope. Consider the function "AC-DC“. The function has the variable rating, with no value assigned. If we define the variable rating in the global scope, then call the function, Python will see there is no value for the variable Rating. As a result, python will leave the scope and check if the variable Ratings exists in the global scope. It will use this value of Ratings in the global scope within the scope of "AC-DC“. In the function, will print out a 9. The value of z in the global scope will be 10, as we added one. The value of rating will be unchanged within the global scope. Consider the function Pink Floyd. If we define the variable Claimed Sales with the keyword global, the variable will be a global variable. We call the function Pink Floyd. The variable claimed sales is set to the string “45 million” in the global scope. When we print the variable, we get a value of “45 million.”" | e84d922924ff336ffec8fb8b5e6d6332 | {
"intermediate": 0.5597121715545654,
"beginner": 0.3214842975139618,
"expert": 0.1188034862279892
} |
20,282 | Command "C:\Users\Nada\AppData\Local\Programs\Python\Python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Nada\\AppData\\Local\\Temp\\pip-build-a0g7pnzo\\typed-ast\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Nada\AppData\Local\Temp\pip-6xwv18_y-record\install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in C:\Users\Nada\AppData\Local\Temp\pip-build-a0g7pnzo\typed-ast\
You are using pip version 9.0.1, however version 23.2.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command. حل الايرور | 039a56996b4645c94fb3097129c93210 | {
"intermediate": 0.3873458504676819,
"beginner": 0.3344966769218445,
"expert": 0.27815744280815125
} |
20,283 | Write me a set of bitwise operations such that a 4 bit number will only have 13 unique values | db06f1e8004672281e55a0d43542fa4b | {
"intermediate": 0.34114110469818115,
"beginner": 0.11333448439836502,
"expert": 0.5455244779586792
} |
20,284 | What is it called in C when you can use the same struct with functions expecting different structs but with the same starting fields? | 479afef9d517bdc10d434a6566433d1b | {
"intermediate": 0.31886643171310425,
"beginner": 0.4383170008659363,
"expert": 0.2428164929151535
} |
20,285 | Create a summary of this text, and make python examples for the problems given: " Functions take some input then produce some output or change. The function is just a piece of code you can reuse. You can implement your own function, but in many cases, you use other people’s functions. In this case, you just have to know how the function works and in some cases how to import the functions. Let the orange and yellow squares represent similar blocks of code. We can run the code using some input and get an output. If we define a function to do the task we just have to call the function. Let the small squares represent the lines of code used to call the function. We can replace these long lines of code by just calling the function a few times. Now we can just call the function; our code is much shorter. The code performs the same task. You can think of the process like this: when we call the function f1, we pass an input to the function. These values are passed to all those lines of code you wrote. This returns a value; you can use the value. For example, you can input this value to a new function f2. When we call this new function f2, the value is passed to another set of lines of code. The function returns a value. The process is repeated passing the values to the function you call. You can save these functions and reuse them, or use other people’s functions. Python has many built-in functions; you don't have to know how those functions work internally, but simply what task those functions perform. The function len takes in an input of type sequence, such as a string or list, or type collection, such as a dictionary or set, and returns the length of that sequence or collection. Consider the following list. The len function takes this list as an argument, and we assign the result to the variable L. The function determines there are 8 items in the list, then returns the length of the list, in this case, 8. The function sum takes in an iterable like a tuple or list and returns the total of all the elements. Consider the following list. We pass the list into the sum function and assign the result to the variable S. The function determines the total of all the elements, then returns it, in this case, the value is 70. There are two ways to sort a list. The first is using the function sorted. We can also use the list method sort. Methods are similar to functions. Let's use this as an example to illustrate the difference. The function sorted Returns a new sorted list or tuple. Consider the list album ratings. We can apply the function sorted to the list album ratings and get a new list sorted album rating. The result is a new sorted list. If we look at the list album ratings, nothing has changed. Generally, functions take an input, in this case, a list. They produce a new output, in this instance, a sorted list. If we use the method sort, the list album ratings will change and no new list will be created. Let's use this diagram to help illustrate the process. In this case, the rectangle represents the list album ratings. When we apply the method sort to the list, the list album rating changes. Unlike the previous case, we see that the list album rating has changed. In this case, no new list is created. Now that we have gone over how to use functions in Python, let’s see how to build our own functions. We will now get you started on building your own functions in python. This is an example of a function in python that returns its input value + 1. To define a function, we start with the keyword def. The name of the function should be descriptive of what it does. We have the function formal parameter "A" in parentheses. Followed by a colon. We have a code block with an indent, for this case, we add 1 to "A" and assign it to B. We return or output the value for b. After we define the function, we can call it. The function will add 1 to 5 and return a 6. We can call the function again; this time assign it to the variable "c" The value for 'c' is 11. Let's explore this further. Let's go over an example when you call a function. It should be noted that this is a simplified model of Python, and Python does not work like this under the hood. We call the function giving it an input, 5. It helps to think of the value of 5 as being passed to the function. Now the sequences of commands are run, the value of "A" is 5. "B" would be assigned a value of 6. We then return the value of b, in this case, as b was assigned a value of 6, the function returns a 6. If we call the function again, the process starts from scratch; we pass in an 8. The subsequent operations are performed. Everything that happened in the last call will happen again with a different value of "A" The function returns a value, in this case, 9. Again, this is just a helpful analogy. Let’s try and make this function more complex. It's customary to document the function on the first few lines; this tells anyone who uses the function what it does. This documentation is surrounded in triple quotes. You can use the help command on the function to display the documentation as follows. This will printout the function name and the documentation. We will not include the documentation in the rest of the examples. A function can have multiple parameters. The function mult multiplies two numbers; in other words, it finds their product. If we pass the integers 2 and 3, the result is a new integer. If we pass the integer 10 and the float 3.14, the result is a float 31.4. If we pass in the integer two and the string “Michael Jackson,” the string Michael Jackson is repeated two times. This is because the multiplication symbol can also mean repeat a sequence. If you accidentally multiply an integer and a String instead of two integers, you won’t get an error. Instead, you will get a String, and your program will progress, potentially failing later because you have a String where you expected an integer. This property will make coding simpler, but you must test your code more thoroughly. In many cases a function does not have a return statement. In these cases, Python will return the special “None” object. Practically speaking, if your function has no return statement, you can treat it as if the function returns nothing at all. The function MJ simply prints the name 'Michael Jackson’. We call the function. The function prints “Michael Jackson.” Let's define the function “No work” that performs no task. Python doesn’t allow a function to have an empty body, so we can use the keyword pass, which doesn’t do anything, but satisfies the requirement of a non-empty body. If we call the function and print it out, the function returns a None. In the background, if the return statement is not called, Python will automatically return a None. It is helpful to view the function No Work with the following return statement. Usually, functions perform more than one task. This function prints a statement then returns a value. Let's use this table to represent the different values as the function is called. We call the function with an input of 2. We find the value of b. The function prints the statement with the values of a and b. Finally, the function returns the value of b, in this case, 3. We can use loops in functions. This function prints out the values and indexes of a loop or tuple. We call the function with the list album ratings as an input. Let's display the list on the right with its corresponding index. Stuff is used as an input to the function enumerate. This operation will pass the index to i and the value in the list to “s”. The function would begin to iterate through the loop. The function will print the first index and the first value in the list. We continue iterating through the loop. The values of i and s are updated. The print statement is reached. Similarly, the next values of the list and index are printed. The process is repeated. The values of i and s are updated. We continue iterating until the final values in the list are printed out. Variadic parameters allow us to input a variable number of elements. Consider the following function; the function has an asterisk on the parameter names. When we call the function, three parameters are packed into the tuple names. We then iterate through the loop; the values are printed out accordingly. If we call the same function with only two parameters as inputs, the variable names only contain two elements. The result is only two values are printed out. The scope of a variable is the part of the program where that variable is accessible. Variables that are defined outside of any function are said to be within the global scope, meaning they can be accessed anywhere after they are defined. Here we have a function that adds the string DC to the parameter x. When we reach the part where the value of x is set to AC, this is within the global scope, meaning x is accessible anywhere after it is defined. A variable defined in the global scope is called a global variable. When we call the function, we enter a new scope or the scope of AddDC. We pass as an argument to the AddDC function, in this case, AC. Within the scope of the function, the value of x is set to ACDC. The function returns the value and is assigned to z. Within the global scope, the value z is set to ACDC After the value is returned, the scope of the function is deleted. Local variables only exist within the scope of a function. Consider the function thriller; the local variable Date is set to 1982. When we call the function, we create a new scope. Within that scope of the function, the value of the date is set to 1982. The value of date does not exist within the global scope. Variables inside the global scope can have the same name as variables in the local scope with no conflict. Consider the function thriller; the local variable Date is set to 1982. The global variable date is set to 2017. When we call the function, we create a new scope. Within that scope, the value of the date is set to 1982. If we call the function, it returns the value of Date in the local scope, in this case, 1982. (click6) When we print in the global scope, we use the global variable value. The global value of the variable is 2017. Therefore, the value is set to 2017. If a variable is not defined within a function, Python will check the global scope. Consider the function "AC-DC“. The function has the variable rating, with no value assigned. If we define the variable rating in the global scope, then call the function, Python will see there is no value for the variable Rating. As a result, python will leave the scope and check if the variable Ratings exists in the global scope. It will use this value of Ratings in the global scope within the scope of "AC-DC“. In the function, will print out a 9. The value of z in the global scope will be 10, as we added one. The value of rating will be unchanged within the global scope. Consider the function Pink Floyd. If we define the variable Claimed Sales with the keyword global, the variable will be a global variable. We call the function Pink Floyd. The variable claimed sales is set to the string “45 million” in the global scope. When we print the variable, we get a value of “45 million.” | 313679faa77ebe4bb6fecd057d9eccf0 | {
"intermediate": 0.44995227456092834,
"beginner": 0.37607982754707336,
"expert": 0.1739678531885147
} |
20,286 | Stevens Institute of Technology is considering constructing a new academic building on the corner of
5th Street and Sinatra Drive. The proposed building
would alleviate space constraints on research and
educational activities, but it would also add significant debt and interest payments to the budget.
You have been contracted by the Board of Trustees
to study this problem and make recommendations.
Figure 1.1 shows several approaches to study a system that you are considering.
(a) 2 PTS Identify a part of the problem that could
be studied using an example of non-simulation
analysis (actual system, physical model, or analytical model) and explain why.
(b) 2 PTS Identify a part of the problem that could
be studied using an example of simulation analysis and explain why.
(c) 1 PT For your simulation analysis example given
above, describe whether it should be static/dynamic
and deterministic/stochastic and explain why. | 24fd6d3b837979b82168b0148214c0e1 | {
"intermediate": 0.31064894795417786,
"beginner": 0.40338051319122314,
"expert": 0.2859704792499542
} |
20,287 | Write code to solve: Problem Description
In the CCC Word Hunt, words are hidden in a grid of letters. The letters of a hidden word
always appear in order on horizontal, vertical, or diagonal line segments in one of two ways.
One way is for the letters of a word to appear on one line segment. The other way is for the
letters of a word to appear on one line segment up to some letter and then on a second line
segment that forms a right angle at this letter.
Given a grid of letters and a single word to search for, your job is to determine the number
of times that particular word is hidden in the grid.
Input Specification
The first line of input will contain a string of distinct uppercase letters, W, representing the
word you are to search for in the grid. The length of W will be at least two. The second line
of input will be an integer R (1 R 100), where R is the number of rows in the grid. The
third line of input will be an integer C (1 C 100), where C is the number of columns in
the grid.
The remaining input will provide the letters in the grid. It will consist of R lines, where
each line contains C uppercase letters separated by single spaces | a9ffa16ca87a0f7570d0cc67e4ce2c48 | {
"intermediate": 0.39148199558258057,
"beginner": 0.260162353515625,
"expert": 0.3483556807041168
} |
20,288 | in python is is def Mult(a,b) the same as def Multiply(a,b)? | cb9f6cde206e9f3c369e3798eacdeb12 | {
"intermediate": 0.26468268036842346,
"beginner": 0.49545013904571533,
"expert": 0.2398671656847
} |
20,289 | How do I have 13 unique next to each other numbers cycle in a 4 bit number using only bit operations. | a24502596c003f05a13f1317b855ed66 | {
"intermediate": 0.33459779620170593,
"beginner": 0.1613895744085312,
"expert": 0.5040126442909241
} |
20,290 | Come up with a function that divides the first input by the second input: | 4c42ff499a58ac7b2de9e598f36579d7 | {
"intermediate": 0.30664917826652527,
"beginner": 0.2682681381702423,
"expert": 0.42508262395858765
} |
20,291 | C# form of typedef | 46ae37dd9701c8cb7d336b9b47055bf4 | {
"intermediate": 0.319908082485199,
"beginner": 0.4037322998046875,
"expert": 0.2763596475124359
} |
20,292 | addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// 语音合成逻辑...
const handleRequest = async (request) => {
if (request.url.includes('/audio')) {
// 获取参数并生成音频响应
const text = getParameter('text', request);
const rate = getParameter('rate', request);
const pitch = getParameter('pitch', request);
const audio = await synthesizeSpeech(text, rate, pitch);
return new Response(audio, {
headers: {
'Content-Type': 'audio/mpeg',
}
});
} else {
// 返回 HTML 页面
return new Response(`
<!DOCTYPE html>
<html>
<body>
<h1>文本转语音</h1>
<label>输入文本:</label>
<textarea id="text"></textarea>
<label>语速:</label>
<select id="rate">
<option value="0%">正常</option>
<option value="-10%">慢</option>
<option value="+10%">快</option>
</select>
<label>音调:</label>
<select id="pitch">
<option value="0%">正常</option>
<option value="-10%">低沉</option>
<option value="+10%">尖细</option>
</select>
<button id="generate">生成音频</button>
<audio id="audio" controls></audio>
<script>
const textarea = document.getElementById('text');
const rateSelect = document.getElementById('rate');
const pitchSelect = document.getElementById('pitch');
const generateBtn = document.getElementById('generate');
generateBtn.addEventListener('click', async () => {
const text = textarea.value;
const rate = rateSelect.value;
const pitch = pitchSelect.value;
const url = '/audio?text=' + encodeURIComponent(text) +
'&rate=' + rate + '&pitch=' + pitch;
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const audio = document.getElementById('audio');
audio.src = URL.createObjectURL(new Blob([arrayBuffer]));
});
</script>
</body>
</html>
`, {
headers: {
'Content-Type': 'text/html;charset=UTF-8',
}
});
}
}
function getParameter(name, request) {
const url = new URL(request.url);
return url.searchParams.get(name);
}
// 语音合成函数
async function synthesizeSpeech(text, rate, pitch) {
// ...生成音频
} | ff13e40d262a0af81c8a588622d8e705 | {
"intermediate": 0.3491494953632355,
"beginner": 0.5531803965568542,
"expert": 0.09767015278339386
} |
20,293 | how to use chagpt 4 | 24e9b9ab63be9b9a4b214779d15e9249 | {
"intermediate": 0.3629959523677826,
"beginner": 0.3449947237968445,
"expert": 0.2920093536376953
} |
20,294 | write a bash script to add a dns cname record on digital ocean using their api and curl | 34fecec709ab0dbe140c7cfb9e313da0 | {
"intermediate": 0.6172878742218018,
"beginner": 0.16200722754001617,
"expert": 0.2207048535346985
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.