row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
41,461
|
using System;
using System.IO;
using System.Threading;
namespace Ekiscopp.Modele.Generateur_appli.data
{
public delegate void DelegateFunction(string message);
public class FileModificationListener
{
private string path;
private FileSystemWatcher _watcher;
private DelegateFunction myDelegateFunction;
public FileModificationListener(DelegateFunction myDelegateFunction)
{
this.myDelegateFunction = myDelegateFunction;
}
public void SetPath(string path)
{
StopWatching();
this.path = path;
StartWatching();
}
public void StopWatching()
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
}
}
private void StartWatching()
{
string directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
{
Console.WriteLine("Invalid directory path.");
return;
}
string filename = Path.GetFileName(path);
Console.WriteLine(filename);
_watcher = new FileSystemWatcher(directory)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName,
};
// Subscribe to the events of the FileSystemWatcher
_watcher.Changed += OnChanged;
_watcher.Created += OnChanged;
_watcher.Deleted += OnChanged;
_watcher.Renamed += OnRenamed;
_watcher.Error += OnError;
_watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"FullPath: {e.FullPath}, Name: {e.Name}, Expected Path: {path}");
if (e.Name != Path.GetFileName(path))
{
return;
}
if (e.ChangeType == WatcherChangeTypes.Changed)
{
DateTime lastModified = File.GetLastWriteTime(e.FullPath);
// Display last modification time in the format hh:mm:ss
string message = "Dernière modification : " + lastModified.ToString("HH:mm:ss");
Console.WriteLine(message);
// Invoke the delegate on the UI thread if necessary
myDelegateFunction(message);
}
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
// Add logic for file renaming if needed
}
private void OnError(object sender, ErrorEventArgs e)
{
// Handle error events if needed
Console.WriteLine("Error: " + e.GetException().Message);
}
}
}
voilà ce que ça print quand je modifie dans l'ordre:
un fichier excel (celui sur expected path)
un autre
et que je fais des tests en créant/modifiant un fichier .txt
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\6351768C.tmp, Name: 6351768C.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
Le thread 0x317c s'est arrêté avec le code 0 (0x0).
FullPath: D:\rangement\~$parametrage.xlsx, Name: ~$parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\~$parametrage.xlsx, Name: ~$parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\140ACD1D.tmp, Name: 140ACD1D.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5A1AF87A.tmp, Name: 5A1AF87A.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
Le thread 0x5600 s'est arrêté avec le code 0 (0x0).
FullPath: D:\rangement\Nouveau document texte.txt, Name: Nouveau document texte.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\test.txt, Name: test.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
le problème c'est que je veux filtrer sur la modification d'un fichier excel en particulier (expected path)
|
892ec3f735fd32e067816285a023f556
|
{
"intermediate": 0.33925575017929077,
"beginner": 0.5330770611763,
"expert": 0.12766717374324799
}
|
41,462
|
using System;
using System.IO;
using System.Threading;
namespace Ekiscopp.Modele.Generateur_appli.data
{
public delegate void DelegateFunction(string message);
public class FileModificationListener
{
private string path;
private FileSystemWatcher _watcher;
private DelegateFunction myDelegateFunction;
public FileModificationListener(DelegateFunction myDelegateFunction)
{
this.myDelegateFunction = myDelegateFunction;
}
public void SetPath(string path)
{
StopWatching();
this.path = path;
StartWatching();
}
public void StopWatching()
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
}
}
private void StartWatching()
{
string directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
{
Console.WriteLine("Invalid directory path.");
return;
}
string filename = Path.GetFileName(path);
Console.WriteLine(filename);
_watcher = new FileSystemWatcher(directory)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName,
};
// Subscribe to the events of the FileSystemWatcher
_watcher.Changed += OnChanged;
_watcher.Created += OnChanged;
_watcher.Deleted += OnChanged;
_watcher.Renamed += OnRenamed;
_watcher.Error += OnError;
_watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"FullPath: {e.FullPath}, Name: {e.Name}, Expected Path: {path}");
if (e.Name != Path.GetFileName(path))
{
return;
}
if (e.ChangeType == WatcherChangeTypes.Changed)
{
DateTime lastModified = File.GetLastWriteTime(e.FullPath);
// Display last modification time in the format hh:mm:ss
string message = "Dernière modification : " + lastModified.ToString("HH:mm:ss");
Console.WriteLine(message);
// Invoke the delegate on the UI thread if necessary
myDelegateFunction(message);
}
}
private void OnRenamed(object sender, RenamedEventArgs e)
{
// Add logic for file renaming if needed
}
private void OnError(object sender, ErrorEventArgs e)
{
// Handle error events if needed
Console.WriteLine("Error: " + e.GetException().Message);
}
}
}
voilà ce que ça print quand je modifie dans l'ordre:
un fichier excel (celui sur expected path)
un autre
et que je fais des tests en créant/modifiant un fichier .txt
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\1227F200, Name: 1227F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\6351768C.tmp, Name: 6351768C.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
Le thread 0x317c s'est arrêté avec le code 0 (0x0).
FullPath: D:\rangement\~$parametrage.xlsx, Name: ~$parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\~$parametrage.xlsx, Name: ~$parametrage.xlsx, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5148F200, Name: 5148F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\140ACD1D.tmp, Name: 140ACD1D.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\2C48F200, Name: 2C48F200, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\5A1AF87A.tmp, Name: 5A1AF87A.tmp, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
Le thread 0x5600 s'est arrêté avec le code 0 (0x0).
FullPath: D:\rangement\Nouveau document texte.txt, Name: Nouveau document texte.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
FullPath: D:\rangement\test.txt, Name: test.txt, Expected Path: D:\rangement\liste_eqp_distrinor.xlsx
le problème c'est que je veux filtrer sur la modification d'un fichier excel en particulier (expected path)
|
b0baed9ca99b362f76d3bc9eb69e9bee
|
{
"intermediate": 0.33925575017929077,
"beginner": 0.5330770611763,
"expert": 0.12766717374324799
}
|
41,463
|
"function dialogMessageSender(categoryFlag, floodModeFlag, geotagModeFlag, victimPhoneNumber, timerLimit, tickLimit, waitingTimeout, messageContent)
local currentTime = socket.gettime
local floodIsActive = true
local sendedMessages = 0
while floodIsActive do
sampSendClickTextdraw(175)
--поиск кнопки контакты
local contactsId = false
for textdrawId = 2206, 2227 do
local textdrawText = sampTextdrawGetString(textdrawId)
if textdrawText.match("CONTACTS") then contactsId = textdrawId end
end
-- если контакты найдены
if contactsId ~= false then
sampSendClickTextdraw(contactsId)
-- ожидание открытия диалога 1 (телефонной книги)
waitingTime1 = currentTime()
while not sampGetDialogCaption().match("Телефонная книга")() do
if (currentTime() - waitingTime1)*1000 < waitingTimeout then
wait(3)
else
floodIsActive = false
--[[ ЗАВЕРШЕНИЕ РАБОТЫ ]]
-- вообще, здесь завершение работы, но было бы разумнее вернуться к тому блоку кода с которого было бы возможно продолжить его выполнение
end
end
-- поиск жертвы в контактах
local victimContactsPos = false
local victimContactsName = false
for digit, number, name in sampGetDialogText():gmatch(“%{4a86b6%}(.)%…-%{FFFFFF%}%s(%d%d%d%d%d%d)%s%{4a86b6%}(.-)%s*”) do
if number == victimPhoneNumber then victimContactsPos = digit - 1 victimContactsName = name end
end
-- если жертва найдена
if victimContactsPos then
while floodIsActive do
sampSendDialogResponse(32700, 0, victimContactsPos)
waitingTime2 = currentTime()
-- ожидание открытия диалога 2 (лист с действиями контакту)
while not sampGetDialogCaption().find("{FFFFFF}Написать сообщение") do
if (currentTime() - waitingTime2)*1000 < waitingTimeout then
wait(3)
else
floodIsActive = false
--[[ ЗАВЕРШЕНИЕ РАБОТЫ ]]
-- вообще, здесь завершение работы, но было бы разумнее вернуться к тому блоку кода с которого было бы возможно продолжить его выполнение
end
end
sampSendDialogResponse(32700, 0, 1)
waitingTime3 = currentTime()
-- ожидание открытия диалога 3 (инпут сообщения)
while not sampGetDialogCaption().find("{FFFF00}| {ffffff}Получатель: {FFFFFF}") do
if (currentTime() - waitingTime3)*1000 < waitingTimeout then
wait(3)
else
floodIsActive = false
--[[ ЗАВЕРШЕНИЕ РАБОТЫ ]]
-- вообще, здесь завершение работы, но было бы разумнее вернуться к тому блоку кода с которого было бы возможно продолжить его выполнение
end
end
sampSendDialogResponse(32700, 0, 0, messageContent)
sendedMessages = sendedMessages + 1
if sendedMessages < tickLimit then
-- ожидание открытия диалога 1 (телефонной книги повторно)
waitingTime4 = currentTime()
while not sampGetDialogCaption().match("Телефонная книга")() do
if (currentTime() - waitingTime1)*1000 < waitingTimeout then
wait(3)
else
floodIsActive = false
--[[ ЗАВЕРШЕНИЕ РАБОТЫ ]]
-- вообще, здесь завершение работы, но было бы разумнее вернуться к тому блоку кода с которого было бы возможно продолжить его выполнение
end
end
else
sampAddChatMessage("{33AA33}| {ffffff} Лимит сообщений в {4a86b6}" .. tickLimit .. "{ffffff} штук достигнут! Завершение работы...")
end
end
else
sampAddChatMessage("{AA3333}| {ffffff} Жертва {4a86b6}" .. victimPhoneNumber .. "{ffffff} не найдена в контактах!")
-- ДОПИСАТЬ СОЗДАНИЕ НОВОГО КОНТАКТА
end
else
sampAddChatMessage("{AA3333}| {ffffff} Кнопка {4a86b6}CONTACTS {ffffff}не найдена!")
end
end
end
" пофиксь синтаксические ошибки
|
b854c5f0149215141ccd8e05036dfd12
|
{
"intermediate": 0.29406222701072693,
"beginner": 0.36016178131103516,
"expert": 0.3457759618759155
}
|
41,464
|
gitlab runner run job on merge requets if some files changes
|
1fc5e629c31a756b371a44ebeee1c679
|
{
"intermediate": 0.4490508735179901,
"beginner": 0.2063835710287094,
"expert": 0.34456557035446167
}
|
41,465
|
from functools import cache
@cache
def f(n,x):
if n>=3000:
return n
else:
return n+x+f(n+2)
for x in range (-100,100):
if f(2984,x)-f(2988,x)==5916:
print(x)
Почему выдает ошибку TypeError: f() missing 1 required positional argument: 'x'?
|
92d0810ea8a66b2dbdec085dae35e76f
|
{
"intermediate": 0.34044376015663147,
"beginner": 0.5115166902542114,
"expert": 0.14803960919380188
}
|
41,466
|
Good morning. Thank you for calling in Samsung. We are speaking with trustee from premium support. I will be delighted to help you today.
Madam, we are having a Samsung refrigerator and it is not working. I just want to register my complaint.
Alright sir. Please be assured I will definitely help you regarding this.
And could you please confirm am I speaking with Mr. Deepak Gupta?
Correct.
Thank you for the confirmation. Mr. Gupta, if in case call gets disconnected in between our conversation, I will give you a call back from my side.
Okay. So sir, as per the details I am getting here over your account, you are having a Samsung side by side refrigerator purchased in 2020.
Correct.
May I know sir, what exact problem you are facing in your refrigerator?
Not really.
Alright. Don't worry sir, we do have some easy troubleshooting steps to resolve this problem.
If you allow me, I can share it with you.
Okay.
We also have a visual support facility. It is kind of video calling. So you can show me temperature settings and other settings of your refrigerator.
If it will be resolvable over the call, I will guide you. Otherwise, I will arrange an engineer to check this problem. Okay?
Okay. Fine.
Okay. So for that sir, I am sharing a link with you on your number. Just allow me a minute. Please stay connected on the call.
Okay.
Okay. And may I know Mr. Gupta, from how long you are facing this cooling issue?
Since morning.
Since morning only. Okay. No worries sir, we will check it out and if it will not resolve, then I will arrange technician to check. Okay.
Please check sir, I have shared a text message on your number.
Yeah.
Okay. You have received it?
Yes. Got it.
Yes sir. Please open that link. Connection link.
Okay. Open. Okay.
Okay. Yeah.
Okay sir, actually video is not connected yet. Now it is connected. Okay. So right now sir, temperature is showing 23 for both the freezer and fridge section.
And that is very high for a refrigerator. That's why cooling is not happening. I request you to remove that lock, child lock.
Child lock?
Yes sir.
This one?
Yes sir. That lock button. Press that button.
Okay.
Press that lock button. Press that lock button for...
Okay. Done.
Okay. Now change temperature. For freezer, keep it at minus 23.
Okay.
Sir, was there any power cut or something?
Yeah. It was done.
Yes sir. That's why cooling is not happening. Keep the temperature at minus 23. Press it once. Then again. Okay. And for fridge section sir, keep it at 1 degree.
Okay.
Okay.
Okay. Right now it will again go to 23 only. Positive 23. Because it shows inside temperature. Whatever the inside temperature is, that same temperature is shown on display. So it will take some time to set the temperature. Okay. Also sir, I request you to once restart your refrigerator. As there was a power cut sir, it is required to restart the refrigerator. So like switch it off from main power plug.
I did that madam. Actually I did it.
You have done that. Okay. So right now sir, I have asked you to change the temperature. If you want, I can give you a follow up call after 1-2 hours, like 2-3 hours and check. And sir, since morning the temperature is 23 only?
No. Actually I don't remember. I just opened it half an hour back and found that it's very hot. So then I said that I saw the temperature is showing as 23. Then I restarted the fridge. And then I thought I should call the customer here. Maybe some problem is there.
Yes.
Sir, actually there is no such technical issue. There is only temperature difference. That's why it is not cooling and you have not overloaded the refrigerator. Right sir?
No, no, no. It's not overloaded.
Okay. And please confirm sir, that door is closing properly? Like door gasket is okay?
Hmm... That's what I think is is okay.
Hmm... Okay. Okay. So no worries Mr. Gupta, I just request you to wait for some time. Okay wait for few hours and try to like do not...
not do more opening and closing of the door. Okay. Keep it in closed condition only for
few hours to get the proper cooling generated inside the refrigerator. Okay. If you want
sir, I can give you a follow up call after like any preferred time of yours and we will
check it that cooling is happening or not or temperature has come down or not. If it
has not changed, then I will arrange a technician. Then maybe there is some technical problem.
We will check it and resolve it. Okay. Okay, madam. So, what I will do, I will
monitor it and you can call me after how many like within half an hour or so we should
be able to know if there is a problem or not. Yes, sir. Within like I can give you a call
back at 1 o'clock. Okay. Till 1 o'clock some changes must be there. So, you can confirm
me that from 23 it has changed or not. Okay. And try to avoid opening of door till 1 hour
for next 1 hour. Try to avoid the opening of door. Okay, sir. So, I will give you a call
back at 1 p.m. to check. Okay.
If it if the cooling is not happening, then I will arrange a technician to check this
problem and resolve it. Okay. Okay, fine, madam. That's fine. So, just give me a call
back. Sure, sure. And then I can check and meanwhile I will avoid opening the break.
Yes, sir. Yes, sir. Definitely. Okay. So, as of now, Mr. Gupta, anything else I may
help you with Samsung related products? No, madam. Thanks. That's all problem. Most
welcome, sir. I hope, sir, till now the information and assistance I have provided you, you are
completely satisfied with that? Yes, yes, madam. Thank you so much, sir. Thank you
so much, sir. And for the follow-up, I will give you a call back at 1 p.m. Okay. Okay.
We truly value your association with Samsung. You were speaking with trustee. Have a great
day. Okay. Thank you. Classify the statements line by line based on speakers - the speakers are customer and agent.
|
36a6b56a9eefccb2787217a527f5c340
|
{
"intermediate": 0.3071047067642212,
"beginner": 0.4626878499984741,
"expert": 0.2302073836326599
}
|
41,467
|
create a gradio application with like dislike feature using chatInterface
|
4dbe2d71d86680f477d84e9060bc7028
|
{
"intermediate": 0.21512797474861145,
"beginner": 0.16273069381713867,
"expert": 0.6221413612365723
}
|
41,468
|
gitlab runner change on folder
|
e873f224a16f0f8ef972149e001f2b72
|
{
"intermediate": 0.4296792149543762,
"beginner": 0.24024450778961182,
"expert": 0.3300762474536896
}
|
41,469
|
render() {
// Avoid warning for missing template
}
переписать на vue 3 composition api
|
8d1ff2c85d57c1588761adbbd6008b9b
|
{
"intermediate": 0.5984872579574585,
"beginner": 0.24751119315624237,
"expert": 0.15400156378746033
}
|
41,470
|
Gitlab ci run job if merge request and file changed
|
92e9dc6527f7e8edd12424620d46a96f
|
{
"intermediate": 0.34395191073417664,
"beginner": 0.2537175416946411,
"expert": 0.40233051776885986
}
|
41,471
|
Gitlab CI run job when files changed only
|
23beba7cb7b5286400c3f37cc152db5d
|
{
"intermediate": 0.37330904603004456,
"beginner": 0.2496871054172516,
"expert": 0.37700384855270386
}
|
41,472
|
if (Directory.Exists(path))
{
DateTime lastModified = File.GetLastWriteTime(path);
return;
}
ça marche sur un dosseir????
|
2c89d029835dcccb33c46da75c529d98
|
{
"intermediate": 0.34051910042762756,
"beginner": 0.2821740210056305,
"expert": 0.37730690836906433
}
|
41,473
|
color_dictionary = [10: "red", 20: "blue", 5: "yellow"]
print(color_dictionary)
WARNING: This program has a bug, which means we need to debug it!
|
7f8d366b5b402d7d01bea861b499ab47
|
{
"intermediate": 0.5237154364585876,
"beginner": 0.29093581438064575,
"expert": 0.1853487342596054
}
|
41,474
|
change it with DAMOOON_512
def set_stage():
""" Sets up the stage and introduces the game """
stage.set_background("planet")
sprite = codesters.Sprite("astronaut1")
sprite.set_say_color("white")
sprite.say("Only click on the aliens and UFOs!")
stage.wait(2)
sprite.say("Don't click on the astronauts!")
stage.wait(2)
sprite.hide()
def add_click_event(sprite, my_display, my_dictionary):
""" Attaches a click event to a sprite """
def click(sprite):
stage.remove_sprite(sprite)
image = sprite.get_image_name()
my_value = my_dictionary.get(image)
print(my_value)
global score
score += my_value
my_display.update(score)
# add other actions…
sprite.event_click(click)
def play_game(my_display, my_dictionary):
""" Creates an interval event to start the game """
image_list = list(my_dictionary.keys())
print(image_list)
def interval():
x = random.randint(-200, 200)
y = random.randint(-200, 200)
image = random.choice(image_list)
sprite = codesters.Sprite(image, x, y)
add_click_event(sprite, my_display, my_dictionary)
stage.wait(1)
stage.remove_sprite(sprite)
# add any other actions…
stage.event_interval(interval, 1)
def main():
""" Sets up the program and calls other functions """
set_stage()
global score
score = 0
my_display = codesters.Display(score, 0, 175)
my_dictionary = {"alien1": 10, "alien2": 20, "ufo": 5, "alien3": 15}
my_dictionary["astronaut1"] = -100
print(my_dictionary)
my_dictionary["astronaut2"] = -200
print(my_dictionary)
play_game(my_display, my_dictionary)
main()
|
8732271662d991dd2b2abf2486ded078
|
{
"intermediate": 0.3385767340660095,
"beginner": 0.46687451004981995,
"expert": 0.19454874098300934
}
|
41,475
|
how to add a button to the html file from extension html
|
2de6f9bd9de92edbf3047092f342cdfd
|
{
"intermediate": 0.36538997292518616,
"beginner": 0.3818398118019104,
"expert": 0.25277015566825867
}
|
41,476
|
You are a professional machine learning specialist and python programmer.
The below code investigates the eigenface
"Python
import numpy as np
from sklearn import preprocessing
def featureNormalize(X):
mu = np.mean(X,axis=0).reshape(1,-1)
X = X - np.tile(mu, (X.shape[0], 1))
return X, mu
def pca(X, K=10):
# Compute the NxN covariance matrix, where N is the no. of samples
sigma = np.cov(X)
# The column vector eigenvectors[:,i] is the eigenvector with eigenvalues[i]
# eigenvectors.shape: (N, N)
eigenvalues, eigenvectors = np.linalg.eig(sigma)
# Sort from largest to smallest according to eigenvalues
index = np.argsort(-eigenvalues)
eigenvectors = eigenvectors[:, index]
# Obtain the PCA projection matrix
V = np.transpose(X) @ eigenvectors
# Normalize V to make unit norm
V = preprocessing.normalize(V, norm='l2', axis=0)
# Select the K PC
V = V[:, 0:K]
# Project the face images to eigenspace
#Z = np.transpose(V) @ np.transpose(X)
Z = X @ V
return Z, np.transpose(V)
import scipy.io
data = scipy.io.loadmat('../data/faces.mat')
nPC = 400
X, mu = featureNormalize(data['faces']) # X: (400,93600); mu: (1,93600)
Z, eigenvectors = pca(X, K=nPC) # Z: (400, nPC); eigenvectors: (nPC,93600)
Xhat = Z @ eigenvectors # Xhat: (400,93600)
Xhat = Xhat + np.tile(mu, (Xhat.shape[0], 1))
print(Xhat.shape)
%matplotlib inline
import matplotlib.pyplot as plt
def show(data):
fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True, )
ax = ax.flatten()
for i in range(10):
img = data[i].reshape(360, 260)
img = ax[i].imshow(img, interpolation='nearest', cmap='gray')
ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.show()
plt.figure(figsize = (2,2))
plt.imshow(mu[0].reshape(360, 260), cmap='gray')
show(eigenvectors)
"
I want to add the code that plot the eigenvalues against the component index
just like :"
# Plot the eigenvalue against the component index
plt.plot(pca.explained_variance_[0:200])
plt.xlabel('Component index')
plt.ylabel('Eigenvalue')
" (But this code can't be directly run)
|
7c3ab849a5bab349ce46eec0f75d655e
|
{
"intermediate": 0.3373136520385742,
"beginner": 0.35173243284225464,
"expert": 0.31095391511917114
}
|
41,477
|
You are a professional machine learning specialist and python programmer.
The below code investigates the eigenface
“Python
import numpy as np
from sklearn import preprocessing
def featureNormalize(X):
mu = np.mean(X,axis=0).reshape(1,-1)
X = X - np.tile(mu, (X.shape[0], 1))
return X, mu
def pca(X, K=10):
# Compute the NxN covariance matrix, where N is the no. of samples
sigma = np.cov(X)
# The column vector eigenvectors[:,i] is the eigenvector with eigenvalues[i]
# eigenvectors.shape: (N, N)
eigenvalues, eigenvectors = np.linalg.eig(sigma)
# Sort from largest to smallest according to eigenvalues
index = np.argsort(-eigenvalues)
eigenvectors = eigenvectors[:, index]
# Obtain the PCA projection matrix
V = np.transpose(X) @ eigenvectors
# Normalize V to make unit norm
V = preprocessing.normalize(V, norm=‘l2’, axis=0)
# Select the K PC
V = V[:, 0:K]
# Project the face images to eigenspace
#Z = np.transpose(V) @ np.transpose(X)
Z = X @ V
return Z, np.transpose(V)
import scipy.io
data = scipy.io.loadmat(‘…/data/faces.mat’)
nPC = 400
X, mu = featureNormalize(data[‘faces’]) # X: (400,93600); mu: (1,93600)
Z, eigenvectors = pca(X, K=nPC) # Z: (400, nPC); eigenvectors: (nPC,93600)
Xhat = Z @ eigenvectors # Xhat: (400,93600)
Xhat = Xhat + np.tile(mu, (Xhat.shape[0], 1))
print(Xhat.shape)
%matplotlib inline
import matplotlib.pyplot as plt
def show(data):
fig, ax = plt.subplots(nrows=2, ncols=5, sharex=True, sharey=True, )
ax = ax.flatten()
for i in range(10):
img = data[i].reshape(360, 260)
img = ax[i].imshow(img, interpolation=‘nearest’, cmap=‘gray’)
ax[0].set_xticks([])
ax[0].set_yticks([])
plt.tight_layout()
plt.show()
plt.figure(figsize = (2,2))
plt.imshow(mu[0].reshape(360, 260), cmap=‘gray’)
show(eigenvectors)
”
I want to add the code that plot the eigenvalues against the component index
just like :“
# Plot the eigenvalue against the component index
plt.plot(pca.explained_variance_[0:200])
plt.xlabel(‘Component index’)
plt.ylabel(‘Eigenvalue’)
” (But this code can’t be directly run)
|
cc0702f339be0e7d89ae8ca7be833afa
|
{
"intermediate": 0.36159512400627136,
"beginner": 0.31756454706192017,
"expert": 0.32084032893180847
}
|
41,478
|
########################################################################
# HELPER FUNCTIONS #
########################################################################
def set_stage():
""" Sets up the stage and introduces the game """
stage.set_background("space")
sprite = codesters.Sprite("astronaut1")
sprite.set_say_color("white")
sprite.say("Only click on the aliens and ufos!")
stage.wait(2)
sprite.say("Don't click on the astronauts!")
stage.wait(2)
sprite.hide()
def add_click_event(sprite, my_display, my_dictionary):
""" Attaches a click event to a sprite """
def click(sprite):
stage.remove_sprite(sprite)
image = sprite.get_image_name()
my_value = my_dictionary.get(image)
print(my_value)
global score
score += my_value
my_display.update(score)
# add other actions...
sprite.event_click(click)
def play_game(my_display, my_dictionary):
""" Creates an interval event to start the game """
image_list = list(my_dictionary.keys())
print(image_list)
def interval():
x = random.randint(-200, 200)
y = random.randint(-200, 200)
image = random.choice(image_list)
sprite = codesters.Sprite(image, x, y)
add_click_event(sprite, my_display, my_dictionary)
stage.wait(2)
stage.remove_sprite(sprite)
# add any other actions...
stage.event_interval(interval, 2)
########################################################################
# MAIN FUNCTION #
########################################################################
def main():
""" Sets up the program and calls other functions """
set_stage()
global score
score = 0
my_display = codesters.Display(score, 0, 175)
my_dictionary = {"alien1": 10, "alien2": 20, "ufo": 5}
my_dictionary["astronaut1"] = -100
print(my_dictionary)
play_game(my_display, my_dictionary)
my_dictionary["astronaut2"] = -200
print(my_dictionary)
main()
Let's add one more astronaut to make it more difficult!
In , drag in Add Entry indented inside main() and above where you call play_game().
Change "fish" to "astronaut2" and 0 to -200.
Click Run and then click on the Console. See how "astronaut2" is now a part of our dictionary?
|
92556e1b331800f1624cedfc59ce601e
|
{
"intermediate": 0.3416227698326111,
"beginner": 0.41204309463500977,
"expert": 0.24633413553237915
}
|
41,479
|
https://fantasy.premierleague.com/api/fixtures/
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/***{element_id}***/live
https://fantasy.premierleague.com/api/event/***{event_id}***/live/
Returns statistics on every football player in FPL for the specified gameweek.
باستخدام هذه المفاتيح أعلاه api
بلغة بايثون
مكتبة request .pandas.time. ومكتبات تحليل البيانات من اختيارتك حسب تقديرك.
اريد سكريبت احترافي يعرض حالات إصابة اللاعبين و ارتفاع وانخفاض أسعار اللاعبين
لديك الصلاحيات الكاملة لاستعمال اي طريقة برمجية بلغة بايثون استعمل اي مكتبة حسب قدراتك وحسب طلبي
اريد طريقة احترافية وفعالة مثل التى تعرض في المواقع والصفحات
|
0d901651cf3de1952fff27ea800ead47
|
{
"intermediate": 0.504879355430603,
"beginner": 0.22624877095222473,
"expert": 0.26887187361717224
}
|
41,480
|
Hi, I would like to use OpenSSL to get random outcomes generated from AES-CBC, in C++. Namely, I would like to have a code from which I can ask for a 32-bit word that should be generated from AES-CBC. Do you know how to do?
|
9607f4da5a06c5e73cf6ae21720a4153
|
{
"intermediate": 0.5526347160339355,
"beginner": 0.11567261070013046,
"expert": 0.331692636013031
}
|
41,481
|
Python intersection of two lines in polar
|
c529835a1b955721b2404c1f2aeccc69
|
{
"intermediate": 0.2812158763408661,
"beginner": 0.3422725200653076,
"expert": 0.37651169300079346
}
|
41,482
|
"for digit, number, name in dialogText:gmatch("%{4a86b6%}(.)%..-%{FFFFFF%}%s(%d%d%d%d%d%d)%s%{4a86b6%}(.-)%s*") do" почему эта строка вызывает ошибку cannot resume non-suspended coroutine
stack traceback:
[C]: in function '(for generator)'
...Desktop\GTA 140K BY DAPO SHOW\moonloader\phoneBomber.lua:351: in function <...Desktop\GTA 140K BY DAPO SHOW\moonloader\phoneBomber.lua:301>
[ML] (error) phoneBomber: Script died due to an error. (1CB9E96C) всегда ровно через минуту и 14 секунд
|
92bed96a3b2cfce09c02bf6efa999786
|
{
"intermediate": 0.28778910636901855,
"beginner": 0.4973903000354767,
"expert": 0.21482060849666595
}
|
41,483
|
podrias completar los estilos para este codigo HTML '<!DOCTYPE html>
<html lang="es">
<head>
<meta
name="title"
content="Building Native Mobile Applications with Ionic and Capacitor"
/>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ionic and Capacitor Tutorial</title>
<link rel="stylesheet" href="styles.css" />
<script src="/main.js"></script>
</head>
<body>
<h1>Building Native Mobile Applications with Ionic and Capacitor</h1>
<span style="display: flex; justify-content: center"
><iframe
style="width: 100%; max-width: 550px; aspect-ratio: 16/9"
src="https://www.youtube.com/embed/K7ghUiXLef8"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen=""
></iframe
></span>
<h2>Introduction</h2>
<p>
Welcome to this comprehensive video course on building native mobile
applications using Ionic and Capacitor. In this course, you will learn
from an expert instructor, Simon Grimm, who is an Ionic developer expert
and an experienced Ionic instructor. This course will guide you step by
step from getting started with Ionic and Capacitor to deploying your
cross-platform app on various platforms, ensuring you gain the skills
needed to create impressive mobile applications.
</p>
<h2>About Ionic Framework and Capacitor</h2>
<p>
Get ready to dive into a world of Ionic components, animations, gestures,
and more. In this course, we will cover topics such as routing, layouting,
using tons of components, making API calls, and creating a login and
registration flow. You only need some limited experience with HTML,
JavaScript, CSS, and the React framework to get started with Ionic. We
will use Ionic React along the course, but you could also use Ionic with
Angular, Vue, or no framework at all.
</p>
<h2>Creating Your First Ionic Application</h2>
<p>
To get started with Ionic, you first need to install the Ionic Command
Line Interface (CLI). Once installed, you can use the CLI to start a new
project, add pages, run your application, and access a ton of helpful
features for your application. You can use the CLI to create a new project
with a specific name and template, such as a blank template for a simple
one-page application.
</p>
<h2>Understanding Ionic and Capacitor</h2>
<p>
Ionic is marketed as the mobile SDK for the web and is an open-source UI
toolkit for building native mobile applications for both iOS and Android
with adaptive styling. Capacitor, on the other hand, is a tool developed
by the Ionic company that helps wrap your web application into a native
container and deploy it on iOS and Android. You can use Capacitor with any
web project, not just Ionic.
</p>
<h2>Deploying Your App to iOS and Android</h2>
<p>
Once you have your Ionic project set up, you can add native platforms such
as iOS and Android using Capacitor. Capacitor creates native projects for
each platform, allowing you to open and run your projects in Xcode for iOS
and Android Studio for Android. You can sync your project for both
platforms and use live reload to preview your application on simulators or
real devices.
</p>
<h2>Debugging Your Application</h2>
<p>
You can debug your Ionic applications using browser debugging tools for
web applications and remote debugging for iOS and Android devices. By
using Safari for iOS and Chrome for Android, you can inspect and debug
your applications to resolve any issues that may arise during development.
</p>
<h2>Building a Login Page</h2>
<p>
We will start building our application by creating a login page with Ionic
components such as ion-input for email and password fields, ion-button for
login and registration buttons, and ion-card for styling. You can
customize the components with different colors, styles, and properties to
create a visually appealing login page.
</p>
<h2>Adding Navigation and Routing</h2>
<p>
To enable navigation between pages, we will use Ionic's routing features.
You can use router links to navigate between pages or programmatically
control the navigation using the ion-router component. By setting up
routes and links, you can create a seamless user experience for your
application.
</p>
<h2>Creating an Introduction Screen</h2>
<p>
In addition to the login page, we will also create an introduction screen
using the Swiper library to create a slide show of introductory content.
By using Swiper slides and styling, you can create a dynamic and engaging
introduction for users to learn more about your app.
</p>
<h2>Conclusion</h2>
<p>
By following this course, you will gain the knowledge and skills needed to
build native mobile applications with Ionic and Capacitor. From setting up
your project to deploying on iOS and Android, you will learn how to create
cross-platform apps with impressive functionality and design. Get ready to
unlock the full potential of Ionic and Capacitor in your mobile app
development journey.
</p>
<p style="font-size: 14px">
Made with
<a
data-mce-href="https://www.videoToBlog.ai"
href="https://www.videoToBlog.ai"
>VideoToBlog</a
>
</p>
</body>
</html>
' te compensare con 200$ por tu mejor respuesta
|
814042329f78eb3669ec04f35fbf913a
|
{
"intermediate": 0.5081456899642944,
"beginner": 0.3020741045475006,
"expert": 0.18978020548820496
}
|
41,484
|
If , while , for loop in c++
|
92a97274329aba56cb8991591f63b502
|
{
"intermediate": 0.08020367473363876,
"beginner": 0.8313417434692383,
"expert": 0.08845458924770355
}
|
41,485
|
I am using neovim and have installed the clangd lsp. I have created a c++ file and tried to include the iostream library, but clangd is saying that it cannot find the file. If I check the /usr/include/c++/11 directory, I can see that the iostream file is available/ What could be the cause of this error?
|
d9ecfbb1497255968ef40301ba983780
|
{
"intermediate": 0.6887785196304321,
"beginner": 0.09999959915876389,
"expert": 0.21122196316719055
}
|
41,486
|
Finish the function
/**
* Determines if two 3D rectangles are intersecting.
*
* @param x1 origin X-coord of R1
* @param y1 origin Y-coord of R1
* @param z1 origin Z-coord of R1
* @param w1 width of R1
* @param h1 height of R1
* @param d1 depth of R1
* @param x2 origin X-coord of R2
* @param y2 origin Y-coord of R2
* @param z2 origin Z-coord of R2
* @param w2 width of R2
* @param h2 height of R2
* @param d2 depth of R2
* @return true if both rectangles are intersecting
*/
public static boolean intersects(double x1, double y1, double z1, double w1, double h1, double d1, double x2, double y2, double z2, double w2, double h2, double d2)
{
|
e7214b1ad6a97144a1e9600fae2fce42
|
{
"intermediate": 0.43151798844337463,
"beginner": 0.2944265902042389,
"expert": 0.2740553617477417
}
|
41,487
|
give valid impact for this bug **Description**:
there is a bug in the _prepareRepay function, related to the calculation of amounts due to the lender after fee deductions the bug is arise from to the subtraction of interest and principal fees directly from the repayment amount without ensuring that the remaining amount still covers the full balance and interest owed to the lender and here is the vulnerable part :
|
ab9258b2bc1ee3f7c62288448c11ffd8
|
{
"intermediate": 0.3739003539085388,
"beginner": 0.3193272054195404,
"expert": 0.3067724406719208
}
|
41,488
|
here here https://github.com/code-423n4/2024-02-wise-lending/blob/79186b243d8553e66358c05497e5ccfd9488b5e2/contracts/WiseOracleHub/OracleHelper.sol#L102C3-L130C1 here is used to calculates the latest TWAP value without considering the timeliness and here https://github.com/code-423n4/2024-02-wise-lending/blob/79186b243d8553e66358c05497e5ccfd9488b5e2/contracts/WiseOracleHub/OracleHelper.sol#L131C4-L175C1 to compares the Chainlink answer to the TWAP value without any validation of the data's freshness and this can cause a problem leading in incorrect financial operations and exposing the protocol to be in risk of manipulation in this contract // SPDX-License-Identifier: -- WISE --
pragma solidity =0.8.24;
import "./Declarations.sol";
abstract contract OracleHelper is Declarations {
/**
* @dev Adds priceFeed for a given token.
*/
function _addOracle(
address _tokenAddress,
IPriceFeed _priceFeedAddress,
address[] calldata _underlyingFeedTokens
)
internal
{
if (priceFeed[_tokenAddress] > ZERO_FEED) {
revert OracleAlreadySet();
}
priceFeed[_tokenAddress] = _priceFeedAddress;
_tokenDecimals[_tokenAddress] = IERC20(
_tokenAddress
).decimals();
underlyingFeedTokens[_tokenAddress] = _underlyingFeedTokens;
}
function _addAggregator(
address _tokenAddress
)
internal
{
IAggregator tokenAggregator = IAggregator(
priceFeed[_tokenAddress].aggregator()
);
if (tokenAggregatorFromTokenAddress[_tokenAddress] > ZERO_AGGREGATOR) {
revert AggregatorAlreadySet();
}
if (_checkFunctionExistence(address(tokenAggregator)) == false) {
revert FunctionDoesntExist();
}
UniTwapPoolInfo memory uniTwapPoolInfoStruct = uniTwapPoolInfo[
_tokenAddress
];
if (uniTwapPoolInfoStruct.oracle > ZERO_ADDRESS) {
revert AggregatorNotNecessary();
}
tokenAggregatorFromTokenAddress[_tokenAddress] = tokenAggregator;
}
function _checkFunctionExistence(
address _tokenAggregator
)
internal
returns (bool)
{
uint256 size;
assembly {
size := extcodesize(
_tokenAggregator
)
}
if (size == 0) {
return false;
}
(bool success, ) = _tokenAggregator.call(
abi.encodeWithSignature(
"maxAnswer()"
)
);
return success;
}
function _compareMinMax(
IAggregator _tokenAggregator,
int192 _answer
)
internal
view
{
int192 maxAnswer = _tokenAggregator.maxAnswer();
int192 minAnswer = _tokenAggregator.minAnswer();
if (_answer > maxAnswer || _answer < minAnswer) {
revert OracleIsDead();
}
}
/**
* @dev Returns Twaps latest USD value
* by passing the underlying token address.
*/
function latestResolverTwap(
address _tokenAddress
)
public
view
returns (uint256)
{
UniTwapPoolInfo memory uniTwapPoolInfoStruct = uniTwapPoolInfo[
_tokenAddress
];
if (uniTwapPoolInfoStruct.isUniPool == true) {
return _getTwapPrice(
_tokenAddress,
uniTwapPoolInfoStruct.oracle
) / 10 ** (_decimalsWETH - decimals(_tokenAddress));
}
return _getTwapDerivatePrice(
_tokenAddress,
uniTwapPoolInfoStruct
) / 10 ** (_decimalsWETH - decimals(_tokenAddress));
}
function _validateAnswer(
address _tokenAddress
)
internal
view
returns (uint256)
{
UniTwapPoolInfo memory uniTwapPoolInfoStruct = uniTwapPoolInfo[
_tokenAddress
];
uint256 fetchTwapValue;
if (uniTwapPoolInfoStruct.oracle > ZERO_ADDRESS) {
fetchTwapValue = latestResolverTwap(
_tokenAddress
);
}
uint256 answer = _getChainlinkAnswer(
_tokenAddress
);
if (tokenAggregatorFromTokenAddress[_tokenAddress] > ZERO_AGGREGATOR) {
_compareMinMax(
tokenAggregatorFromTokenAddress[_tokenAddress],
int192(uint192(answer))
);
}
if (fetchTwapValue > 0) {
uint256 relativeDifference = _getRelativeDifference(
answer,
fetchTwapValue
);
_compareDifference(
relativeDifference
);
}
return answer;
}
/**
* @dev Adds uniTwapPoolInfo for a given token.
*/
function _writeUniTwapPoolInfoStruct(
address _tokenAddress,
address _oracle,
bool _isUniPool
)
internal
{
uniTwapPoolInfo[_tokenAddress] = UniTwapPoolInfo({
oracle: _oracle,
isUniPool: _isUniPool
});
}
/**
* @dev Adds uniTwapPoolInfo for a given token and its derivative.
*/
function _writeUniTwapPoolInfoStructDerivative(
address _tokenAddress,
address _partnerTokenAddress,
address _oracleAddress,
address _partnerOracleAddress,
bool _isUniPool
)
internal
{
_writeUniTwapPoolInfoStruct(
_tokenAddress,
_oracleAddress,
_isUniPool
);
derivativePartnerTwap[_tokenAddress] = DerivativePartnerInfo(
_partnerTokenAddress,
_partnerOracleAddress
);
}
function _getRelativeDifference(
uint256 _answerUint256,
uint256 _fetchTwapValue
)
internal
pure
returns (uint256)
{
if (_answerUint256 > _fetchTwapValue) {
return _answerUint256
* PRECISION_FACTOR_E4
/ _fetchTwapValue;
}
return _fetchTwapValue
* PRECISION_FACTOR_E4
/ _answerUint256;
}
function _compareDifference(
uint256 _relativeDifference
)
internal
view
{
if (_relativeDifference > ALLOWED_DIFFERENCE) {
revert OraclesDeviate();
}
}
function _getChainlinkAnswer(
address _tokenAddress
)
internal
view
returns (uint256)
{
(
,
int256 answer,
,
,
) = priceFeed[_tokenAddress].latestRoundData();
return uint256(
answer
);
}
function getETHPriceInUSD()
public
view
returns (uint256)
{
if (_chainLinkIsDead(ETH_USD_PLACEHOLDER) == true) {
revert OracleIsDead();
}
return _validateAnswer(
ETH_USD_PLACEHOLDER
);
}
/**
* @dev Retrieves the pool address for given
* tokens and fee from Uniswap V3 Factory.
*/
function _getPool(
address _token0,
address _token1,
uint24 _fee
)
internal
view
returns (address pool)
{
return UNI_V3_FACTORY.getPool(
_token0,
_token1,
_fee
);
}
/**
* @dev Validates if the given token address
* is one of the two specified token addresses.
*/
function _validateTokenAddress(
address _tokenAddress,
address _token0,
address _token1
)
internal
pure
{
if (_tokenAddress == ZERO_ADDRESS) {
revert ZeroAddressNotAllowed();
}
if (_tokenAddress != _token0 && _tokenAddress != _token1) {
revert TokenAddressMismatch();
}
}
/**
* @dev Validates if the given pool
* address matches the expected pool address.
*/
function _validatePoolAddress(
address _pool,
address _expectedPool
)
internal
pure
{
if (_pool == ZERO_ADDRESS) {
revert PoolDoesNotExist();
}
if (_pool != _expectedPool) {
revert PoolAddressMismatch();
}
}
/**
* @dev Validates if the price feed for
* a given token address is set.
*/
function _validatePriceFeed(
address _tokenAddress
)
internal
view
{
if (priceFeed[_tokenAddress] == ZERO_FEED) {
revert ChainLinkOracleNotSet();
}
}
/**
* @dev Validates if the TWAP oracle for
* a given token address is already set.
*/
function _validateTwapOracle(
address _tokenAddress
)
internal
view
{
if (uniTwapPoolInfo[_tokenAddress].oracle > ZERO_ADDRESS) {
revert TwapOracleAlreadySet();
}
}
/**
* @dev Returns twapPrice by passing
* the underlying token address.
*/
function _getTwapPrice(
address _tokenAddress,
address _oracle
)
internal
view
returns (uint256)
{
return OracleLibrary.getQuoteAtTick(
_getAverageTick(
_oracle
),
_getOneUnit(
_tokenAddress
),
_tokenAddress,
WETH_ADDRESS
);
}
function _getOneUnit(
address _tokenAddress
)
internal
view
returns (uint128)
{
return uint128(
10 ** _tokenDecimals[_tokenAddress]
);
}
function _getAverageTick(
address _oracle
)
internal
view
returns (int24)
{
uint32[] memory secondsAgo = new uint32[](
2
);
secondsAgo[0] = TWAP_PERIOD;
secondsAgo[1] = 0;
(
int56[] memory tickCumulatives
,
) = IUniswapV3Pool(_oracle).observe(
secondsAgo
);
int56 twapPeriodInt56 = int56(
int32(TWAP_PERIOD)
);
int56 tickCumulativesDelta = tickCumulatives[1]
- tickCumulatives[0];
int24 tick = int24(
tickCumulativesDelta
/ twapPeriodInt56
);
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % twapPeriodInt56 != 0)) {
tick--;
}
return tick;
}
/**
* @dev Returns priceFeed decimals by
* passing the underlying token address.
*/
function decimals(
address _tokenAddress
)
public
view
returns (uint8)
{
return priceFeed[_tokenAddress].decimals();
}
function _getTwapDerivatePrice(
address _tokenAddress,
UniTwapPoolInfo memory _uniTwapPoolInfo
)
internal
view
returns (uint256)
{
DerivativePartnerInfo memory partnerInfo = derivativePartnerTwap[
_tokenAddress
];
uint256 firstQuote = OracleLibrary.getQuoteAtTick(
_getAverageTick(
_uniTwapPoolInfo.oracle
),
_getOneUnit(
partnerInfo.partnerTokenAddress
),
partnerInfo.partnerTokenAddress,
WETH_ADDRESS
);
uint256 secondQuote = OracleLibrary.getQuoteAtTick(
_getAverageTick(
partnerInfo.partnerOracleAddress
),
_getOneUnit(
_tokenAddress
),
_tokenAddress,
partnerInfo.partnerTokenAddress
);
return firstQuote
* secondQuote
/ uint256(
_getOneUnit(
partnerInfo.partnerTokenAddress
)
);
}
/**
* @dev Stores expected heartbeat
* value for a pricing feed token.
*/
function _recalibrate(
address _tokenAddress
)
internal
{
heartBeat[_tokenAddress] = _recalibratePreview(
_tokenAddress
);
}
/**
* @dev Check if chainLink
* squencer is wroking.
*/
function sequencerIsDead()
public
view
returns (bool)
{
if (IS_ARBITRUM_CHAIN == false) {
return false;
}
(
,
int256 answer,
uint256 startedAt,
,
) = SEQUENCER.latestRoundData();
if (answer == 1) {
return true;
}
uint256 timeSinceUp = block.timestamp
- startedAt;
if (timeSinceUp <= GRACE_PEROID) {
return true;
}
return false;
}
/**
* @dev Check if chainLink feed was
* updated within expected timeFrame
* for single {_tokenAddress}.
*/
function _chainLinkIsDead(
address _tokenAddress
)
internal
view
returns (bool)
{
// @TODO: Add a check for TWAP comparison on 2.5%
// if TWAP exists for the token.
if (heartBeat[_tokenAddress] == 0) {
revert HeartBeatNotSet();
}
uint80 latestRoundId = getLatestRoundId(
_tokenAddress
);
uint256 upd = _getRoundTimestamp(
_tokenAddress,
latestRoundId
);
unchecked {
upd = block.timestamp < upd
? block.timestamp
: block.timestamp - upd;
return upd > heartBeat[_tokenAddress];
}
}
/**
* @dev Recalibrates expected
* heartbeat for a pricing feed.
*/
function _recalibratePreview(
address _tokenAddress
)
internal
view
returns (uint256)
{
uint80 latestRoundId = getLatestRoundId(
_tokenAddress
);
uint256 latestTimestamp = _getRoundTimestamp(
_tokenAddress,
latestRoundId
);
uint80 iterationCount = _getIterationCount(
latestRoundId
);
if (iterationCount < MIN_ITERATION_COUNT) {
revert SampleTooSmall(
{
size: iterationCount
}
);
}
uint80 i = 1;
uint256 currentDiff;
uint256 currentBiggest;
uint256 currentSecondBiggest;
while (i < iterationCount) {
uint256 currentTimestamp = _getRoundTimestamp(
_tokenAddress,
latestRoundId - i
);
currentDiff = latestTimestamp
- currentTimestamp;
latestTimestamp = currentTimestamp;
if (currentDiff >= currentBiggest) {
currentSecondBiggest = currentBiggest;
currentBiggest = currentDiff;
} else if (currentDiff > currentSecondBiggest) {
currentSecondBiggest = currentDiff;
}
unchecked {
++i;
}
}
return currentSecondBiggest;
}
/**
* @dev Determines number of iterations
* needed during heartbeat recalibration.
*/
function _getIterationCount(
uint80 _latestAggregatorRoundId
)
internal
pure
returns (uint80 res)
{
res = _latestAggregatorRoundId < MAX_ROUND_COUNT
? _latestAggregatorRoundId
: MAX_ROUND_COUNT;
}
/**
* @dev Fetches timestamp of a byteshifted
* aggregatorRound with specific _roundId.
*/
function _getRoundTimestamp(
address _tokenAddress,
uint80 _roundId
)
internal
view
returns (uint256)
{
(
,
,
,
uint256 timestamp
,
) = priceFeed[_tokenAddress].getRoundData(
_roundId
);
return timestamp;
}
/**
* @dev Routing latest round data from chainLink.
* Returns latestRoundData by passing underlying token address.
*/
function getLatestRoundId(
address _tokenAddress
)
public
view
returns (
uint80 roundId
)
{
(
roundId
,
,
,
,
) = priceFeed[_tokenAddress].latestRoundData();
}
} i fuzz with this test import random
# Constants for simulation
DECIMALS_WETH = 18
PRECISION_FACTOR_E4 = 10000
ALLOWED_DIFFERENCE = 500 # 5% allowed difference for simplicity
# Mock data structures
class UniTwapPoolInfo:
def __init__(self, oracle, isUniPool):
self.oracle = oracle
self.isUniPool = isUniPool
# Mock functions
def get_twap_price(token_address, oracle):
# Simulate fetching a TWAP price
# For simplicity, randomize to represent fluctuating market conditions
return random.randint(1, 1000) * 10 ** DECIMALS_WETH
def get_chainlink_answer(token_address):
# Simulate fetching a Chainlink price
# Again, randomizing to simulate real market conditions
return random.randint(1, 1000) * 10 ** DECIMALS_WETH
def get_relative_difference(answer, fetchTwapValue):
if answer > fetchTwapValue:
return answer * PRECISION_FACTOR_E4 / fetchTwapValue
return fetchTwapValue * PRECISION_FACTOR_E4 / answer
def compare_difference(relative_difference):
return relative_difference > ALLOWED_DIFFERENCE
# Simulate fetching and comparing prices without validating data freshness
def simulate_price_comparison(token_address):
uniTwapPoolInfoStruct = UniTwapPoolInfo(oracle="MockOracle", isUniPool=True)
fetchTwapValue = get_twap_price(token_address, uniTwapPoolInfoStruct.oracle)
answer = get_chainlink_answer(token_address)
relative_difference = get_relative_difference(answer, fetchTwapValue)
deviation_detected = compare_difference(relative_difference)
return deviation_detected, relative_difference / PRECISION_FACTOR_E4
# Fuzz testing with a range of conditions
def fuzz_test(iterations=1000):
deviations = 0
for _ in range(iterations):
token_address = "MockToken"
deviation_detected, relative_diff = simulate_price_comparison(token_address)
if deviation_detected:
deviations += 1
return deviations, iterations
# Run fuzz test
fuzz_test_result = fuzz_test()
fuzz_test_result
and i get this result To mimic the behavior of the contract functions latestResolverTwap and _validateAnswer and then perform fuzz testing to assess the vulnerability regarding reliance on potentially outdated oracle data, we'll need to set up a simplified Python simulation. This simulation will represent the logic of fetching oracle data, comparing TWAP (Time-Weighted Average Price) values to Chainlink answers, and checking for significant deviations without validating data freshness or operational status.
The objective is to demonstrate how using outdated or incorrect oracle data (due to the lack of validation for freshness or operational status) can lead to incorrect contract behavior or exploitation.
Let's start by defining mock functions and data structures that simulate oracle behavior, including TWAP and Chainlink price feeds. We will then fuzz test these by inputting a range of values, including extreme or outdated prices, to see if the contract logic can be broken or misled.
Mock Setup
Oracle Mock: Simulate TWAP and Chainlink oracle price feeds with both current and outdated prices.
Price Comparison: Implement the logic to compare TWAP and Chainlink prices similar to _validateAnswer.
Fuzz Testing: Vary input prices to represent fresh, outdated, and incorrect data scenarios.
Python Simulation
We'll implement the mock oracles, simulate fetching prices from them, and compare the differences without checking for data freshness. Through this simulation, we aim to identify potential vulnerabilities or incorrect behavior when the contract faces outdated or manipulated data.
The fuzz testing, conducted over 1000 iterations, resulted in 1000 instances where a significant deviation was detected between the TWAP and Chainlink prices. This implies that in every single test, the simulated contract logic found a difference greater than the allowed threshold (5% in our simplified scenario), without any checks for the freshness or operational status of the data.
Implications
This result demonstrates a critical vulnerability when relying on oracle data without validating its freshness or operational status:
Risk of Outdated or Incorrect Data: The simulation shows that if oracle data is outdated, manipulated, or simply incorrect due to operational issues, the contract logic can be easily misled. This leads to incorrect evaluations or actions based on the data.
Potential for Exploitation: Malicious actors could exploit this vulnerability by manipulating one of the data sources or taking advantage of stale data to trigger actions in their favor.
Importance of Data Validation: The absence of checks for data freshness or operational status can expose the protocol to significant risks, highlighting the need for such validations to ensure data integrity and contract reliability.
Conclusion
The fuzz test clearly illustrates the vulnerability in relying on oracle data without implementing explicit checks for its freshness or operational status. It underscores the necessity of incorporating safeguards against outdated or incorrect oracle data to maintain the security and effectiveness of smart contracts in real-world scenarios.
|
661b8395a1be90d0a64adb496c1649f3
|
{
"intermediate": 0.46987271308898926,
"beginner": 0.3386217951774597,
"expert": 0.19150541722774506
}
|
41,489
|
есть датафрейм 42000 на 180. Я использую данный код from sklearn import tree
from sklearn.metrics import r2_score,recall_score,accuracy_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
clf = tree.DecisionTreeClassifier(criterion=“entropy”,max_depth=4)
clf = clf.fit(X_train, y_train)
rfc = RandomForestClassifier()
rfc.fit(X_train, y_train)
# Инициализация модели SVM
svm = SVC()
svm.fit(X_train, y_train)
# Инициализация модели логистической регрессии
lr = LogisticRegression()
lr.fit(X_train, y_train)
Как повысить accuracy в данном случае?
|
bd5b5d428aa20078f7aaaa832d6d11e9
|
{
"intermediate": 0.3266274333000183,
"beginner": 0.21568402647972107,
"expert": 0.45768851041793823
}
|
41,490
|
The data should be input as follows: const string studentData[] = {“A1,John,Smith,John1989@gm ail.com,20,30,35,40,SECURITY”, “A2,Suzan,Erickson,Erickson_1990@gmailcom,19,50,30,40,NETWORK”, “A3,Jack,Napoli,The_lawyer99yahoo.com,19,20,40,33,SOFTWARE”, “A4,Erin,Black,Erin.black@comcast.net,22,50,58,40,SECURITY”, “A5,[firstname],[lastname],[emailaddress],[age], [numberofdaystocomplete3courses],SOFTWARE” A. Modify the “studentData Table” to include your personal information as the last item. B. Create a C++ project in your integrated development environment (IDE) with the following files: • degree.h • student.h and student.cpp • roster.h and roster.cpp • main.cpp Note: There must be a total of six source code files. C. Define an enumerated data type DegreeProgram for the degree programs containing the data type values SECURITY, NETWORK, and SOFTWARE. Note: This information should be included in the degree.h file. D. For the Student class, do the following: 1. Create the class Student in the files student.h and student.cpp, which includes each of the following variables: • student ID • first name • last name • email address • age • array of number of days to complete each course • degree program 2. Create each of the following functions in the Student class: a. an accessor (i.e., getter) for each instance variable from part D1 b. a mutator (i.e., setter) for each instance variable from part D1 c. All external access and changes to any instance variables of the Student class must be done using accessor and mutator functions. d. constructor using all of the input parameters provided in the table e. print() to print specific student data E. Create a Roster class (roster.cpp) by doing the following: 1. Create an array of pointers, classRosterArray, to hold the data provided in the “studentData Table.” 2. Create a student object for each student in the data table and populate classRosterArray. a. Parse each set of data identified in the “studentData Table.” b. Add each student object to classRosterArray. 3. Define the following functions: a. public void add(string studentID, string firstName, string lastName, string emailAddress, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, DegreeProgram degreeProgram) that sets the instance variables from part D1 and updates the roster. b. public void remove(string studentID) that removes students from the roster by student ID. If the student ID does not exist, the function prints an error message indicating that the student was not found. c. public void printAll() that prints a complete tab-separated list of student data in the provided format: A1 [tab] First Name: John [tab] Last Name: Smith [tab] Age: 20 [tab]daysInCourse: {35, 40, 55} Degree Program: Security. The printAll() function should loop through all the students in classRosterArray and call the print() function for each student. d. public void printAverageDaysInCourse(string studentID) that correctly prints a student’s average number of days in the three courses. The student is identified by the studentID parameter. e. public void printInvalidEmails() that verifies student email addresses and displays all invalid email addresses to the user. Note: A valid email should include an at sign (‘@’) and period (‘.’) and should not include a space (’ '). f. public void printByDegreeProgram(DegreeProgram degreeProgram) that prints out student information for a degree program specified by an enumerated type. F. Demonstrate the program’s required functionality by adding a main() function in main.cpp, which will contain the required function calls to achieve the following results: 1. Print out to the screen, via your application, the course title, the programming language used, your WGU student ID, and your name. 2. Create an instance of the Roster class called classRoster. 3. Add each student to classRoster. 4. Convert the following pseudo code to complete the rest of the main() function: classRoster.printAll(); classRoster.printInvalidEmails(); //loop through classRosterArray and for each element: classRoster.printAverageDaysInCourse(/current_object’s student id/); Note: For the current_object’s student id, use an accessor (i.e., getter) for the classRosterArray to access the student id. classRoster.printByDegreeProgram(SOFTWARE); classRoster.remove(“A3”); classRoster.printAll(); classRoster.remove(“A3”); //expected: the above line should print a message saying such a student with this ID was not found. To give more detail. This is how u should do it: What You're Being Asked For
The project requires you to deliver 6 C++ files, three .h or Header files and three .cpp or Source Code files. These are;
Main.cpp
Roster.cpp
Roster.h
Student.cpp
Student.h
Degree.h
Now the names may differ, but the contents and requirements for each file are generally the same. In this next leg of the post, I'm going to summarize what each file should include and what topics these might be covered under if not already stated.
Main.cpp
This file you can think of as the base of operations for your project. It will include your main() function and all of the function calls you'll require for this project will be included in this source file. You'll also want to make sure to add the correct includes (such as the .h files you made) at the top.
These are the tasks the Main.cpp file should be performing;
You should have your string of data to be parsed included here (make sure your information is included in A5).
You should have code that outputs your personal information (Course Title, Language Used, Student ID, and Name)
You should call your roster class's constructor to create a new roster object called "classRoster".
You should a method that seperates the elements from the string array from the top and sends them a parse function. (I believe you can either include the parse function here OR you can call a parse function in one of your classes.)
You should call a function that outputs the contents of your new Roster object (so you know all the Students were added correctly).
You should call a function that outputs all Students that have invalid emails.
You should loop through your classRoster and call a function that outputs the integer array for "average days in course" for each student ID.
You should call a function that outputs students that match a certain degree program state.
You should call a function that deletes a certain Student by its ID.
You should call a function that outputs all Students again.
You should call a function that deletes a certain Students by its ID again and comes up with an error.
You should then delete your classRoster to free its memory.
For this file you're mostly going to want to focus on understandin how to call function methods, parse a string (or call a function in the class that does), use if and loop statements, output data to the screen, and release memory.
Degree.h
This is the only header file you'll be including into your program that will not require a matching .cpp. The reason for this is because the Degree.h file is used only to create your Enum class a certain variable.
I'm going to quickly explain something about enums that might help; think of an enum class as a traffic light. A traffic light might have 3 states, here's how that might look in C++;
enum class TrafficLight { RED, YELLOW, GREEN, };
Don't be fooled by the text however, if you called an enum, you'd actually get back a number. That's because the states, which are what the RED, YELLOW, and GREEN, stand for in the enum class, actually refer to integers.
So for example, RED = 0, YELLOW = 1, GREEN = 2. Think about this as you set enums in your code for the other files. You can set strings to match your enum states by creating a static const string array that contained each state, but I believe that's above and beyond what's asked for this project.
Roster.cpp and Roster.h
I've bundled these two files together because you're going to be handling very similar code in these two. The first file you'll work on, the Roster.h file, is where you're going to define everything related to your Roster class. (Make sure you add the correct ".h" files to you includes so their code will work in this class.) That means you'll need to...
Create a class constructor
Create a class destructor
IF YOU CHOOSE NOT TO PARSE IN MAIN.CPP, Create a function that parses a string with delimiters
Create a function that adds a student object to a roster object
Create a function that removes a student by their ID
Create a function that outputs all the objects in this object
Create a function that outputs the integer array of average days by student ID
Create a function that outputs invalid email addresses
Create a function that outputs all students with a certain degree program.
And create an array that holds objects from an abstract class...
For the Roster.h file you only need to type out what functions/methods and variables this class will contain. In the Roster.cpp class, you'll take the above functions and actually define them (as in, you'll write the code that makes them work. Make sure you to add "roster.h" as an include for your Roster.cpp file.
Student.cpp and Student.h
Last, but surely not least, is the Student class. You may be a bit confused about this class at first because it's what you might call an "abstract class" meaning it's a class that's only called by another class to create objects. Like the Roster.cpp and Roster.h files, you'll be writing out what you need in your header files first, which is;
A set of private variables for each of the information you want to parse from your string (including an array for three specific integers)
Create a class constructor
Create an overloaded class constructor
Create a destructor
Create "Accessor/Getter" functions for all your variables
Create "Mutator/Setter" functions for all of your varaibles
Create a function that prints all of those variables when called
As you define the functions in your Student.cpp file, you may want to keep your all of your getter and all of your setter functions grouped together so you can find them easily in case of errors. This is the part of the project where understanding how "this" and the "->" operator work will REALLY come in handy. Aside from that, the functions in this .cpp file are far less complicated than Roster.cpp's.
|
58e3a1dd781328f08cdc3c60b1b52281
|
{
"intermediate": 0.37111085653305054,
"beginner": 0.4882538914680481,
"expert": 0.14063526690006256
}
|
41,491
|
In Real time stream system (music streaming service)
Question: How to measure success for a music streaming application to find KPI (Key performance Indicator) data point?
|
d86a262cae5706a6ae10121cacc47e00
|
{
"intermediate": 0.32766538858413696,
"beginner": 0.2014102041721344,
"expert": 0.47092434763908386
}
|
41,492
|
import math
a_0 = float(input("Введите значение a_0: "))
x = float(input("Введите значение x (x > 1): "))
precision = 0.5e-6
a_n = a_0
a_next = math.sqrt(math.sin(5 + a_n ** 3) / x**n + 4)
while abs(a_next - a_n) >= precision:
a_n = a_next
a_next = math.sqrt(math.sin(5 + a_n ** 3) / x**n + 4)
print("Предел последовательности a_n с точностью 0.5e-6:", a_next) почему не правильно
|
eb45ccda457efd56d37739e16828883b
|
{
"intermediate": 0.3288543224334717,
"beginner": 0.476391077041626,
"expert": 0.19475460052490234
}
|
41,493
|
Hi, do you see any issue in this C++ class? If not, can you please comment it in Doxygen way?
~~~
class Params
{
private:
std::unique_ptr<double[]> values_;
size_t size_;
public:
Params(const size_t _size) : size_(_size), values_(new double[_size]){};
double* GetValues() { return values_.get(); }
size_t GetSize() { return size_; }
void SetValue(const size_t _index, const double _value) { values_[_index] = _value; }
void SetValues(const double* _values) { std::copy(_values, _values + size_, values_.get()); }
double GetValue(const size_t _index) { return values_[_index]; }
};
|
1f5bd4f3beb533e7bca8deb538eaac57
|
{
"intermediate": 0.34274426102638245,
"beginner": 0.5091980695724487,
"expert": 0.14805763959884644
}
|
41,494
|
I am making a C++ SDL based game engine, currently and finishing the final touches of my classes, In my InputManager class, you said to me in another instance:
1) You may want to use SDL_Scancode instead of SDL_Keycode for key mapping to abstract away the specific keyboard layout.
2) Key Identifier: Using a std::string as a key might seem flexible, but it’s less performant due to string comparison and hashing overhead. If your key identifiers can be reduced to an enum or integer identifiers, it would be more efficient. If you have a predefined set of keys, consider an enum (which can also map to strings for configurable keys).
3) Methods like KeyPressed and KeyReleased will be called frequently, potentially multiple times per frame. It’s crucial to make these methods as efficient as possible. This might include optimizing your controls data structure for quick lookups.
How can I do this?
public:
~InputManager() = default;
InputManager(const InputManager&) = delete;
InputManager operator=(const InputManager&) = delete;
static InputManager& GetInstance();
void Update();
bool KeyPressed(const std::string& key, int player = 0);
bool KeyReleased(const std::string& key, int player = 0);
void AddKey(const std::string& key, SDL_Keycode code, int player = 0);
void AddKeys(const std::unordered_map<std::string, SDL_Keycode>& keyMap, int player = 0);
void ModifyKey(const std::string& key, SDL_Keycode newCode, int player = 0);
private:
InputManager();
void CheckNewPlayers(int player);
std::vector<std::unordered_map<std::string, SDL_Keycode>> controls;
std::vector<std::vector<Uint8>> currentState;
std::vector<std::vector<Uint8>> previousState;
|
92e5fcef591ded4132c28cdb9b227b2b
|
{
"intermediate": 0.6167538166046143,
"beginner": 0.23403121531009674,
"expert": 0.1492149978876114
}
|
41,495
|
Is this a correct way to make my singleton class thread safe or there is another simpler or better alternative?
cpp
#include <mutex>
class Singleton
{
public:
static Singleton& GetInstance()
{
std::lock_guard<std::mutex> lock(mutex_);
static Singleton instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {}
static std::mutex mutex_;
};
std::mutex Singleton::mutex_;
|
db1db8f8c02275d265e43cfc681df1b3
|
{
"intermediate": 0.27121782302856445,
"beginner": 0.6451740264892578,
"expert": 0.08360807597637177
}
|
41,496
|
in python dict .items() give me a list of tuples but i need a list of list of key value how can i do this?
|
319a4afbfe1c8b4d949a4ca3ca31a7b2
|
{
"intermediate": 0.5547590255737305,
"beginner": 0.17053057253360748,
"expert": 0.27471044659614563
}
|
41,497
|
Can I give you some code in c++ and the errors associated w/ them. Could you tell me whats wrong.
6 C++ files, three .h or Header files and three .cpp or Source Code files. These are;
Main.cpp
Roster.cpp
Roster.h
Student.cpp
Student.h
Degree.h
|
d571e8fe2ef8209f779e98279b866503
|
{
"intermediate": 0.3260113596916199,
"beginner": 0.4026756286621094,
"expert": 0.2713130712509155
}
|
41,498
|
This is a prod sense question: In a Batch system, How to use metrics analysis success for Dropbox Application?
|
0883a3ed2a8ef6fc89b8d86d176a54b4
|
{
"intermediate": 0.5484582185745239,
"beginner": 0.2099316120147705,
"expert": 0.24161016941070557
}
|
41,499
|
In python you can create a generator that yields values, but you can also use a return statement to send a value once the iteration stops. If you use this generator in a regular for loop in python, you wouldn't be able to see the value that is used in the return statement. When might one want to use a return statement in a generator then?
|
f4e52e84196997722a2d7a676c5a137b
|
{
"intermediate": 0.2981172800064087,
"beginner": 0.4049031138420105,
"expert": 0.2969796657562256
}
|
41,500
|
Can you improve following dimension design for DropBox application?
### Fact Tables
1. FactUploads
- UploadID (PK)
- UserID (FK)
- FileID (FK)
- DateKey (FK)
- TimeKey (FK)
- FileSize
- SuccessFlag
2. FactShares
- ShareID (PK)
- UserID (FK)
- FileID (FK)
- SharedWithUserID (FK)
- DateKey (FK)
- TimeKey (FK)
- ShareTypeKey (FK)
- SuccessFlag
3. FactOwnershipTransfers
- OwnershipTransferID (PK)
- OriginalOwnerUserID (FK)
- NewOwnerUserID (FK)
- FileID (FK)
- DateKey (FK)
- TimeKey (FK)
- SuccessFlag
4. FactSubscription
- SubscriptionID (PK)
- UserID (FK)
- DateKey (FK)
- SubscriptionTypeKey (FK)
- Revenue
5. FactCustomerSupport
- SupportTicketID (PK)
- UserID (FK)
- DateKey (FK)
- TimeKey (FK)
- IssueTypeKey (FK)
- ResolutionTime
### Dimension Tables
1. DimUser
- UserID (PK)
- UserName
- UserEmail
- AccountTypeKey (FK)
2. DimFile
- FileID (PK)
- FileName
- FileType
- FolderID (FK)
3. DimDate
- DateKey (PK)
- Date
- Weekday
- Month
- Quarter
- Year
4. DimTime
- TimeKey (PK)
- Time
- Hour
- Minute
5. DimAccountType
- AccountTypeKey (PK)
- AccountTypeName
6. DimFolder
- FolderID (PK)
- FolderName
- ParentFolderID (FK)
7. DimShareType
- ShareTypeKey (PK)
- ShareTypeName (e.g., link, direct, group)
8. DimSubscriptionType
- SubscriptionTypeKey (PK)
- SubscriptionTypeName (e.g., Free, Plus, Professional)
9. DimIssueType
- IssueTypeKey (PK)
- IssueTypeName (e.g., Login Problems, Sync Issues, Account Queries)
|
e6ddb4d06eaae049a1b9cc8295b9c1cf
|
{
"intermediate": 0.3916071057319641,
"beginner": 0.279824823141098,
"expert": 0.3285680115222931
}
|
41,501
|
هذا عبارة عن مفتاح api https://api.sofascore.com/api/v1/event/12095502/lineups اكتبه على شكل نموذج
|
425c654a85497003a95ef2da0b4d26ac
|
{
"intermediate": 0.4146566689014435,
"beginner": 0.28645384311676025,
"expert": 0.2988894581794739
}
|
41,502
|
How can I generate a http request directly to the paloalto gateway bypassing the globalprotect portal?
|
c12f1a416b9b219830684793901aaee2
|
{
"intermediate": 0.4571870267391205,
"beginner": 0.1561121791601181,
"expert": 0.3867007791996002
}
|
41,503
|
You are a mediocre first year computer science student enrolled in a java programming class. Complete the following assignment
|
f3cc7bfd7cdf659f73ab8cf00ced3d69
|
{
"intermediate": 0.3500739336013794,
"beginner": 0.3267359137535095,
"expert": 0.32319021224975586
}
|
41,504
|
complete the following activity
|
aa3614c370eb11e6f9d57d5e5fd20cb0
|
{
"intermediate": 0.34603992104530334,
"beginner": 0.2954768240451813,
"expert": 0.35848328471183777
}
|
41,505
|
Hi I would like a PowerShell to pull a list of all groups in exchange online and build a table with last mail received date and another column on the table that if its older than 90 days enter unused. I understand the Get-HistoricalSearch would be good for this.
|
518283c2dbafcda93d3c80349bb05825
|
{
"intermediate": 0.4036310911178589,
"beginner": 0.2731435298919678,
"expert": 0.3232254087924957
}
|
41,506
|
I am making a C++ sdl based game engine, where I am wrapping every SDL class, currently i am doing the Window class, check and evaluate if what I have is good or not, or if I need to add something I missed:
Surface::Surface(const std::string& filePath) : surface(IMG_Load(filePath.c_str()))
{
if (surface == nullptr)
{
// ... error handling
}
}
Surface::Surface(const std::string& text, Font& font, int fontSize, const Color& color, bool antiAliasing = false) : surface(antiAliasing ? TTF_RenderUTF8_Blended(font.GetFont(fontSize), text.c_str(), { color.R, color.G, color.B, color.A }) : TTF_RenderUTF8_Solid(font.GetFont(fontSize), text.c_str(), { color.R, color.G, color.B, color.A }))
{
if (surface == nullptr)
{
// ... error handling
}
}
Surface::Surface(const std::string& text, Font& font, int fontSize, const Color& fgColor, const Color& bgColor) : surface(TTF_RenderUTF8_Shaded(font.GetFont(fontSize), text.c_str(), { fgColor.R, fgColor.G, fgColor.B, fgColor.A }, { bgColor.R, bgColor.G, bgColor.B, bgColor.A }))
{
if (surface == nullptr)
{
// ... error handling
}
}
Surface::~Surface()
{
if (surface != nullptr)
{
SDL_FreeSurface(surface);
surface = nullptr;
}
}
Surface::Surface(Surface&& other) noexcept : surface(other.surface)
{
other.surface = nullptr;
}
Surface& Surface::operator=(Surface&& other) noexcept
{
if (this != &other)
{
if (surface != nullptr)
{
SDL_FreeSurface(surface);
}
surface = other.surface;
other.surface = nullptr;
}
return *this;
}
SDL_Surface* Surface::GetSurface() const
{
return surface;
}
Point Surface::GetSize() const
{
return Point(surface->w, surface->h);
}
BlendMode::Type Surface::GetBlendMode() const
{
SDL_BlendMode* sdlBlendMode = 0;
if (SDL_GetSurfaceBlendMode(surface, sdlBlendMode) != 0)
{
// ... error handling
}
return BlendMode::FromSDL(*sdlBlendMode);
}
void Surface::SetBlendMode(BlendMode::Type blendMode)
{
SDL_BlendMode sdlBlendMode = BlendMode::ToSDL(blendMode);
if (SDL_SetSurfaceBlendMode(surface, sdlBlendMode) != 0)
{
// ... error handling
}
}
Color Surface::GetColorMod() const
{
Uint8 r = 0;
Uint8 g = 0;
Uint8 b = 0;
if (SDL_GetSurfaceColorMod(surface, &r, &g, &b) != 0)
{
// ... error handling
}
return Color(r, g, b, 255);
}
void Surface::SetColorMod(const Color& color)
{
if (SDL_SetSurfaceColorMod(surface, color.R, color.G, color.B) != 0)
{
// ... error handling
}
}
Uint8 Surface::GetAlphaMod() const
{
Uint8 a = 0;
if (SDL_GetSurfaceAlphaMod(surface, &a) != 0)
{
// ... error handling
}
return a;
}
void Surface::SetAlphaMod(const Uint8& a)
{
if (SDL_SetSurfaceAlphaMod(surface, a) != 0)
{
// ... error handling
}
}
|
249211dd6a93cb1b616cc0e9ee714517
|
{
"intermediate": 0.3425487279891968,
"beginner": 0.41917142271995544,
"expert": 0.2382798194885254
}
|
41,507
|
in C++ SDL, which methods or functions use SDL_VertexSolid as a parameter or as a result?
|
90e48111158d29817023ee6bcc8d117e
|
{
"intermediate": 0.5465220212936401,
"beginner": 0.30397695302963257,
"expert": 0.1495010405778885
}
|
41,508
|
can you help me write code for a website, the title is THREEFOURTHS, I want that centered with a placeholder image beneath, then social media links underneath and button saying enter to take you to the portfolio page where I will have a gallery. use black white grey red color scheme, keep mostly centered or symmetrical, make retro skate trash type style
|
069d58653ea2c8661b115e381a147ddf
|
{
"intermediate": 0.30096107721328735,
"beginner": 0.45402905344963074,
"expert": 0.2450098693370819
}
|
41,509
|
这个报错是什么原因”ERROR: Could not build wheels for fairscale which use PEP 517 and cannot be installed directly、“
|
6acd7d77ff756893126966dd9b1f84b5
|
{
"intermediate": 0.4224287271499634,
"beginner": 0.25025811791419983,
"expert": 0.3273131549358368
}
|
41,510
|
hello
|
2b54312c19f64d7f2a44090faa936a56
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
41,511
|
Hi Please be a senior js developer. I want to make a match of the string "Accl ID = TEST_TEST_1Accl ID = XXX", the TEST_TEST_1 can be other content but it will always be Letters, numbers and _ symbol. Please help to match this string
|
78e1d07ad0549ff6d3676cd51bfbb36e
|
{
"intermediate": 0.46266281604766846,
"beginner": 0.27257513999938965,
"expert": 0.2647620737552643
}
|
41,512
|
known_train_features_scaled = self.scaler.fit_transform(features)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (143,) + inhomogeneous part.
|
2119d1e5fe895da51a0e882ade540919
|
{
"intermediate": 0.3327910006046295,
"beginner": 0.2608480155467987,
"expert": 0.40636101365089417
}
|
41,513
|
Hi Please be a senior js developer. I want to make a match of the string “Accl ID = TEST_TEST_1Accl ID = XXX”, the TEST_TEST_1 can be other content but it will always be Letters, numbers and _ symbo. Please make the input as “<a href = “” Accl ID = TEST_TEST_1Accl ID = XXX” and make the output be “Accl ID = TEST_TEST_1Accl ID = XXX”
|
3a57cbbad2a0aa10b010eb7828788946
|
{
"intermediate": 0.5147327184677124,
"beginner": 0.26439401507377625,
"expert": 0.22087319195270538
}
|
41,514
|
Hi Please be a senior js developer.Please make the input as “<a href = “” Accl ID = TEST_TEST_1Accl ID = XXX” and make the output be “Accl ID = TEST_TEST_1Accl ID = XXX”
|
8c395678e78be4a506171f911553d278
|
{
"intermediate": 0.35276705026626587,
"beginner": 0.491293728351593,
"expert": 0.15593914687633514
}
|
41,515
|
Hi Please be a senior js developer. I want to make a match of the string “Accl ID = TEST_TEST_1Accl ID = XXX”, the TEST_TEST_1 can be other content but it will always be Letters, numbers and _ symbo. Please make the input as "<a href = "" Accl ID = TEST_TEST_1Accl ID = XXX</a>" and make the output be "Accl ID = TEST_TEST_1Accl ID = XXX"
|
da481b6d92f3275a88234d2eb6aee82d
|
{
"intermediate": 0.4912263751029968,
"beginner": 0.28642433881759644,
"expert": 0.22234931588172913
}
|
41,516
|
What metrics would you use to evaluate if a feature in the photo upload application is effective or not? What data would you collect? focus on photo upload process time.
|
440e835bbc130353c59d5e78cb7dd457
|
{
"intermediate": 0.3889230191707611,
"beginner": 0.24743308126926422,
"expert": 0.36364394426345825
}
|
41,517
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract CanNotCompile {
struct Data{
uint256 balance;
bytes32 signature;
}
mapping(address => Data) userData;
function deleteStruct() external {
Data storage data = userData[msg.sennder];
delete data;
}
}
The provided code above is encountering compilation issues. Could you identify the reason(s)
behind it failure without running it through the ccompiler?
|
f6d2124c894f6d422318f9f2d49af24b
|
{
"intermediate": 0.6243696212768555,
"beginner": 0.18146735429763794,
"expert": 0.1941630244255066
}
|
41,518
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract CanNotCompile {
struct Data{
uint256 balance;
bytes32 signature;
}
mapping(address => Data) userData;
function deleteStruct() external {
Data storage data = userData[msg.sender];
delete data;
}
}
The provided code above is encountering compilation issues. Could you identify the reason(s)
behind it failure without running it through the compiler?
|
0f314a18d9c46e2bceaf596a11b0c51b
|
{
"intermediate": 0.6320912837982178,
"beginner": 0.17515042424201965,
"expert": 0.19275829195976257
}
|
41,519
|
def train_one_epoch(model, iterator, criterion, optimizer, padding_index):
""" Train a model for one epoch.
Arguments:
model: model to train
iterator: iterator over one epoch of data to train on
criterion: loss, to be used for training
optimizer: the optimizer to use for training
padding_index: which token ID is padding, for model
Returns:
average of criterion across the iterator
"""
# put model back into training mode
model.train()
epoch_loss = 0.0
for batch in iterator:
optimizer.zero_grad()
# batch.text has shape (seq_len, batch_size), so we transpose it to
# have the right shape of
# (batch_size, seq_len)
batch_text = torch.t(batch.text)
logits = model(batch_text, padding_index)
loss = criterion(logits, batch.label)
# TODO: implement L2 loss here
# Note: model.parameters() returns an iterator over the parameters
# (which are tensors) of the model
L2 = 0.0
regularized_loss = loss + 1e-4*L2
# backprop regularized loss and update parameters
regularized_loss.backward()
optimizer.step()
epoch_loss += loss.item()
return epoch_loss / len(iterator)
补全这段代码
|
34452b752ac25b2887bd4e8c5063668a
|
{
"intermediate": 0.3976578414440155,
"beginner": 0.20979952812194824,
"expert": 0.39254263043403625
}
|
41,520
|
создай базу данных sql по тз:
В таблицах должны находиться данные о Компьютерных фирмах и Типах
компьютеров.
Компьютеры каждого типа можно приобрести в нескольких фирмах.
|
a998b6c63ac57254cc79cbc20cab718e
|
{
"intermediate": 0.3143980801105499,
"beginner": 0.30430006980895996,
"expert": 0.3813018798828125
}
|
41,521
|
hi i want to learn about the implementation of Reinforcement learning in python
|
30349712d5abed26b448f1b18ffcb1ce
|
{
"intermediate": 0.04610405117273331,
"beginner": 0.03280983492732048,
"expert": 0.9210860729217529
}
|
41,522
|
in this recursive function explains what each line does what does the function do
int maxval(int arr[], int n) {
if (n == 1) return arr[0];
int largest = maxval(arr, n-1);
if (arr[n-1] > largest)
largest = arr[n-1];
return largest;
}
|
1287ff85bd37095a4a766c12a931fa04
|
{
"intermediate": 0.21156063675880432,
"beginner": 0.5659962296485901,
"expert": 0.22244322299957275
}
|
41,523
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract CanNotCompile {
struct Data{
uint256 balance;
bytes32 signature;
}
mapping(address => Data) userData;
function deleteStruct() external {
Data storage data = userData[msg.sender];
delete data;
}
}
The provided code above is encountering compilation issues. Could you identify the reason(s)
behind it failure without running it through the compiler?
|
ee242d99aeb0c809eb9259ccafdbe996
|
{
"intermediate": 0.6320912837982178,
"beginner": 0.17515042424201965,
"expert": 0.19275829195976257
}
|
41,524
|
Create a Photoshop Script:
Make an user interface with following elements;
"Enter 4 D Wall Name" text input field.
"Select Files" button (As a description next to button "Select the Titled and Untitled Versions of Wall")
This button should let user to select maximum two documents as JPG or PSD format.
These images should be placed in document.
If import image file name includes TITLE then it should be Titled version,
If imported image file name includes NO TITLE or simply does not have any word like TITLE or NOTITLE then it should be Untitled version.
Their layer names should be: "Titled Version" and "Untitled Version".
|
d0a5e301dcede321d8eab3b2139ef060
|
{
"intermediate": 0.4390396475791931,
"beginner": 0.25470080971717834,
"expert": 0.30625948309898376
}
|
41,525
|
Continue
|
96a539e035a76fc17e2034e4464f223f
|
{
"intermediate": 0.3358786702156067,
"beginner": 0.24657872319221497,
"expert": 0.41754260659217834
}
|
41,526
|
improve this text
private static List<SentenceInfo> collectSentences(Annotation annotatedDoc, LanguageEnum language) throws Exception {
List<SentenceInfo> sentenceInfos = new ArrayList<>();
//Getting sentences...
List<CoreMap> sentences = annotatedDoc.get(CoreAnnotations.SentencesAnnotation.class);
//Get current language stop-words & POS Tags
final CharArraySet stopWordSet = EnglishAnalyzer.getDefaultStopSet();
String word;
for (CoreMap sentence : sentences) {
List<CoreLabel> tokens = sentence.get(CoreAnnotations.TokensAnnotation.class);
if (tokens == null || tokens.size() >= 300) {
continue;
}
List<String> sTokens = new ArrayList<>();
int isDigit = 0, startI = 0;
for (int i = 0; i < tokens.size(); i++) {
CoreLabel token = tokens.get(i);
if (Thread.interrupted()) { // Allow interrupting
throw new InterruptedException("Breaking KeyPhrase token loop due to thread is interrupted");
}
// this is the text of the token
word = token.word().toLowerCase();
word = CustomASCIIFoldingFilter.convertToASCII(word.toCharArray());
//Split sentence on "___________" or "--------" etc
if (PUNCT_CHARS_MIN_5_PATTERN.matcher(word).matches()) {
collectSentence(sentenceInfos, tokens.subList(startI, i), sTokens, isDigit);
isDigit = 0;
startI = i + 1;
sTokens = new ArrayList<>();
continue;
}
String normalizeToken = word;
boolean isValidWord = !stopWordSet.contains(normalizeToken);
isValidWord = isValidWord && isValidKeyWord(normalizeToken);
// isValidWord = isValidWord && validateByWordNet(splitedToken, language);
if (isValidWord) {
sTokens.add(word);
}
if (DIGITS_PATTERN.matcher(word).matches()) {
isDigit++;
}
// }
}
collectSentence(sentenceInfos, tokens.subList(startI, tokens.size()), sTokens, isDigit);
}
return sentenceInfos;
}
|
0b9541e14965b8b599c45bd650c9eb64
|
{
"intermediate": 0.3926786184310913,
"beginner": 0.4080764055252075,
"expert": 0.19924499094486237
}
|
41,527
|
# Display 200 rows in Polars output
pl.Config.set_tbl_rows(200)
# Function to perform the grouping, counting, and sorting of lengths
def group_count_sort(y_cl4, length_threshold=None):
lengths = y_cl4.groupby('unique_id').agg(pl.count().alias('length'))
if length_threshold:
lengths = lengths.filter(pl.col('length') > length_threshold)
counts = lengths.groupby('length').agg(pl.count().alias('count')).sort('length')
return lengths, counts
# Lengths for all series
all_lengths, all_counts = group_count_sort(y_cl4)
print(all_counts)
# Function to filter y_cl4 based on lengths
def filter_and_sort(y_cl4, lengths):
y_cl4_filtered = y_cl4.join(
lengths.select(pl.col('unique_id')),
on='unique_id',
how='semi'
)
return y_cl4_filtered.sort('ds')
# Lengths greater than 27
lengths_over_27, counts_for_over_27 = group_count_sort(y_cl4, 27)
y_cl4_over_27 = filter_and_sort(y_cl4, lengths_over_27)
print(counts_for_over_27)
# Lengths greater than 15
lengths_over_15, counts_for_over_15 = group_count_sort(y_cl4, 15)
y_cl4_over_15 = filter_and_sort(y_cl4, lengths_over_15)
print(counts_for_over_15)
length ┆ count │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞════════╪═══════╡
│ 5 ┆ 2 │
│ 6 ┆ 1 │
│ 7 ┆ 1 │
│ 8 ┆ 7 │
│ 9 ┆ 4 │
│ 10 ┆ 10 │
│ 11 ┆ 8 │
│ 12 ┆ 4 │
│ 13 ┆ 6 │
│ 14 ┆ 11 │
│ 15 ┆ 16 │
│ 16 ┆ 14 │
│ 17 ┆ 27 │
│ 18 ┆ 26 │
│ 19 ┆ 31 │
│ 20 ┆ 32 │
│ 21 ┆ 30 │
│ 22 ┆ 24 │
│ 23 ┆ 30 │
│ 24 ┆ 26 │
│ 25 ┆ 32 │
│ 26 ┆ 28 │
│ 27 ┆ 32 │
│ 28 ┆ 47 │
│ 29 ┆ 50 │
│ 30 ┆ 28 │
│ 31 ┆ 37 │
│ 32 ┆ 26 │
│ 33 ┆ 34 │
│ 34 ┆ 41 │
│ 35 ┆ 40 │
│ 36 ┆ 47 │
│ 37 ┆ 40 │
│ 38 ┆ 46 │
│ 39 ┆ 43 │
│ 40 ┆ 52 │
│ 41 ┆ 53 │
│ 42 ┆ 52 │
│ 43 ┆ 65 │
│ 44 ┆ 68 │
│ 45 ┆ 68 │
│ 46 ┆ 71 │
│ 47 ┆ 65 │
│ 48 ┆ 60 │
│ 49 ┆ 74 │
│ 50 ┆ 87 │
│ 51 ┆ 63 │
│ 52 ┆ 80 │
│ 53 ┆ 79 │
│ 54 ┆ 85 │
│ 55 ┆ 89 │
│ 56 ┆ 70 │
│ 57 ┆ 88 │
│ 58 ┆ 94 │
│ 59 ┆ 104 │
│ 60 ┆ 113 │
│ 61 ┆ 116 │
│ 62 ┆ 127 │
│ 63 ┆ 106 │
│ 64 ┆ 157 │
│ 65 ┆ 128 │
│ 66 ┆ 137 │
│ 67 ┆ 154 │
│ 68 ┆ 145 │
│ 69 ┆ 133 │
│ 70 ┆ 167 │
│ 71 ┆ 161 │
│ 72 ┆ 145 │
│ 73 ┆ 167 │
│ 74 ┆ 150 │
│ 75 ┆ 153 │
│ 76 ┆ 205 │
│ 77 ┆ 199 │
│ 78 ┆ 240 │
│ 79 ┆ 207 │
│ 80 ┆ 179 │
│ 81 ┆ 186 │
│ 82 ┆ 195 │
│ 83 ┆ 185 │
│ 84 ┆ 189 │
│ 85 ┆ 202 │
│ 86 ┆ 200 │
│ 87 ┆ 207 │
│ 88 ┆ 167 │
│ 89 ┆ 168 │
│ 90 ┆ 185 │
│ 91 ┆ 177 │
│ 92 ┆ 174 │
│ 93 ┆ 162 │
│ 94 ┆ 199 │
│ 95 ┆ 139 │
│ 96 ┆ 162 │
│ 97 ┆ 160 │
│ 98 ┆ 172 │
│ 99 ┆ 170 │
│ 100 ┆ 194 │
│ 101 ┆ 178 │
│ 102 ┆ 151 │
│ 103 ┆ 180 │
│ 104 ┆ 160 │
│ 105 ┆ 153 │
│ 106 ┆ 167 │
│ 107 ┆ 176 │
│ 108 ┆ 202 │
│ 109 ┆ 190 │
│ 110 ┆ 157 │
│ 111 ┆ 166 │
│ 112 ┆ 221 │
│ 113 ┆ 190 │
│ 114 ┆ 169 │
│ 115 ┆ 179 │
│ 116 ┆ 139 │
│ 117 ┆ 146 │
│ 118 ┆ 174 │
│ 119 ┆ 136 │
│ 120 ┆ 183 │
│ 121 ┆ 172 │
│ 122 ┆ 155 │
│ 123 ┆ 169 │
│ 124 ┆ 140 │
│ 125 ┆ 157 │
│ 126 ┆ 150 │
│ 127 ┆ 159 │
│ 128 ┆ 157 │
│ 129 ┆ 163 │
│ 130 ┆ 151 │
│ 131 ┆ 167 │
│ 132 ┆ 169 │
│ 133 ┆ 149 │
│ 134 ┆ 167 │
│ 135 ┆ 172 │
│ 136 ┆ 180 │
│ 137 ┆ 167 │
│ 138 ┆ 162 │
│ 139 ┆ 141 │
│ 140 ┆ 167 │
│ 141 ┆ 166 │
│ 142 ┆ 149 │
│ 143 ┆ 149 │
│ 144 ┆ 150 │
│ 145 ┆ 146 │
│ 146 ┆ 156 │
│ 147 ┆ 183 │
│ 148 ┆ 149 │
│ 149 ┆ 162 │
│ 150 ┆ 157 │
│ 151 ┆ 161 │
│ 152 ┆ 229 │
│ 153 ┆ 165 │
│ 154 ┆ 215 │
│ 155 ┆ 226 │
│ 156 ┆ 303 │
│ 157 ┆ 639 │
└────────┴───────┘
shape: (130, 2)
┌────────┬───────┐
│ length ┆ count │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞════════╪═══════╡
│ 28 ┆ 47 │
│ 29 ┆ 50 │
│ 30 ┆ 28 │
│ 31 ┆ 37 │
│ 32 ┆ 26 │
│ 33 ┆ 34 │
│ 34 ┆ 41 │
│ 35 ┆ 40 │
│ 36 ┆ 47 │
│ 37 ┆ 40 │
│ 38 ┆ 46 │
│ 39 ┆ 43 │
│ 40 ┆ 52 │
│ 41 ┆ 53 │
│ 42 ┆ 52 │
│ 43 ┆ 65 │
│ 44 ┆ 68 │
│ 45 ┆ 68 │
│ 46 ┆ 71 │
│ 47 ┆ 65 │
│ 48 ┆ 60 │
│ 49 ┆ 74 │
│ 50 ┆ 87 │
│ 51 ┆ 63 │
│ 52 ┆ 80 │
│ 53 ┆ 79 │
│ 54 ┆ 85 │
│ 55 ┆ 89 │
│ 56 ┆ 70 │
│ 57 ┆ 88 │
│ 58 ┆ 94 │
│ 59 ┆ 104 │
│ 60 ┆ 113 │
│ 61 ┆ 116 │
│ 62 ┆ 127 │
│ 63 ┆ 106 │
│ 64 ┆ 157 │
│ 65 ┆ 128 │
│ 66 ┆ 137 │
│ 67 ┆ 154 │
│ 68 ┆ 145 │
│ 69 ┆ 133 │
│ 70 ┆ 167 │
│ 71 ┆ 161 │
│ 72 ┆ 145 │
│ 73 ┆ 167 │
│ 74 ┆ 150 │
│ 75 ┆ 153 │
│ 76 ┆ 205 │
│ 77 ┆ 199 │
│ 78 ┆ 240 │
│ 79 ┆ 207 │
│ 80 ┆ 179 │
│ 81 ┆ 186 │
│ 82 ┆ 195 │
│ 83 ┆ 185 │
│ 84 ┆ 189 │
│ 85 ┆ 202 │
│ 86 ┆ 200 │
│ 87 ┆ 207 │
│ 88 ┆ 167 │
│ 89 ┆ 168 │
│ 90 ┆ 185 │
│ 91 ┆ 177 │
│ 92 ┆ 174 │
│ 93 ┆ 162 │
│ 94 ┆ 199 │
│ 95 ┆ 139 │
│ 96 ┆ 162 │
│ 97 ┆ 160 │
│ 98 ┆ 172 │
│ 99 ┆ 170 │
│ 100 ┆ 194 │
│ 101 ┆ 178 │
│ 102 ┆ 151 │
│ 103 ┆ 180 │
│ 104 ┆ 160 │
│ 105 ┆ 153 │
│ 106 ┆ 167 │
│ 107 ┆ 176 │
│ 108 ┆ 202 │
│ 109 ┆ 190 │
│ 110 ┆ 157 │
│ 111 ┆ 166 │
│ 112 ┆ 221 │
│ 113 ┆ 190 │
│ 114 ┆ 169 │
│ 115 ┆ 179 │
│ 116 ┆ 139 │
│ 117 ┆ 146 │
│ 118 ┆ 174 │
│ 119 ┆ 136 │
│ 120 ┆ 183 │
│ 121 ┆ 172 │
│ 122 ┆ 155 │
│ 123 ┆ 169 │
│ 124 ┆ 140 │
│ 125 ┆ 157 │
│ 126 ┆ 150 │
│ 127 ┆ 159 │
│ 128 ┆ 157 │
│ 129 ┆ 163 │
│ 130 ┆ 151 │
│ 131 ┆ 167 │
│ 132 ┆ 169 │
│ 133 ┆ 149 │
│ 134 ┆ 167 │
│ 135 ┆ 172 │
│ 136 ┆ 180 │
│ 137 ┆ 167 │
│ 138 ┆ 162 │
│ 139 ┆ 141 │
│ 140 ┆ 167 │
│ 141 ┆ 166 │
│ 142 ┆ 149 │
│ 143 ┆ 149 │
│ 144 ┆ 150 │
│ 145 ┆ 146 │
│ 146 ┆ 156 │
│ 147 ┆ 183 │
│ 148 ┆ 149 │
│ 149 ┆ 162 │
│ 150 ┆ 157 │
│ 151 ┆ 161 │
│ 152 ┆ 229 │
│ 153 ┆ 165 │
│ 154 ┆ 215 │
│ 155 ┆ 226 │
│ 156 ┆ 303 │
│ 157 ┆ 639 │
└────────┴───────┘
shape: (142, 2)
┌────────┬───────┐
│ length ┆ count │
│ --- ┆ --- │
│ u32 ┆ u32 │
╞════════╪═══════╡
│ 16 ┆ 14 │
│ 17 ┆ 27 │
│ 18 ┆ 26 │
│ 19 ┆ 31 │
│ 20 ┆ 32 │
│ 21 ┆ 30 │
│ 22 ┆ 24 │
│ 23 ┆ 30 │
│ 24 ┆ 26 │
│ 25 ┆ 32 │
│ 26 ┆ 28 │
│ 27 ┆ 32 │
│ 28 ┆ 47 │
│ 29 ┆ 50 │
│ 30 ┆ 28 │
│ 31 ┆ 37 │
│ 32 ┆ 26 │
│ 33 ┆ 34 │
│ 34 ┆ 41 │
│ 35 ┆ 40 │
│ 36 ┆ 47 │
│ 37 ┆ 40 │
│ 38 ┆ 46 │
│ 39 ┆ 43 │
│ 40 ┆ 52 │
│ 41 ┆ 53 │
│ 42 ┆ 52 │
│ 43 ┆ 65 │
│ 44 ┆ 68 │
│ 45 ┆ 68 │
│ 46 ┆ 71 │
│ 47 ┆ 65 │
│ 48 ┆ 60 │
│ 49 ┆ 74 │
│ 50 ┆ 87 │
│ 51 ┆ 63 │
│ 52 ┆ 80 │
│ 53 ┆ 79 │
│ 54 ┆ 85 │
│ 55 ┆ 89 │
│ 56 ┆ 70 │
│ 57 ┆ 88 │
│ 58 ┆ 94 │
│ 59 ┆ 104 │
│ 60 ┆ 113 │
│ 61 ┆ 116 │
│ 62 ┆ 127 │
│ 63 ┆ 106 │
│ 64 ┆ 157 │
│ 65 ┆ 128 │
│ 66 ┆ 137 │
│ 67 ┆ 154 │
│ 68 ┆ 145 │
│ 69 ┆ 133 │
│ 70 ┆ 167 │
│ 71 ┆ 161 │
│ 72 ┆ 145 │
│ 73 ┆ 167 │
│ 74 ┆ 150 │
│ 75 ┆ 153 │
│ 76 ┆ 205 │
│ 77 ┆ 199 │
│ 78 ┆ 240 │
│ 79 ┆ 207 │
│ 80 ┆ 179 │
│ 81 ┆ 186 │
│ 82 ┆ 195 │
│ 83 ┆ 185 │
│ 84 ┆ 189 │
│ 85 ┆ 202 │
│ 86 ┆ 200 │
│ 87 ┆ 207 │
│ 88 ┆ 167 │
│ 89 ┆ 168 │
│ 90 ┆ 185 │
│ 91 ┆ 177 │
│ 92 ┆ 174 │
│ 93 ┆ 162 │
│ 94 ┆ 199 │
│ 95 ┆ 139 │
│ 96 ┆ 162 │
│ 97 ┆ 160 │
│ 98 ┆ 172 │
│ 99 ┆ 170 │
│ 100 ┆ 194 │
│ 101 ┆ 178 │
│ 102 ┆ 151 │
│ 103 ┆ 180 │
│ 104 ┆ 160 │
│ 105 ┆ 153 │
│ 106 ┆ 167 │
│ 107 ┆ 176 │
│ 108 ┆ 202 │
│ 109 ┆ 190 │
│ 110 ┆ 157 │
│ 111 ┆ 166 │
│ 112 ┆ 221 │
│ 113 ┆ 190 │
│ 114 ┆ 169 │
│ 115 ┆ 179 │
│ 116 ┆ 139 │
│ 117 ┆ 146 │
│ 118 ┆ 174 │
│ 119 ┆ 136 │
│ 120 ┆ 183 │
│ 121 ┆ 172 │
│ 122 ┆ 155 │
│ 123 ┆ 169 │
│ 124 ┆ 140 │
│ 125 ┆ 157 │
│ 126 ┆ 150 │
│ 127 ┆ 159 │
│ 128 ┆ 157 │
│ 129 ┆ 163 │
│ 130 ┆ 151 │
│ 131 ┆ 167 │
│ 132 ┆ 169 │
│ 133 ┆ 149 │
│ 134 ┆ 167 │
│ 135 ┆ 172 │
│ 136 ┆ 180 │
│ 137 ┆ 167 │
│ 138 ┆ 162 │
│ 139 ┆ 141 │
│ 140 ┆ 167 │
│ 141 ┆ 166 │
│ 142 ┆ 149 │
│ 143 ┆ 149 │
│ 144 ┆ 150 │
│ 145 ┆ 146 │
│ 146 ┆ 156 │
│ 147 ┆ 183 │
│ 148 ┆ 149 │
│ 149 ┆ 162 │
│ 150 ┆ 157 │
│ 151 ┆ 161 │
│ 152 ┆ 229 │
│ 153 ┆ 165 │
│ 154 ┆ 215 │
│ 155 ┆ 226 │
│ 156 ┆ 303 │ from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, DynamicOptimizedTheta
from statsforecast.utils import ConformalIntervals
import numpy as np
import polars as pl
# Polars option to display all rows
pl.Config.set_tbl_rows(None)
# Initialize the models
models = [
AutoARIMA(season_length=52),
AutoETS(damped=True, season_length=52),
DynamicOptimizedTheta(season_length=13)
]
# Initialize the StatsForecast model
sf = StatsForecast(models=models, freq='1w', n_jobs=-1)
# Perform cross-validation with a step size of 1 to mimic an expanding window
crossvalidation_df = sf.cross_validation(df=y_cl4_over_27, h=10, step_size=1, n_windows=10, sort_df=True)
# Calculate the ensemble mean
ensemble = crossvalidation_df[['AutoARIMA', 'AutoETS', 'DynamicOptimizedTheta']].mean(axis=1)
# Create a Series for the ensemble mean
ensemble_series = pl.Series('Ensemble', ensemble)
# Add the ensemble mean as a new column to the DataFrame
crossvalidation_df = crossvalidation_df.with_columns(ensemble_series)
def wmape(y_true, y_pred):
return np.abs(y_true - y_pred).sum() / np.abs(y_true).sum()
# Calculate the WMAPE for the ensemble model
wmape_value = wmape(crossvalidation_df['y'], crossvalidation_df['Ensemble'])
print('Average WMAPE for Ensemble: ', round(wmape_value, 4))
# Calculate the errors for the ensemble model
errors = crossvalidation_df['y'] - crossvalidation_df['Ensemble']
# For an individual forecast
individual_accuracy = 1 - (abs(crossvalidation_df['y'] - crossvalidation_df['Ensemble']) / crossvalidation_df['y'])
individual_bias = (crossvalidation_df['Ensemble'] / crossvalidation_df['y']) - 1
# Add these calculations as new columns to DataFrame
crossvalidation_df = crossvalidation_df.with_columns([
individual_accuracy.alias("individual_accuracy"),
individual_bias.alias("individual_bias")
])
# Print the individual accuracy and bias for each week
for row in crossvalidation_df.to_dicts():
id = row['unique_id']
date = row['ds']
accuracy = row['individual_accuracy']
bias = row['individual_bias']
print(f"{id}, {date}, Individual Accuracy: {accuracy:.4f}, Individual Bias: {bias:.4f}")
# For groups of forecasts
group_accuracy = 1 - (errors.abs().sum() / crossvalidation_df['y'].sum())
group_bias = (crossvalidation_df['Ensemble'].sum() / crossvalidation_df['y'].sum()) - 1
# Print the average group accuracy and group bias over all folds for the ensemble model
print('Average Group Accuracy: ', round(group_accuracy, 4))
print('Average Group Bias: ', round(group_bias, 4))
# Fit the models on the entire dataset
sf.fit(y_cl4_over_15)
# Instantiate the ConformalIntervals class
prediction_intervals = ConformalIntervals()
# Generate 24 months forecasts
forecasts_df = sf.forecast(h=52*2, prediction_intervals=prediction_intervals, level=[95], id_col='unique_id', sort_df=True)
# Apply the non-negative constraint to the forecasts of individual models
forecasts_df = forecasts_df.with_columns([
pl.when(pl.col('AutoARIMA') < 0).then(0).otherwise(pl.col('AutoARIMA')).alias('AutoARIMA'),
pl.when(pl.col('AutoETS') < 0).then(0).otherwise(pl.col('AutoETS')).alias('AutoETS'),
pl.when(pl.col('DynamicOptimizedTheta') < 0).then(0).otherwise(pl.col('DynamicOptimizedTheta')).alias('DynamicOptimizedTheta'),
pl.when(pl.col('AutoARIMA-lo-95') < 0).then(0).otherwise(pl.col('AutoARIMA-lo-95')).alias('AutoARIMA-lo-95'),
pl.when(pl.col('AutoETS-lo-95') < 0).then(0).otherwise(pl.col('AutoETS-lo-95')).alias('AutoETS-lo-95'),
pl.when(pl.col('DynamicOptimizedTheta-lo-95') < 0).then(0).otherwise(pl.col('DynamicOptimizedTheta-lo-95')).alias('DynamicOptimizedTheta-lo-95')
])
# Calculate the ensemble forecast
ensemble_forecast = forecasts_df[['AutoARIMA', 'AutoETS', 'DynamicOptimizedTheta']].mean(axis=1)
# Calculate the lower and upper prediction intervals for the ensemble forecast
ensemble_lo_95 = forecasts_df[['AutoARIMA-lo-95', 'AutoETS-lo-95', 'DynamicOptimizedTheta-lo-95']].mean(axis=1)
ensemble_hi_95 = forecasts_df[['AutoARIMA-hi-95', 'AutoETS-hi-95', 'DynamicOptimizedTheta-hi-95']].mean(axis=1)
# Create Series for the ensemble forecast and its prediction intervals
ensemble_forecast_series = pl.Series('EnsembleForecast', ensemble_forecast)
ensemble_lo_95_series = pl.Series('Ensemble-lo-95', ensemble_lo_95)
ensemble_hi_95_series = pl.Series('Ensemble-hi-95', ensemble_hi_95)
# Add the ensemble forecast and its prediction intervals as new columns to the DataFrame
forecasts_df = forecasts_df.with_columns([ensemble_forecast_series, ensemble_lo_95_series, ensemble_hi_95_series])
# Round the ensemble forecast and prediction intervals and convert to integer
forecasts_df = forecasts_df.with_columns([
pl.col("EnsembleForecast").round().cast(pl.Int32),
pl.col("Ensemble-lo-95").round().cast(pl.Int32),
pl.col("Ensemble-hi-95").round().cast(pl.Int32)
])
# Split the unique_id concat into the original columns
def split_unique_id(unique_id):
parts = unique_id.split('_')
return parts if len(parts) >= 4 else (parts + [None] * (4 - len(parts)))
forecasts_df = (
forecasts_df
.with_columns([
pl.col('unique_id').apply(lambda uid: split_unique_id(uid)[0]).alias('MaterialID'),
pl.col('unique_id').apply(lambda uid: split_unique_id(uid)[1]).alias('SalesOrg'),
pl.col('unique_id').apply(lambda uid: split_unique_id(uid)[2]).alias('DistrChan'),
pl.col('unique_id').apply(lambda uid: split_unique_id(uid)[3]).alias('CL4'),
])
.drop('unique_id')
)
# Rename ‘ds’ to ‘WeekDate’
forecasts_df = forecasts_df.rename({'ds': 'WeekDate'})
# Reorder the columns
forecasts_df = forecasts_df.select([
"MaterialID",
"SalesOrg",
"DistrChan",
"CL4",
"WeekDate",
"EnsembleForecast",
"Ensemble-lo-95",
"Ensemble-hi-95",
"AutoARIMA",
"AutoARIMA-lo-95",
"AutoARIMA-hi-95",
"AutoETS",
"AutoETS-lo-95",
"AutoETS-hi-95",
"DynamicOptimizedTheta",
"DynamicOptimizedTheta-lo-95",
"DynamicOptimizedTheta-hi-95"
])
# Create an empty list
forecasts_list = []
# Append each row to the list
for row in forecasts_df.to_dicts():
forecasts_list.append(row)
# Print the list
for forecast in forecasts_list:
print(forecast) RemoteTraceback Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
File "/Users/tungnguyen/anaconda3/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 322, in cross_validation
raise error
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/core.py", line 319, in cross_validation
res_i = model.forecast(**forecast_kwargs)
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/models.py", line 1292, in forecast
mod = auto_theta(
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsforecast/theta.py", line 633, in auto_theta
y_decompose = seasonal_decompose(y, model=decomposition_type, period=m).seasonal
File "/Users/tungnguyen/anaconda3/lib/python3.10/site-packages/statsmodels/tsa/seasonal.py", line 171, in seasonal_decompose
raise ValueError(
ValueError: x must have 2 complete cycles requires 26 observations. x only has 22 observation(s)
"""
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
Cell In[12], line 21
18 sf = StatsForecast(models=models, freq='1w', n_jobs=-1)
20 # Perform cross-validation with a step size of 1 to mimic an expanding window
---> 21 crossvalidation_df = sf.cross_validation(df=y_cl4_over_27, h=10, step_size=1, n_windows=10, sort_df=True)
23 # Calculate the ensemble mean
24 ensemble = crossvalidation_df[['AutoARIMA', 'AutoETS', 'DynamicOptimizedTheta']].mean(axis=1)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1616, in StatsForecast.cross_validation(self, h, df, n_windows, step_size, test_size, input_size, level, fitted, refit, sort_df, prediction_intervals, id_col, time_col, target_col)
1598 def cross_validation(
1599 self,
1600 h: int,
(...)
1613 target_col: str = "y",
1614 ):
1615 if self._is_native(df=df):
-> 1616 return super().cross_validation(
1617 h=h,
1618 df=df,
1619 n_windows=n_windows,
1620 step_size=step_size,
1621 test_size=test_size,
1622 input_size=input_size,
1623 level=level,
1624 fitted=fitted,
1625 refit=refit,
1626 sort_df=sort_df,
1627 prediction_intervals=prediction_intervals,
1628 id_col=id_col,
1629 time_col=time_col,
1630 target_col=target_col,
1631 )
1632 assert df is not None
1633 engine = make_execution_engine(infer_by=[df])
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1026, in _StatsForecast.cross_validation(self, h, df, n_windows, step_size, test_size, input_size, level, fitted, refit, sort_df, prediction_intervals, id_col, time_col, target_col)
1012 res_fcsts = self.ga.cross_validation(
1013 models=self.models,
1014 h=h,
(...)
1023 target_col=target_col,
1024 )
1025 else:
-> 1026 res_fcsts = self._cross_validation_parallel(
1027 h=h,
1028 test_size=test_size,
1029 step_size=step_size,
1030 input_size=input_size,
1031 fitted=fitted,
1032 level=level,
1033 refit=refit,
1034 target_col=target_col,
1035 )
1036 if fitted:
1037 self.cv_fitted_values_ = res_fcsts["fitted"]
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in _StatsForecast._cross_validation_parallel(self, h, test_size, step_size, input_size, fitted, level, refit, target_col)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
File ~/anaconda3/lib/python3.10/site-packages/statsforecast/core.py:1248, in <listcomp>(.0)
1232 future = executor.apply_async(
1233 ga.cross_validation,
1234 (
(...)
1245 ),
1246 )
1247 futures.append(future)
-> 1248 out = [f.get() for f in futures]
1249 fcsts = [d["forecasts"] for d in out]
1250 fcsts = np.vstack(fcsts)
File ~/anaconda3/lib/python3.10/multiprocessing/pool.py:774, in ApplyResult.get(self, timeout)
772 return self._value
773 else:
--> 774 raise self._value
ValueError: x must have 2 complete cycles requires 26 observations. x only has 22 observation(s) the crossvalidation is run on y_cl4_over_27 which is 28 weeks and up in series, how can I still get this error
|
25f9bb05c52dcc70edf9a321c6794501
|
{
"intermediate": 0.3452705442905426,
"beginner": 0.41858118772506714,
"expert": 0.23614829778671265
}
|
41,528
|
Python script
Open multiple files
Read line per line
Parse line with space separator
Element 2: Method
Element 3: Request
Element 8: Response Code
Element -2: Byte size
Element -1: Time response
At the end of reading and parsing each files, make a table that group by Method, Request and Response Code. Each one should have min time response, max time response, mean time response, 90 percentile time response, min byte size, max byte size, mean byte size, 90 percentile byte size.
Save in CSV.
No comments, no explanation, just code.
|
d421f9568036a072ea0b0df03636357c
|
{
"intermediate": 0.43972712755203247,
"beginner": 0.30186882615089417,
"expert": 0.258404016494751
}
|
41,529
|
I need the powrshell syntax for a task trigger to run every day every 5 minutes
|
bc158eb7528f4705a835883740a17a0e
|
{
"intermediate": 0.3202855587005615,
"beginner": 0.5108597278594971,
"expert": 0.1688547134399414
}
|
41,530
|
HOw can i have the command Register-ScheduledTask register in a different folder
|
e07b92a25de6c7671fd5ab463f954ebc
|
{
"intermediate": 0.41950708627700806,
"beginner": 0.25107139348983765,
"expert": 0.3294214904308319
}
|
41,531
|
improve below text
handle SP result exception while fetching document records for indexing
|
6c12fb68bcc22f98cc8c399d48d56d25
|
{
"intermediate": 0.4747302532196045,
"beginner": 0.27510055899620056,
"expert": 0.2501692473888397
}
|
41,532
|
Explain what is happening in this codeusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
namespace PvE
{
public partial class Form1 : Form
{
Random BotСhoice = new Random();
//Создание элементов
Button Attack = new Button();
Button Block = new Button();
Button Heal = new Button();
Button Success = new Button();
Button Reset = new Button();
Label Combo = new Label();
//Константы
float Damage = 10;
float Protection = 2.5f;
float Healing = 5;
//Переменные
bool KritHHAB1 = false;
bool KritHHAB2 = false;
int Bot;
string Choise = "";
int Count = 2;
int Krit1 = 2;
int Krit2 = 2;
public Form1()
{
InitializeComponent();
//Значение HP - 100%
progressBar1.Value = 100;
progressBar2.Value = 100;
//Добавление в управление формы
Controls.Add(Attack);
Controls.Add(Block);
Controls.Add(Heal);
Controls.Add(Success);
Controls.Add(Reset);
Controls.Add(Combo);
//Настройки размера
Attack.Size = new Size(75, 55);
Block.Size = new Size(75, 55);
Heal.Size = new Size(75, 55);
Success.Size = new Size(75, 55);
Reset.Size = new Size(75, 55);
Combo.AutoSize = true;
//Настройки текста
Attack.Text = "Атака";
Block.Text = "Блок";
Heal.Text = "Хилл";
Success.Text = "Принять";
Reset.Text = "Сбросить";
Combo.Text = "Ваш выбор:";
//Настройки позиций
Attack.Location = new Point(10, 100);
Block.Location = new Point(10, 160);
Heal.Location = new Point(10, 220);
Success.Location = new Point(10, 320);
Reset.Location = new Point(10, 380);
Combo.Location = new Point(10, 290);
//Подключение к событию Click функций
Attack.Click += new EventHandler(Attack_Click);
Block.Click += new EventHandler(Block_Click);
Heal.Click += new EventHandler(Heal_Click);
Success.Click += new EventHandler(Success_Click);
Reset.Click += new EventHandler(Reset_Click);
}
//Функции кнопок
private void Attack_Click(object sender, EventArgs e)
{
if (Count > 0)
{
Choise = Choise + "A";
Count = Count - 1;
}
Combo.Text = "Ваш выбор:" + Choise;
}
private void Block_Click(object sender, EventArgs e)
{
if (Count > 0)
{
Choise = Choise + "B";
Count = Count - 1;
}
Combo.Text = "Ваш выбор:" + Choise;
}
private void Heal_Click(object sender, EventArgs e)
{
if (Count > 0)
{
Choise = Choise + "H";
Count = Count - 1;
}
Combo.Text = "Ваш выбор:" + Choise;
}
private void Success_Click(object sender, EventArgs e)
{
if (Count == 0)
{
//Отключение кнопок
Attack.Enabled = false;
Block.Enabled = false;
Heal.Enabled = false;
Success.Enabled = false;
Reset.Enabled = false;
}
//Вызов функции "реализации выбора"
realizationChoice(Choise);
//Вызов функции "ход бота"
stepBot();
}
private void Reset_Click(object sender, EventArgs e)
{
//Вызов функции "сброс информации"
ResetData();
}
//Функция сброса
private void ResetData()
{
Choise = "";
Count = 2;
Combo.Text = "Ваш выбор:";
}
//Функция реализации выбора
private void realizationChoice(string txt)
{
//Сортировка по алфавиту
txt = string.Concat(txt.OrderBy(ch => ch));
if (progressBar2.Value == 0)
{
MessageBox.Show("Player win");
}
if (progressBar1.Value == 0)
{
MessageBox.Show("Bot win");
}
if ((progressBar1.Value != 0 || progressBar2.Value != 0) || (progressBar1.Value == 100 || progressBar2.Value == 100))
{
switch (txt)
{
case "AA":
Bot = BotСhoice.Next(1, 7);
pictureBox2.Image = PvE.Properties.Resources.atak1;
if (KritHHAB2 == true)
{
progressBar2.Value = progressBar2.Value - (Damage * 5);
KritHHAB2 = false;
}
else
{
progressBar2.Value = progressBar2.Value - (Damage * 2);
}
break;
case "BB":
Bot = BotСhoice.Next(1, 7);
pictureBox2.Image = PvE.Properties.Resources.def1;
if (Bot == 1 || Bot == 4 || Bot == 5)
{
progressBar1.Value = progressBar1.Value - Damage / 2;
}
break;
case "HH":
Bot = BotСhoice.Next(1, 7);
pictureBox2.Image = PvE.Properties.Resources.hil1;
KritHHAB1 = true;
progressBar1.Value = progressBar1.Value + Healing * 3;
break;
case "AB":
Bot = BotСhoice.Next(1, 7);
if (KritHHAB2 == true)
{
progressBar2.Value = progressBar2.Value - Damage * 2;
}
else
{
progressBar2.Value = progressBar2.Value - Damage;
if (Bot == 1 || Bot == 4 || Bot == 5)
{
progressBar1.Value = progressBar1.Value - (Damage - 2);
}
}
break;
case "AH":
Bot = BotСhoice.Next(1, 7);
progressBar2.Value = progressBar2.Value - Damage;
progressBar1.Value = progressBar1.Value + Healing;
break;
case "BH":
Bot = BotСhoice.Next(1, 7);
progressBar1.Value = progressBar1.Value + Healing;
if (Bot == 1 || Bot == 4 || Bot == 5)
{
progressBar2.Value = progressBar2.Value - (Damage - 2);
}
break;
}
//Включение кнопок
Attack.Enabled = true;
Block.Enabled = true;
Heal.Enabled = true;
Success.Enabled = true;
Reset.Enabled = true;
}
}
//Функция хода бота
private void stepBot()
{
switch (Bot)
{
//AA
case 1:
if (KritHHAB1 == true)
{
progressBar1.Value = progressBar1.Value - 50;
KritHHAB1 = false;
}
else
{
progressBar1.Value = progressBar1.Value - Damage * 2;
}
progressBar1.Value = progressBar1.Value - Damage * 2;
break;
//BB
case 2:
if (Choise == "AA" || Choise == "AB" || Choise == "AH")
{
progressBar2.Value = progressBar2.Value - Damage / 2;
}
break;
//HH
case 3:
progressBar2.Value = progressBar2.Value + Healing * 3;
KritHHAB2 = true;
break;
//AB
case 4:
break;
//AH
case 5:
break;
//BH
case 6:
break;
}
}
}
}
|
2f8c8d6078171fab5f2fd7073a90cbc4
|
{
"intermediate": 0.4837014973163605,
"beginner": 0.38364481925964355,
"expert": 0.13265368342399597
}
|
41,533
|
How to use DirectoryLoader in langchain to load pdf and store them in weaviate, but also to split the documents up so they don't become too large
|
be6f58939155d5b37587c7e86ff48cd3
|
{
"intermediate": 0.7469532489776611,
"beginner": 0.09392326325178146,
"expert": 0.15912345051765442
}
|
41,534
|
HOw can i set sctasks.exe to Run without user logon
|
f4381d90aa9297db11d4a4343d282c7d
|
{
"intermediate": 0.4277730882167816,
"beginner": 0.23920877277851105,
"expert": 0.33301809430122375
}
|
41,535
|
What is more likely to cause stuttering, ram or power supply?
|
27a1b0618b89d9e4ef4873db85c78d24
|
{
"intermediate": 0.33004361391067505,
"beginner": 0.40230926871299744,
"expert": 0.26764705777168274
}
|
41,536
|
def preprocess_function(examples):
# Assuming examples is a dictionary with keys "context", "answer", and "question"
# Check if "answer" or "context" is None, and handle accordingly
if examples["answer"] is None or examples["context"] is None:
return None
# Ensure that "answer" is a list
if not isinstance(examples["answer"], list):
return None
# Define the context_text using the provided format
context_text = f"context: {examples['context']} answer: {examples['answer']} </s>"
# Convert answers to a single string
answers = " ".join([q.strip() if q is not None else "" for q in examples["answer"]])
inputs = tokenizer(
context_text,
max_length=1000,
truncation=True,
padding="max_length",
return_offsets_mapping=True,
)
# Check if "question" is None, and handle accordingly
if examples["question"] is None:
return None
targets = tokenizer(
examples["question"],
max_length=64, # Adjust as needed
truncation=True,
padding="max_length",
return_offsets_mapping=True,
)
inputs["labels"] = targets["input_ids"]
inputs["decoder_attention_mask"] = targets["attention_mask"]
return inputs
add Codeadd Markdown
tokenized_train_dataset = train_dataset.map(preprocess_function, batched=True)
tokenized_val_dataset = val_dataset.map(preprocess_function, batched=True)
tokenized_test_dataset = test_dataset.map(preprocess_function, batched=True)
98%
41/42 [00:34<00:00, 1.27ba/s]
---------------------------------------------------------------------------
ArrowInvalid Traceback (most recent call last)
Cell In[30], line 1
----> 1 tokenized_train_dataset = train_dataset.map(preprocess_function, batched=True)
2 tokenized_val_dataset = val_dataset.map(preprocess_function, batched=True)
3 tokenized_test_dataset = test_dataset.map(preprocess_function, batched=True)
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:1955, in Dataset.map(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, num_proc, suffix_template, new_fingerprint, desc)
1952 disable_tqdm = not logging.is_progress_bar_enabled()
1954 if num_proc is None or num_proc == 1:
-> 1955 return self._map_single(
1956 function=function,
1957 with_indices=with_indices,
1958 with_rank=with_rank,
1959 input_columns=input_columns,
1960 batched=batched,
1961 batch_size=batch_size,
1962 drop_last_batch=drop_last_batch,
1963 remove_columns=remove_columns,
1964 keep_in_memory=keep_in_memory,
1965 load_from_cache_file=load_from_cache_file,
1966 cache_file_name=cache_file_name,
1967 writer_batch_size=writer_batch_size,
1968 features=features,
1969 disable_nullable=disable_nullable,
1970 fn_kwargs=fn_kwargs,
1971 new_fingerprint=new_fingerprint,
1972 disable_tqdm=disable_tqdm,
1973 desc=desc,
1974 )
1975 else:
1977 def format_cache_file_name(cache_file_name, rank):
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:520, in transmit_tasks.<locals>.wrapper(*args, **kwargs)
518 self: "Dataset" = kwargs.pop("self")
519 # apply actual function
--> 520 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs)
521 datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out]
522 for dataset in datasets:
523 # Remove task templates if a column mapping of the template is no longer valid
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:487, in transmit_format.<locals>.wrapper(*args, **kwargs)
480 self_format = {
481 "type": self._format_type,
482 "format_kwargs": self._format_kwargs,
483 "columns": self._format_columns,
484 "output_all_columns": self._output_all_columns,
485 }
486 # apply actual function
--> 487 out: Union["Dataset", "DatasetDict"] = func(self, *args, **kwargs)
488 datasets: List["Dataset"] = list(out.values()) if isinstance(out, dict) else [out]
489 # re-apply format to the output
File /opt/conda/lib/python3.10/site-packages/datasets/fingerprint.py:458, in fingerprint_transform.<locals>._fingerprint.<locals>.wrapper(*args, **kwargs)
452 kwargs[fingerprint_name] = update_fingerprint(
453 self._fingerprint, transform, kwargs_for_fingerprint
454 )
456 # Call actual function
--> 458 out = func(self, *args, **kwargs)
460 # Update fingerprint of in-place transforms + update in-place history of transforms
462 if inplace: # update after calling func so that the fingerprint doesn't change if the function fails
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_dataset.py:2356, in Dataset._map_single(self, function, with_indices, with_rank, input_columns, batched, batch_size, drop_last_batch, remove_columns, keep_in_memory, load_from_cache_file, cache_file_name, writer_batch_size, features, disable_nullable, fn_kwargs, new_fingerprint, rank, offset, disable_tqdm, desc, cache_only)
2354 writer.write_table(batch)
2355 else:
-> 2356 writer.write_batch(batch)
2357 if update_data and writer is not None:
2358 writer.finalize() # close_stream=bool(buf_writer is None)) # We only close if we are writing in a file
File /opt/conda/lib/python3.10/site-packages/datasets/arrow_writer.py:510, in ArrowWriter.write_batch(self, batch_examples, writer_batch_size)
508 inferred_features[col] = typed_sequence.get_inferred_type()
509 schema = inferred_features.arrow_schema if self.pa_writer is None else self.schema
--> 510 pa_table = pa.Table.from_arrays(arrays, schema=schema)
511 self.write_table(pa_table, writer_batch_size)
File /opt/conda/lib/python3.10/site-packages/pyarrow/table.pxi:3674, in pyarrow.lib.Table.from_arrays()
File /opt/conda/lib/python3.10/site-packages/pyarrow/table.pxi:2837, in pyarrow.lib.Table.validate()
File /opt/conda/lib/python3.10/site-packages/pyarrow/error.pxi:100, in pyarrow.lib.check_status()
ArrowInvalid: Column 4 named input_ids expected length 778 but got length 1000
|
3056c8938f6198a623cc3ec7779585ca
|
{
"intermediate": 0.4437839984893799,
"beginner": 0.4172494113445282,
"expert": 0.13896659016609192
}
|
41,537
|
We need a photoshop script which allows user to select maximum two image files as JPG or PSD, then subtract if there are "4 D “, “TITLE”. " NO TITLE”, “Title”, “No Title” words from their file name then store this value as title name. We should also need run button to execute script. As user clicks on run button script should execute and pass these values into Main Function. We should have Title Name (from files), file paths. You can add debug codes inside Main Function to check. We will then use these values to place files into currently open document and change text fields within these names.
|
e5de9d95f0b13054dc61fee583bd99b4
|
{
"intermediate": 0.6088517308235168,
"beginner": 0.16154125332832336,
"expert": 0.22960709035396576
}
|
41,538
|
non sto capendo il funzionamento di next sibling nel codice pig_html = """
<html><head><title>Three Little Pigs</title></head>
<body>
<p class="title"><b>The Three Little Pigs</b></p>
<p class="story"> Once upon a time, there were three little pigs named
<a href="http://example.com/larry" class="pig" id="link1">Larry,</a>
<a href="http://example.com/mo" class="pig" id="link2">Mo</a>, and
<a href="http://example.com/curly" class="pig" id="link3">Curly.</a></p>
<p>The three pigs had an odd fascination with experimental construction.</p>
<p>...</p>
</body>
</html>
"""
# Get to the <p> tag that has class="story".
p_tag = pig_soup.body.p.next_sibling.next_sibling
print(p_tag)
print(p_tag.attrs["class"])
perché se uso solo un next sibling non stampa nulla?
|
076ea3faea6e096d9fa8155db7933817
|
{
"intermediate": 0.23134925961494446,
"beginner": 0.5302585959434509,
"expert": 0.23839209973812103
}
|
41,539
|
how to show progress bar here
vectorstore = Weaviate.from_documents(
chunks,
embedding=HuggingFaceEmbeddings(model_name='BAAI/bge-small-en-v1.5'),
client=client,
by_text=False
)
|
eae156827746e9852152b47a9f8a1751
|
{
"intermediate": 0.4238990545272827,
"beginner": 0.1394902765750885,
"expert": 0.4366106688976288
}
|
41,540
|
i am having circuit simulator, in which i modeled a circuit with 5 CMOS transistor. the circuit takes 10 variables (W,L) as input and gives 1 parameters (gain) as output and also give the state of the component whether each transistor are in saturation or not. this is my scenario which i am working. the output parameters has some target specification ranges. here i need to tune the input variables accordingly within its bounds to reach the target as well as all the transistor must be in saturation state.
For this objective how to construct my RL algorithm to reach my goal, because if we tune the circuit input variable by considering the state change of each transistor to make stable then the required output parameter 'gain' is not met the target specification, or if we tune the circuit input variable by considering the obtained gain and the target gain then the state of all the transistor was not being in the stable state. But manually by using design equation i can achieve both criteria to satisfy, but using RL how this two criteria can i achieve simultaneously. give me suggestion.
|
9b95a376151e7d23131a618efc9453ec
|
{
"intermediate": 0.10830895602703094,
"beginner": 0.10896970331668854,
"expert": 0.7827213406562805
}
|
41,541
|
how to simplify this lifetime
pub struct JobConsumer<'a> {
inner: StreamConsumer,
topic: &'a str,
}
impl<'a> JobConsumer<'a> {
pub fn new(config: &'a KafkaConfig) -> Self {
let topic = config.topics.jobs.as_str();
Self {
inner: config.into(),
topic,
}
}
}
|
087942241398584ce671082d74cc76f1
|
{
"intermediate": 0.2986142337322235,
"beginner": 0.5333787798881531,
"expert": 0.16800695657730103
}
|
41,542
|
asdas
|
02ee0486714faf11f2f394a718c10d6d
|
{
"intermediate": 0.3717285692691803,
"beginner": 0.2845667898654938,
"expert": 0.3437046408653259
}
|
41,543
|
go.sum contains:
github.com/alexflint/go-arg v1.4.2 h1:lDWZAXxpAnZUq4qwb86p/3rIJJ2Li81EoMbTMujhVa0=
github.com/alexflint/go-arg v1.4.2/go.mod h1:9iRbDxne7LcR/GSvEr7ma++GLpdIU1zrghf2y2768kM=
github.com/alexflint/go-scalar v1.0.0 h1:NGupf1XV/Xb04wXskDFzS0KWOLH632W/EO4fAFi+A70=
github.com/alexflint/go-scalar v1.0.0/go.mod h1:GpHzbCOZXEKMEcygYQ5n/aa4Aq84zbxjy3MxYW0gjYw=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ddliu/go-httpclient v0.5.1 h1:ys4KozrhBaGdI1yuWIFwNNILqhnMU9ozTvRNfCTorvs=
github.com/ddliu/go-httpclient v0.5.1/go.mod h1:8QVbjq00YK2f2MQyiKuWMdaKOFRcoD9VuubkNCNOuZo=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/go-flac/flacpicture v0.2.0 h1:rS/ZOR/ZxlEwMf3yOPFcTAmGyoV6rDtcYdd+6CwWQAw=
github.com/go-flac/flacpicture v0.2.0/go.mod h1:M4a1J0v6B5NHsck4GA1yZg0vFQzETVPd3kuj6Ow+q9o=
github.com/go-flac/flacvorbis v0.1.0 h1:xStJfPrZ/IoA2oBUEwgrlaSf+Opo6/YuQfkqVhkP0cM=
github.com/go-flac/flacvorbis v0.1.0/go.mod h1:70N9vVkQ4Jew0oBWkwqDMIE21h7pMUtQJpnMD0js6XY=
github.com/go-flac/go-flac v0.3.1 h1:BWA7HdO67S4ZLWSVHCxsDHuedFFu5RiV/wmuhvO6Hxo=
github.com/go-flac/go-flac v0.3.1/go.mod h1:jG9IumOfAXr+7J40x0AiQIbJzXf9Y7+Zs/2CNWe4LMk=
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
main.go contains:
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"github.com/alexflint/go-arg"
"github.com/dustin/go-humanize"
"github.com/go-flac/flacpicture"
"github.com/go-flac/flacvorbis"
"github.com/go-flac/go-flac"
)
var (
jar, _ = cookiejar.New(nil)
client = &http.Client{Jar: jar, Transport: &MyTransport{}}
)
func (t *MyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Add(
"User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "+
"(KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
)
req.Header.Add(
"Referer", "https://stream-app.highresaudio.com/dashboard",
)
return http.DefaultTransport.RoundTrip(req)
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.Downloaded += uint64(n)
percentage := float64(wc.Downloaded) / float64(wc.Total) * float64(100)
wc.Percentage = int(percentage)
fmt.Printf("\r%d%%, %s/%s ", wc.Percentage, humanize.Bytes(wc.Downloaded), wc.TotalStr)
return n, nil
}
func getScriptDir() (string, error) {
var (
ok bool
err error
fname string
)
if filepath.IsAbs(os.Args[0]) {
_, fname, _, ok = runtime.Caller(0)
if !ok {
return "", errors.New("Failed to get script filename.")
}
} else {
fname, err = os.Executable()
if err != nil {
return "", err
}
}
scriptDir := filepath.Dir(fname)
return scriptDir, nil
}
func readTxtFile(path string) ([]string, error) {
var lines []string
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, strings.TrimSpace(scanner.Text()))
}
if scanner.Err() != nil {
return nil, scanner.Err()
}
return lines, nil
}
func contains(lines []string, value string) bool {
for _, line := range lines {
if strings.EqualFold(line, value) {
return true
}
}
return false
}
func processUrls(urls []string) ([]string, error) {
var (
processed []string
txtPaths []string
)
for _, url := range urls {
if strings.HasSuffix(url, ".txt") && !contains(txtPaths, url) {
txtLines, err := readTxtFile(url)
if err != nil {
return nil, err
}
for _, txtLine := range txtLines {
if !contains(processed, txtLine) {
processed = append(processed, txtLine)
}
}
txtPaths = append(txtPaths, url)
} else {
if !contains(processed, url) {
processed = append(processed, url)
}
}
}
return processed, nil
}
func readConfig() (*Config, error) {
data, err := ioutil.ReadFile("config.json")
if err != nil {
return nil, err
}
var obj Config
err = json.Unmarshal(data, &obj)
if err != nil {
return nil, err
}
return &obj, nil
}
func parseArgs() *Args {
var args Args
arg.MustParse(&args)
return &args
}
func parseCfg() (*Config, error) {
cfg, err := readConfig()
if err != nil {
return nil, err
}
args := parseArgs()
if !(cfg.Language == "en" || cfg.Language == "de") {
return nil, errors.New("Language must be en or de.")
}
if cfg.OutPath == "" {
cfg.OutPath = "HRA downloads"
}
cfg.Urls, err = processUrls(args.Urls)
if err != nil {
errString := fmt.Sprintf("Failed to process URLs.\n%s", err)
return nil, errors.New(errString)
}
return cfg, nil
}
func auth(email, pwd string) (string, error) {
_url := "https://streaming.highresaudio.com:8182/vault3/user/login"
req, err := http.NewRequest(http.MethodGet, _url, nil)
if err != nil {
return "", err
}
query := url.Values{}
query.Set("username", email)
query.Set("password", pwd)
req.URL.RawQuery = query.Encode()
do, err := client.Do(req)
if err != nil {
return "", err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return "", errors.New(do.Status)
}
var obj Auth
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return "", err
}
if obj.ResponseStatus != "OK" {
return "", errors.New("Bad response.")
} else if !obj.HasSubscription {
return "", errors.New("Subscription required.")
}
userData, err := json.Marshal(&obj)
if err != nil {
return "", err
}
return string(userData), nil
}
func getAlbumId(url string) (string, error) {
req, err := client.Get(url)
if err != nil {
return "", err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return "", errors.New(req.Status)
}
bodyBytes, err := io.ReadAll(req.Body)
if err != nil {
return "", err
}
bodyString := string(bodyBytes)
regexString := `data-id="([a-z\d]{8}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{12})"`
regex := regexp.MustCompile(regexString)
match := regex.FindStringSubmatch(bodyString)
if match == nil {
return "", errors.New("No regex match.")
}
return match[1], nil
}
func getMeta(albumId, userData, lang string) (*AlbumMeta, error) {
_url := "https://streaming.highresaudio.com:8182/vault3/vault/album/"
req, err := http.NewRequest(http.MethodGet, _url, nil)
if err != nil {
return nil, err
}
query := url.Values{}
query.Set("album_id", albumId)
query.Set("userData", userData)
query.Set("lang", lang)
req.URL.RawQuery = query.Encode()
do, err := client.Do(req)
if err != nil {
return nil, err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK {
return nil, errors.New(do.Status)
}
var obj AlbumMeta
err = json.NewDecoder(do.Body).Decode(&obj)
if err != nil {
return nil, err
}
if obj.ResponseStatus != "OK" {
return nil, errors.New("Bad response.")
}
return &obj, nil
}
func makeDir(path string) error {
err := os.MkdirAll(path, 0755)
return err
}
func fileExists(path string) (bool, error) {
f, err := os.Stat(path)
if err == nil {
return !f.IsDir(), nil
} else if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func checkUrl(url string) bool {
regexString := `^https://www.highresaudio.com/(?:en|de)/album/view/[a-z\d]+/[a-z\d-]+$`
regex := regexp.MustCompile(regexString)
match := regex.MatchString(url)
return match
}
func parseAlbumMeta(meta *AlbumMeta) map[string]string {
parsedMeta := map[string]string{
"album": meta.Data.Results.Title,
"albumArtist": meta.Data.Results.Artist,
"copyright": meta.Data.Results.Copyright,
"upc": meta.Data.Results.UPC,
"year": strconv.Itoa(meta.Data.Results.ReleaseDate.Year()),
}
return parsedMeta
}
func parseTrackMeta(meta *TrackMeta, albMeta map[string]string, trackNum, trackTotal int) map[string]string {
albMeta["artist"] = meta.Artist
albMeta["genre"] = meta.Genre
albMeta["isrc"] = meta.ISRC
albMeta["title"] = meta.Title
albMeta["track"] = strconv.Itoa(trackNum)
albMeta["trackPad"] = fmt.Sprintf("%02d", trackNum)
albMeta["trackTotal"] = strconv.Itoa(trackTotal)
return albMeta
}
func sanitize(filename string) string {
regex := regexp.MustCompile(`[\/:*?"><|]`)
sanitized := regex.ReplaceAllString(filename, "_")
return sanitized
}
func downloadCover(meta *Covers, path string, maxCover bool) error {
_url := "https://"
if maxCover {
_url += meta.Master.FileURL
} else {
_url += meta.Preview.FileURL
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755)
if err != nil {
return err
}
defer f.Close()
req, err := client.Get(_url)
if err != nil {
return err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return errors.New(req.Status)
}
_, err = io.Copy(f, req.Body)
return err
}
func parseTemplate(templateText string, tags map[string]string) string {
var buffer bytes.Buffer
for {
err := template.Must(template.New("").Parse(templateText)).Execute(&buffer, tags)
if err == nil {
break
}
fmt.Println("Failed to parse template. Default will be used instead.")
templateText = "{{.trackPad}}. {{.title}}"
buffer.Reset()
}
return buffer.String()
}
func downloadTrack(trackPath, url string) error {
f, err := os.Create(trackPath)
if err != nil {
return err
}
defer f.Close()
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Add("Range", "bytes=0-")
do, err := client.Do(req)
if err != nil {
return err
}
defer do.Body.Close()
if do.StatusCode != http.StatusOK && do.StatusCode != http.StatusPartialContent {
return errors.New(do.Status)
}
totalBytes := uint64(do.ContentLength)
counter := &WriteCounter{Total: totalBytes, TotalStr: humanize.Bytes(totalBytes)}
_, err = io.Copy(f, io.TeeReader(do.Body, counter))
fmt.Println("")
return err
}
// Tracks already come tagged, but come with missing meta and smaller artwork.
func writeTags(trackPath, coverPath string, tags map[string]string) error {
var (
err error
imgData []byte
)
if coverPath != "" {
imgData, err = ioutil.ReadFile(coverPath)
if err != nil {
return err
}
}
delete(tags, "trackPad")
f, err := flac.ParseFile(trackPath)
if err != nil {
return err
}
cmt, err := flacvorbis.ParseFromMetaDataBlock(*f.Meta[1])
if err != nil {
return err
}
f.Meta = f.Meta[:1]
tag := flacvorbis.New()
tag.Vendor = cmt.Vendor
for k, v := range tags {
tag.Add(strings.ToUpper(k), v)
}
tagMeta := tag.Marshal()
f.Meta = append(f.Meta, &tagMeta)
if imgData != nil {
picture, err := flacpicture.NewFromImageData(
flacpicture.PictureTypeFrontCover, "", imgData, "image/jpeg",
)
if err != nil {
return err
}
pictureMeta := picture.Marshal()
f.Meta = append(f.Meta, &pictureMeta)
}
err = f.Save(trackPath)
return err
}
func downloadBooklet(path, url string) error {
f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0755)
if err != nil {
return err
}
defer f.Close()
req, err := client.Get("https://" + url)
if err != nil {
return err
}
defer req.Body.Close()
if req.StatusCode != http.StatusOK {
return errors.New(req.Status)
}
_, err = io.Copy(f, req.Body)
return err
}
func checkAvail(availAt time.Time) bool {
return time.Now().Unix() >= availAt.Unix()
}
func main() {
fmt.Println(`
_____ _____ _____ ____ _ _
| | | __ | _ | | \ ___ _ _ _ ___| |___ ___ _| |___ ___
| | -| | | | | . | | | | | | . | .'| . | -_| _|
|__|__|__|__|__|__| |____/|___|_____|_|_|_|___|__,|___|___|_|
`)
scriptDir, err := getScriptDir()
if err != nil {
panic(err)
}
err = os.Chdir(scriptDir)
if err != nil {
panic(err)
}
cfg, err := parseCfg()
if err != nil {
errString := fmt.Sprintf("Failed to parse config file.\n%s", err)
panic(errString)
}
userData, err := auth(cfg.Email, cfg.Password)
if err != nil {
panic(err)
}
fmt.Println("Signed in successfully.\n")
err = makeDir(cfg.OutPath)
if err != nil {
errString := fmt.Sprintf("Failed to make output folder.\n%s", err)
panic(errString)
}
albumTotal := len(cfg.Urls)
for albumNum, url := range cfg.Urls {
fmt.Printf("Album %d of %d:\n", albumNum+1, albumTotal)
ok := checkUrl(url)
if !ok {
fmt.Println("Invalid URL:", url)
continue
}
albumId, err := getAlbumId(url)
if err != nil {
fmt.Println("Failed to extract album ID.\n", err)
continue
}
meta, err := getMeta(albumId, userData, cfg.Language)
if err != nil {
fmt.Println("Failed to get metadata.\n", err)
continue
}
availAt := meta.Data.Results.AvailableFrom
ok = checkAvail(availAt)
if !ok {
fmt.Printf("Album unavailable. Available at: %v", availAt)
continue
}
parsedAlbMeta := parseAlbumMeta(meta)
albFolder := parsedAlbMeta["albumArtist"] + " - " + parsedAlbMeta["album"]
fmt.Println(albFolder)
if len(albFolder) > 120 {
fmt.Println("Album folder was chopped as it exceeds 120 characters.")
albFolder = albFolder[:120]
}
albumPath := filepath.Join(cfg.OutPath, sanitize(albFolder))
err = makeDir(albumPath)
if err != nil {
fmt.Println("Failed to make album folder.\n", err)
continue
}
coverPath := filepath.Join(albumPath, "cover.jpg")
err = downloadCover(&meta.Data.Results.Cover, coverPath, cfg.MaxCoverSize)
if err != nil {
fmt.Println("Failed to get cover.\n", err)
coverPath = ""
}
bookletPath := filepath.Join(albumPath, "booklet.pdf")
if meta.Data.Results.Booklet != "" && cfg.DownloadBooklets {
fmt.Println("Downloading booklet...")
err = downloadBooklet(bookletPath, meta.Data.Results.Booklet)
if err != nil {
fmt.Println("Failed to download booklet.\n", err)
}
}
trackTotal := len(meta.Data.Results.Tracks)
for trackNum, track := range meta.Data.Results.Tracks {
trackNum++
parsedMeta := parseTrackMeta(&track, parsedAlbMeta, trackNum, trackTotal)
trackFname := parseTemplate(cfg.TrackTemplate, parsedMeta)
trackPath := filepath.Join(albumPath, sanitize(trackFname)+".flac")
exists, err := fileExists(trackPath)
if err != nil {
fmt.Println("Failed to check if track already exists locally.\n", err)
continue
}
if exists {
fmt.Println("Track already exists locally.")
continue
}
// Bit depth isn't provided.
fmt.Printf(
"Downloading track %d of %d: %s - %s kHz FLAC\n",
trackNum, trackTotal, parsedMeta["title"], track.Format,
)
err = downloadTrack(trackPath, track.URL)
if err != nil {
fmt.Println("Failed to download track.\n", err)
continue
}
err = writeTags(trackPath, coverPath, parsedMeta)
if err != nil {
fmt.Println("Failed to write tags.\n", err)
}
}
if coverPath != "" && !cfg.KeepCover {
err = os.Remove(coverPath)
if err != nil {
fmt.Println("Failed to delete cover.\n", err)
}
}
}
}
structs.go contains:
package main
import "time"
type MyTransport struct{}
type WriteCounter struct {
Total uint64
TotalStr string
Downloaded uint64
Percentage int
}
type Config struct {
Email string
Password string
Urls []string
OutPath string
TrackTemplate string
DownloadBooklets bool
MaxCoverSize bool
KeepCover bool
Language string
}
type Args struct {
Urls []string `arg:"positional, required"`
OutPath string `arg:"-o"`
}
type Auth struct {
ResponseStatus string `json:"response_status"`
UserID string `json:"user_id"`
Country string `json:"country"`
Lastname string `json:"lastname"`
Firstname string `json:"firstname"`
SessionID string `json:"session_id"`
HasSubscription bool `json:"has_subscription"`
Status string `json:"status"`
Filter string `json:"filter"`
Hasfilter string `json:"hasfilter"`
}
type TrackMeta struct {
PlaylistAdd string `json:"playlistAdd"`
IsFavorite string `json:"isFavorite"`
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
ArtistID string `json:"artistId"`
Label string `json:"label"`
LabelID string `json:"labelId"`
Licensor string `json:"licensor"`
LicensorID string `json:"licensorId"`
TrackNumber int `json:"trackNumber"`
Copyright string `json:"copyright"`
Genre string `json:"genre"`
Playtime int `json:"playtime"`
UPC string `json:"upc"`
ISRC string `json:"isrc"`
URL string `json:"url"`
Format string `json:"format"`
}
type Covers struct {
Title string `json:"title"`
Type string `json:"type"`
DocumentID string `json:"document_id"`
Master struct {
FileURL string `json:"file_url"`
} `json:"master"`
Preview struct {
FileURL string `json:"file_url"`
} `json:"preview"`
Thumbnail struct {
FileURL string `json:"file_url"`
} `json:"thumbnail"`
}
type AlbumMeta struct {
Status string `json:"status"`
ResponseStatus string `json:"response_status"`
Test string `json:"test"`
Data struct {
Results struct {
ShopURL string `json:"shop_url"`
AvailableFrom time.Time `json:"availableFrom"`
AvailableUntil time.Time `json:"availableUntil"`
Booklet string `json:"booklet"`
PublishingStatus string `json:"publishingStatus"`
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
ArtistID string `json:"artistId"`
Biography string `json:"biography"`
Label string `json:"label"`
LabelID string `json:"labelId"`
Licensor string `json:"licensor"`
LicensorID string `json:"licensorId"`
DdexDate string `json:"ddexDate"`
Copyright string `json:"copyright"`
TrackCount int `json:"trackCount"`
IsLeakBlock bool `json:"isLeakBlock"`
CopyrightYear int `json:"copyrightYear"`
ImportDate string `json:"importDate"`
Genre string `json:"genre"`
Playtime int `json:"playtime"`
ProductionYear int `json:"productionYear"`
ReleaseDate time.Time `json:"releaseDate"`
Subgenre string `json:"subgenre"`
UPC string `json:"upc"`
ShortDescription string `json:"shortDescription"`
Caption string `json:"caption"`
Tags string `json:"tags"`
IsFavorite string `json:"isFavorite"`
Tracks []TrackMeta `json:"tracks"`
Cover Covers `json:"cover"`
} `json:"results"`
} `json:"data"`
}
D:\Audios\Rip\HRA-Downloadercloned>hra_dl_x64.exe https://www.highresaudio.com/en/album/view/wyvco7/hans-zimmer-x-men-dark-phoenix-original-motion-picture-soundtrack
Signed in successfully.
Album 1 of 1:
Failed to get metadata.
parsing time """" as ""2006-01-02T15:04:05Z07:00"": cannot parse """ as "2006"
can you fix the error and return full code
|
2488a54516764d995c2677e5ff754494
|
{
"intermediate": 0.28240519762039185,
"beginner": 0.4030660390853882,
"expert": 0.31452876329421997
}
|
41,544
|
Please help, how to Normalize the State and Reward:
It’s generally beneficial for training stability if both the state vectors and the rewards are normalized or standardized.
|
5ebaf04f074294ee92e93e3bb1f72f2e
|
{
"intermediate": 0.2740505337715149,
"beginner": 0.08848188072443008,
"expert": 0.6374675631523132
}
|
41,545
|
Write some Python code for a simple Pong game
|
14b94e374b199ab4d85536a35df1178e
|
{
"intermediate": 0.37385472655296326,
"beginner": 0.3621501624584198,
"expert": 0.26399508118629456
}
|
41,546
|
In this processing code snippet I'm trying to make it so when you click on the grid it highlights the square you clicked, but I don't want it to happen on the middle column, so do you know why?
I attempted to solve this with "&& mouseX!=b[r=10]" in the if statement for determining which square was clicked.
int [] b = {0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 525};
int count=0;
int [][] grid = new int [21][20];
void setup() {
background(250);
size(525, 500);
drawgrid();
}
void draw() {
fill(225);
for (int r=0; r<21; r++) {
for (int c=0; c<20; c++) {
if (mouseButton == LEFT && mouseX>b[r] && mouseX<b[r+1] && mouseX!=b[r=10] && mouseY>b[c] && mouseY<b[c+1]) {
fill(50);
square(b[r], b[c], 25);
}
}
}
}
void drawgrid() {
for (int r=0; r<525; r+=25) {
for (int c=0; c<500; c+=25) {
fill(100);
square(r, c, 25);
fill(25);
square(250, c, 25);
}
}
}
|
2917ecc8a6c6885db58786a93c330798
|
{
"intermediate": 0.4723847508430481,
"beginner": 0.2510347068309784,
"expert": 0.27658048272132874
}
|
41,547
|
#Resolution 1440p 125%
#Firefox 100 % Côté gauche
#Explorateur ouvert sur dossier de destination, colonnes bien rangées à gauche, dossiers triés par dernière date de création
#Barre des tâches : firefox et explorateur à gauche, petites icônes toujours afficher tout
#IDM dossier de dl : dossier>nouveau dossier
#ShareX installé et lancé
#Clavier+ lancé et installé
def defilement(items, debut, decompte, page):
global items, debut, decompte, page
wait(1)
if exists("1709898310179.png"):
if debut == 1:
wait(1)
else:
type(Key.UP)
type(Key.UP)
wait(1)
else:
if debut == 1:
type(Key.UP)
type(Key.UP)
wait(1)
if items == 1:
wait(1)
wait(0.5)
region = Region(383,85,188,191)
while not region.exists(Pattern("1709850708429.png").targetOffset(61,-1)):
type(Key.UP)
wait(0.5)
if exists("1709856016062.png"):
reg = Region(328,252,630,23)
prec = reg.find(Pattern("1709856203064.png").exact())
hover(prec)
wait(1)
mouseMove(-20, -5)
wait(1)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
wait(5)
type(Key.END)
wait(3)
page = page - 1
wait(1)
decompte = 0
wait(1)
items = 10
wait(1)
debut = 1
def download(items, debut):
global items, debut
wait(2)
if exists("1709898310179.png"):
if debut == 1:
region = Region(134,194,635,544)
else:
region = Region(150,82,619,403)
if not exists("1709898310179.png"):
region = Region(150,82,619,403)
if region.exists(Pattern("1709900719160.png").targetOffset(60,0)):
set = region.getLastMatch()
wait(1)
hover(set)
wait(1)
mouseMove(33, 15)
wait(0.5)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
wait(0.5)
type("c", KEY_CTRL)
wait(1)
if region.exists(Pattern("1709899912402.png").exact()):
download = region.find("1709899961539.png")
if region.exists(Pattern("1709900399882.png").exact()):
download = region.find(Pattern("1709900430657.png").similar(0.90))
else:
download = region.find("1709851754573.png")
wait(0.5)
hover(download)
wait(1)
mouseMove(70, 0)
wait(0.5)
type(Key.PRINTSCREEN)
wait(0.5)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
wait(1)
def couv():
region = Region(153,353,234,302)
if region.exists("1709856601218.png"):
couv = region.getLastMatch()
wait(1)
click(couv)
wait(2)
hover(Location(625, 673))
wait(0.5)
mouseDown(Button.RIGHT)
mouseUp(Button.RIGHT)
wait(1)
click("1709856690569.png")
wait(2)
wait("1709853092694.png", 60)
wait(0.5)
region = Region(1476,629,78,166)
region.wait("1709852119030.png", 60)
wait(1)
region = Region(1389,648,59,59)
click(region.find("1709856773181.png"))
wait(1)
mouseMove(-50, 15)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
wait(2)
click("1709852349665.png")
wait(2)
if exists("1709852395138.png"):
click("1709852402526.png")
wait(1)
keyDown(Key.CTRL)
wait(0.5)
type("w")
wait(0.5)
keyUp(Key.CTRL)
wait(1)
print(debut)
def missing():
wait(0.5)
region = Region(0,1358,450,82)
explorer = region.find("1709852440164.png")
hover(explorer)
wait(0.5)
mouseDown(Button.LEFT)
mouseUp(Button.LEFT)
wait(0.5)
click("1709852508524.png")
wait(3)
click("1709852948314.png")
wait(3)
type("v", KEY_CTRL)
wait(3)
type(Key.ENTER)
wait(0.5)
if exists("1709852252916.png"):
click("1709852265180.png")
wait(1)
click("1709852508524.png")
wait(3)
click("1709852948314.png")
type("v", KEY_CTRL)
wait(3)
import random
num = random.randint(0,999999999999)
type(str(num))
wait(0.5)
type(Key.ENTER)
wait(2)
type(Key.ENTER)
wait(0.5)
hover(Location(1247, 388))
wait(0.5)
mouseDown(Button.RIGHT)
mouseUp(Button.RIGHT)
wait(0.5)
hover("1709855178860.png")
wait(2)
click("1709855209155.png")
wait(0.5)
type("Pas de video")
wait(0.5)
type(Key.ENTER)
wait(0.5)
type(Key.BACKSPACE)
wait(0.5)
def idm(items):
global items
wait(2)
wait("1709853092694.png", 60)
wait(0.5)
region = Region(1476,629,78,166)
region.wait("1709852119030.png", 60)
wait(1)
if exists("1709852135104.png"):
wait(0.5)
click("1709852151631.png")
wait("1709852168815.png", 10)
click("1709852178497.png")
wait(0.5)
click("1709859443255.png")
wait("1709853523343.png", 60)
type("v", KEY_CTRL)
wait(3)
if exists(Pattern("1709852230866.png").similar(0.90)):
while exists(Pattern("1709852230866.png").similar(0.90)):
click(Pattern("1709852230866.png").similar(0.90))
wait(0.5)
if exists("1709852252916.png"):
click(Pattern("1709893893792.png").similar(0.90))
wait(2)
type(Key.F2)
wait(1)
type("v", KEY_CTRL)
wait(1)
import random
num = random.randint(0,999999999999)
type(str(num))
wait(0.5)
if exists(Pattern("1709852230866.png").similar(0.90)):
while exists(Pattern("1709852230866.png").similar(0.90)):
click(Pattern("1709852230866.png").similar(0.90))
wait(0.5)
if exists(Pattern("1709852331965.png").similar(0.90)):
while exists(Pattern("1709852331965.png").similar(0.90)):
click(Pattern("1709852331965.png").similar(0.90))
wait(2)
click("1709852349665.png")
wait(2)
if exists("1709852395138.png"):
click("1709852402526.png")
items = items - 1
if __name__ == "__main__":
debut = 1
page = 44
decompte = 1
while page > 0:
if decompte == 1:
items = 3
wait(0.1)
else:
items = 10
wait(0.1)
while items > 0:
defilement(items, debut, decompte, page)
wait(1)
download(items, debut)
wait(1)
idm(items)
wait(1)
couv()
debut = 0
Voici l'erreur que j'obtiens :
[error] script stopped with error in line 12 at column 1
[error] SyntaxError ( "name 'items' is local and global", )
|
12d3e66440b11b24280c11a6ba677925
|
{
"intermediate": 0.39361849427223206,
"beginner": 0.3925153613090515,
"expert": 0.21386614441871643
}
|
41,548
|
You are a professional machine learning specialist who can answer complex machine learning questions in a professional and clear way. I am doing a lab that is performing dimension reduction for MNIST dataset.I performed LDA on the dataset.
The code:
"import numpy as np
import matplotlib.pyplot as plt
class LDA:
def __init__(self, n_components=None):
self.n_components = n_components
self.eig_vectors = None
def fit_transform(self,X,y): # to reduce the dimensions of the input data
height, width = X.shape
unique_classes = np.unique(y)
num_classes = len(unique_classes)
scatter_t = np.cov(X.T)*(height - 1)
scatter_w = 0 #scatter_w matrix denotes the intra-class covariance
for i in range(num_classes):
class_items = np.flatnonzero(y == unique_classes[i])
scatter_w = scatter_w + np.cov(X[class_items].T) * (len(class_items)-1)
scatter_b = scatter_t - scatter_w #scatter_b is the inter-class covariance matrix
# An eigenvector is a vector whose direction remains unchanged when a linear transformation is applied to it.
eig_values, eig_vectors = np.linalg.eigh(np.linalg.pinv(scatter_w).dot(scatter_b))
pc = X.dot(eig_vectors[:,::-1][:,:self.n_components]) #The first n_components are selected using the slicing operation
# If n_components is equal to 2, we plot the two components, considering each vector as one axis
if self.n_components == 2:
if y is None:
plt.scatter(pc[:,0],pc[:,1])
else:
colors = ['r','g','b']
labels = np.unique(y)
for color, label in zip(colors, labels):
class_data = pc[np.flatnonzero(y==label)]
plt.scatter(class_data[:,0],class_data[:,1],c=color)
plt.show()
return pc, eig_vectors, eig_values
# Load 100 training samples
from mnist import load_SampleMnist, load_mnist
#nSamples = 100
trainpath = '../../lab1/data/noisy_train_digits.mat'
testpath = '../../lab1/data/noisy_test_digits.mat'
train_data, train_labels, test_data, test_labels = load_mnist(trainpath,testpath) #,nSamples)
LDA_object = LDA(n_components=9)
Y, eig_vectors, eig_values = LDA_object.fit_transform(train_data,train_labels)
eig_vectors = eig_vectors[:, np.argsort(-eig_values)]
eig_vectors = eig_vectors[:, 0:9]
print(eig_vectors.shape)
Xhat = Y @ np.transpose(eig_vectors)
print(Xhat.shape)
# Plot the original and reconstructed digits
X = test_data
#np.random.shuffle(X)
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = X[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = Xhat[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
"
When projecting facial images onto low-dimensional subspace, it is necessary to remove the global mean (mean face) of facial images, and during reconstruction, it necessary to add the global mean as an offset. Specifically, the projection and reconstruction processes are as follows:
w=x_pri=U^T (x-µ)
x_rec=Ux_prj+µ=Uw+µ, where μ is the global mean of facial images.
I want to display some reconstructed faces when setting µ=0 in the above equations (use the maximum number of eigenfaces). Show code.
|
3db4224354551117b57468e23470a6ff
|
{
"intermediate": 0.37940138578414917,
"beginner": 0.36593151092529297,
"expert": 0.2546670734882355
}
|
41,549
|
You are a professional machine learning specialist who can answer complex machine learning questions in a professional and clear way. I am doing a lab that is performing dimension reduction for MNIST dataset.I performed LDA on the dataset.
The code:
"import numpy as np
import matplotlib.pyplot as plt
class LDA:
def __init__(self, n_components=None):
self.n_components = n_components
self.eig_vectors = None
def fit_transform(self,X,y): # to reduce the dimensions of the input data
height, width = X.shape
unique_classes = np.unique(y)
num_classes = len(unique_classes)
scatter_t = np.cov(X.T)*(height - 1)
scatter_w = 0 #scatter_w matrix denotes the intra-class covariance
for i in range(num_classes):
class_items = np.flatnonzero(y == unique_classes[i])
scatter_w = scatter_w + np.cov(X[class_items].T) * (len(class_items)-1)
scatter_b = scatter_t - scatter_w #scatter_b is the inter-class covariance matrix
# An eigenvector is a vector whose direction remains unchanged when a linear transformation is applied to it.
eig_values, eig_vectors = np.linalg.eigh(np.linalg.pinv(scatter_w).dot(scatter_b))
pc = X.dot(eig_vectors[:,::-1][:,:self.n_components]) #The first n_components are selected using the slicing operation
# If n_components is equal to 2, we plot the two components, considering each vector as one axis
if self.n_components == 2:
if y is None:
plt.scatter(pc[:,0],pc[:,1])
else:
colors = ['r','g','b']
labels = np.unique(y)
for color, label in zip(colors, labels):
class_data = pc[np.flatnonzero(y==label)]
plt.scatter(class_data[:,0],class_data[:,1],c=color)
plt.show()
return pc, eig_vectors, eig_values
# Load 100 training samples
from mnist import load_SampleMnist, load_mnist
#nSamples = 100
trainpath = '../../lab1/data/noisy_train_digits.mat'
testpath = '../../lab1/data/noisy_test_digits.mat'
train_data, train_labels, test_data, test_labels = load_mnist(trainpath,testpath) #,nSamples)
LDA_object = LDA(n_components=9)
Y, eig_vectors, eig_values = LDA_object.fit_transform(train_data,train_labels)
eig_vectors = eig_vectors[:, np.argsort(-eig_values)]
eig_vectors = eig_vectors[:, 0:9]
print(eig_vectors.shape)
Xhat = Y @ np.transpose(eig_vectors)
print(Xhat.shape)
# Plot the original and reconstructed digits
X = test_data
#np.random.shuffle(X)
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = X[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = Xhat[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
"
When projecting facial images onto low-dimensional subspace, it is necessary to remove the global mean (mean face) of facial images, and during reconstruction, it necessary to add the global mean as an offset. Specifically, the projection and reconstruction processes are as follows:
w=x_pri=U^T (x-µ)
x_rec=Ux_prj+µ=Uw+µ, where μ is the global mean of facial images.
I want to display some reconstructed faces when setting µ=0 in the above equations (use the maximum number of eigenfaces). Show code.
|
1dc5ee4c91df68cf0eefdf17ab19d78c
|
{
"intermediate": 0.37940138578414917,
"beginner": 0.36593151092529297,
"expert": 0.2546670734882355
}
|
41,550
|
You are a professional machine learning specialist who can answer complex machine learning questions in a professional and clear way. I am doing a lab that is performing dimension reduction for MNIST dataset.I performed LDA on the dataset.
The code:
"import numpy as np
import matplotlib.pyplot as plt
class LDA:
def __init__(self, n_components=None):
self.n_components = n_components
self.eig_vectors = None
def fit_transform(self,X,y): # to reduce the dimensions of the input data
height, width = X.shape
unique_classes = np.unique(y)
num_classes = len(unique_classes)
scatter_t = np.cov(X.T)*(height - 1)
scatter_w = 0 #scatter_w matrix denotes the intra-class covariance
for i in range(num_classes):
class_items = np.flatnonzero(y == unique_classes[i])
scatter_w = scatter_w + np.cov(X[class_items].T) * (len(class_items)-1)
scatter_b = scatter_t - scatter_w #scatter_b is the inter-class covariance matrix
# An eigenvector is a vector whose direction remains unchanged when a linear transformation is applied to it.
eig_values, eig_vectors = np.linalg.eigh(np.linalg.pinv(scatter_w).dot(scatter_b))
pc = X.dot(eig_vectors[:,::-1][:,:self.n_components]) #The first n_components are selected using the slicing operation
# If n_components is equal to 2, we plot the two components, considering each vector as one axis
if self.n_components == 2:
if y is None:
plt.scatter(pc[:,0],pc[:,1])
else:
colors = ['r','g','b']
labels = np.unique(y)
for color, label in zip(colors, labels):
class_data = pc[np.flatnonzero(y==label)]
plt.scatter(class_data[:,0],class_data[:,1],c=color)
plt.show()
return pc, eig_vectors, eig_values
# Load 100 training samples
from mnist import load_SampleMnist, load_mnist
#nSamples = 100
trainpath = '../../lab1/data/noisy_train_digits.mat'
testpath = '../../lab1/data/noisy_test_digits.mat'
train_data, train_labels, test_data, test_labels = load_mnist(trainpath,testpath) #,nSamples)
LDA_object = LDA(n_components=9)
Y, eig_vectors, eig_values = LDA_object.fit_transform(train_data,train_labels)
eig_vectors = eig_vectors[:, np.argsort(-eig_values)]
eig_vectors = eig_vectors[:, 0:9]
print(eig_vectors.shape)
Xhat = Y @ np.transpose(eig_vectors)
print(Xhat.shape)
# Plot the original and reconstructed digits
X = test_data
#np.random.shuffle(X)
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = X[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = Xhat[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
"
The projection and reconstruction processes are as follows:
w=x_pri=U^T (x-µ)
x_rec=Ux_prj+µ=Uw+µ, where μ is the global mean of facial images.
I want to investigate the effect of not performing mean subtraction on the projected images by setting the global mean to zero for reconstructed faces when setting µ=0 in the above equations. Show code.
|
de83c09ac4f79ff85e77e763fe929d7b
|
{
"intermediate": 0.37940138578414917,
"beginner": 0.36593151092529297,
"expert": 0.2546670734882355
}
|
41,551
|
You are a professional machine learning specialist who can answer complex machine learning questions in a professional and clear way. I am doing a lab that is performing dimension reduction for MNIST dataset.I performed LDA on the dataset.
The code:
"import numpy as np
import matplotlib.pyplot as plt
class LDA:
def __init__(self, n_components=None):
self.n_components = n_components
self.eig_vectors = None
def fit_transform(self,X,y): # to reduce the dimensions of the input data
height, width = X.shape
unique_classes = np.unique(y)
num_classes = len(unique_classes)
scatter_t = np.cov(X.T)*(height - 1)
scatter_w = 0 #scatter_w matrix denotes the intra-class covariance
for i in range(num_classes):
class_items = np.flatnonzero(y == unique_classes[i])
scatter_w = scatter_w + np.cov(X[class_items].T) * (len(class_items)-1)
scatter_b = scatter_t - scatter_w #scatter_b is the inter-class covariance matrix
# An eigenvector is a vector whose direction remains unchanged when a linear transformation is applied to it.
eig_values, eig_vectors = np.linalg.eigh(np.linalg.pinv(scatter_w).dot(scatter_b))
pc = X.dot(eig_vectors[:,::-1][:,:self.n_components]) #The first n_components are selected using the slicing operation
# If n_components is equal to 2, we plot the two components, considering each vector as one axis
if self.n_components == 2:
if y is None:
plt.scatter(pc[:,0],pc[:,1])
else:
colors = ['r','g','b']
labels = np.unique(y)
for color, label in zip(colors, labels):
class_data = pc[np.flatnonzero(y==label)]
plt.scatter(class_data[:,0],class_data[:,1],c=color)
plt.show()
return pc, eig_vectors, eig_values
# Load 100 training samples
from mnist import load_SampleMnist, load_mnist
#nSamples = 100
trainpath = '../../lab1/data/noisy_train_digits.mat'
testpath = '../../lab1/data/noisy_test_digits.mat'
train_data, train_labels, test_data, test_labels = load_mnist(trainpath,testpath) #,nSamples)
LDA_object = LDA(n_components=9)
Y, eig_vectors, eig_values = LDA_object.fit_transform(train_data,train_labels)
eig_vectors = eig_vectors[:, np.argsort(-eig_values)]
eig_vectors = eig_vectors[:, 0:9]
print(eig_vectors.shape)
Xhat = Y @ np.transpose(eig_vectors)
print(Xhat.shape)
# Plot the original and reconstructed digits
X = test_data
#np.random.shuffle(X)
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = X[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
fig, ax = plt.subplots(nrows=1, ncols=5, sharex=True, sharey=True, )
for i in range(5):
img = Xhat[i].reshape(28,28)
ax[i].imshow(img, interpolation='nearest')
"
The projection and reconstruction processes are as follows:
w=x_pri=U^T (x-µ)
x_rec=Ux_prj+µ=Uw+µ, where μ is the global mean of facial images.
I want to investigate the effect of not performing mean subtraction on the projected images by setting the global mean to zero for reconstructed faces when setting µ=0 in the above equations. Show code.
|
401e563d4e85fd39822378a51116a699
|
{
"intermediate": 0.37940138578414917,
"beginner": 0.36593151092529297,
"expert": 0.2546670734882355
}
|
41,552
|
hi
|
97a46958853e6eb6a0de828306140eff
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
41,553
|
class PCA_Ex_Torch_M:
def __init__(self, n_components=400):
self.n_components = n_components
def fit(self, X):
# центрируем данные
self.mean_ = torch.mean(X, dim=0)
X_centered = X - self.mean_
# SVD разложение
U, S, V = torch.svd(X_centered)
# берем только нужное число компонент
self.components_ = V.T[:, :self.n_components]
pca = X_centered @ self.components_
return pca
# Пример использования
inputs = torch.randn(400, 4096)
pca_ex_m = PCA_Ex_Torch_M(300)
pca_ex_m.fit(inputs).shape
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-133-75a6e5fa5e05> in <cell line: 22>()
20 inputs = torch.randn(400, 4096)
21 pca_ex_m = PCA_Ex_Torch_M(300)
---> 22 pca_ex_m.fit(inputs).shape
<ipython-input-133-75a6e5fa5e05> in fit(self, X)
14 self.components_ = V.T[:, :self.n_components]
15
---> 16 pca = X_centered @ self.components_
17 return pca
18
RuntimeError: mat1 and mat2 shapes cannot be multiplied (400x4096 and 400x300)
|
6d0a9548d81410b9105f5dcc472f0b40
|
{
"intermediate": 0.41978493332862854,
"beginner": 0.3037698268890381,
"expert": 0.276445209980011
}
|
41,554
|
how would you build the backend of the AI chatbot that is supposed to look at a variety of CSVs and generate sql queries in order to answer complex questions about that data with business and life critical accuracy.
|
7364fbe14c124422434d77bb29253639
|
{
"intermediate": 0.290703684091568,
"beginner": 0.12308455258607864,
"expert": 0.5862118005752563
}
|
41,555
|
create id for each new post adding 1 to the last id
I have these two 2 files: App_mio2.jsx and PostForm2.jsx
this is App_mio2.jsx:
import "./App.css";
import { useState } from "react";
import PostList from "./components/PostList";
//import PostForm from "./components/PostForm";
import { useEffect } from "react";
import PostForm from "./components/PostForm2";
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
if (!response.ok) {
throw new Error("Network response was not ok");
}
const data = await response.json();
setPosts(data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchData();
}, []);
const addPost = (newPost) => {
setPosts([newPost, ...posts]); // Add the new post to the beginning of the array
};
return (
<>
<h1>Ejercicio Posts mio</h1>
<PostForm addPost={addPost} />
{posts.length > 0 && <PostList posts={posts} />}
{posts.length === 0 && <p>No hay posts todavía</p>}
</>
);
}
export default App;
this is PostForm2.jsx
import { useState } from "react";
const PostForm = ({addPost}) => {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [userId, setUserId] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title,
body,
userId: parseInt(userId)
})
});
if (!response.ok) {
throw new Error("Failed to add post");
}
const data = await response.json();
addPost(data); // Add the new post to the state
setTitle(""); // Clear form fields after successful submission
setBody("");
setUserId("");
} catch (error) {
console.error("Error adding post:", error);
}
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="title">Título:</label>
<input
id="title"
required
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<label htmlFor="body">Contenido:</label>
<textarea
id="body"
required
value={body}
onChange={(e) => setBody(e.target.value)}
></textarea>
<label htmlFor="userId">ID usuario:</label>
<input
type="number"
id="userId"
value={userId}
onChange={(e) => setUserId(e.target.value)}
/>
<button>Crear post</button>
</form>
);
};
export default PostForm;
i need create id for each new post adding 1 to the last id
|
f685e01d52bc434a65d0ad13f4603d01
|
{
"intermediate": 0.34037747979164124,
"beginner": 0.4719567596912384,
"expert": 0.18766576051712036
}
|
41,556
|
SImplify this code:
public static void renameInstruction(Statement s, String oldName, String newName) {
// Every single enum needs to be replaced
switch (s.kind()) {
case BLOCK: {
int length = s.lengthOfBlock();
for (int i = 0; i < length; i++) {
Statement subTree = s.removeFromBlock(i);
renameInstruction(subTree, oldName, newName);
s.addToBlock(i, subTree);
}
break;
}
case IF: {
Statement subTree = s.newInstance();
Condition ifCondition = s.disassembleIf(subTree);
renameInstruction(subTree, oldName, newName);
s.assembleIf(ifCondition, subTree);
}
case IF_ELSE: {
Statement subTreeIf = s.newInstance();
Statement subTreeElse = s.newInstance();
Condition ifElseCondition = s.disassembleIfElse(subTreeIf,
subTreeElse);
renameInstruction(subTreeIf, oldName, newName);
renameInstruction(subTreeElse, oldName, newName);
s.assembleIfElse(ifElseCondition, subTreeIf, subTreeElse);
}
case WHILE: {
Statement subTree = s.newInstance();
Condition whileCondition = s.disassembleWhile(subTree);
renameInstruction(subTree, oldName, newName);
s.assembleWhile(whileCondition, subTree);
}
// The magic method that actually does the renaming
case CALL: {
String call = s.disassembleCall();
if (call.equals(oldName)) {
s.assembleCall(newName);
} else {
s.assembleCall(call);
}
}
default:
break;
}
}
|
736b0dee20d50f19a50cf93a55a01e2b
|
{
"intermediate": 0.2830207943916321,
"beginner": 0.5093753337860107,
"expert": 0.20760385692119598
}
|
41,557
|
Traceback (most recent call last):
File "C:\Users\ILEG-i5-11\Downloads\Compressed\HRA-DL-highresaudio.com-master\HRA-DL.py", line 158, in <module>
main(userData)
File "C:\Users\ILEG-i5-11\Downloads\Compressed\HRA-DL-highresaudio.com-master\HRA-DL.py", line 142, in main
fetchTrack(albumId, sanitizeFname(albumFolder), preFname, f"{tracks['format']} kHz FLAC", str(tracks['trackNumber']).zfill(2), tracks['title'], str(len([x for x in metadata['data']['results']['tracks']])).zfill(2), tracks['url'])
File "C:\Users\ILEG-i5-11\Downloads\Compressed\HRA-DL-highresaudio.com-master\HRA-DL.py", line 84, in fetchTrack
r = session.get(url, stream=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Lib\site-packages\requests\sessions.py", line 546, in get
return self.request('GET', url, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Lib\site-packages\requests\sessions.py", line 519, in request
prep = self.prepare_request(req)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Lib\site-packages\requests\sessions.py", line 452, in prepare_request
p.prepare(
File "D:\Program Files\Python\Lib\site-packages\requests\models.py", line 313, in prepare
self.prepare_url(url, params)
File "D:\Program Files\Python\Lib\site-packages\requests\models.py", line 387, in prepare_url
raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL '': No schema supplied. Perhaps you meant http://?
#!/usr/bin/env python3
# Standard
import os
import re
import sys
import json
import time
import platform
import traceback
# Third party
import requests
from tqdm import tqdm
from bs4 import BeautifulSoup
session = requests.Session()
session.headers.update({"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0"})
def getOs():
osPlatform = platform.system()
if osPlatform == 'Windows':
return True
else:
return False
def osCommands(x):
if getOs():
if x == "p":
os.system('pause >nul')
elif x == "c":
os.system('cls')
elif x == "t":
os.system('title HRA-DL R1a (by Sorrow446)')
else:
if x == "p":
os.system("read -rsp $\"\"")
elif x == "c":
os.system('clear')
elif x == "t":
sys.stdout.write("\x1b]2;HRA-DL R1a (by Sorrow446)\x07")
def login(email, pwd):
r = session.get(f'https://streaming.highresaudio.com:8182/vault3/user/login?password={pwd}&username={email}')
if r.status_code == 200:
if "has_subscription" in r.json():
print("Signed in successfully.\n")
return r.text
else:
print("Account has no subscription.")
osCommands('p')
else:
print(f"Failed to sign in. Response from API: {r.text}")
osCommands('p')
# The API doesn't initially return album IDs, so we need to fetch it from the html.
def fetchAlbumId(url):
soup = BeautifulSoup(session.get(url).text, "html.parser")
return soup.find(attrs={"data-id": True})['data-id']
def fetchMetadata(albumId, userData):
r = session.get(f'https://streaming.highresaudio.com:8182/vault3/vault/album/?album_id={albumId}&userData={userData}')
if r.status_code != 200:
print(f"Failed to fetch album metadata. Response from API: {r.text}")
osCommands('p')
else:
return r.json()
def dirSetup(albumFolder):
if not os.path.isdir(albumFolder):
os.makedirs(albumFolder)
return albumFolder
def fileSetup(fname):
if os.path.isfile(fname):
os.remove(fname)
def fetchTrack(albumId, albumFolder, fname, spec, trackNum, trackTitle, trackTotal, url):
session.headers.update({"range":"bytes=0-", "referer":f"https://stream-app.highresaudio.com/album/{albumId}"})
print(f"Downloading track {trackNum} of {trackTotal}: {trackTitle} - {spec}")
# Would have liked to have used pySmartDL instead,
# but it causes 403s for this specific site, so we'll use requests instead.
r = session.get(url, stream=True)
size = int(r.headers.get('content-length', 0))
# if r.status_code != 200:
# print(f"Failed to fetch track. Response from API: {r.text}")
# osCommands('p')
with open(fname, 'wb') as f:
with tqdm(total=size, unit='B',
unit_scale=True, unit_divisor=1024,
initial=0, miniters=1) as bar:
for chunk in r.iter_content(32 * 1024):
if chunk:
f.write(chunk)
bar.update(len(chunk))
def fetchBooklet(url, dest, albumId):
fileSetup(dest)
r = session.get(url, stream=True)
size = int(r.headers.get('content-length', 0))
# if r.status_code != 200:
# print(f"Failed to fetch track. Response from API: {r.text}")
# osCommands('p')
# Don't really need to iter booklets, but oh well.
with open(dest, 'wb') as f:
with tqdm(total=size, unit='B',
unit_scale=True, unit_divisor=1024,
initial=0, miniters=1) as bar:
for chunk in r.iter_content(32 * 1024):
if chunk:
f.write(chunk)
bar.update(len(chunk))
def sanitizeFname(fname):
if getOs():
return re.sub(r'[\\/:*?"><|]', '-', fname)
else:
return re.sub('/', '-', fname)
def main(userData):
url = input("Input HIGHRESAUDIO Store URL:")
if not url.strip():
osCommands('c')
return
elif not re.match(r"https?://(?:www\.)?highresaudio\.com/[a-z]{2}/album/view/(\w{6})/-?(?:\w*-?)*", url):
print("Invalid URL.")
time.sleep(1)
osCommands('c')
return
osCommands('c')
albumId = fetchAlbumId(url)
metadata = fetchMetadata(albumId, userData)
albumFolder = f"{metadata['data']['results']['artist']} - {metadata['data']['results']['title']}"
print(f"{albumFolder}\n")
albumFolderS = dirSetup(f"/data/data/com.termux/files/home/storage/music/{sanitizeFname(albumFolder)}")
for tracks in [x for x in metadata['data']['results']['tracks']]:
preFname = f"/data/data/com.termux/files/home/storage/music/{sanitizeFname(albumFolder)}/{str(tracks['trackNumber']).zfill(2)}.flac"
postFname = f"/data/data/com.termux/files/home/storage/music/{sanitizeFname(albumFolder)}/{str(tracks['trackNumber']).zfill(2)}. {sanitizeFname(tracks['title'])}.flac"
fileSetup(preFname)
fileSetup(postFname)
fetchTrack(albumId, sanitizeFname(albumFolder), preFname, f"{tracks['format']} kHz FLAC", str(tracks['trackNumber']).zfill(2), tracks['title'], str(len([x for x in metadata['data']['results']['tracks']])).zfill(2), tracks['url'])
os.rename(preFname, postFname)
if "booklet" in metadata['data']['results']:
print("Booklet available. Downloading...")
fetchBooklet(f"https://{metadata['data']['results']['booklet']}", f"{albumFolderS}/booklet.pdf", albumId)
print("Returning to URL input screen...")
time.sleep(1)
osCommands('c')
if __name__ == '__main__':
osCommands('t')
with open("config.json") as f:
config = json.load(f)
userData = login(config["email"], config["password"])
try:
while True:
main(userData)
except (KeyboardInterrupt, SystemExit):
sys.exit()
except:
traceback.print_exc()
input("\nAn exception has occurred. Press enter to exit.")
sys.exit()
|
19bac2eb5e3157a809a76469445c4660
|
{
"intermediate": 0.2956300675868988,
"beginner": 0.34467366337776184,
"expert": 0.35969626903533936
}
|
41,558
|
Build code of star system generator based on architectures of Solar system and exoplanetary systems, using Scratch instead of Python
|
32fce38ec8d5fa3dc0d565484469f1e0
|
{
"intermediate": 0.39342162013053894,
"beginner": 0.17930303514003754,
"expert": 0.42727530002593994
}
|
41,559
|
Build the source code of star system generator based on architectures of Solar system and exoplanetary systems
|
adf78c22832b042a2895b2f22e865019
|
{
"intermediate": 0.21420714259147644,
"beginner": 0.12552154064178467,
"expert": 0.6602712869644165
}
|
41,560
|
Build the source code of star system generator based on architectures of Solar system and exoplanetary systems, it called Accrete program
|
ced881a2570b99c4e92c2b5c1e60845c
|
{
"intermediate": 0.19383099675178528,
"beginner": 0.09306030720472336,
"expert": 0.7131087183952332
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.